blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9fb46227b3c9bf356ac6993d444519438325ed0e | 19e7076b4ace7a7f0380284bed5eb1530514a166 | /Stack_Queue/stack_linked_list.cpp | 0c0f464319803b49280774ee665d3aa8164b6143 | [] | no_license | mayur-aggarwal/Data-Structures | a78808a5800e61c2090b2108dd928ddde141a8f0 | b9bc4f7bb9a3d9e5532c106f8436325df06f2d61 | refs/heads/master | 2022-11-20T12:49:25.936766 | 2022-11-14T11:53:50 | 2022-11-14T11:53:50 | 230,951,973 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | cpp | stack_linked_list.cpp | #include <iostream>
using namespace std;
//A structure to represent stack
struct stack{
int data;
struct stack* next;
};
struct stack* top;
int isEmpty()
{
return (top == NULL);
}
void push(int data)
{
struct stack* temp;
temp = new stack();
temp->data = data;
temp->next = top;
top = temp;
}
int pop()
{
if(top == NULL) return -1;
struct stack* temp;
temp = top;
int popped = temp->data;
top = top->next;
free(temp);
return popped;
}
int peek()
{
if(!isEmpty())
{
return top->data;
}
return -1;
}
int main()
{
push(10); //[10]
push(20); //[20, 10]
push(30); //[30, 20, 10]
cout << pop(); //[20, 10]
return 0;
} |
790f9fe28631bcf66701a3a0308be4561a532b0f | 1eddfc58034e70dbf32c93c5ecdfc47e377eca84 | /arrayStabilization.cpp | 16db6f504242040c721569eb937e7ed027968eb7 | [] | no_license | Rodagui/CodeForces-Solutions | ec90ad3806ca6025c9f588eb298b33a47f097bd4 | fbcce297deb645ea8f6d7a30297071a12e447489 | refs/heads/master | 2022-07-27T21:36:20.656936 | 2022-07-15T00:54:17 | 2022-07-15T00:54:17 | 178,289,421 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 572 | cpp | arrayStabilization.cpp | /*B. Array Stabilization*/
#include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int min = 10000000;
int aux;
int tam;
cin >> tam;
vector <int> nums(tam);
for (int i = 0; i < tam; ++i)
{
cin >> nums[i];
}
if(tam == 2)
cout << "0";
else{
sort(nums.begin(), nums.end());
aux = nums[tam-1] - nums[1];
if(aux < min)
min = aux;
aux = nums[tam-2] - nums[0];
if (aux < min)
min = aux;
cout << min;
}
return 0;
} |
56ab3987896b475342814530d6886a9a7265496c | 55f54c9d18e3781255c157d63381579261dde405 | /Code/Core/Math/Conversions.h | de1205df8da97e76d48b85132ea77b131218de32 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fastbuild/fastbuild | 8f5f94802c6cce54d903936c8551fd8791479001 | 1b3935069d29b965a9d1d6798d9cf651319dbe87 | refs/heads/main | 2023-08-22T19:28:12.587510 | 2023-08-19T02:56:25 | 2023-08-19T02:56:25 | 32,647,696 | 1,175 | 409 | null | 2023-08-23T22:40:15 | 2015-03-21T19:53:07 | C++ | UTF-8 | C++ | false | false | 1,034 | h | Conversions.h | // Conversion.h
//------------------------------------------------------------------------------
#pragma once
// Includes
//------------------------------------------------------------------------------
#include "Core/Env/Types.h"
// Math
//------------------------------------------------------------------------------
namespace Math
{
template <class T>
static inline T RoundUp( T value, T alignment )
{
return ( value + alignment - 1) & ~( alignment - 1 );
}
template <class T>
static inline T Max( T a, T b )
{
return ( a > b ) ? a : b;
}
template <class T>
static inline T Min( T a, T b )
{
return ( a < b ) ? a : b;
}
template <class T>
static inline T Clamp( T a, T b, T c )
{
return Min( Max( a, b ), c );
}
template <typename T>
static inline bool IsPowerOf2( T value )
{
return ( ( ( value - 1 ) & value ) == 0 );
}
};
//------------------------------------------------------------------------------
|
dcf41752379b9a59d36058593f5450f49fbb784d | f13bcf309973ed4713ef39067e7746f474ab8077 | /src/widget2.h | cb163344a831fdd33a68dbf3de79c43d0cd832d4 | [] | no_license | ForeverDavid/MedicalVisualization | ab84a76b7232ff40e187d354fee22a16f26ac599 | 55dfd09d40cbe3b2e719daf847d85057c78f9cad | refs/heads/master | 2020-04-06T16:48:16.902837 | 2018-11-14T18:10:23 | 2018-11-14T18:10:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | h | widget2.h | #ifndef WIDGET2_H
#define WIDGET2_H
#include <QWidget>
#include <string>
using namespace std;
class Controller;
namespace Ui {
class Widget2;
}
class Widget2 : public QWidget
{
Q_OBJECT
public:
explicit Widget2(QWidget *parent = 0);
~Widget2();
Ui::Widget2* getUi();
void setController(Controller* c);
private:
Ui::Widget2 *ui;
Controller* controller;
private slots:
void on_btnPrevious_clicked();
void on_btnNext_clicked();
void on_radioBtnComplete_clicked();
void on_radioBtnComponent_clicked();
void on_threshold_valueChanged(int val);
void on_btnRemove_clicked();
void on_btnRemove2_clicked();
void on_tabMode_currentChanged(int mode);
void on_btnAnnotation_clicked();
void on_btnPrint_clicked();
};
#endif // WIDGET2_H
|
b8a20ff5db406b0ee4c785230472f57f15b21e39 | 80cf6334fb1330b74998423da1bd1cd7700d42f5 | /cpp_flySingleTracer_multiTask/classes/MStringTool.hpp | bea046519a78a05d002842ec5677a24cad787049 | [
"MIT"
] | permissive | yzyw0702/flySleepPrograms | 144750e58b83699b472d5b0ffe1feb30e05f6c3a | 402a31261963992dc8439e4326cb7bca5487c684 | refs/heads/master | 2020-04-17T04:30:44.112879 | 2019-01-19T05:27:10 | 2019-01-19T05:27:10 | 166,233,063 | 2 | 0 | null | 2019-01-18T03:09:17 | 2019-01-17T13:46:51 | Python | UTF-8 | C++ | false | false | 3,580 | hpp | MStringTool.hpp | //===========================
//====> MStringTool
//===========================
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#ifndef _MSTRINGTOOL_HPP_
#define _MSTRINGTOOL_HPP_
namespace toolstring {
void printStringList(vector<string>& v) {
for (size_t i = 0; i < v.size(); i++) {
cout << "[" << i << "] = " << v[i] << endl;
}
}
vector<string> split(string& src, char delim = ' ') {
int iL = 0, iR = 0;
vector<string> ret;
while (src[iL] == delim) { // jump all delims at left space
iL++;
}
for (int i = iL; i < (int)src.size(); i++) { // traverse all char
if (src[i] == delim) { // delim found
iR = i; // set right marker
ret.push_back(src.substr(iL, iR - iL)); // split current word
iL = i+1; // set left marker to current position
}
}
if (src[src.size() - 1] != delim) { // add last one if it's not a delim
ret.push_back(src.substr(iL, src.size() - iL));
} return ret;
}
void rstrip(string& src, char c = ' ') {
int n = src.size();
while (src[n - 1] == c && n > 0) n--;
src = src.substr(0, n);
}
void lstrip(string& src, char c = ' ') {
int n = 0;
int N = src.size();
while (src[n] == c && n < N) n++;
src = src.substr(n, N);
}
string rstrip(string src, string lpatterns) {
bool isFinish = false;
char suffix;
int iLast = (int)src.size();
while (!isFinish) { // clear all the characters listed in lpatterns
suffix = src[iLast - 1];
bool isClear = true;
for (int i = 0; i < (int)lpatterns.size(); i++) { // check the list lpatters
if (suffix == lpatterns[i]) {
iLast--;
isClear = false;
break;
}
}
if (isClear || iLast == 0) // exit only when all listed suffices are cleared
isFinish = true;
}
return src.substr(0, iLast);
}
string lstrip(string src, string lpatterns) {
bool isFinish = false;
char prefix;
int iFirst = 0;
while (!isFinish) { // clear all the characters listed in lpatterns
prefix = src[iFirst];
bool isClear = true;
for (int i = 0; i < (int)lpatterns.size(); i++) { // check the list lpatters
if (prefix == lpatterns[i]) {
iFirst++;
isClear = false;
break;
}
}
if (isClear || iFirst == src.size() - 1) // exit only when all listed suffices are cleared
isFinish = true;
}
return src.substr(iFirst, src.size());
}
template <class T>
int isInList(vector<T>& list, T query) {
if (list.size() == 0) return -1;
for (int i = 0; i < (int)list.size(); i++)
if (query == list[i]) return i;
return -1;
}
void replace(string& target, string before, string after) {
string::size_type pos = 0;
string::size_type nBefore = before.size();
string::size_type nAfter = after.size();
while ((pos = target.find(before, pos)) != string::npos) {
target.replace(pos, nBefore, after);
pos += nAfter;
}
}
};
namespace debug_toolstring {
using namespace toolstring;
void debug_split() {
string s1 = "This is a string list.";
string s2 = "This is another string list with some bug. ";
string s3 = " There is a space at first position.";
string s4 = " Several left spaces appear. ";
string s5 = "Several in-between spaces should be split.";
string s6 = "use,comma,to,split,this,string,";
printStringList(split(s1));
printStringList(split(s2));
printStringList(split(s3));
printStringList(split(s4));
printStringList(split(s5));
printStringList(split(s6, ','));
}
};
#endif
|
610fcf4fda0c1628778d9f7bae935eac981fb9fd | 7ff7d609ee7917990479a60337903484f3f02f4e | /myshell.cpp | e543f95ef66f528859922db507fc7fc3d0f37ad4 | [] | no_license | qhuang266/myshell | 88e3f78893059639e923d418d055396bf1f4817d | ff8924d7b27c19d8e986dba7370fe54ab346bc4a | refs/heads/master | 2021-01-10T04:44:47.813641 | 2015-10-02T14:29:45 | 2015-10-02T14:29:45 | 43,557,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,650 | cpp | myshell.cpp | /**
* myshell
* @author: QianHuang
* about input command:
* 1. no backtick `
* 2. no append redirect >> <<
* 3. no
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "command.h"
#define ARGV_MAX 100
#define MAX_LEN 256
enum STATE
{
ONE_SPACE,
INPUT_REDIRECT,
OUTPUT_REDIRECT,
NORMAL,
PIPE
};
// print current path
void printPath()
{
char current_path[MAX_LEN];
char user[MAX_LEN];
char hostname[MAX_LEN];
getcwd(current_path, MAX_LEN);
getlogin_r(user, MAX_LEN);
gethostname(hostname, MAX_LEN);
printf("%s@%s %s$ ", user, hostname, current_path);
}
// format the input command, delete or add some space, make it easier to be tokenized
void format(char *input)
{
char tmp[MAX_LEN];
strcpy(tmp, input);
int new_ptr = 0, tmp_ptr = 0;
STATE status = NORMAL;
while (tmp[tmp_ptr] != '\0')
{
switch(status)
{
case NORMAL:
{
if (tmp[tmp_ptr] == ' ')
status = ONE_SPACE;
else if (tmp[tmp_ptr] == '<')
{
input[new_ptr++] = ' ';
status = INPUT_REDIRECT;
}
else if (tmp[tmp_ptr] == '>')
{
input[new_ptr++] = ' ';
status = OUTPUT_REDIRECT;
}
else if (tmp[tmp_ptr] == '|')
{
input[new_ptr++] = ' ';
status = PIPE;
}
input[new_ptr] = tmp[tmp_ptr];
++tmp_ptr;
++new_ptr;
break;
}
case ONE_SPACE:
{
if (tmp[tmp_ptr] == ' ')
++tmp_ptr;
else
{
if (tmp[tmp_ptr] == '>')
{
if (new_ptr > 2 && (input[new_ptr - 2] == '1' || input[new_ptr - 2] == '2' || input[new_ptr - 2] == '0') && input[new_ptr - 3] == ' ')
new_ptr -= 1;
status = OUTPUT_REDIRECT;
}
else if (tmp[tmp_ptr] == '<')
{
if (new_ptr > 2 && (input[new_ptr - 2] == '1' || input[new_ptr - 2] == '2' || input[new_ptr - 2] == '0') && input[new_ptr - 3] == ' ')
new_ptr -= 1;
status = INPUT_REDIRECT;
}
else if (tmp[tmp_ptr] == '|')
{
status = PIPE;
}
else
status = NORMAL;
input[new_ptr] = tmp[tmp_ptr];
++tmp_ptr;
++new_ptr;
}
break;
}
case PIPE:
{
if (tmp[tmp_ptr] == ' ')
++tmp_ptr;
else
{
input[new_ptr++] = ' ';
input[new_ptr] = tmp[tmp_ptr];
++tmp_ptr;
++new_ptr;
}
break;
}
case OUTPUT_REDIRECT:
case INPUT_REDIRECT:
{
if (tmp[tmp_ptr] == ' ')
++tmp_ptr;
else
status = NORMAL;
break;
}
}
}
input[new_ptr] = '\0';
}
void deleteCommandList(command *head)
{
command *ptr = head->next;
while (ptr)
{
head->next = ptr->next;
delete ptr;
ptr = head->next;
}
delete head;
}
command *parse(char *input)
{
command *dummy = new command(COMMAND);
command *tail = dummy;
command *node_pointer = nullptr;
char *token = strtok(input, " ");
while (token != nullptr)
{
// redirect first
if (token[0] == '<' || token[0] == '>' || ((token[0] == '0' || token[0] == '1' || token[0] == '2') && (token[1] == '<' || token[1] == '>')))
{
// check whether there is duplicate redirect already
if (dummy->next)
{
command *ptr = dummy->next;
while (ptr && (ptr->type == REDIRECT_INPUT || ptr->type == REDIRECT_OUTPUT))
{
if ((ptr->type == REDIRECT_INPUT && token[0] == '<') || (ptr->type == REDIRECT_OUTPUT && token[0] == '>'))
{
deleteCommandList(dummy);
return new command(REDIRECT_ERROR);
}
}
}
// check follow with filename
if (strlen(token) == 1)
{
deleteCommandList(dummy);
return new command(REDIRECT_ERROR);
}
else
{
if (node_pointer != nullptr)
{
tail->next = node_pointer;
tail = tail->next;
node_pointer = nullptr;
}
if (token[0] == '>')
{
++token;
command *new_node = new command(REDIRECT_OUTPUT);
new_node->setOutputfile(token);
new_node->next = dummy->next;
dummy->next = new_node;
}
else if (token[0] == '<')
{
++token;
command *new_node = new command(REDIRECT_INPUT);
new_node->setInputfile(token);
new_node->next = dummy->next;
dummy->next = new_node;
}
else if (token[1] == '>')
{
char *output_file = token + 2;
token[1] = '\0';
command *new_node = new command(REDIRECT_INPUT);
new_node->setInputfile(token);
new_node->next = dummy->next;
dummy->next = new_node;
new_node = new command(REDIRECT_OUTPUT);
new_node->setOutputfile(output_file);
new_node->next = dummy->next;
dummy->next = new_node;
}
else
{
char *input_file = token + 2;
token[1] = '\0';
command *new_node = new command(REDIRECT_OUTPUT);
new_node->setInputfile(token);
new_node->next = dummy->next;
dummy->next = new_node;
new_node = new command(REDIRECT_INPUT);
new_node->setOutputfile(input_file);
new_node->next = dummy->next;
dummy->next = new_node;
}
}
}
else if (token[0] == '|')
{
if (node_pointer != nullptr)
{
node_pointer->addArgument("\0");
tail->next = node_pointer;
tail = tail->next;
node_pointer = nullptr;
}
}
else
{
if (node_pointer == nullptr)
{
node_pointer = new command(COMMAND);
node_pointer->setName(token);
}
else
{
node_pointer->addArgument(token);
}
}
token = strtok(nullptr, " ");
}
if (node_pointer != nullptr)
{
node_pointer->addArgument("\0");
tail->next = node_pointer;
}
return dummy->next;
}
void executeInputRedirect(command *ptr)
{
int fd = open(ptr->getInputfile(), O_RDONLY, 0);
dup2(fd, 0);
close(fd);
}
void executeOutputRedirect(command *ptr)
{
int fd = creat(ptr->getOutputfile(), 0644);
dup2(fd, 1);
close(fd);
}
bool isBuildin(char *command_name)
{
if (strcmp(command_name, "cd") == 0 )
return true;
// ...
else
return false;
}
void executeCd(command *ptr)
{
int result = chdir(ptr->getArguments_str());
if (result < 0)
{
perror("can't do cd command");
}
}
void executeBuildin(command *ptr)
{
if (strcmp(ptr->getName(), "cd") == 0)
executeCd(ptr);
}
void execute(command *ptr)
{
pid_t pid = fork();
int status;
if (pid < 0)
{
perror("error to fork a new process");
_exit(1);
}
else if (pid == 0)
{
if (execvp(ptr->getName(), ptr->getArguments()) < 0)
{
perror("something wrong when execute process");
_exit(1);
}
}
else
{
while (wait(&status) != pid)
;
}
}
int main(int argc, char const *argv[])
{
char *input_line = nullptr;
char *arg_vector[ARGV_MAX];
size_t line_length = 0;
while (true)
{
printPath();
getline(&input_line, &line_length, stdin);
format(input_line);
command *cmd_list = parse(input_line);
if (cmd_list == nullptr) // empty input
continue;
else if (strcmp(cmd_list->getName(), "exit") == 0) // exit
return 0;
else
{
command *ptr = cmd_list;
while (ptr != nullptr)
{
if (ptr->type == REDIRECT_ERROR)
{
printf("duplicate redirect error!\n");
break;
}
else if (ptr->type == REDIRECT_INPUT)
executeInputRedirect(ptr);
else if (ptr->type == REDIRECT_OUTPUT)
executeOutputRedirect(ptr);
else if (isBuildin(ptr->getName()))
executeBuildin(ptr);
else
execute(ptr);
ptr = ptr->next;
}
}
}
return 0;
}
|
caea5dc6189b2cff6c21be7025e6e8d1b37907af | c509ec170f31580895c457c29e78463866397c17 | /offline/Examples/FirstAlg/src/RWExample/RWExample.h | 7c9a52596602f043935cbc7c7261921b319ff80b | [] | no_license | feipengsy/lodestar | 9e2c35cdbb6edf7ce31eff5fcf05412ff7f8453e | e05c01f15d8b3aeed265210a910e475beb11d9b6 | refs/heads/master | 2021-01-09T21:47:12.332609 | 2015-06-24T14:54:59 | 2015-06-24T14:54:59 | 36,277,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 322 | h | RWExample.h | #ifndef RW_EXAMPLE_H
#define RW_EXAMPLE_H
#include "Sniperkernel/AlgBase.h"
class RWExample : public AlgBase {
public:
RWExample(const std::string& name);
~RWExample();
bool initialize();
bool execute();
bool finalize();
private:
int m_iEvt;
};
#endif
|
963fcc05b6265352cbe57f17832abf5a36f522e0 | 71e7675390503901564239473b56ad26bdfa13db | /src/iofwdutil/stats/CounterConfig.cpp | f3a0f1c6eba213bb9459aa2a8604db6476169f51 | [] | no_license | radix-io-archived/iofsl | 1b5263f066da8ca50c7935009c142314410325d8 | 35f2973e8648ac66297df551516c06691383997a | refs/heads/main | 2023-06-30T13:59:18.734208 | 2013-09-11T15:24:26 | 2013-09-11T15:24:26 | 388,571,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 874 | cpp | CounterConfig.cpp | #include "iofwdutil/stats/CounterConfig.hh"
namespace iofwdutil
{
namespace stats
{
CounterConfig::CounterConfig() :
log_(IOFWDLog::getSource("counterconfig")),
all_mode_(false),
all_mode_set_(false)
{
}
CounterConfig::CounterConfig(const CounterConfig & rhs) :
counter_config_(rhs.counter_config_),
log_(rhs.log_),
all_mode_(rhs.all_mode_),
all_mode_set_(rhs.all_mode_set_)
{
}
CounterConfig & CounterConfig::operator=(const CounterConfig & rhs)
{
/* copy the rhs data */
counter_config_ = rhs.counter_config_;
all_mode_ = rhs.all_mode_;
all_mode_set_ = rhs.all_mode_set_;
/* return ref to this object */
return (*this);
}
CounterConfig::~CounterConfig()
{
counter_config_.clear();
}
bool const & counterEnabled(CounterConfig & cfg, std::string & key)
{
return cfg.counter_config_[key];
}
}
}
|
d931b39ffa0681ebc8c8bed0e01a9720b169973c | fd9e81f3609ec9bd50f9dbcf2581bcdf99abe192 | /src/examples/pipeline/pipelinenodefactory.cpp | 5935e8ce461b6e2c2f58d68711e457002ec7f9c0 | [] | no_license | BlackStar-EoP/eop-node-editor | 8ca3275698264ffb9b1499f4bd36415c74c65626 | 02237f2adbf0243c9dc9a7835bf3bb7486b83d8d | refs/heads/master | 2022-05-09T13:16:54.063299 | 2022-04-18T18:27:04 | 2022-04-18T18:27:04 | 114,267,992 | 18 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,603 | cpp | pipelinenodefactory.cpp | #include "pipelinenodefactory.h"
#include "materialnodemodel.h"
#include "material.h"
#include "rendertargetmodel.h"
#include "rendertarget.h"
PipeLineNodeFactory::PipeLineNodeFactory()
{
register_node_type(MaterialNodeModel::TYPE_NAME);
register_node_type(RenderTargetNodeModel::TYPE_NAME);
}
NodeModel* PipeLineNodeFactory::create_node_model()
{
static int type = 0;
++type;
if (type % 2 == 0)
{
static int materialnr = 0;
Material* material = new Material(materialnr++, "Material");
uint32_t num_flt = rand() % 2 + 1;
uint32_t num_vec2 = rand() % 2;
uint32_t num_vec3 = rand() % 2;
uint32_t num_vec4 = rand() % 2;
uint32_t num_tex = rand() % 2;
for (uint32_t i = 0; i < num_flt; ++i)
material->addUniform(MaterialUniform(MaterialUniform::FLOAT, "Float var"));
for (uint32_t i = 0; i < num_vec2; ++i)
material->addUniform(MaterialUniform(MaterialUniform::VEC2, "Vec2 var"));
for (uint32_t i = 0; i < num_vec3; ++i)
material->addUniform(MaterialUniform(MaterialUniform::VEC3, "Vec3 var"));
for (uint32_t i = 0; i < num_vec4; ++i)
material->addUniform(MaterialUniform(MaterialUniform::VEC4, "Vec4 var"));
for (uint32_t i = 0; i < num_tex; ++i)
material->addUniform(MaterialUniform(MaterialUniform::SAMPLER_2D, "Texture"));
uint32_t num_outputs = rand() % 2 + 1;
for (uint32_t i = 0; i < num_outputs; ++i)
material->addOutput(ShaderOutput(i, MaterialUniform::VEC4, "fragcolor"));
return new MaterialNodeModel(material);
}
else
{
return new RenderTargetNodeModel(new RenderTarget());
}
} |
4b97f55ff8fbaa23a6942c18cd6670cb9139c1a3 | ea494a1c796276934ad206e37c19af567a0da5f7 | /WorldGenerator/src/Ellipse.cpp | bd8f741be32740adafb6a96a476d22d2a5787a73 | [] | no_license | jorgeayllon1/WorldGenerator | 8b87ffbda6810d26531a24c6db60c8c9e90a2c52 | e5fcadd0a665cf07b50bb7c232bdd3d7e2e64acd | refs/heads/master | 2023-03-17T20:59:44.243064 | 2019-04-15T17:32:08 | 2019-04-15T17:32:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | cpp | Ellipse.cpp | #include "Ellipse.h"
void Ellipse::sedessiner()
{
std::string const nomFichier("output.svg");
std::ofstream monFlux(nomFichier.c_str(),std::ios::app);//ouverture de fichier, code identique à celui d'openclassroom
if(monFlux)
{
monFlux.seekp(0,std::ios::end);
monFlux<<"\n<ellipse cx=\""<<m_barycentre.getx()<<"\" cy=\""<<m_barycentre.gety()<<"\" rx=\""<<m_rayonx<<"\" ry=\""<<m_rayony<<"\" fill=\""<<m_couleur<<"\" />";
}
else
{
std::cout<<"ERREUR: Impossible d'ouvrir le fichier.\n";
}
}
|
f646ad6f98611a27b08d4184269497f07e6c2383 | 4e47655b035b285f9c2194a434fe1c1c8f0ae144 | /Classes/PrologScene1.cpp | 1e3a3f428d138757457c2c23f45df696e2638a08 | [] | no_license | chanyipk/lucishistoria | 823b21b699b3eba76df6cfadda7530b70262951f | f81f56e48c455fb29ce17a3fbc6557192009a15e | refs/heads/master | 2021-09-05T03:59:47.179023 | 2018-01-24T02:04:03 | 2018-01-24T02:04:03 | 103,842,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,701 | cpp | PrologScene1.cpp | #include "MapScene.h"
#include "PrologScene1.h"
#include "PrologScene2.h"
#include "Jdata.h"
Jdata* pP;
Scene* PrologScene1::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = PrologScene1::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool PrologScene1::init()
{
//////////////////////////////
// 1. super init first
if (!Layer::init())
{
return false;
}
std::string prol_uname = pP->jjgetuserName(0);
pP->jjsetBool(true, "pro", prol_uname);
auto pro0 = Sprite::create("pro0.png");
pro0->setAnchorPoint(Point(0.5, 0.5));
pro0->setPosition(Point(Director::getInstance()->
getWinSize().width / 2, Director::getInstance()->
getWinSize().height / 2));
this->addChild(pro0);
auto dt = DelayTime::create(8.0);
auto prolog = Sequence::create(dt, CallFuncN::create(CC_CALLBACK_1(PrologScene1::changeScene, this)), NULL);
this->runAction(prolog);
auto skip_but = MenuItemImage::create("cirbut.png", "cirbut_push.png", CC_CALLBACK_1(PrologScene1::skipScene, this));
auto skip = Menu::create(skip_but, NULL);
skip->alignItemsVertically();
skip->setAnchorPoint(Point(0.5, 0.5));
skip->setPosition(Point(1200, -300));
skip->setScale(0.35);
pro0->addChild(skip);
return true;
}
void PrologScene1::changeScene(Ref* Sender)
{
auto scene = TransitionFade::create(3.0, PrologScene2::createScene());
Director::getInstance()->replaceScene(scene);
}
void PrologScene1::skipScene(Ref* Sender)
{
this->stopAllActions();
Director::getInstance()->replaceScene(MapScene::createScene());
} |
74a7290a337a2b8ce29b6867a85682fbcf43375e | e137c414883f56a3c80e382426aac7bde7d1f056 | /FlowTree/Helpers.h | d95c1830a53683084966e982dc1655942ab8dccf | [] | no_license | simonyanmikayel/FlowTree | 1d53d9c13dbde3f13b77caaab00e9acf6660012e | df29a3332c33df0c6da1dbad9e66e62ae453f82a | refs/heads/master | 2023-08-09T11:34:29.679729 | 2023-07-23T17:19:49 | 2023-07-23T17:19:49 | 232,781,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,399 | h | Helpers.h | #pragma once
struct LOG_NODE;
struct FLOW_NODE;
extern HWND hwndMain;
extern FLOW_NODE* gSyncronizedNode;
#define WM_UPDATE_FILTER WM_USER + 1000
#define WM_INPORT_TASK WM_USER + 1001
#define WM_MOVE_SELECTION_TO_END WM_USER + 1002
#define WM_SHOW_NGS WM_USER + 1003
#define WM_UPDATE_BACK_TRACE WM_USER + 1004
static const int ICON_LEN = 16;
static const int ICON_OFFSET = 16 + 4;
static const int TEXT_MARGIN = 8;
static const int INFO_TEXT_MARGIN = 4;
enum MENU_ICON { MENU_ICON_NON = -1, MENU_ICON_SYNC, MENU_ICON_FUNC_IN_STUDIO, MENU_ICON_CALL_IN_STUDIO, MENU_ICON_MAX};
namespace Helpers
{
void CopyToClipboard(HWND hWnd, char* szText, int cbText);
std::string CommErr(HRESULT hr);
void SysErrMessageBox(CHAR* lpFormat, ...);
void ErrMessageBox(CHAR* lpFormat, ...);
CHAR* find_str(const CHAR *phaystack, const CHAR *pneedle, int bMatchCase);
CHAR* str_format_int_grouped(__int64 num);
void GetTime(DWORD &sec, DWORD& msec);
void CloseSocket(SOCKET &s);
void OnLButtonDoun(LOG_NODE* pNode, WPARAM wParam, LPARAM lParam);
void ShowInIDE(LOG_NODE* pNode, bool bShowCallSite);
void AddCommonMenu(LOG_NODE* pNode, HMENU hMenu, int& cMenu);
void AddMenu(HMENU hMenu, int& cMenu, int ID_MENU, LPCTCH str, bool disable = false, MENU_ICON ID_ICON = MENU_ICON_NON);
void SetMenuIcon(HMENU hMenu, UINT item, MENU_ICON icon);
void UpdateStatusBar();
// convert UTF-8 string to wstring
std::wstring utf8_to_wstring(const std::string& str);
// convert wstring to UTF-8 string
std::string wstring_to_utf8(const std::wstring& str);
// convert wchar_t to UTF-8 string
std::string wchar_to_utf8(const wchar_t* sz);
// convert char to wstring
std::wstring char_to_wstring(const char* sz);
};
//case insensitive search
template <typename CharType> inline bool FindStrIC(const CharType* p, const CharType* str)
{
CharType* pch = (CharType*)str;
const CharType* begin = NULL;
while (*p)
{
if (toupper(*pch) == toupper(*p))
{
if (!begin)
begin = p;
pch++;
}
else
{
if (begin)
{
p = begin;
begin = NULL;
}
pch = (CharType*)str;
}
if (*pch == 0)
break;
p++;
}
return (*pch == 0);
} |
b55575bd45826b69530444aebaeda2211bbaef02 | 4d24cffbff8f60b00cd1780a96a12626399d1df8 | /combination-sum.cc | 4c617d93836b5e238bccd08cbb301bc581af3033 | [
"MIT"
] | permissive | tyrowang/CC | a37a4d4925952f8b11b810f8cb47863b4a277a06 | 9be3602a40567187ee27eb744773f8092c36b6b6 | refs/heads/master | 2021-01-10T00:53:10.338843 | 2014-08-18T02:50:35 | 2014-08-18T02:50:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cc | combination-sum.cc | class Solution {
public
void one(vectorint &candidates, vectorint& tmp, vectorvectorint &ret, int tail,int target){
for(int i=tail;i=0;i--){
if(target-candidates[i]==0){
vectorint tmp2(tmp);
tmp2.insert(tmp2.begin(),candidates[i]);
ret.push_back(tmp2);
}
if(target-candidates[i]0){
vectorint tmp2(tmp);
tmp2.insert(tmp2.begin(),candidates[i]);
one(candidates,tmp2,ret,i,target-candidates[i]);
}
}
}
vectorvectorint combinationSum(vectorint &candidates, int target) {
sort(candidates.begin(),candidates.end());
vectorvectorint ret;
vectorint tmp;
one(candidates, tmp, ret,candidates.size()-1,target);
return ret;
}
}; |
baf5184df5711fd05b088de671e50e473eca9a07 | e9b434b024995bebb62e016d65b407a83b8454de | /BerserkFear/Intermediate/Build/Win64/UE4Editor/Inc/BerserkFear/BerserkFearGameMode.generated.h | 04259ba6a846ed870eeab1a1c2331874ab63f600 | [] | no_license | berserkturtle/TurtleSpam | 2f5b5a95b3fece0cd39abfc0956bd8e0ffaff738 | 82a997e220a4a974c24f9bcb4c357426d5d69991 | refs/heads/master | 2020-05-23T20:59:50.114376 | 2017-03-14T07:52:37 | 2017-03-14T07:52:37 | 84,789,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,484 | h | BerserkFearGameMode.generated.h | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
C++ class header boilerplate exported from UnrealHeaderTool.
This is automatically generated by the tools.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef BERSERKFEAR_BerserkFearGameMode_generated_h
#error "BerserkFearGameMode.generated.h already included, missing '#pragma once' in BerserkFearGameMode.h"
#endif
#define BERSERKFEAR_BerserkFearGameMode_generated_h
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_RPC_WRAPPERS
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_RPC_WRAPPERS_NO_PURE_DECLS
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesABerserkFearGameMode(); \
friend BERSERKFEAR_API class UClass* Z_Construct_UClass_ABerserkFearGameMode(); \
public: \
DECLARE_CLASS(ABerserkFearGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), 0, TEXT("/Script/BerserkFear"), BERSERKFEAR_API) \
DECLARE_SERIALIZER(ABerserkFearGameMode) \
/** Indicates whether the class is compiled into the engine */ \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_INCLASS \
private: \
static void StaticRegisterNativesABerserkFearGameMode(); \
friend BERSERKFEAR_API class UClass* Z_Construct_UClass_ABerserkFearGameMode(); \
public: \
DECLARE_CLASS(ABerserkFearGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), 0, TEXT("/Script/BerserkFear"), BERSERKFEAR_API) \
DECLARE_SERIALIZER(ABerserkFearGameMode) \
/** Indicates whether the class is compiled into the engine */ \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
BERSERKFEAR_API ABerserkFearGameMode(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ABerserkFearGameMode) \
DECLARE_VTABLE_PTR_HELPER_CTOR(BERSERKFEAR_API, ABerserkFearGameMode); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ABerserkFearGameMode); \
private: \
/** Private move- and copy-constructors, should never be used */ \
BERSERKFEAR_API ABerserkFearGameMode(ABerserkFearGameMode&&); \
BERSERKFEAR_API ABerserkFearGameMode(const ABerserkFearGameMode&); \
public:
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
BERSERKFEAR_API ABerserkFearGameMode(ABerserkFearGameMode&&); \
BERSERKFEAR_API ABerserkFearGameMode(const ABerserkFearGameMode&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(BERSERKFEAR_API, ABerserkFearGameMode); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ABerserkFearGameMode); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(ABerserkFearGameMode)
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_PRIVATE_PROPERTY_OFFSET
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_6_PROLOG
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_PRIVATE_PROPERTY_OFFSET \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_RPC_WRAPPERS \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_INCLASS \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_PRIVATE_PROPERTY_OFFSET \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_RPC_WRAPPERS_NO_PURE_DECLS \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_INCLASS_NO_PURE_DECLS \
repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h_9_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID repo_BerserkFear_Source_BerserkFear_BerserkFearGameMode_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
f6bf3425801f623a274cf3fd9df171c24c18ffff | 815486fd4ac8010bebce3d7cce1081d56a54179c | /exp01/task15.cpp | fd9e8f78e37f729ddab29e5e4e9166e4583ab658 | [] | no_license | Jinyers/homework | ca7d567bc3d4f2125be11eabf7808506960e6085 | 1331a6e145a33501abaa1dc3bda19f9b3dad99d2 | refs/heads/master | 2023-02-05T18:00:30.988969 | 2020-12-21T22:57:11 | 2020-12-21T22:57:11 | 308,596,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 896 | cpp | task15.cpp | // Найти сумму квадратов положительных элементов массива
// целых чисел, расположенных на четных позициях.
#include <iostream>
#include "math.h"
using namespace std;
int main()
{
unsigned int size = 0;
cout << "Введите размер массива: ";
cin >> size;
int* massive = new int[size];
for (int i=0; i<size; i++)
{
cout << "Введите " << i+1 << " элемент массива: ";
cin >> massive[i];
}
int result = 0;
for (int i=0; i<size; i++)
if (massive[i] > 0 && (i+1)%2 == 0)
result += pow(massive[i], 2);
cout << "Сумма квадратов положительных элементов массива целых чисел, расположенных на четных позициях, равна: " << result << endl;
return 0;
}
|
15342bd2a0095bcc4d58ca981fb12778d3083d75 | d28097530c05e0559a68b8e8c8548571667c4bb7 | /3001_TIP_NEW/TA_BASE/transactive/core/types/test/test_ta_types_solaris_linux.cpp | 15378c38128cfc145f8d2889fbcb5fcfdea5634e | [] | no_license | lslProjectOrg/Projects | 88d941574265b86c88806fb2997a1aeb5bd84398 | f366eb01a0c27cee10cce6fb6c7dd0bc3d30126f | refs/heads/master | 2021-01-01T19:21:12.510332 | 2014-03-20T14:02:24 | 2014-03-20T14:02:24 | 14,391,288 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,483 | cpp | test_ta_types_solaris_linux.cpp | /**
* The source code in this file is the property of
* Ripple Systems and is not for redistribution
* in any form.
*
* Source: $File: //depot/3001_TIP_NEW/TA_BASE/transactive/core/types/test/test_ta_types_solaris_linux.cpp $
* @author: Ripple
* @version: $Revision: #2 $
*
* Last modification: $DateTime: 2012/02/06 16:15:14 $
* Last modified by: $Author: haijun.li $
*
* <description>
*
*/
#include <string>
#include <iostream>
#include <stdio.h>
#define LINUX
//#define __WORDSIZE 64
#include "ta_types.h"
int main()
{
#if defined( LINUX ) || defined( __linux__ )
printf("LINUX\n\n");
#elif defined( WIN32 ) || defined( __WIN32__ )
printf("WINDOWS\n\n");
#elif defined( SOLARIS ) || defined( __solaris__ )
printf("SOLARIS\n\n");
#endif
printf( "size of 8 bits long signed integer: %d ... %s\n", sizeof(ta_int8), ((sizeof(ta_int8)==1)?"OK":"ERROR!"));
printf( "size of 16 bits long signed integer: %d ... %s\n", sizeof(ta_int16), ((sizeof(ta_int16)==2)?"OK":"ERROR!"));
printf( "size of 32 bits long signed integer: %d ... %s\n", sizeof(ta_int32), ((sizeof(ta_int32)==4)?"OK":"ERROR!"));
printf( "size of 8 bits long unsigned integer: %d ... %s\n", sizeof(ta_uint8), ((sizeof(ta_uint8)==1)?"OK":"ERROR!"));
printf( "size of 16 bits long unsigned integer: %d ... %s\n", sizeof(ta_uint16), ((sizeof(ta_uint16)==2)?"OK":"ERROR!"));
printf( "size of 32 bits long unsigned integer: %d ... %s\n", sizeof(ta_uint32), ((sizeof(ta_uint32)==4)?"OK":"ERROR!"));
printf( "single, 4 bytes long float: %d ... %s\n", sizeof(ta_float32), ((sizeof(ta_float32)==4)?"OK":"ERROR!"));
//printf( "double, 8 bytes long float: %d ... %s\n", sizeof(ta_float64), ((sizeof(ta_float64)==8)?"OK":"ERROR!"));
// as << doesn't support 32 unsigned integer and 64 bits integers, just look
// at these values in the debugger and make sure they're correct.
ta_uint32 umax_32 = TA_MAX_UINT32; // 4294967295
ta_uint32 umin_32 = TA_MIN_UINT32; // 0
#if __WORDSIZE==64
//printf("size of 64 bits long signed integer: %d ... %s\n", sizeof(ta_int64), ((sizeof(ta_int64)==8)?"OK":"ERROR!"));
//printf( "size of 64 bits long unsigned integer: %d ... %s\n", sizeof(ta_uint64), ((sizeof(ta_uint64)==8)?"OK":"ERROR!"));
ta_int64 nmax_64 = TA_MAX_INT64; // 9223372036854775807
ta_int64 nmin_64 = TA_MIN_INT64; // -9223372036854775808
ta_uint64 umax_64 = TA_MAX_UINT64; // 18446744073709551615
ta_uint64 umin_64 = TA_MIN_UINT64; // 0
#endif
return 0;
}
|
9e1f616749521b9fa4ba7f9de01a0e897a98bbf4 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Plugins/Editor/USDImporter/Source/UnrealUSDWrapper/Source/Public/UnrealUSDWrapper.h | 2ef7d590761416c9549fb51acdfaac081c3d8acf | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 8,370 | h | UnrealUSDWrapper.h | #pragma once
#include <string>
#include <vector>
#include <memory>
#ifdef UNREALUSDWRAPPER_EXPORTS
#if _WINDOWS
#define UNREALUSDWRAPPER_API __declspec(dllexport)
#elif defined(__linux__) || defined(__APPLE__)
#define UNREALUSDWRAPPER_API __attribute__((visibility("default")))
#else
#error "Add definition for UNREALUSDWRAPPER_API macro for your platform."
#endif
#else
#define UNREALUSDWRAPPER_API //__declspec(dllimport)
#endif
void InitWrapper();
class IUsdPrim;
enum EUsdInterpolationMethod
{
/** Each element in a buffer maps directly to a specific vertex */
Vertex,
/** Each element in a buffer maps to a specific face/vertex pair */
FaceVarying,
/** Each vertex on a face is the same value */
Uniform,
};
enum EUsdGeomOrientation
{
/** Right handed coordinate system */
RightHanded,
/** Left handed coordinate system */
LeftHanded,
};
enum EUsdSubdivisionScheme
{
None,
CatmullClark,
Loop,
Bilinear,
};
enum EUsdUpAxis
{
XAxis,
YAxis,
ZAxis,
};
struct FUsdVector2Data
{
FUsdVector2Data(float InX = 0, float InY = 0)
: X(InX)
, Y(InY)
{}
float X;
float Y;
};
struct FUsdVectorData
{
FUsdVectorData(float InX = 0, float InY = 0, float InZ = 0)
: X(InX)
, Y(InY)
, Z(InZ)
{}
float X;
float Y;
float Z;
};
struct FUsdVector4Data
{
FUsdVector4Data(float InX = 0, float InY = 0, float InZ = 0, float InW = 0)
: X(InX)
, Y(InY)
, Z(InZ)
, W(InW)
{}
float X;
float Y;
float Z;
float W;
};
struct FUsdUVData
{
FUsdUVData()
{}
/** Defines how UVs are mapped to faces */
EUsdInterpolationMethod UVInterpMethod;
/** Raw UVs */
std::vector<FUsdVector2Data> Coords;
};
struct FUsdQuatData
{
FUsdQuatData(float InX=0, float InY = 0, float InZ = 0, float InW = 0)
: X(InX)
, Y(InY)
, Z(InZ)
, W(InW)
{}
float X;
float Y;
float Z;
float W;
};
struct FUsdMatrixData
{
static const int NumRows = 4;
static const int NumColumns = 4;
double Data[NumRows*NumColumns];
double* operator[](int Row)
{
return Data + (Row*NumColumns);
}
const double* operator[](int Row) const
{
return Data + (Row*NumColumns);
}
};
struct FUsdGeomData
{
FUsdGeomData()
: NumUVs(0)
{}
/** How many vertices are in each face. The size of this array tells you how many faces there are */
std::vector<int> FaceVertexCounts;
/** Index buffer which matches faces to Points */
std::vector<int> FaceIndices;
/** Maps a face to a material index. MaterialIndex = FaceMaterialIndices[FaceNum] */
std::vector<int> FaceMaterialIndices;
/** For subdivision surfaces these are the indices to vertices that have creases */
std::vector<int> CreaseIndices;
/** For subdivision surfaces. Each element gives the number of (must be adjacent) vertices in each crease, whose indices are linearly laid out in the 'CreaseIndices' array. */
std::vector<int> CreaseLengths;
/** The per-crease or per-edge sharpness for all creases*/
std::vector<float> CreaseSharpnesses;
/** Indices to points that have sharpness */
std::vector<int> CornerCreaseIndices;
/** The per-corner sharpness for all corner creases*/
std::vector<float> CornerSharpnesses;
/** List of all vertices in the mesh. This just holds the untransformed position of the vertex */
std::vector<FUsdVectorData> Points;
/** List of all normals in the mesh. */
std::vector<FUsdVectorData> Normals;
/** List of all vertex colors in the mesh */
std::vector<FUsdVectorData> VertexColors;
/** List of all materials in the mesh. The size of this array represents the number of materials */
std::vector<std::string> MaterialNames;
/** Raw UVs. The size of this array represents how many UV sets there are */
FUsdUVData UVs[8];
FUsdUVData SeparateUMap;
FUsdUVData SeparateVMap;
/** Orientation of the points */
EUsdGeomOrientation Orientation;
EUsdSubdivisionScheme SubdivisionScheme;
EUsdInterpolationMethod VertexColorInterpMethod;
int NumUVs;
};
class UnrealUSDWrapper
{
public:
UNREALUSDWRAPPER_API static void Initialize(const std::vector<std::string>& PluginDirectories);
UNREALUSDWRAPPER_API static class IUsdStage* ImportUSDFile(const char* Path, const char* Filename);
UNREALUSDWRAPPER_API static void CleanUp();
UNREALUSDWRAPPER_API static double GetDefaultTimeCode();
UNREALUSDWRAPPER_API static const char* GetErrors();
private:
static class FUsdStage* CurrentStage;
static std::string Errors;
static bool bInitialized;
};
class FAttribInternalData;
class FUsdAttribute
{
public:
FUsdAttribute(std::shared_ptr<FAttribInternalData> InternalData);
~FUsdAttribute();
UNREALUSDWRAPPER_API const char* GetAttributeName() const;
/** Returns the type name for an attribute or null if the attribute doesn't exist */
UNREALUSDWRAPPER_API const char* GetTypeName() const;
UNREALUSDWRAPPER_API bool AsInt(int64_t& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsUnsignedInt(uint64_t& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsDouble(double& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsString(const char*& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsBool(bool& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsVector2(FUsdVector2Data& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsVector3(FUsdVectorData& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsVector4(FUsdVector4Data& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool AsColor(FUsdVector4Data& OutVal, int ArrayIndex = -1, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const;
UNREALUSDWRAPPER_API bool IsUnsigned() const;
// Get the number of elements in the array if it is an array. Otherwise -1
UNREALUSDWRAPPER_API int GetArraySize() const;
UNREALUSDWRAPPER_API const char* GetUnrealPropertyPath() const;
private:
std::shared_ptr<FAttribInternalData> InternalData;
};
class IUsdPrim
{
public:
virtual ~IUsdPrim() {}
virtual const char* GetPrimName() const = 0;
virtual const char* GetPrimPath() const = 0;
virtual const char* GetUnrealPropertyPath() const = 0;
virtual const char* GetKind() const = 0;
virtual bool IsKindChildOf(const std::string& InKind) const = 0;
virtual bool IsGroup() const = 0;
virtual bool IsModel() const = 0;
virtual bool IsUnrealProperty() const = 0;
virtual bool HasTransform() const = 0;
virtual FUsdMatrixData GetLocalToWorldTransform(double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const = 0;
virtual FUsdMatrixData GetLocalToParentTransform(double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const = 0;
virtual FUsdMatrixData GetLocalToAncestorTransform(IUsdPrim* Ancestor, double Time = UnrealUSDWrapper::GetDefaultTimeCode()) const = 0;
virtual int GetNumChildren() const = 0;
virtual IUsdPrim* GetChild(int ChildIndex) = 0;
virtual const char* GetUnrealAssetPath() const = 0;
virtual const char* GetUnrealActorClass() const = 0;
virtual bool HasGeometryData() const = 0;
/** Returns geometry data at the default USD time */
virtual const FUsdGeomData* GetGeometryData() = 0;
/** Returns usd geometry data at a given time. Note that it will reuse internal structures so */
virtual const FUsdGeomData* GetGeometryData(double Time) = 0;
virtual int GetNumLODs() const = 0;
virtual IUsdPrim* GetLODChild(int LODIndex) = 0;
virtual const std::vector<FUsdAttribute>& GetAttributes() const = 0;
/** Get attributes which map to unreal properties (i.e have unrealPropertyPath metadata)*/
virtual const std::vector<FUsdAttribute>& GetUnrealPropertyAttributes() const = 0;
};
class IUsdStage
{
public:
virtual ~IUsdStage() {}
virtual EUsdUpAxis GetUpAxis() const = 0;
virtual IUsdPrim* GetRootPrim() = 0;
virtual bool HasAuthoredTimeCodeRange() const = 0;
virtual double GetStartTimeCode() const = 0;
virtual double GetEndTimeCode() const = 0;
virtual double GetFramesPerSecond() const = 0;
virtual double GetTimeCodesPerSecond() const = 0;
};
|
cab1ad4fceb782c8e85021e4000e0c6214363161 | 4de61cba1855fc2528857a56938d06f8be3f792b | /Linux/file/rename.cpp | 7933e2c7ab5dc5011501e7d254e8056593b3ee84 | [] | no_license | chenfan2014/CFgit | ea7dd863bddc3232725c6bebc38d025d3812870c | b6e06589537862e634b1f710d8e9221244a6a6c5 | refs/heads/master | 2020-12-24T17:18:01.417439 | 2015-05-13T01:06:46 | 2015-05-13T01:06:46 | 23,918,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | rename.cpp | #include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
int main(int argc, const char *argv[])
{
if(rename("test.txt", "test.txt") < 0){
cout << "can not rename of file" << endl;
}else{
cout << "rename file success" << endl;
}
if(rename("kdir", "dir") < 0){
cout << "can not rename dir" << endl;
}else{
cout << "rename dir success " << endl;
}
return 0;
}
|
c2f977d41e3904dfa7ded00f6e132b667c35feaf | 0b5a42bfa450f664fea35e11aea1ed542b36f38c | /linkedlist.h | a727de4c1f1ae70a9482dc27adf519a9aa402320 | [] | no_license | Fgarcia19/lru-cache | d0e973e0cde5b87f7777023ce860637bc63b5811 | 6ed7703645d0a3ac0e1a014a4c78793ae10a17cc | refs/heads/master | 2022-12-15T12:01:47.453915 | 2020-09-10T19:42:13 | 2020-09-10T19:42:13 | 294,506,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | h | linkedlist.h | //
// Created by user on 9/8/2020.
//
#ifndef UNTITLED3_LINKEDLIST_H
#define UNTITLED3_LINKEDLIST_H
//#include <string>
//#include <iostream>
using namespace std;
template <typename T1,typename T2>
struct Node {
T1 key;
T2 data;
Node<T1,T2>* next;
Node<T1,T2>* prev;
};
template <typename T1,typename T2>
class linkedlist {
private:
Node<T1,T2>* head;
Node<T1,T2>* tail;
int nodes;
public:
linkedlist(): head(nullptr), tail(nullptr), nodes(0) {};
int size();
void pop_front();
Node<T1,T2>*front();
Node<T1,T2>*back();
void push_front(Node<T1,T2>* value);
void pop_back();
void push_back(Node<T1,T2>* value);
void move_to_back(Node<T1,T2>* value);
void imprimir();
void imprimir_inverso();
};
#endif //UNTITLED3_LINKEDLIST_H
|
3592b3d53abe80dc5943650a5c780065e0091c52 | 039622ed6bdcdd1a00aec0bc419db4e8f4135424 | /hdsfuseoper.cpp | da3c0f6a2660156b4f7005a36e9ec9d9e3aea8d8 | [] | no_license | lookup69/fuseUtil | 60d5155d85313bff358825364537639b654fb39c | b2297993e0cf318b1b347d923b9a0100a15168ab | refs/heads/master | 2021-01-10T08:17:32.342876 | 2016-03-28T09:28:23 | 2016-03-28T09:28:23 | 54,880,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,032 | cpp | hdsfuseoper.cpp | #include "hdsfuseoper.h"
extern "C" {
#include <ulockmgr.h>
}
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <dirent.h>
#include "debugUtility.h"
using namespace std;
static void get_file_mode(string &strmode, int mode)
{
if(mode & S_IRWXU)
strmode = strmode + "S_IRWXU ";
if(mode & S_IRUSR)
strmode = strmode + "S_IRUSR ";
if(mode & S_IWUSR)
strmode = strmode + "S_IWUSR ";
if(mode & S_IXUSR)
strmode = strmode + "S_IXUSR ";
if(mode & S_IRWXG)
strmode = strmode + "S_IRWXG ";
if(mode & S_IRGRP)
strmode = strmode + "S_IRGRP ";
if(mode & S_IWGRP)
strmode = strmode + "S_IWGRP ";
if(mode & S_IXGRP)
strmode = strmode + "S_IXGRP ";
if(mode & S_IRWXO)
strmode = strmode + "S_IRWXO ";
if(mode & S_IROTH)
strmode = strmode + "S_IROTH ";
if(mode & S_IWOTH)
strmode = strmode + "S_IWOTH ";
if(mode & S_IXOTH)
strmode = strmode + "S_IXOTH ";
if(mode & S_IFIFO)
strmode = strmode + "S_IFIFO ";
if(mode & S_IXOTH)
strmode = strmode + "S_IXOTH ";
if(mode & S_IFCHR)
strmode = strmode + "S_IFCHR ";
if(mode & S_IFDIR)
strmode = strmode + "S_IFDIR ";
if(mode & S_IFBLK)
strmode = strmode + "S_IFBLK ";
if(mode & S_IFREG)
strmode = strmode + "S_IFREG ";
if(mode & S_ISUID)
strmode = strmode + "S_ISUID ";
if(mode & S_ISGID)
strmode = strmode + "S_ISGID ";
if(mode & S_ISVTX)
strmode = strmode + "S_ISVTX ";
}
static void get_file_flags(string &strflags, int flags)
{
if(flags & O_APPEND)
strflags = strflags + "O_APPEND ";
if(flags & O_ASYNC)
strflags = strflags + "O_ASYNC ";
if(flags & O_CLOEXEC)
strflags = strflags + "O_CLOEXEC ";
if(flags & O_CREAT)
strflags = strflags + "O_CREAT ";
if(flags & O_DIRECT)
strflags = strflags + "O_DIRECT ";
if(flags & O_DIRECTORY)
strflags = strflags + "O_DIRECTORY ";
if(flags & O_EXCL)
strflags = strflags + "O_EXCL ";
if(flags & O_LARGEFILE)
strflags = strflags + "O_LARGEFILE ";
if(flags & O_NOATIME)
strflags = strflags + "O_NOATIME ";
if(flags & O_NOCTTY)
strflags = strflags + "O_NOCTTY ";
if(flags & O_PATH)
strflags = strflags + "O_PATH ";
if(flags & O_SYNC)
strflags = strflags + "O_SYNC ";
if(flags & O_TRUNC)
strflags = strflags + "O_TRUNC ";
}
HdsFuseOper::HdsFuseOper()
{
initMapperPath_();
}
HdsFuseOper::HdsFuseOper(const string &path) : m_basePath(path)
{
size_t pos = m_basePath.size();
initMapperPath_();
if(m_basePath[pos - 1] == '/')
m_basePath.erase(pos - 1, 1);
}
HdsFuseOper::~HdsFuseOper()
{
DEBUG_PRINT_COLOR(LIGHT_GREEN, "\n");
}
void HdsFuseOper::initMapperPath_(void)
{
FILE *fp;
string cmd = "mount | grep mapper | awk '{print $1,$3}'";
mapper_s external{"/share/external", "/share/external"};
m_mapperVec.push_back(external);
fp = popen(cmd.c_str(), "r");
if(fp) {
char buf[1024] = { 0 };
while(fgets(buf, sizeof(buf), fp) != NULL) {
mapper_s mapper;
char *v_;
v_ = strchr(buf, ' ');
if(v_) {
size_t pos;
*v_ = 0;
mapper.from = buf;
++v_;
mapper.to = v_;
pos = mapper.from.find("\n");
if(pos != string::npos)
mapper.from.erase(pos, mapper.from.size() - pos);
pos = mapper.to.find("\n");
if(pos != string::npos)
mapper.to.erase(pos, mapper.to.size() - pos);
m_mapperVec.push_back(mapper);
}
}
pclose(fp);
}
for(auto it = m_mapperVec.begin(); it != m_mapperVec.end(); ++it) {
DEBUG_PRINT_COLOR(LIGHT_GREEN, "from:%s to%s\n", it->from.c_str(), it->to.c_str());
}
}
int HdsFuseOper::Getattr(const char *path, struct stat *stbuf)
{
string realPath = m_basePath + path;
int ret;
//DEBUG_PRINT_COLOR(LIGHT_GREEN, "Path:%s\n", path);
//DEBUG_PRINT_COLOR(LIGHT_GREEN, "RealPath:%s\n", realPath.c_str());
ret = lstat(realPath.c_str(), stbuf);
if(ret < 0) {
ret = -errno;
// DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return 0;
}
int HdsFuseOper::Fgetattr(const char *path,
struct stat *stbuf,
struct fuse_file_info *fi)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu\n", fi->fh);
ret = fstat(fi->fh, stbuf);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return 0;
}
int HdsFuseOper::Access(const char *path, int mask)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "mask:%d RealPath:%s\n", mask, realPath.c_str());
ret = access(realPath.c_str(), mask);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return 0;
}
int HdsFuseOper::Create(const char *path, mode_t mode, struct fuse_file_info *fi)
{
string realPath = m_basePath + path;
int fd;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "RealPath:%s\n", realPath.c_str());
{
string strmode;
get_file_mode(strmode, mode);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Mode(%X):%s\n", mode, strmode.c_str());
}
//fd = creat(realPath.c_str(), mode);
fd = open(path, fi->flags, mode);
if(fd < 0) {
fd = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return fd;
}
#ifdef USE_FILE_PATH
close(fd);
#else
fi->fh = fd;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu:%d\n", fi->fh, fd);
#endif
return 0;
}
int HdsFuseOper::Readlink(const char *path, char *buf, size_t size)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "size:%lu realPath:%s\n", size, realPath.c_str());
memset(buf, 0, size);
ret = readlink(realPath.c_str(), buf, size - 1);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
} else if(static_cast<size_t>(ret) < size) {
ret = 0;
}
return ret;
}
int HdsFuseOper::Opendir(const char *path, fuse_file_info *fi)
{
HdsFuseOper::dir_s *dirP;
string realPath = m_basePath + path;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "RealPath:%s\n", realPath.c_str());
dirP = static_cast<HdsFuseOper::dir_s *>(new HdsFuseOper::dir_s);
if(dirP == NULL)
return -ENOMEM;
dirP->dp = opendir(realPath.c_str());
if(dirP->dp == NULL) {
int ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
delete dirP;
return ret;
}
dirP->offset = 0;
dirP->entry = NULL;
fi->fh = (uint64_t)dirP;
return 0;
}
int HdsFuseOper::Releasedir(const char *path,
struct fuse_file_info *fi)
{
//HdsFuseOper::dir_s *dirP = (HdsFuseOper::dir_s *)fi->fh;
HdsFuseOper::dir_s *dirP = static_cast<HdsFuseOper::dir_s *>((void *)fi->fh);
closedir(dirP->dp);
delete dirP;
return 0;
}
int HdsFuseOper::Readdir(const char *path,
void *buf,
fuse_fill_dir_t filler,
off_t offset,
struct fuse_file_info *fi)
{
#ifdef USE_FILE_PATH
string realPath = m_basePath + path;
struct dirent *de;
DIR *dp;
(void)offset;
(void)fi;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
dp = opendir(realPath.c_str());
if(dp == NULL) {
int ret = errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return -ret;
}
while((de = readdir(dp)) != NULL) {
struct stat st;
memset(&st, 0, sizeof(st));
st.st_ino = de->d_ino;
if(realPath.size() > (m_basePath.size() + 1)) {
if(filler(buf, de->d_name, &st, 0))
break;
} else {
if((strcmp(de->d_name, ".") == 0) ||
(strcmp(de->d_name, "..") == 0) ||
(de->d_type & DT_LNK) ||
isEntryOfMapperDir_(de->d_name)) {
if(filler(buf, de->d_name, &st, 0))
break;
}
}
}
closedir(dp);
#else
HdsFuseOper::dir_s *dirP = (HdsFuseOper::dir_s *)fi->fh;
//struct dirent *de;
//DIR *dp;
if(offset != dirP->offset) {
seekdir(dirP->dp, offset);
dirP->entry = NULL;
dirP->offset = offset;
}
while (1) {
struct stat st;
off_t nextoff;
if(!dirP->entry) {
dirP->entry = readdir(dirP->dp);
if(!dirP->entry)
break;
}
memset(&st, 0, sizeof(st));
st.st_ino = dirP->entry->d_ino;
st.st_mode = dirP->entry->d_type << 12;
nextoff = telldir(dirP->dp);
//printf("xxxx %s\n", dirP->entry->d_name);
if(filler(buf, dirP->entry->d_name, &st, nextoff))
break;
//if((strcmp(de->d_name, ".") == 0) ||
// (strcmp(de->d_name, "..") == 0) ||
// (de->d_type & DT_LNK) ||
// isEntryOfMapperDir_(de->d_name))
//{
// if(filler(buf, de->d_name, &st, 0))
// break;
//}
dirP->entry = NULL;
dirP->offset = nextoff;
}
#endif
return 0;
}
int HdsFuseOper::Mknod(const char *path, mode_t mode, dev_t rdev)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "dev:%lX realPath:%s\n", rdev, realPath.c_str());
{
string strmode;
get_file_mode(strmode, mode);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Mode(%X):%s\n", mode, strmode.c_str());
}
if(S_ISFIFO(mode))
ret = mkfifo(realPath.c_str(), mode);
else
ret = mknod(realPath.c_str(), mode, rdev);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Mkdir(const char *path, mode_t mode)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Path :%s\n", path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
{
string strmode;
get_file_mode(strmode, mode);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Mode(%X):%s\n", mode, strmode.c_str());
}
ret = mkdir(realPath.c_str(), mode);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Unlink(const char *path)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Path :%s\n", path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
ret = unlink(realPath.c_str());
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Rmdir(const char *path)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Path :%s\n", path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
ret = rmdir(realPath.c_str());
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Symlink(const char *from, const char *to)
{
string realFromPath = from;
string realToPath = m_basePath + to;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "from :%s to:%s\n", from, to);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realFromPath:%s realToPath:%s\n", realFromPath.c_str(), realToPath.c_str());
ret = symlink(realFromPath.c_str(), realToPath.c_str());
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Rename(const char *from, const char *to)
{
string realFromPath = m_basePath + from;
string realToPath = m_basePath + to;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realFromPath:%s realToPath:%s\n", realFromPath.c_str(), realToPath.c_str());
ret = rename(realFromPath.c_str(), realToPath.c_str());
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Link(const char *from, const char *to)
{
string realFromPath = m_basePath + from;
string realToPath = m_basePath + to;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realFromPath:%s realToPath:%s\n", realFromPath.c_str(), realToPath.c_str());
ret = link(realFromPath.c_str(), realToPath.c_str());
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Chmod(const char *path, mode_t mode)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Path :%s\n", path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
{
string strmode;
get_file_mode(strmode, mode);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Mode(%X):%s\n", mode, strmode.c_str());
}
ret = chmod(realPath.c_str(), mode);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Chown(const char *path, uid_t uid, gid_t gid)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "uid:%u git:%u realPath:%s\n", uid, gid, realPath.c_str());
ret = chown(realPath.c_str(), uid, gid);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return 0;
}
int HdsFuseOper::Truncate(const char *path, off_t size)
{
string realPath = m_basePath + path;
int ret = 0;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "size:%lu realPath:%s\n", size, realPath.c_str());
ret = truncate(realPath.c_str(), size);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Ftruncate(const char *path,
off_t size,
struct fuse_file_info *fi)
{
int ret = 0;
{
string realPath = m_basePath + path;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "size:%lu realPath:%s\n", size, realPath.c_str());
}
ret = ftruncate(fi->fh, size);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Open(const char *path, struct fuse_file_info *fi)
{
string realPath = m_basePath + path;
int fd;
//DEBUG_PRINT_COLOR(LIGHT_GREEN, "Path :%s\n", path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
{
string flags;
get_file_flags(flags, fi->flags);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "FLAGS(%X) :%s\n", fi->flags, flags.c_str());
}
fd = open(realPath.c_str(), fi->flags);
if(fd < 0) {
fd = errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return -fd;
}
#ifdef USE_FILE_PATH
close(fd);
#else
fi->fh = fd;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu realPath:%s\n", fi->fh, realPath.c_str());
#endif
return 0;
}
int HdsFuseOper::Read(const char *path,
char *buf,
size_t size,
off_t offset,
struct fuse_file_info *fi)
{
int ret = 0;
#ifdef USE_FILE_PATH
string realPath = m_basePath + path;
int fd;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
fd = open(realPath.c_str(), O_RDONLY);
if(fd == -1) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return ret;
}
ret = pread(fd, buf, size, offset);
DEBUG_PRINT_COLOR(LIGHT_CYAN, "ret:%d\n", ret);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
close(fd);
#else
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%ld size:%lu offset:%lu path:%s\n", fi->fh, size, offset, path);
ret = pread(fi->fh, buf, size, offset);
DEBUG_PRINT_COLOR(LIGHT_CYAN, "ret:%d\n", ret);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
#endif
return ret;
}
int HdsFuseOper::Write(const char *path,
const char *buf,
size_t size,
off_t offset,
struct fuse_file_info *fi)
{
int ret = 0;
#ifdef USE_FILE_PATH
string realPath = m_basePath + path;
int fd;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
fd = open(realPath.c_str(), O_WRONLY);
if(fd == -1) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return ret;
}
ret = pwrite(fd, buf, size, offset);
DEBUG_PRINT_COLOR(LIGHT_CYAN, "ret:%d\n", ret);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
close(fd);
#else
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu size:%lu path:%s\n", fi->fh, size, path);
ret = pwrite(fi->fh, buf, size, offset);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
#endif
return ret;
}
int HdsFuseOper::ReadBuf(const char *path,
struct fuse_bufvec **bufp,
size_t size,
off_t offset,
struct fuse_file_info *fi)
{
struct fuse_bufvec *src;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu size:%lu offset:%lu Path:%s\n", fi->fh, size, offset, path);
src = static_cast<struct fuse_bufvec *>(malloc(sizeof(struct fuse_bufvec)));
if (src == NULL)
return -ENOMEM;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "bufp:%p\n", src);
*src = FUSE_BUFVEC_INIT(size);
src->buf[0].flags = (fuse_buf_flags)(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
src->buf[0].fd = fi->fh;
src->buf[0].pos = offset;
*bufp = src;
return 0;
}
int HdsFuseOper::WriteBuf(const char *path,
struct fuse_bufvec *buf,
off_t offset,
struct fuse_file_info *fi)
{
struct fuse_bufvec dst = FUSE_BUFVEC_INIT(fuse_buf_size(buf));
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu offset:%lu buf:%p Path:%s\n", fi->fh, offset, buf, path);
dst.buf[0].flags = (fuse_buf_flags)(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
dst.buf[0].fd = fi->fh;
dst.buf[0].pos = offset;
return fuse_buf_copy(&dst, buf, FUSE_BUF_SPLICE_NONBLOCK);
}
int HdsFuseOper::Statfs(const char *path, struct statvfs *stbuf)
{
string realPath = m_basePath + path;
int ret = 0;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
ret = statvfs(path, stbuf);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
int HdsFuseOper::Flush(const char *path, struct fuse_file_info *fi)
{
int ret = 0;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu Path:%s\n", fi->fh, path);
#ifndef USE_FILE_PATH
ret = close(dup(fi->fh));
if(ret == -1) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
#endif
return ret;
}
int HdsFuseOper::Fsync(const char *path, int isdatasync, struct fuse_file_info *fi)
{
int ret = 0;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "Path:%s\n", path);
#ifndef USE_FILE_PATH
if(isdatasync)
ret = fdatasync(fi->fh);
else
ret = fsync(fi->fh);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
#endif
return ret;
}
int HdsFuseOper::Release(const char *path, struct fuse_file_info *fi)
{
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu Path:%s\n", fi->fh, path);
#ifndef USE_FILE_PATH
close(fi->fh);
#endif
return 0;
}
int HdsFuseOper::Setxattr(const char *path,
const char *name,
const char *value,
size_t size,
int flags)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "name:%s size:%lu flags:%X value:%s Path:%s\n", name, size, flags, value, path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "name:%s size:%lu flags:%X valuse:%s realPath:%s\n", name, size, flags, value, realPath.c_str());
ret = lsetxattr(realPath.c_str(), name, value, size, flags);
if(ret < 0) {
ret = errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return -ret;
}
return ret;
}
int HdsFuseOper::Getxattr(const char *path,
const char *name,
char *value,
size_t size)
{
string realPath = m_basePath + path;
int ret;
//DEBUG_PRINT_COLOR(LIGHT_GREEN, "name:%s size:%lu Path:%s\n", name, size, path);
//DEBUG_PRINT_COLOR(LIGHT_GREEN, "name:%s size:%lu realPath:%s\n", name, size, realPath.c_str());
ret = lgetxattr(realPath.c_str(), name, value, size);
if(ret < 0) {
ret = errno;
//DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return -ret;
}
return ret;
}
int HdsFuseOper::Listxattr(const char *path,
char *list,
size_t size)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "size:%lu Path:%s\n", size, path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "size:%lu realPath:%s\n", size, realPath.c_str());
ret = llistxattr(realPath.c_str(), list, size);
if(ret < 0) {
ret = errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return -ret;
}
return ret;
}
int HdsFuseOper::Removexattr(const char *path, const char *name)
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "name:%s Path:%s\n", name, path);
DEBUG_PRINT_COLOR(LIGHT_GREEN, "name:%s realPath:%s\n", name, realPath.c_str());
ret = removexattr(realPath.c_str(), name);
if(ret < 0) {
ret = errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
return -ret;
}
return ret;
}
int HdsFuseOper::Ioctl(const char *path,
int cmd,
void *arg,
struct fuse_file_info *fi,
unsigned int flags,
void *data)
{
DEBUG_PRINT_COLOR(LIGHT_PURPLE, "[NO_IMP]path:%s\n", path);
return -EACCES;
}
int HdsFuseOper::Lock(const char *path,
struct fuse_file_info *fi,
int cmd,
struct flock *lock)
{
int ret = 0;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu Path:%s\n", fi->fh, path);
#ifndef USE_FILE_PATH
//ret = ulockmgr_op(fi->fh, cmd, lock, &fi->lock_owner, sizeof(fi->lock_owner));
ret = ulockmgr_op(fi->fh, cmd, lock, &fi->lock_owner,
sizeof(fi->lock_owner));
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
#endif
return ret;
}
int HdsFuseOper::Flock(const char *path,
struct fuse_file_info *fi,
int op)
{
int ret = 0;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "fd:%lu Path:%s\n", fi->fh, path);
#ifndef USE_FILE_PATH
ret = flock(fi->fh, op);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
#endif
return ret;
}
int HdsFuseOper::Utimens(const char *path,
const struct timespec ts[2])
{
string realPath = m_basePath + path;
int ret;
DEBUG_PRINT_COLOR(LIGHT_GREEN, "realPath:%s\n", realPath.c_str());
/* don't use utime/utimes since they follow symlinks */
ret = utimensat(0, realPath.c_str(), ts, AT_SYMLINK_NOFOLLOW);
if(ret < 0) {
ret = -errno;
DEBUG_PRINT_COLOR(LIGHT_RED, "[err]%s\n", strerror(errno));
}
return ret;
}
|
aa0ca1667a7412daf635b5b3dc6ee38afcc71b37 | 9639c4451a7f2845a57931b6a670a2f744f58e0f | /ji-park/DP/쉬운 계단수.cpp | 7a472ca68d3f53c796fcb85821f80f46976697d2 | [] | no_license | 42somoim/42somoim2 | d00a256c5ca949d89b444e1600043afac2c0c4d6 | 64c9fb657736c84d88df901e3d1662c05ddc5954 | refs/heads/master | 2023-03-24T13:42:43.489332 | 2021-03-15T13:25:57 | 2021-03-15T13:25:57 | 300,144,427 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 528 | cpp | 쉬운 계단수.cpp | #include <iostream>
using namespace std;
int main()
{
int n;
int dp[100][10] = { 0 };
int sum = 0;
cin >> n;
dp[0][0] = 0;
for (int i = 1; i < 10; i++)
{
dp[0][i] = 1;
}
for (int j = 1; j < n; j++)
{
dp[j][0] = dp[j - 1][1] ;
for (int k = 1; k <= 9; k++)
{
if (k == 9)
dp[j][k] = dp[j - 1][k - 1] % 1000000000;
else
dp[j][k] = (dp[j - 1][k - 1] + dp[j - 1][k + 1]) % 1000000000;
}
}
for (int i = 0; i <= 9; i++)
{
sum = (sum + dp[n - 1][i]) % 1000000000;
}
cout << sum;
return (0);
} |
413492a032c7aa853f783a06105aade9ef648cfc | dcb85b9b6c093c93bca2a1d1549702c69d47a23e | /simulator/runtime/rdo_simulator.h | b2f7c3afcbb39a96bb23f028bdf50f50277b31ec | [
"MIT"
] | permissive | MachinaDeusEx/rdo_studio | c7c2657187099da9c2c15104df6735a337f01a0b | 9c9c5df518a83ef8554b0bc1dc30a9e83ad40a4a | refs/heads/master | 2020-08-04T14:38:35.726548 | 2015-12-06T17:40:02 | 2016-04-15T08:14:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | h | rdo_simulator.h | #pragma once
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo.h"
#include "simulator/runtime/rdobase.h"
#include "simulator/runtime/rdo_logic_i.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
class RDOSimulator: public RDOSimulatorBase
{
public:
RDOSimulator();
virtual ~RDOSimulator();
void appendLogic(const LPIBaseOperation& pLogic, LPIBaseOperationContainer pParent);
LPIBaseOperation getMustContinueOpr() const;
void setMustContinueOpr(const LPIBaseOperation& pOperation);
virtual void onPutToTreeNode() = 0;
std::string writeActivitiesStructure(std::size_t& counter);
std::size_t getSizeofSim() const;
LPIBaseOperationContainer m_pMetaLogic;
protected:
void appendBaseOperation(LPIBaseOperationContainer pLogic, const LPIBaseOperation& pBaseOperation);
// Инициализирует нерегулярные события и блоки GENERATE: задает время первого срабатывания
virtual void preProcess();
virtual void onResetResult () = 0;
virtual void onCheckResult () = 0;
virtual void onAfterCheckResult() = 0;
std::size_t m_sizeofSim;
private:
LPIBaseOperation m_pOprMustContinue;
virtual bool doOperation();
};
CLOSE_RDO_RUNTIME_NAMESPACE
|
2fbdc846abe8750874356c3b6f38b6fde90a9ae6 | 37b1cc093229626cb58199379f39b6b1ec6f6fb0 | /src/common/TensorPack.cpp | 6c2c7f96226bd0f72134c1f4cfd37b46eb2853e0 | [
"MIT",
"LicenseRef-scancode-dco-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | ARM-software/ComputeLibrary | d4dfccb6a75b9f7bb79ae6c61b2338d519497211 | 874e0c7b3fe93a6764ecb2d8cfad924af19a9d25 | refs/heads/main | 2023-09-04T07:01:32.449866 | 2023-08-23T13:06:10 | 2023-08-23T13:06:10 | 84,570,214 | 2,706 | 810 | MIT | 2023-01-16T16:04:32 | 2017-03-10T14:51:43 | C++ | UTF-8 | C++ | false | false | 2,173 | cpp | TensorPack.cpp | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "src/common/TensorPack.h"
#include "src/common/ITensorV2.h"
#include "src/common/utils/Validate.h"
namespace arm_compute
{
TensorPack::TensorPack(IContext *ctx)
: AclTensorPack_(), _pack()
{
ARM_COMPUTE_ASSERT_NOT_NULLPTR(ctx);
this->header.ctx = ctx;
this->header.ctx->inc_ref();
}
TensorPack::~TensorPack()
{
this->header.ctx->dec_ref();
this->header.type = detail::ObjectType::Invalid;
}
AclStatus TensorPack::add_tensor(ITensorV2 *tensor, int32_t slot_id)
{
_pack.add_tensor(slot_id, tensor->tensor());
return AclStatus::AclSuccess;
}
size_t TensorPack::size() const
{
return _pack.size();
}
bool TensorPack::empty() const
{
return _pack.empty();
}
bool TensorPack::is_valid() const
{
return this->header.type == detail::ObjectType::TensorPack;
}
arm_compute::ITensor *TensorPack::get_tensor(int32_t slot_id)
{
return _pack.get_tensor(slot_id);
}
arm_compute::ITensorPack &TensorPack::get_tensor_pack()
{
return _pack;
}
} // namespace arm_compute
|
f3f524e6ef229bdf690b781012630dab38c0da08 | 275e1b57bcdf0c0efc5747024e567df6deb315ff | /virus/lib/headers/nngpp/platform/cv_view.h | 47c29c8ead76780deb270ab0fbe48d155b474242 | [
"MIT"
] | permissive | lolepop/osu-Rate-Changer | c19b241c9d22afca20b2eb6b4f12a5536598ed7c | e6429e6c8e7191b38a7ee963b69fb51fc8236712 | refs/heads/master | 2022-04-30T23:19:02.818178 | 2022-03-29T09:45:31 | 2022-03-29T09:45:31 | 173,297,077 | 12 | 1 | MIT | 2021-07-05T13:30:43 | 2019-03-01T12:18:06 | C# | UTF-8 | C++ | false | false | 869 | h | cv_view.h | #ifndef NNGPP_CV_VIEW_H
#define NNGPP_CV_VIEW_H
#include <nngpp/error.h>
#include <nng/supplemental/util/platform.h>
namespace nng {
struct cv_view {
protected:
nng_cv* c = nullptr;
public:
cv_view() = default;
cv_view( nng_cv* c ) noexcept : c(c) {}
nng_cv* get() const noexcept {
return c;
}
nng_cv* operator->() const noexcept {
return c;
}
explicit operator bool() const noexcept {
return c != nullptr;
}
void wait() const noexcept {
nng_cv_wait(c);
}
/** wait until time t
* returns true if signalled, false if timed out
*/
bool wait_until( nng_time t ) const {
int r = nng_cv_until(c,t);
if( r != 0 && r != (int)error::timedout ) {
throw exception(r,"nng_cv_until");
}
return r == 0;
}
void wake_all() const noexcept {
nng_cv_wake(c);
}
void wake_one() const noexcept {
nng_cv_wake1(c);
}
};
}
#endif
|
35345d6b653555e8d23166a998fb49d4aacfb164 | 26f7c777a81061a8bcc80fae91fdc6663ec2a7bf | /Testing/igstkObjectRepresentationRemovalTest.cxx | 28f2bdb33c3f4e9dad2a76b62d5e309c23d1cd70 | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | JQiu/IGSTK-5.2 | 0af66324623d33d171ee775098894048e12e9023 | 605a87e177c6e68acc773efe1fe5206cfb15dfbd | HEAD | 2016-09-05T13:55:54.626920 | 2014-11-23T15:57:09 | 2014-11-23T15:57:09 | 27,037,331 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,564 | cxx | igstkObjectRepresentationRemovalTest.cxx | /*=========================================================================
Program: Image Guided Surgery Software Toolkit
Module: igstkObjectRepresentationRemovalTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) ISC Insight Software Consortium. All rights reserved.
See IGSTKCopyright.txt or http://www.igstk.org/copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
// Warning about: identifier was truncated to '255' characters
// in the debug information (MVC6.0 Debug)
#pragma warning( disable : 4786 )
#endif
#include "igstkEllipsoidObject.h"
#include "igstkEllipsoidObjectRepresentation.h"
#include "igstkView3D.h"
#include "igstkDefaultWidget.h"
#include "igstkVTKLoggerOutput.h"
#include "igstkLogger.h"
#include "itkStdStreamLogOutput.h"
int igstkObjectRepresentationRemovalTest( int , char* [] )
{
typedef igstk::Object::LoggerType LoggerType;
typedef itk::StdStreamLogOutput LogOutputType;
typedef igstk::EllipsoidObjectRepresentation ObjectRepresentationType;
typedef igstk::EllipsoidObject ObjectType;
typedef igstk::View3D View3DType;
typedef igstk::DefaultWidget WidgetType;
// Make a logger object
LoggerType::Pointer logger = LoggerType::New();
LogOutputType::Pointer logOutput = LogOutputType::New();
std::ofstream logFile("igstkObjectRepresentationRemovalTestLog.txt");
logOutput->SetStream( logFile );
logger->AddLogOutput( logOutput );
logger->SetPriorityLevel( itk::Logger::DEBUG );
// Make the spatial object
ObjectType::Pointer ellipsoidObject1 = ObjectType::New();
ellipsoidObject1->SetLogger( logger );
// Make a spatial object representation
ObjectRepresentationType::Pointer
ellipsoidRepresentation1 = ObjectRepresentationType::New();
ellipsoidRepresentation1->SetLogger( logger );
ellipsoidRepresentation1->RequestSetEllipsoidObject(ellipsoidObject1);
ellipsoidRepresentation1->SetColor( 0.0, 0.0, 1.0 );
ellipsoidRepresentation1->SetOpacity( 0.4 );
// Make a view and set the logger
View3DType::Pointer view3D = View3DType::New();
view3D->SetLogger( logger );
// Create an minimal GUI
WidgetType * widget = new WidgetType( 512, 512 );
widget->RequestSetView( view3D );
// Add the object we want to display.
view3D->RequestAddObject( ellipsoidRepresentation1 );
// Setup the coordinate system graph
//
// View
// |
// Ellipsoid
//
igstk::Transform identityTransform;
identityTransform.SetToIdentity( igstk::TimeStamp::GetLongestPossibleTime() );
ellipsoidObject1->RequestSetTransformAndParent( identityTransform, view3D );
// Reset the camera so that it shows the objects in the scene
view3D->RequestResetCamera();
// Start the pulse generator in the view.
view3D->RequestStart();
// The following code tests the cleanup of the observers created in the
// locally scoped object representation.
{ // <- Start a local scope
// Make a locally scoped representation that share the spatial object
// we created above.
ObjectRepresentationType::Pointer
ellipsoidRepresentation2 =
ObjectRepresentationType::New();
ellipsoidRepresentation2->RequestSetEllipsoidObject(ellipsoidObject1);
ellipsoidRepresentation2->SetColor( 1.0, 0.0, 0.0 );
ellipsoidRepresentation2->SetOpacity( 0.4 );
// Add the local representation to the view.
view3D->RequestAddObject( ellipsoidRepresentation2 );
// Render for a bit.
for(int i = 0; i < 10; i++)
{
igstk::PulseGenerator::Sleep(50);
igstk::PulseGenerator::CheckTimeouts();
}
// Remove the locally scoped object
view3D->RequestRemoveObject( ellipsoidRepresentation2 );
} // <- End a local scope - ellipsoidRepresentation2 should be deleted here
// and its observers should be cleaned up.
// Render some more.
for(int i = 0; i < 10; i++)
{
igstk::PulseGenerator::Sleep(50);
igstk::PulseGenerator::CheckTimeouts();
}
delete widget;
// The goal is to exit without a crash.
return EXIT_SUCCESS;
}
|
7f28c3c408eb6676f32382effd8672a62200b2b4 | 073e166a3034046ace8c7198cc5d70495acac57f | /20.cpp | 8b162d3aa5377e44fda95260b7fba7c14b33d555 | [] | no_license | shulgaalexey/other | ff048db9a246b24388d5d9fa79bac1b7fa14451e | ee3be171ce9ac3820c841e2a743c2549b92b4ce9 | refs/heads/master | 2020-12-11T09:42:31.006891 | 2018-07-03T09:37:58 | 2018-07-03T09:37:58 | 52,915,730 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,505 | cpp | 20.cpp | // 20. Topological sort: in-degree analysis + BFS
#include <iostream>
using namespace std;
class list {
public:
int val;
list *next;
public:
list(int v) : val(v), next(NULL) {}
};
class node {
public:
int tag;
list *out_edges;
int in_degree;
};
node *G = NULL;
node *sorted_G = NULL;
int V = 0;
int E = 0;
void topological_sort() {
// 1. Calc initial in-degree
for(int i = 0; i < V; i ++) {
list *h = G[i].out_edges;
while(h) {
G[h->val].in_degree ++;
h = h->next;
}
}
// 2. pop nodes with in-degree = 0 to start the sort
node *st = new node[V];
int st_size = 0;
for(int i = 0; i < V; i ++) {
if(G[i].in_degree == 0)
st[st_size ++] = G[i];
}
// 3. Topological sort: in-degree analysis + BFS
int sorted_idx = 0;
while(st_size) {
node n = st[--st_size];
sorted_G[sorted_idx++] = n;
list *h = n.out_edges;
while(h) {
G[h->val].in_degree--;
if(G[h->val].in_degree == 0)
st[st_size ++] = G[h->val];
h = h->next;
}
}
delete [] st;
}
int main(void) {
{ // 1
// Test case input
V = 9;
E = 9;
const int test_case[] =
{4, 1, 1, 2, 2, 3, 2, 7, 5, 6, 7, 6, 1, 5, 8, 5, 8, 9};
// Preparing a graph
G = new node[V];
sorted_G = new node[V];
for(int i = 0; i < V; i ++) {
G[i].tag = i;
G[i].out_edges = NULL;
G[i].in_degree = 0;
}
for(int i = 0; i < E; i ++) {
int n = test_case[2 * i] - 1;
int out_n = test_case[2 * i + 1] - 1;
if(!G[n].out_edges)
G[n].out_edges = new list(out_n);
else {
list *h = G[n].out_edges;
while(h->next)
h = h->next;
h->next = new list(out_n);
}
}
// Sort
topological_sort();
for(int i = 0; i < V; i++)
cout << int(sorted_G[i].tag + 1) << " ";
cout << endl;
delete [] G;
delete [] sorted_G;
}
{ // 2
// Test case input
V = 5;
E = 4;
const int test_case[] =
{1, 2, 2, 3, 4, 1, 1, 5};
// Preparing a graph
G = new node[V];
sorted_G = new node[V];
for(int i = 0; i < V; i ++) {
G[i].tag = i;
G[i].out_edges = NULL;
G[i].in_degree = 0;
}
for(int i = 0; i < E; i ++) {
int n = test_case[2 * i] - 1;
int out_n = test_case[2 * i + 1] - 1;
if(!G[n].out_edges)
G[n].out_edges = new list(out_n);
else {
list *h = G[n].out_edges;
while(h->next)
h = h->next;
h->next = new list(out_n);
}
}
// Sort
topological_sort();
for(int i = 0; i < V; i++)
cout << int(sorted_G[i].tag + 1) << " ";
cout << endl;
delete [] G;
delete [] sorted_G;
}
return 0;
}
|
ce01ad9d684be4857f8bcf9e62851ebb9f44658f | 7b3899819c46272554c0ab2a584030ad1fc92e79 | /antsupporter/src/antlib/file/Ant_FileInfoImpl.h | 36b4b6cc32a255183822b56c6749d48bcc863621 | [
"Apache-2.0"
] | permissive | summerquiet/NmeaAnalysisTool | 63a303f5fd0b7cb76704b6f74908afe9a0547291 | 73d10e421a5face988444fb04d7d61d3f30333f7 | refs/heads/master | 2020-04-05T08:06:51.994203 | 2018-11-08T12:48:55 | 2018-11-08T12:48:55 | 156,701,514 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,505 | h | Ant_FileInfoImpl.h | /**
* Copyright @ 2014 - 2017 Personal
* All Rights Reserved.
*/
#ifndef ANT_FILEINFO_IMPLH
#define ANT_FILEINFO_IMPLH
#ifndef __cplusplus
# error ERROR: This file requires C++ compilation (use a .cpp suffix)
#endif
/*---------------------------------------------------------------------------*/
// Include files
#ifndef ANT_OBJECT_H
# include "Ant_Object.h"
#endif
#ifndef ANT_FILEPUBDEF_H
# include "Ant_FilePubDef.h"
#endif
#ifndef ANT_STRING_H
# include "Ant_String.h"
#endif
#ifndef ANT_TIME_H
# include "Ant_Time.h"
#endif
/*---------------------------------------------------------------------------*/
// Namespace
namespace antsupporter {
/*---------------------------------------------------------------------------*/
// class declare
// external class declaration
class Ant_AbstractFileEngine;
/**
* @class Ant_FileInfoImpl
* @brief The class to manipulate normal files
*/
class Ant_FileInfoImpl : public virtual Ant_Object
{
public:
explicit Ant_FileInfoImpl(const BOOL& bRecLog);
Ant_FileInfoImpl(const Ant_String& strFileName, const BOOL& bRecLog);
virtual ~Ant_FileInfoImpl();
VOID setFileName(const Ant_String& strFileName);
Ant_String fileName() const {return m_strFilePath;}
BOOL exists();
BOOL isReadable();
BOOL isWritable();
BOOL isExecutable();
BOOL isHidden();
DWORD getFileType();
BOOL isFile();
BOOL isDir();
BOOL isLink();
Ant_Time creationTime();
Ant_Time lastWriteTime();
Ant_Time lastAccessTime();
Ant_String user();
DWORD userID();
Ant_String group();
DWORD groupID();
LONGLONG size();
DWORD entryNum(const DWORD& dwFilters);
Ant_FileError getLastError() const {return m_eLastError;}
protected:
Ant_AbstractFileEngine* m_pFileEngine;
VOID setLastError(const Ant_FileError& eError) { m_eLastError = eError;}
VOID cleanLastError() {setLastError(ANT_FER_NoError);}
private:
Ant_String m_strFilePath;
Ant_FileError m_eLastError;
BOOL m_bRecLog;
private:
// Disable the copy constructor and operator =
Ant_FileInfoImpl(const Ant_FileInfoImpl&);
Ant_FileInfoImpl& operator= (const Ant_FileInfoImpl&);
};
/*---------------------------------------------------------------------------*/
// Namespace
}
/*---------------------------------------------------------------------------*/
#endif //ANT_FILEINFOIMPL_H
/*---------------------------------------------------------------------------*/
/* EOF */
|
db56a67dbe438c90349ff02a53553893d1bbc652 | 122cacfeaab64979d09dcaa70756a96763e83d12 | /writeDataLoop/writeDataLoop.ino | 24712054cb69689889a5d369a9ea22cf70446598 | [] | no_license | velobrain/BLE | 074253166bd8afbd92abe6f1c2120901c7463ae9 | 377d2c722e13dcda446a0812c69b0c050b22e8bc | refs/heads/master | 2021-09-06T18:32:53.631476 | 2018-02-09T19:23:33 | 2018-02-09T19:23:33 | 111,169,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,490 | ino | writeDataLoop.ino |
#include <SPI.h>
#include "Adafruit_BLE_UART.h"
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9
#define REPORTING_PERIOD_MS 1000
PulseOximeter pox;
const int REED_PIN = 3; // Pin connected to reed switch
const int LED_PIN = 13; // LED pin - active-high
const float RADIUS = 0.3; // metres
const float PIE = 3.14159;
const int numberOfMagnets = 1;
const int intervalLength = 5; // 10 seconds
const uint32_t period = intervalLength*1000; // 10 seconds
boolean closed = false;
int revs = 0;
float circumference = 2*PIE*RADIUS;
float arcLength = circumference/numberOfMagnets;
int numIntervals = 0;
int numHeartBeats = 1;
uint32_t tsLastReport = 0;
Adafruit_BLE_UART BT = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);
aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;
void onBeatDetected()
{
Serial.println("Beat!");
numHeartBeats += 1;
}
void setup(void) {
Serial.begin(115200);
while(!Serial);
randomSeed(analogRead(0));
pinMode(REED_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
BT.begin();
Serial.print("Initializing pulse oximeter..");
// Initialize the PulseOximeter instance
// Failures are generally due to an improper I2C wiring, missing power supply
// or wrong target chip
if (!pox.begin()) {
Serial.println("FAILED");
for(;;);
} else {
Serial.println("SUCCESS");
}
// The default current for the IR LED is 50mA and it could be changed
// by uncommenting the following line. Check MAX30100_Registers.h for all the
// available options.
// pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);
// Register a callback for the beat detection
pox.setOnBeatDetectedCallback(onBeatDetected);
}
int x;
void loop() {
float distance = 0;
for( uint32_t tStart = millis(); (millis()-tStart) < period; ) {
pox.update();
int proximity = digitalRead(REED_PIN); // Read the state of the switch
if (proximity == LOW) // If the pin reads low, the switch is closed.
{
Serial.println("Switch closed");
Serial.print("revs: ");
Serial.println(revs);
closed = true;
digitalWrite(LED_PIN, HIGH); // Turn the LED on
}
else
{
if (closed == true) {
revs++;
distance += arcLength;
}
closed = false;
digitalWrite(LED_PIN, LOW); // Turn the LED off
// Serial.print("distance: ");
// Serial.println(distance);
}
pox.setOnBeatDetectedCallback(onBeatDetected);
}
numIntervals++;
Serial.println("10 seconds elapsed.....................");
Serial.print("Distance this interval: ");
Serial.print(distance);
Serial.println(" m");
Serial.print("Speed this interval: ");
Serial.print(distance/intervalLength);
Serial.println(" m/s");
Serial.print("Total distance: ");
Serial.println(revs*arcLength);
Serial.print("Average speed: ");
Serial.println((revs*arcLength)/(numIntervals*intervalLength));
Serial.print("number of heart beats: ");
Serial.println(numHeartBeats);
float totalDistance = revs*arcLength; //the total distance so far
BT.pollACI();
// String s = String(x);
// uint8_t dataBuffer[2];
// dataBuffer[0] = numHeartBeats;
// dataBuffer[1] = totalDistance;
// BT.write(dataBuffer, 2);
// send using different signs, so distance is always a positive number and heartbeats is always negative
BT.write(totalDistance+1);
BT.write(-numHeartBeats);
}
|
2ebce79f094dcb20e0cb38f736d8b4ffc9dd794e | 27dd76458bf04a8215978982d6f125587dfc583d | /projects/hole_creation/lsm_hole_insertion.hpp | 90c50f3d0f666029c3cc8ab7c97c84a016636f63 | [
"Apache-2.0"
] | permissive | M2DOLab/OpenLSTO | 247b5bffad92f6de30c3d9730cbae7a96220677b | 853b9cc433b84c60cd1318a36f9a1d0e6cf65877 | refs/heads/master | 2021-06-11T08:16:25.998105 | 2021-03-19T18:37:48 | 2021-03-19T18:37:48 | 146,038,694 | 84 | 24 | Apache-2.0 | 2021-03-19T18:37:50 | 2018-08-24T20:48:37 | C++ | UTF-8 | C++ | false | false | 20,916 | hpp | lsm_hole_insertion.hpp |
namespace M2DO_LSM {
/*
! Structure containing attributes for an individual grid node.
*/
struct h_Node {
std::vector<double> sensitivities; //!< Objective and constraint sensitivities.
};
/*
! Structure containing attributes for an individual grid element.
*/
struct h_Element {
std::vector<double> sensitivities; //!< Objective and constraint sensitivities.
};
/*
Get the index and map of elements and nodes involved in the hole insertion
*/
int hole_map (M2DO_LSM::Mesh lsmMesh, M2DO_LSM::LevelSet levelSet, double h, double lBand, vector <double>& h_index, vector <bool>& h_elem) {
// Read in mesh variables
int nNodes = lsmMesh.nNodes;
int nElementsX = lsmMesh.width; // Number of elements in X
int nElementsY = lsmMesh.height; // Number of elements in Y
int nElements = lsmMesh.nElements;
vector <double> lsf; // Primary level set function
//double h; // unit length of element ???
int HC; // parameters for narrow band ???
double NB = lBand*h;
int nd_count = 0;
//vector <int> h_index(nNodes); // Identifier of whether this node can have a hole inserted.
h_index.resize(nNodes); fill(h_index.begin(), h_index.end(), 0);
for (int inode = 0; inode < nNodes; inode++) {
h_index[inode] = 0;
// Check whether a node is fixed or inside narrow band via its
// properties lsmMesh.nodes[theNode].isActive &
// lsmMesh.nodes[theNode].isFixed
//
// Feasible nodes should be :
// a. outside 'narrow band' area;
// b. active;
// c. not be fixed.
if ( ( levelSet.signedDistance[inode] >= NB ) &&
( lsmMesh.nodes[inode].isActive || !lsmMesh.nodes[inode].isFixed ) ) {
nd_count++;
h_index[inode] = 1;
}
}
// Count the number of elements that can be inserted hole
int count = 0;
h_elem.resize(nElements); fill(h_elem.begin(), h_elem.end(), false);
for (int iel = 0; iel < nElements; iel++) {
//h_elem[iel] = 0;
bool isAvailableForHole = false;
for (int ind = 0; ind < 4; ind++) {
int inode = lsmMesh.elements[iel].nodes[ind];
if ( ( levelSet.signedDistance[inode] >= NB ) &&
( lsmMesh.nodes[inode].isActive || !lsmMesh.nodes[inode].isFixed ) ) {
isAvailableForHole = true;
}
}
if (isAvailableForHole) { count++; h_elem[iel] = true;}
}
cout << "\nNumber of feasible LS nodes are: " << nd_count <<endl;
cout << "\nNumber of available elements for hole insertion is: " << count << endl;
return(count);
}
/*
Set value of the secondary level set function
*/
// void get_h_lsf( int nNodes, vector <double>& h_index, vector <M2DO_LSM::h_Node> h_Nsens,
// vector <double> gammas, vector <double>& h_lsf ) {
// // h_lsf.resize(nNodes); fill( h_lsf.begin(), h_lsf.end(), 0.0 );
// for ( int inode = 0; inode < nNodes; inode++ ) {
// // h_lsf[inode] = 1.0;
// if ( h_index[inode] ) {
// for (int j = 0; j < h_Nsens[inode].sensitivities.size(); j++ ) {
// h_lsf[inode] -= gammas[j] * ( 1 - h_Nsens[inode].sensitivities[j] );
// }
// if (h_lsf[inode]<0) {
// cout << "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
// cout << "\n The h_lsf of node " << inode << "\t is " << h_lsf[inode] << endl;
// cout << "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
// }
// }
// }
// }
void get_h_lsf( int nNodes, vector <double>& h_index, vector <M2DO_LSM::h_Node> h_Nsens,
vector <double> gammas, vector <double>& h_lsf ) {
// h_lsf.resize(nNodes); fill( h_lsf.begin(), h_lsf.end(), 0.0 );
for ( int inode = 0; inode < nNodes; inode++ ) {
// h_lsf[inode] = 1.0;
if ( h_index[inode] ) {
for (int j = 0; j < h_Nsens[inode].sensitivities.size(); j++ ) {
h_lsf[inode] -= gammas[j] * h_Nsens[inode].sensitivities[j];
}
// if (h_lsf[inode]<0) {
// cout << "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
// cout << "\n The h_lsf of node " << inode << "\t is " << h_lsf[inode] << endl;
// cout << "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
// }
}
}
}
void get_h_lsf2( int nNodes, vector <double>& h_index, vector <M2DO_LSM::h_Node> h_Nsens,
vector <double> gammas, vector <double>& h_lsf ) {
// h_lsf.resize(nNodes); fill( h_lsf.begin(), h_lsf.end(), 0.0 );
for ( int inode = 0; inode < nNodes; inode++ ) {
h_lsf[inode] = 1.0;
if ( h_index[inode] ) {
for (int j = 0; j < h_Nsens[inode].sensitivities.size(); j++ ) {
h_lsf[inode] -= gammas[j] * (1 - h_Nsens[inode].sensitivities[j]);
}
// if (h_lsf[inode]<0) {
// cout << "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
// cout << "\n The h_lsf of node " << inode << "\t is " << h_lsf[inode] << endl;
// cout << "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
// }
}
}
}
/*
Get area of elements availabe to insert hole
*/
double get_h_area( M2DO_LSM::Mesh lsmMesh, vector<bool>& h_elem ) {
double Atotal = 0.0;
for ( int iel = 0; iel < lsmMesh.nElements; iel++ ) {
if ( h_elem[iel] ) { // available element for hole insertion
// Add to the total area
Atotal += lsmMesh.elements[iel].area;
}
}
cout << "\nAvailable area for hole insertion is:\t " << Atotal << endl;
return(Atotal);
}
/*
Compute area related to holes
*/
// double computeAreaFractions_hole(){
// //
// }
/*
Function to find minimal value of h_lsf, thus revealing if signed distance
function has been changed beyond CFL condition
*/
double find_min_h_lsf(vector <double>& h_lsf) {
double Atemp = 1000;
int nNodes = h_lsf.size();
for ( int inode = 0; inode < nNodes; inode++ ) {
Atemp = h_lsf[inode] < Atemp ? h_lsf[inode] : Atemp;
}
return Atemp;
}
/*
Function to do Finite Difference analysis on minimum value of h_lsf
*/
double hole_FD_h_lsf(vector <double>& h_index,
vector <M2DO_LSM::h_Node> h_Nsens,
vector <double>& h_lsf,
vector <double> gammas,
double DA,
double TargetV,
double perb) {
double Atemp, DAperb, FDiff;
int nGammas = gammas.size();
int nNodes = h_lsf.size();
// Get perturbed gamma
for ( int i = 0; i < nGammas; i++ ) {
gammas[i] = gammas[i] + perb;
}
// Get hole lsf and total area of perturbed gamma
get_h_lsf2( nNodes, h_index, h_Nsens, gammas, h_lsf );
Atemp = find_min_h_lsf( h_lsf );
// Get change in the objective
DAperb = Atemp - TargetV;
FDiff = ( DA - DAperb ) / perb;
return(FDiff);
}
/*
Function to initialise the hole level set function and the maximum and
minimum values of gamma (side limits)
*/
void initialise_hole_lsf(M2DO_LSM::Mesh lsmMesh, int h_count, double holeCFL,
M2DO_LSM::LevelSet levelSet,
double moveLimit,
vector <double>& h_index,
vector <bool>& h_elem,
vector <M2DO_LSM::h_Node> h_Nsens,
vector <double>& h_lsf,
vector <double> lambdas) {
// read mesh data
double h; // unit length of element in level set mesh (?)
int nNodes = lsmMesh.nNodes; // Number of nodes in level set mesh
int nElements = lsmMesh.nElements; // Number of elements in level set mesh
// vector <double> h_lsf(nNodes); // Hole level set function
// vector <double> h_Nsens; // Node sensitivity
// vector <double> h_Esens; // Element sensitivity
int nGammas = lambdas.size(); // Number of constraints + 1
vector <double> gammas(nGammas); // Weight factors for the linear combination of sensitivities
vector <double> h_area; // Store change in element area caused by holes
vector <double> h_gMin(nGammas); // Minimum hole weighting
vector <double> h_gMax(nGammas); // Maximum hole weighting
/*
int *h_index = malloc(inMesh.NumNodes*sizeof(int)); //Identifier of weather this node can have a hole inserted
int *h_EmapX = malloc(inMesh.NumElem*sizeof(int)); //Element mapping in x direction
int *h_EmapY = malloc(inMesh.NumElem*sizeof(int)); //Element mapping in y direction
int *h_posN = malloc((1+lsprob.num)*sizeof(int)); //Node sensitivity mapping
int *h_posE = malloc((1+lsprob.num)*sizeof(int)); //Element sensitivity mapping
double *h_Nsens = malloc((1+lsprob.num)*inMesh.NumNodes*sizeof(double)); //Node sensitivity
double *h_Esens = malloc((1+lsprob.num)*inMesh.NumElem*sizeof(double)); //Element sensitivity
double *h_lsf = malloc(inMesh.NumNodes*sizeof(double)); //hole level set funtion
double *h_area = malloc(inMesh.NumElem*sizeof(double)); //store change in element area caused by holes
double *h_gMin = malloc(1*sizeof(double)); //Minimumum Hole weighting
double *h_gMax = malloc(1*sizeof(double)); //Maximumum Hole weighting
int *Reint = malloc(1*sizeof(int)); //Flag to let us know if we need to reinitailise the model
*/
double minlsf = 0.0, max_dh_lsh;
double dh_lsf, temp, Atemp;
/*
Find minimum of h_lsf or maximum of change of h_lsf,
and in turm get minmum gamma values ??? [for setting side limits for gamma]
*/
for (int i = 0; i < nGammas; i++ ) { gammas[i] = 1.0; }
int h_nodes_count = 0;
for (int inode = 0; inode < nNodes; inode++) {
h_lsf[inode] = 1.0;
if (h_index[inode]) {
h_nodes_count++;
dh_lsf = 0;
for (int j = 0; j < nGammas; j++) {
dh_lsf += gammas[j] * h_Nsens[inode].sensitivities[j];
}
if (h_nodes_count == 1) {
max_dh_lsh = dh_lsf;
} else {
max_dh_lsh = ( max_dh_lsh > dh_lsf ) ? max_dh_lsh : dh_lsf ;
}
//cout<<"Node " << inode << " minlsf is " << minlsf << " delta lsf is " << temp << " h_lsf " << h_lsf[inode] << endl;
}
}
h_gMin[0] = (1.0/max_dh_lsh)*1.00;
cout<<"\nMinimal weight factor should be: " << h_gMin[0] << endl;
for (int i = 0; i < nGammas; i++ ) { gammas[i] = h_gMin[0]; }
get_h_lsf2( nNodes, h_index, h_Nsens, gammas, h_lsf );
// compute the sum of availabe area for hole insertion
// Atemp = get_h_area( lsmMesh, h_elem );
// Now use Newton's method to find maximum of gammer or lambda
double Gtemp = 1.0001 * h_gMin[0];
double perb = 0.0001 * h_gMin[0];
double Gabove = 10000 * Gtemp;
double Gbelow = 0.0;
double gamma_old = Gtemp;
double Atotal = h * h * h_count;
double TargetV = -1.0 * holeCFL * h; // TargetV = Atotal * ( 1 - holeCFL );
double DA, DAP;
double FDiff;
int loop = 0;
do {
gamma_old = Gtemp;
get_h_lsf2( nNodes, h_index, h_Nsens, gammas, h_lsf );
Atemp = find_min_h_lsf( h_lsf );
// See if removed area Atotal is the matches the targeted maximum (within range)
DA = Atemp - TargetV;
DAP = Atemp / Atotal;
// Update overshoot variables
if ( loop > 2 ) {
if ( DA > 0 ) {
Gbelow = ( Gtemp > Gbelow ) ? Gtemp : Gbelow;
}
else if ( DA < 0 ) {
Gabove = ( Gtemp < Gabove ) ? Gtemp : Gabove;
}
}
// Make allowances for initial gradient being so low
if ( Atotal == 0 ) { Gabove = Gtemp - perb; }
// some words here
if ( fabs( DA ) < 0.01 ) {
loop = 501;
}
else {
// Get gradient by Finite Difference
FDiff = hole_FD_h_lsf(h_index, h_Nsens, h_lsf, gammas, DA, TargetV, perb);
// Cover for no gradient due to too small Gtemp (gammer temp)
if (FDiff == 0) {
Gtemp += perb;
}
else {
Gtemp += ( DA / FDiff );
}
// If outsie range then biset the range for the new value.
if ( ( Gtemp <= Gbelow) || ( Gtemp >= Gabove ) || ( Atemp = 0.0 ) ) {
Gtemp = ( Gabove + Gbelow ) / 2.0;
}
// Update Gtemp (gammer temp)
for ( int j = 0; j < nGammas; j++ ) {
gammas[j] = Gtemp;
}
loop++;
}
} while( loop < 500 );
if ( loop == 500 ) {
printf("\nWARNING HOLE CFL DID NOT CONVERGE, HOLES MAY BE TOO LARRGE");
}
// Assign value for upper bound of gamma
h_gMax[0] = Gtemp;
printf( "\nHole gamma side limits: %f and %f \n.", h_gMin[0], h_gMax[0] );
get_h_lsf2( nNodes, h_index, h_Nsens, gammas, h_lsf );
// // For plotting set up the output to be gammer max
// for ( int j = 0; j < num_gam; j++ ) { Gam[j] = h_gMax[0]; }
// get_h_lsf( nNodes, h_index, h_Nsens, lambdas, h_lsf );
// Atemp = M2DO_LSM::Boundary::computeAreaFractions();
}
// /*
// Conduct the Finite Difference method to calculate gradient
// */
// double hole_FD_SG( int nNodes, vector <double>& h_index,
// vector <M2DO_LSM::h_Node> h_Nsens, vector <double> lambdas,
// vector <double>& h_lsf, double perb, double DA, doulbe TargetV ) {
// double Atemp, DAperb, FDiff;
// int num_gam = lambdas.size();
// // Get perturbed gammer
// for ( int i = 0; i < num_gam; i++ ) {
// Gam[i] = Gam[i] + perb;
// }
// // Get hole lsf and total area of perturbed gammer
// get_h_lsf( nNodes, h_index, h_Nsens, lambdas, h_lsf );
// Atemp = M2DO_LSM::Boundary::computeAreaFractions();
// // Get change in the objective
// DAperb = Atemp - TargetV;
// FDiff = ( DA - DAperb ) / perb;
// return(FDiff);
// }
// // Calculate sensitivities using least squares of integratiin points for AFG
// // method
// void sens_hole();
// // Function to set velocity (or move dist) using SLP (???)
// // - filter method with jole insertion
// void SLPsubSol4_hole();
/*
void reinitialise_hole(){
int nNodes = lsmMesh.nNodes;
//
for (int inode = 0; inode < nNodes; inode++) {
lsf_temp[inode] = 0.0;
}
// Ensure all nodes on domain boundary have lsf <=0.0
//
// Initalise Known set
for(int inode = 0; inode < nNodes; inode++) {
// If node is fixed or on boundary, then retain the lsf
if(fabs(lsf[inode]) < tol) {
known[i] = true;
lsf_temp[inode] = lsf[inode]; // or 0.0 ??
}
}
//
for (int sign = 1; sign > -2; sign-=2) {
ftemp = h * 1000.0;
// Initialise trial set
for(inode = 0; inode < nNodes; inode++) {
// If current node not in known set and is the correct side of the boundary
if(!known[inode] && (sign * lsf[inode]) > 0.0) {
NS = ftemp * lsf[inode];
// If any neighbouring node is on opposite side of the boundary, or on boundary, then it is a trial node
for (int i = 0; i < 4; i++) {
int neighbour_node;
neighbour_node = lsmMesh.nNodes[inode].neighbours[i];
if (lsf[neighbour_node] * NS < 0.0) { trial[inode] = true; }
}
}
}
// Calculate lsf_temp for all current trial nodes
// ???LocalInt
// Update trial set by considering neighbours of nodes in known set
for (int inode = 0; inode < nNodes; inode++ ) {
if ( !known[inode] && (sign * lsf[inode]>0.0) ) {
// If any neighbouring node not in known set and is the current side of the boundary
for (int i = 0; i < 4; i++) {
int neighbour_node;
neighbour_node = lsmMesh.nNodes[inode].neighbours[i];
if (known[neighbour_node]) { trial[inode] = true; }
}
}
}
// Do until trial set is empty
int flag, ncount;
vector <double> lsf_trial(nNodes);
vector <int> xind;
do {
flag = 0;
// for (int inode = 0; inode < nNodes; inode++) {
// flag = 0;
// if (trial[inode]) {
// flag = 1;
// if ( fabs(lsf_trial[inode]) < 0.0 ) {
// Af = 0.0; Bf = 0.0; Cf = 0.0;
// ftemp = 0.0; // initial
// }
// }
// }
if (flag == 0) { break; } // if there are no trial nodes, then end the loop
ncount = 0; // re-initialise
// check to see which nodes need updating this iteration
for (int inode = 0; inode < nNodes; inode++) {
if ( lsf_trial[inode] < 0.0 ) {
printf("\nERROR IN ReInt:");
}
// If a trial node has a trial lsf value <= minimum then update
if ( trial[inode] && (fabs(lsf_trial[inode] - lsf_min) < tol ) ) {
lsf_temp[inode] = sign * lsf_trial[inode];
// Move node to known set
xind.pushback(inode);
}
}
// Update knonw set for next iteration
// .1
for (int i = 0; i<ncount; i++) {
trial[xind[i]] = false;
knonw[xind[i]] = true;
}
// .2
for (int i = 0; i<ncount; i++) {
int inode_temp = xind[i];
for (int j = 0; j < 4; j++){
int neighbour_node = lsmMesh.nodes[inode_temp].neighbours[j];
if (!known[neighbour_node] && (sign * lsf[neighbour_node] > 0.0) ) {
trial[neighbour_node] = true;
lsf_trial[neighbour_node] = 0.0;
}
}
}
if (ncount == 0) {
printf("\nERROR! ncount=0 in ReInt! Aborting");
}
} while ( ncount > 0 )
}
}*/
}
|
46f23f471022d9672a9de5e5fe265bf2be7a9996 | db2d8e0cf6036c3d5d7a05d6f38e23c1265d003b | /lib/abstractblock.h | 10eedd6725f27698f53702bd11fa0b15bf2126a4 | [] | no_license | Ray-SunR/the-Game-of-Quadris | 7dd041a59523bfdb2f889421f8316a22afeb333d | 0952293503a01b21c61acba8d3f7002f5ac52490 | refs/heads/master | 2021-01-01T17:48:25.888430 | 2014-03-07T23:55:51 | 2014-03-07T23:55:51 | 11,751,079 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,502 | h | abstractblock.h | //
// abstractblock.h
// The Game of Quadris
//
// Created by Sun Renchen& Chi Zhang on 2013-07-11.
// Copyright (c) 2013 University of Waterloo. All rights reserved.
//
#ifndef __Project__abstractblock__
#define __Project__abstractblock__
#include <iostream>
#include <vector>
#include <map>
#include "coordinate.h"
class Grid;
class Cell;
class AbstractBlock
{
protected:
int level;
char shape;
coordinate refcoord;//used as a reference coordinate in the left corner as x& y.
coordinate rightCorner;//Used to contain the right corner of the block
const int tolShapeType;//how many shapes it has
std::map < int, std::vector<coordinate> > maCoord;//map int to coordinate, 'int' means which status the block is, originally it is 0, max is tolShapeType; e.g:
std::map < int, std::vector<Cell*> > maCell;//map int to array of cell pointers. Used to store each kind of shape's pointer condition
int currentType;//current type of shape
virtual void update(Grid* gd) = 0;
bool canBeSLeft(int c, Grid* gd);//This function is used to determine whether column c can contain the current type of this block, true can, false not
bool canBeSRight(int c, Grid* gd);//check if this block can be shifted to right by 1 position
bool canBeSDown(int r, Grid* gd);//check if this block can be shifted down by 1 position
bool canBeRotate(Grid* gd, std::string c);//check whether the block can be rotate, string is used to indicate what kind of rotate it is
virtual void calculatePotentialPos(coordinate& ref, std::vector<coordinate>& vcoor) = 0;//by given a reference coordinate, calculate the potential position of a specific block
public:
AbstractBlock(int num, int level):tolShapeType(num), level(level){};//base class's constructor.
virtual ~AbstractBlock();//destructor
virtual void draw(Grid* gd, int level);//Once call draw block, then it will use gd to call the specific cell to be alive
virtual void undraw(Grid* gd);//Once call undraw blcok, then it will use gd to call the specific cell to be dead.
virtual void clockwiseRotate(Grid* gd) = 0;//clockwise rotate
virtual void counterClockwiseRotate(Grid* gd) = 0;//counter clockwise rotate
bool canBeDropped(int r, Grid* gd); //This function is used to determine whether row r can contain the current type of this block, true can, false not.
virtual coordinate getRefCoord() const {return refcoord;}//get the reference coordinate
int getCurrentType() const {return currentType;}//return the current type of this block
std::vector<coordinate> getMapCoordinate(int Type) {return maCoord[Type];}//return the coordinate of this block based on the current type of it.
std::vector<Cell*> getMapCell(int Type) {return maCell[Type];}//return the pointers to the cells based on the current type of it.
virtual coordinate getRightCorner() = 0;//will return the right corner of this block
int getLevel() const {return level;}//used to store which level is this block in.
void setRefCoord(coordinate& c, Grid* gd);//set the reference coordinate to c
void shiftLeft(Grid* gd);//shift left
void shiftRight(Grid* gd);//shift right
void shiftDown(Grid* gd);//shift down
bool Fall(Grid* gd);//drop a block
bool canBeDraw(Grid* gd);//check whether the this block can be drawn on the grid.
char getShape() const {return shape;}//answer which type of block it is.
};
#endif /* defined(__Project__abstractblock__) */
|
bbf5b64f4e484a660ad1cc67f7955a46b27f4663 | 97cc82f966fd4be6e95e9eb33a11400802fce762 | /Dining Philosopher Sim/341HW4_phliosophers.cpp | bc642447728419ac57ee5db06a3d80e344c682b5 | [] | no_license | JDArcher/Jace-Archer-Projects | cb5a252b89c9c548d1e8658be1395b779e6b23ab | 5614e6a74e4fc5b5920cabc43756c789aef58220 | refs/heads/master | 2021-01-19T17:59:45.246905 | 2020-02-27T02:20:19 | 2020-02-27T02:20:19 | 101,103,716 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,879 | cpp | 341HW4_phliosophers.cpp | #include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include "341_Monitor.h"
#define N 5
#define lock pthread_mutex_lock
#define unlock pthread_mutex_unlock
using namespace std;
const char *name[N] = {"Aristotle", "Kant", "Spinoza", "Marx", "Russell" };
pthread_mutex_t forks2[N];
void eat(int id)
{
get_forks(id);
string pname(name[id]);
int lfork = id;
int rfork = (id + 1)%N;
ostringstream lfid, rfid;
lfid << lfork;
rfid << rfork;
string s = "Philosopher " + pname + " beginning to eat.";
print(s.c_str());
sleep(rand()%4+2);
release_forks(id);
}//The eat method tries to grab the forks through the monitor, wait, and then release the forks through the monitor
void think(int id)
{
string pname(name[id]);
string s = "Philosopher " + pname + " is thinking.";
print(s.c_str());
sleep(rand()%5 + 5);
s = "Philosopher " + pname + " is hungry, ready to eat.";
eat(id);
}//The think method will print out the philosophers who are currently thinking, wait for a second, and then try to eat
void* Philosophize(void *id)
{
int threadid = (int)id;
cout << threadid << ": " << name[threadid] << endl;
while(true){
think(threadid);
}//This loop will run infinitely, placing philosophers back in to the thinking state
pthread_exit(NULL);
}//end Philosophize
int main(int argc, char **argv){
int id[N];
pthread_t tid[N];
srand(time(NULL));
for(int i = 0; i < N; i++)
{
id[i] = i;
pthread_mutex_init(&forks2[i], NULL);
}
for(int i = 0; i < N; i++) {
pthread_create(&tid[i], NULL, Philosophize, (void*)i);
}
for(int i = 0; i < N; i++) {
pthread_join(tid[i], NULL);
}
pthread_exit(NULL);
return 0;
}//end main
|
530175360e5ebc70bd015778cd3c43163eb1d88e | 8103a6a032f7b3ec42bbf7a4ad1423e220e769e0 | /Prominence/XInputController.cpp | 2566816453971b03a8f14ba334d68310b37d350a | [] | no_license | wgoddard/2d-opengl-engine | 0400bb36c2852ce4f5619f8b5526ba612fda780c | 765b422277a309b3d4356df2e58ee8db30d91914 | refs/heads/master | 2016-08-08T14:28:07.909649 | 2010-06-17T19:13:12 | 2010-06-17T19:13:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | XInputController.cpp | #include "XInputController.h"
namespace Prominence {
XInputController::XInputController(void)
{
}
XInputController::~XInputController(void)
{
}
bool XInputController::GetAKey()
{
return false;
}
bool XInputController::GetBKey()
{
return false;
}
bool XInputController::GeyXKey()
{
return false;
}
bool XInputController::GetYKey()
{
return false;
}
void XInputController::GetDirection(int &MagX, int &MagY)
{
}
bool XInputController::GetLKey()
{
return false;
}
bool XInputController::GetRKey()
{
return false;
}
} |
ca7cb93bf7beec42b6bd52d174e26156fb626ea9 | a86e02e2d77ec6ab4a7da09df0262b363690b55e | /eg5_11.cpp | ff01f96fb8df9374a0e4c22db34f0681612c5729 | [] | no_license | rajaniket/Cpp_programs | 59e20ef7c0918b0dfad1ed9468a479c49bd7ccc0 | 6528a5bff5c58dd734d46cf8a6aa5363b90219d9 | refs/heads/master | 2021-06-18T11:19:51.830199 | 2021-06-08T17:26:59 | 2021-06-08T17:26:59 | 215,588,831 | 5 | 0 | null | 2020-01-04T18:15:40 | 2019-10-16T16:00:09 | C++ | UTF-8 | C++ | false | false | 702 | cpp | eg5_11.cpp | // Program to Transpose a 3x3 matrix;
#include<iostream>
using namespace std;
class matrix
{
int m[3][3];
public:
void getmatrix(){
cout<<"type matrix elements\n";
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
{
cin>>m[i][j];
}}}
void displaymatrix(){
for(int i=0;i<3;i++){
cout<<endl;
for(int j=0;j<3;j++)
cout<<m[i][j]<<"\t";
} cout<<"\n"<<endl;
}
friend matrix transmatrix(matrix);
};
matrix transmatrix(matrix z){
matrix temp;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
temp.m[i][j]=z.m[j][i]; // interchanging row & col
return temp;
}
int main(){
matrix a,b;
a.getmatrix();
cout<<"you entered the matrix\n";
a.displaymatrix();
cout<<"Transposed Matrix:\n";
b=transmatrix(a);
b.displaymatrix();
}
|
f9b6d3dd20a4bce467e686e40a94481e92692657 | 4c9ed7ef524b4790ad03ffa80cecb1a3cb07ac9e | /GiaoTrinh/DoHoa/SuperBible4/examples/src/chapt03/stencil/stencil.cpp | 4e11fc8745c0064dffca73045c40c5132f142bf7 | [] | no_license | mymoon89/SPKT_TRANTHITHUY | 12bdcb71584c15969b1a85739c7e3a778e584176 | da43e4ec58ecf5d06138d42cc771cc1d7fa64db8 | refs/heads/master | 2020-06-04T04:29:52.944958 | 2011-09-10T05:21:47 | 2011-09-10T05:21:47 | 2,354,266 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,418 | cpp | stencil.cpp | // Stencil.cpp
// OpenGL SuperBible
// Richard S. Wright Jr.
// rwright@starstonesoftware.com
#include "../../shared/gltools.h" // OpenGL toolkit
// Initial square position and size
GLfloat x = 0.0f;
GLfloat y = 0.0f;
GLfloat rsize = 25;
// Step size in x and y directions
// (number of pixels to move each time)
GLfloat xstep = 1.0f;
GLfloat ystep = 1.0f;
// Keep track of windows changing width and height
GLfloat windowWidth;
GLfloat windowHeight;
///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
GLdouble dRadius = 0.1; // Initial radius of spiral
GLdouble dAngle; // Looping variable
// Clear blue window
glClearColor(0.0f, 0.0f, 1.0f, 0.0f);
// Use 0 for clear stencil, enable stencil test
glClearStencil(0.0f);
glEnable(GL_STENCIL_TEST);
// Clear color and stencil buffer
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// All drawing commands fail the stencil test, and are not
// drawn, but increment the value in the stencil buffer.
glStencilFunc(GL_NEVER, 0x0, 0x0);
glStencilOp(GL_INCR, GL_INCR, GL_INCR);
// Spiral pattern will create stencil pattern
// Draw the spiral pattern with white lines. We
// make the lines white to demonstrate that the
// stencil function prevents them from being drawn
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINE_STRIP);
for(dAngle = 0; dAngle < 400.0; dAngle += 0.1)
{
glVertex2d(dRadius * cos(dAngle), dRadius * sin(dAngle));
dRadius *= 1.002;
}
glEnd();
// Now, allow drawing, except where the stencil pattern is 0x1
// and do not make any further changes to the stencil buffer
glStencilFunc(GL_NOTEQUAL, 0x1, 0x1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// Now draw red bouncing square
// (x and y) are modified by a timer function
glColor3f(1.0f, 0.0f, 0.0f);
glRectf(x, y, x + rsize, y - rsize);
// All done, do the buffer swap
glutSwapBuffers();
}
///////////////////////////////////////////////////////////
// Called by GLUT library when idle (window not being
// resized or moved)
void TimerFunction(int value)
{
// Reverse direction when you reach left or right edge
if(x > windowWidth-rsize || x < -windowWidth)
xstep = -xstep;
// Reverse direction when you reach top or bottom edge
if(y > windowHeight || y < -windowHeight + rsize)
ystep = -ystep;
// Check bounds. This is in case the window is made
// smaller while the rectangle is bouncing and the
// rectangle suddenly finds itself outside the new
// clipping volume
if(x > windowWidth-rsize)
x = windowWidth-rsize-1;
if(y > windowHeight)
y = windowHeight-1;
// Actually move the square
x += xstep;
y += ystep;
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(33,TimerFunction, 1);
}
///////////////////////////////////////////////////////////
// Called by GLUT library when the window has chanaged size
void ChangeSize(int w, int h)
{
GLfloat aspectRatio;
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Establish clipping volume (left, right, bottom, top, near, far)
aspectRatio = (GLfloat)w / (GLfloat)h;
if (w <= h)
{
windowWidth = 100;
windowHeight = 100 / aspectRatio;
glOrtho (-100.0, 100.0, -windowHeight, windowHeight, 1.0, -1.0);
}
else
{
windowWidth = 100 * aspectRatio;
windowHeight = 100;
glOrtho (-windowWidth, windowWidth, -100.0, 100.0, 1.0, -1.0);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
///////////////////////////////////////////////////////////
// Program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_STENCIL);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL Stencil Test");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutTimerFunc(33, TimerFunction, 1);
glutMainLoop();
return 0;
}
|
292cbf13a091e534e78a0e39ddf6b9ce3b36b41f | bce4edcafec4a403f41b31f594daff23fe319aa5 | /3DOpenGL/lengnan/lengnan/ADOConn.cpp | b71a054e25d012f9564ddca70a935d03a087a886 | [] | no_license | XZM-CN/3DOpenGL | afc3e9cc922c8d94e5ecff42bc12ed0594e36bc9 | ed84ec70418fe2033fdba0ac80e3b89be5f1a890 | refs/heads/master | 2021-01-22T07:42:24.789493 | 2017-09-04T02:51:09 | 2017-09-04T02:51:09 | 102,310,936 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,256 | cpp | ADOConn.cpp | #include "StdAfx.h"
#include "ADOConn.h"
CADOConn::CADOConn(void)
{
// 初始化库环境
::CoInitialize(NULL);
//连接对象
m_pConnection.CreateInstance(_T("ADODB.Connection"));
//数据库文件对象
m_pCatalog.CreateInstance(__uuidof (ADOX::Catalog));
}
CADOConn::~CADOConn(void)
{
//释放环境
::CoUninitialize();
}
////////////////////////////////Access函数/////////////////////////////////////////////////////////////////
//创建Access数据库文件
BOOL CADOConn::CreateAccess(CString filepathname)
{
HRESULT hr = S_OK;
//创建Access2007的文件SQL字符串
CString myConnection=_T("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=")+filepathname;
try
{
m_pCatalog->Create(_bstr_t(myConnection)); //Create MDB
return TRUE;
}
catch(...)
{
return FALSE;
}
}
//连接Access数据库
bool CADOConn::ADO_Connection(CString filepathname)
{
try
{
if (m_pConnection->GetState() == adStateOpen)
{
m_pConnection->Close();
}
m_pConnection->ConnectionTimeout=5;
//设置连接字符串
_bstr_t myConnection;
//链接字符串根据需要具体配置
myConnection=_T("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=")+filepathname;
m_pConnection->Open(myConnection,"","",adModeUnknown);
return true;
}
catch (...)
{
return false;
}
}
//以动态方式打开Access数据集
_RecordsetPtr CADOConn::ADO_GetRecordSet(CString tablename)
{
_RecordsetPtr myprecordset;
CString sql=_T("select *from ");
sql+=tablename;
_bstr_t bstrsql=(_bstr_t)sql;
try
{
//创建记录集对象
myprecordset.CreateInstance(_T("ADODB.Recordset"));
//取得表中的记录
myprecordset->Open(bstrsql,m_pConnection.GetInterfacePtr(),adOpenStatic,adLockOptimistic,adCmdText);
return myprecordset;
}
catch(...)
{
return NULL;
}
}
//以静态光标打开Access数据集
_RecordsetPtr CADOConn::ADO_GetRecordSet2(CString tablename)
{
_RecordsetPtr myprecordset;
CString sql=_T("select *from ");
sql+=tablename;
_bstr_t bstrsql=(_bstr_t)sql;
try
{
//创建记录集对象
myprecordset.CreateInstance(_T("ADODB.Recordset"));
//取得表中的记录:采用静态光标实时显示对数据库的修改,乐观锁定光标,文本命令支撑对SQL语句的使用
myprecordset->Open(bstrsql,m_pConnection.GetInterfacePtr(),adOpenStatic,adLockOptimistic,adCmdText);
return myprecordset;
}
catch(...)
{
return NULL;
}
}
//////////////////////////////////////////////////////////Excel/////////////////////////////////////////////////
//打开并获得数据集
_RecordsetPtr CADOConn::ADO_GetRecordSetExcel(CString tablename)
{
_RecordsetPtr myprecordset;
CString sql=_T("select *from [");
sql+=tablename;
sql+=_T("$]");
_bstr_t bstrsql=(_bstr_t)sql;
try
{
//创建记录集对象
myprecordset.CreateInstance(_T("ADODB.Recordset"));
//取得表中的记录
myprecordset->Open(bstrsql,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
return myprecordset;
}
catch(...)
{
return NULL;
}
}
//创建和打开Excel文件
BOOL CADOConn::ADO_CreateOrOpenExcel(CString filepathname)
{
//创建Excel2007的文件SQL字符串
CString myConnection=_T("Provider=Microsoft.Ace.OleDb.12.0;Data Source=");
myConnection+=filepathname;
myConnection+=_T(";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=0\"");
try
{
if (m_pConnection->GetState() == adStateOpen)
{
return false;
}
m_pConnection->ConnectionTimeout=5;
//设置连接字符串
_bstr_t myconnection=(_bstr_t)myConnection;
//链接字符串根据需要具体配置
m_pConnection->Open(myconnection,"","",adModeUnknown);
return true;
}
catch (...)
{
return false;
}
}
/////////////////////////////////////////////////////////数据库操作公用函数////////////////////////////////////////////////////////////
//新建数据集
_RecordsetPtr CADOConn::ADO_Createtable(CString tablename,CString prama)
{
//建立数据表
CString sql=_T("CREATE TABLE ");
sql+=tablename;
sql+=prama;
_bstr_t bstrsql=(_bstr_t)sql;
if (ExecuteSQL(bstrsql)==NULL)
{
return NULL;
}
//打开数据表
return ADO_GetRecordSet(tablename);
}
//执行SQL语句
_RecordsetPtr CADOConn::ExecuteSQL(_bstr_t bstrSQL)
{
try
{
return m_pConnection->Execute(bstrSQL,NULL,adCmdText);
}
catch(...)
{
return NULL;
}
}
bool CADOConn::ADO_ExitConnect()
{
//关闭记录集和链接
try
{
if (m_pConnection->GetState() == adStateOpen)
{
m_pConnection->Close();
}
return true;
}
catch(...)
{
return false;
}
}
bool CADOConn::ADO_Insertdata(_RecordsetPtr* PIntoreport,CString datastr,double* datas,int num)
{
static int numofrecord=0;
CString tempstr;
CString dataname;
try
{
//序号
tempstr.Format(_T("%d"),numofrecord+1);
numofrecord++;
int numofrecords=num/250;
if (num%250!=0)
{
numofrecords+=1;
}
for (int i=0;i<numofrecords;i++)
{
PIntoreport[i]->AddNew();
if (i==0)
{
PIntoreport[i]->PutCollect(_T("序号"),(_bstr_t)tempstr);
PIntoreport[i]->PutCollect(_T("时间"),(_bstr_t)datastr);
}
else
{
PIntoreport[i]->PutCollect(_T("序号"),(_bstr_t)tempstr);
}
}
for (int i=0;i<num;i++)
{
dataname.Format(_T("采集点%d"),i+1);
tempstr.Format(_T("%.3f"),datas[i]);
//当前数据所在的表格
PIntoreport[i/250]->PutCollect((_bstr_t)dataname,(_bstr_t)tempstr);
}
for (int i=0;i<numofrecords;i++)
{
PIntoreport[i]->Update();
}
return true;
}
catch (...)
{
return false;
}
}
bool CADOConn::ADO_CloseRecord(_RecordsetPtr closereport)
{
//关闭记录集和链接
try
{
if (closereport->GetState() == adStateOpen)
{
closereport->Close();
}
return true;
}
catch(...)
{
return false;
}
}
////////////////////////////如下是从数据表中读取数据,不同的项目各有不同,不适合用于封装/////////////////////////////////
/*
_variant_t vCount=Rs1->GetCollect("geshu");
int num1=vCount.lVal; //符合条件的记录个数
pRst->MoveFirst(); //只读取第一行
_variant_t t = _variant_t(long(6));
result = (LPCSTR)_bstr_t(pRecordset->GetCollect(t));//以列序号的方式来读取字段内容 0based
result = (LPCSTR)_bstr_t(pRecordset->GetCollect("人口"));//以字段名的方式来读字段内容
*/
|
abd491e38b9ccce3fa295d0196c821dd22f82afb | 78bae575fe525533c5bb0f6ac0c8075b11a4271d | /139. Word Break.cpp | d674e5bfdd5211fff6f2fcdf2c583b14dbd26d3a | [] | no_license | Shubhamrawat5/LeetCode | 23eba3bfd3a03451d0f04014cb47de12504b6399 | 939b5f33ad5aef78df761e930d6ff873324eb4bb | refs/heads/master | 2023-07-18T00:01:21.140280 | 2021-08-21T18:51:27 | 2021-08-21T18:51:27 | 280,733,721 | 1 | 3 | null | 2020-10-21T11:18:24 | 2020-07-18T20:26:20 | C++ | UTF-8 | C++ | false | false | 1,957 | cpp | 139. Word Break.cpp | class Solution {
public:
bool check(string substr,string s) //checking if string substr is a prefix of string s or not
{
if(substr.length()>s.length()) return false;
int i=0;
while(i<substr.length() && i<s.length())
{
if(substr[i]!=s[i]) return false;
++i;
}
return true;
}
bool can(string s,vector<string>& wordDict,vector<bool>& dp,int curIndex) //using curIndex to know of which index of main string s we are at. so that we can mark it as true or false in bool vector
{
if(dp[curIndex]==false) return false; //problem has already checked before and having false value means program cant be solved further
if(s.length()==0) return true; //found answer
bool canMake=false; //to know if ans is found or not
//Logic: checking for each index that if any wordDict string is same as the prefix of current string.. using check function for this (created above)
for(int i=0;i<wordDict.size();++i)
{
if(canMake==true) break; //if ans was found before this will not evaluate further
if(check(wordDict[i],s)) //yes, current string prefix is same as a wordDict string of index i
{
canMake=can(&s[0]+wordDict[i].length(),wordDict,dp,curIndex+wordDict[i].length()); //checking for right side string then. passing address of string which will be O(1) not like substr O(n).
}
}
dp[curIndex]=false; //we have checked all possible combinations for current index of main string and current string so marking it as false
return canMake;
}
bool wordBreak(string s, vector<string>& wordDict) {
if(s.length()==0) return true;
vector<bool> dp(s.length(),1); //a dynamic programming array to avoid checking same problem more than once, filling it value true(1)
return can(s,wordDict,dp,0);
}
}; |
b426ffe2518e705d8e04c1550bee9081829ed269 | 8bd875339cee344a4ac5d3a347a54f407ed2e7a1 | /practice_1/practice_5/HanShuDeShengMing.cpp | 7a856d998287717e7f4b84e3062c2c34020b39b9 | [] | no_license | Gundam2887/C-Plus-Plus-Project | 177e9a845f2d9e26aa8b7ec6aa916ed854a8a5e2 | 05661496639d97740f305fdc68fe946f70586315 | refs/heads/master | 2022-11-30T09:05:12.987545 | 2020-08-14T04:19:37 | 2020-08-14T04:19:37 | 284,626,702 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 431 | cpp | HanShuDeShengMing.cpp | #include<iostream>
using namespace std;
//函数的声明
//提前告诉编译器函数的存在,可以利用函数的声明
//比较函数,实现两个整型数组进行比较,返回较大的值
//函数的声明
//声明可以写多次,但是定义只能有一次
int max(int a,int b);
int main(){
int a = 10;
int b = 20;
cout << max(a,b) << endl;
}
int max(int a,int b){
return a > b ? a : b;
} |
535a461bf6123b683bdbf42e8230fae0de806be6 | 6c85250695200779f38728d2278ef88f450d2987 | /test/Test_MemoryMappedFile.cpp | 307351bec741a7b1f2bedc28b7cdd5839b25d1ba | [] | no_license | msareena/MemoryMappedFile | 5850b8c5d626679908d798ad43da236a28bf6900 | 968e6a9eae9763b60290d96dd2db05297c2ce056 | refs/heads/main | 2023-03-07T07:13:15.752779 | 2021-02-20T14:10:25 | 2021-02-20T14:10:25 | 336,555,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,107 | cpp | Test_MemoryMappedFile.cpp | #include <gmock/gmock.h>
#include <filesystem>
#include <fstream>
#include <MemoryMappedFile.h>
using namespace ::testing;
class AMemoryMappedFile : public Test
{
public:
void SetUp() override
{
{
std::fstream fs(TEST_FILEPATH, fs.out | fs.trunc);
fs.write(TEST_FILE_CONTENT.data(), TEST_FILE_CONTENT.length());
}
{
std::fstream fs(EMPTY_FILE_TEST_FILEPATH, fs.out | fs.trunc);
}
}
void TearDown() override
{
std::filesystem::remove(TEST_FILEPATH);
}
static const std::filesystem::path TEST_FILEPATH;
static const std::filesystem::path EMPTY_FILE_TEST_FILEPATH;
static const std::string TEST_FILE_CONTENT;
MemoryMappedFile mMMapFile;
};
class MockMemoryMappedFile
{
public:
MOCK_METHOD(bool, IsOpen, ());
MOCK_METHOD(void, Close, ());
~MockMemoryMappedFile() { if (IsOpen()) Close(); }
};
const std::filesystem::path AMemoryMappedFile::TEST_FILEPATH{"testfile"};
const std::filesystem::path
AMemoryMappedFile::EMPTY_FILE_TEST_FILEPATH{"emptyfile"};
const std::string AMemoryMappedFile::TEST_FILE_CONTENT{"This is a test file."};
TEST_F(AMemoryMappedFile, CanOpenAFile)
{
mMMapFile.Open(TEST_FILEPATH);
ASSERT_TRUE(mMMapFile.IsOpen());
}
TEST_F(AMemoryMappedFile, ThrowsIfFileDoesNotExist)
{
ASSERT_THROW(mMMapFile.Open("NONEXISTANT"), CannotOpenFileException);
}
TEST_F(AMemoryMappedFile, ThrowsIfCannotOpenFile)
{
std::filesystem::permissions(TEST_FILEPATH, std::filesystem::perms::none);
ASSERT_THROW(mMMapFile.Open(TEST_FILEPATH), CannotOpenFileException);
}
TEST_F(AMemoryMappedFile, OpenedFileCanBeClosed)
{
mMMapFile.Open(TEST_FILEPATH);
mMMapFile.Close();
ASSERT_FALSE(mMMapFile.IsOpen());
}
TEST_F(AMemoryMappedFile, ThrowsIfClosedFileIsNotOpen)
{
ASSERT_THROW(mMMapFile.Close(), CannotCloseFileException);
}
TEST_F(AMemoryMappedFile, ClosesOpenFileUponDestruction)
{
InSequence s;
MockMemoryMappedFile mockMemoryMappedFile = MockMemoryMappedFile();
EXPECT_CALL(mockMemoryMappedFile, IsOpen()).WillOnce(Return(true));
EXPECT_CALL(mockMemoryMappedFile, Close()).Times(1);
}
TEST_F(AMemoryMappedFile, DoesNotCloseUnopenFileUponDestruction)
{
MockMemoryMappedFile mockMemoryMappedFile = MockMemoryMappedFile();
EXPECT_CALL(mockMemoryMappedFile, IsOpen()).WillOnce(Return(false));
EXPECT_CALL(mockMemoryMappedFile, Close()).Times(0);
}
TEST_F(AMemoryMappedFile, CreatesAMemoryMapWhenOpeningAFile)
{
mMMapFile.Open(TEST_FILEPATH);
ASSERT_NE(mMMapFile.Data(), nullptr);
}
TEST_F(AMemoryMappedFile, ThrowsIfFailesToCreateAMemoryMap)
{
ASSERT_THROW(mMMapFile.Open(EMPTY_FILE_TEST_FILEPATH),
CannotMapFileException);
}
TEST_F(AMemoryMappedFile, HasNoDataIfMapFails)
{
EXPECT_THROW(mMMapFile.Open(EMPTY_FILE_TEST_FILEPATH),
CannotMapFileException);
ASSERT_EQ(mMMapFile.Data(), nullptr);
}
TEST_F(AMemoryMappedFile, HasNoDataAfterClosingTheMappedFile)
{
mMMapFile.Open(TEST_FILEPATH);
mMMapFile.Close();
ASSERT_EQ(mMMapFile.Data(), nullptr);
}
TEST_F(AMemoryMappedFile, CanReadDataFromMappedFile)
{
mMMapFile.Open(TEST_FILEPATH);
auto data = mMMapFile.Data();
const std::string actual{reinterpret_cast<const char*>(data) + 5, 2};
const std::string expected{"is"};
ASSERT_STREQ(actual.c_str(), expected.c_str());
}
TEST_F(AMemoryMappedFile, ReturnsTheMappedSizeOfTheFile)
{
mMMapFile.Open(TEST_FILEPATH);
auto actual = mMMapFile.Size();
auto expected = TEST_FILE_CONTENT.length();
ASSERT_EQ(actual, expected);
}
TEST_F(AMemoryMappedFile, CanReadDataFromMappedFileAtSpecifiedOffset)
{
mMMapFile.Open(TEST_FILEPATH);
auto data = mMMapFile.Data(5);
const std::string actual{reinterpret_cast<const char*>(data), 2};
const std::string expected{"is"};
ASSERT_EQ(actual, expected);
}
TEST_F(AMemoryMappedFile, CanOpenAMapDuringConstruction)
{
ASSERT_FALSE(mMMapFile.IsOpen());
mMMapFile = MemoryMappedFile(TEST_FILEPATH);
ASSERT_TRUE(mMMapFile.IsOpen());
}
|
0e06e6abaefa5e7b7b9492d994b321937f931da6 | 439b9018740c2767b61a27d24cb407fed747152b | /ns_image_server/image_processing/ns_image_registration.h | fb6199b7cb3a0acb2d4e482c28b1ce239d43ca6d | [] | no_license | cinquin/lifespan | e2c6ba2206670869e62b4feb90ad50decb56b485 | 46c02870058e5cde484a99f817027b4ce807a010 | refs/heads/master | 2020-12-13T16:55:12.318448 | 2015-02-10T22:00:34 | 2015-02-10T22:00:34 | 30,616,647 | 0 | 0 | null | 2015-02-10T21:55:23 | 2015-02-10T21:55:21 | null | UTF-8 | C++ | false | false | 11,358 | h | ns_image_registration.h | #ifndef NS_IMAGE_REGISTRATION
#define NS_IMAGE_REGISTRATION
#include "ns_image.h"
#include "ns_ex.h"
#include "ns_image_registration_cache.h"
#include <iostream>
template<int thresh, class ns_component>
class ns_image_registration{
public:
template<class profile_type>
static void generate_profiles(const ns_image_whole<ns_component> & r, ns_image_registration_profile<profile_type> & profile,const ns_registration_method & method,const unsigned long downsampling_factor=0){
profile.registration_method = method;
if (method == ns_full_registration){
return;
}
profile.horizontal_profile.resize(0);
profile.vertical_profile.resize(0);
profile.horizontal_profile.resize(r.properties().width,0);
profile.vertical_profile.resize(r.properties().height,0);
profile.average = 0;
const unsigned long h(r.properties().height),
w(r.properties().width);
if (method == ns_threshold_registration){
for (unsigned int y = 0; y < h; y++){
for (unsigned int x = 0; x < w; x++){
profile.vertical_profile[y]+=(r[y][x] >= thresh);
profile.horizontal_profile[x]+=(r[y][x] >= thresh);
}
}
}
else if (method == ns_sum_registration || method == ns_compound_registration){
ns_64_bit average(0);
for (unsigned int y = 0; y < h; y++){
for (unsigned int x = 0; x < w; x++){
profile.vertical_profile[y]+=(r[y][x]);
profile.horizontal_profile[x]+=(r[y][x]);
profile.average+=r[y][x];
}
}
profile.average = profile.average/(ns_64_bit)(w*h);
if (method == ns_compound_registration)
r.pump(profile.whole_image,1024*1024);
}
else throw ns_ex("Unknown registration method");
}
template<class T1>
static ns_vector_2i register_full_images(ns_image_registration_profile<T1> & r , ns_image_registration_profile<T1> & a, ns_vector_2i max_offset = ns_vector_2i(0,0), const std::string & debug_name=""){
if (r.downsampling_factor != a.downsampling_factor)
throw ns_ex("Downsampling factor mismatch");
if (max_offset == ns_vector_2i(0,0))
max_offset = ns_vector_2i(r.whole_image.properties().width/5,r.whole_image.properties().height/5);
ns_vector_2i downsampled_max_offset(max_offset/r.downsampling_factor);
ns_high_precision_timer t;
t.start();
std::cerr << "Running course alignment at low resolution...";
ns_vector_2i downsampled_shift(register_whole_images<ns_image_standard,1>(r.downsampled_image,a.downsampled_image,downsampled_max_offset*-1,downsampled_max_offset,"c:\\server\\distances_low_res.csv"));
downsampled_shift = downsampled_shift*r.downsampling_factor;
ns_vector_2i downsample_v(r.downsampling_factor,r.downsampling_factor);
//cerr << "low_res: " << t.stop()/1000.0/1000.0 << "\n";
if (r.downsampling_factor > NS_SECONDARY_DOWNSAMPLE_FACTOR){
r.downsampled_image_2.seek_to_beginning();
a.downsampled_image_2.seek_to_beginning();
t.start();
std::cerr << "Running finer alignment at medium resolution...";
ns_vector_2i downsampled_shift_2(
register_whole_images<T1,3>(r.downsampled_image_2,a.downsampled_image_2,
(downsampled_shift-downsample_v)/NS_SECONDARY_DOWNSAMPLE_FACTOR,(downsampled_shift+downsample_v)/NS_SECONDARY_DOWNSAMPLE_FACTOR,"c:\\server\\distances_med_res.csv"));
//cerr << "med_res: " << t.stop()/1000.0/1000.0 << "\n";
downsampled_shift_2 = downsampled_shift_2*NS_SECONDARY_DOWNSAMPLE_FACTOR;
ns_vector_2i downsample_v(NS_SECONDARY_DOWNSAMPLE_FACTOR,NS_SECONDARY_DOWNSAMPLE_FACTOR);
r.whole_image.seek_to_beginning();
a.whole_image.seek_to_beginning();
t.start();
std::cerr << "\nRunning fine alignment at full resolution...";
return register_whole_images<T1,3>(r.whole_image,a.whole_image,downsampled_shift_2-downsample_v,downsampled_shift_2+downsample_v,"c:\\server\\distances_full_res.csv");
//cerr << "high_res: " << t.stop()/1000.0/1000.0 << "\n";
}
return register_whole_images<T1,4>(r.whole_image,a.whole_image,downsampled_shift-downsample_v,downsampled_shift+downsample_v);
}
template <class random_access_image_type,int pixel_skip>
static ns_vector_2i register_whole_images(random_access_image_type & r, random_access_image_type & a, const ns_vector_2i offset_minimums,const ns_vector_2i offset_maximums,const std::string & debug=""){
unsigned long h(r.properties().height);
if (h > a.properties().height)
h = a.properties().height;
unsigned long w(r.properties().width);
if (w > a.properties().width)
w = a.properties().width;
//we calculate the difference for each offset simultaneously
//to minimize the total amount of image data loaded in memory at any point
//and thereby mimimize paging.
std::vector<std::vector<ns_64_bit> > differences;
differences.resize(offset_maximums.y - offset_minimums.y);
for (unsigned int i = 0; i < differences.size(); i++)
differences[i].resize(offset_maximums.x - offset_minimums.x,0);
int x_distance_from_edge(abs(offset_minimums.x));
if (x_distance_from_edge < abs(offset_maximums.x))
x_distance_from_edge = abs(offset_maximums.x);
int y_distance_from_edge(abs(offset_minimums.y));
if (y_distance_from_edge < abs(offset_maximums.y))
y_distance_from_edge = abs(offset_maximums.y);
if (offset_maximums.y - offset_minimums.y > NS_MAX_CAPTURED_IMAGE_REGISTRATION_VERTICAL_OFFSET)
throw ns_ex("Requested image alignment distance exceeds hard-coded maximum");
unsigned long ten_percent((h-2*y_distance_from_edge)/(pixel_skip*20));
unsigned long count(0);
for (unsigned int y = y_distance_from_edge; y < h-y_distance_from_edge; y+=pixel_skip){
if (count == 0 || count >= ten_percent){
std::cerr << (100*(y-y_distance_from_edge))/(h-2*y_distance_from_edge) << "%...";
count = 0;
}
count++;
r.make_line_available(y);
a.make_line_available(y+offset_maximums.y);
for (int dy = offset_minimums.y; dy < offset_maximums.y; dy++){
for (unsigned int x = x_distance_from_edge; x < w-x_distance_from_edge; x+=pixel_skip){
for (int dx = offset_minimums.x; dx < offset_maximums.x; dx++){
differences[dy-offset_minimums.y][dx-offset_minimums.x]+=(ns_64_bit)abs((int)r[y][x]-(int)a[y+dy][x+dx]);
}
}
}
}
ns_vector_2i minimum_offset(0,0);
ns_64_bit minimum_offset_difference((ns_64_bit)-1);
// ofstream o(debug.c_str());
//o << "dx,dy,distance\n";
for (int dy = offset_minimums.y; dy < offset_maximums.y; dy++){
for (int dx = offset_minimums.x; dx < offset_maximums.x; dx++){
// o << dx << "," << dy<< "," << differences[dy-offset_minimums.y][dx-offset_minimums.x] << "\n";
if (minimum_offset_difference > differences[dy-offset_minimums.y][dx-offset_minimums.x]){
minimum_offset_difference = differences[dy-offset_minimums.y][dx-offset_minimums.x];
minimum_offset = ns_vector_2i(dx,dy);
}
}
}
// o.close();
return minimum_offset;
}
template<class profile_storage_type_1,class profile_storage_type_2>
static ns_vector_2i register_profiles(const ns_image_registration_profile<profile_storage_type_1> & r , const ns_image_registration_profile<profile_storage_type_2> & a, const ns_vector_2i max_offset = ns_vector_2i(0,0), const std::string & debug_name=""){
if (r.registration_method == ns_full_registration){
return register_full_images(r,a,max_offset);
}
return ns_vector_2i(register_profile(r.horizontal_profile, a.horizontal_profile,r.registration_method,max_offset.x,r.average,a.average,debug_name+"_horiz"),
register_profile(r.vertical_profile, a.vertical_profile,r.registration_method, max_offset.y,r.average,a.average,debug_name+"_vert"));
}
static int register_profile(const ns_image_registation_profile_dimension & r , const ns_image_registation_profile_dimension & a, const ns_registration_method & registration_method,const unsigned int max_offset = 0,const ns_64_bit &r_avg=1,const ns_64_bit & a_avg=1,const std::string & debug_filename=""){
//now we minimize the distance between the rows.
unsigned long h(r.size());
if (h > a.size())
h = a.size();
int minimum_offset = 0;
int d = (int)max_offset;
if (d == 0){
if (h > 10) d = h/10;
else d = h;
}
//ofstream o(std::string("c:\\server\\alignments_")+debug_filename + ".csv");
//o << "offset,diff\n";
//ofstream o2(std::string("c:\\server\\distance_")+debug_filename + ".csv");
//o2 << "registration_shift,x_position,diff,cumulative_diff,r,a\n";
if (registration_method == ns_sum_registration || registration_method == ns_compound_registration){
double minimum_offset_difference = DBL_MAX;
const double aavg(a_avg),
ravg(r_avg);
//test positive offset
for (int i = 0; i < d; i++){
double diff = 0;
for (unsigned int y = d; y < h-d; y++){
diff += fabs(r[y]/ravg-a[y+i]/aavg);
// o2 << i << "," << y << "," << fabs(r[y]/ravg-a[y+i]/aavg) << "," << diff <<","<< r[y]/ravg <<","<< a[y+i]/aavg << "\n";
}
// o << i << "," << diff << "\n";
if (minimum_offset_difference > diff){
minimum_offset_difference = diff;
minimum_offset = i;
}
}
//test negative offset
for (int i = 1; i < d; i++){
double diff = 0;
for (unsigned int y = d; y < h-d; y++){
diff +=fabs(r[y]/ravg-a[y-i]/aavg);
// o2 << -i << "," << y << "," << fabs(r[y]/ravg-a[y-i]/aavg) << "," << diff << ","<<r[y]/ravg <<","<< a[y-i]/aavg << "\n";
}
// o << -i << "," << diff << "\n";
if (minimum_offset_difference > diff){
minimum_offset_difference = diff;
minimum_offset = -i;
}
}
// o.close();
// o2.close();
}
else{
ns_64_bit minimum_offset_difference = (ns_64_bit)(-1);
//test positive offset
for (int i = 0; i < d; i++){
ns_64_bit diff = 0;
for (unsigned int y = d; y < h-d; y++)
diff += (ns_64_bit)ns_64_bit_abs((ns_s64_bit)r[y]-(ns_s64_bit)a[y+i]);
// o << i << "," << diff << "\n";
if (minimum_offset_difference > diff){
minimum_offset_difference = diff;
minimum_offset = i;
}
}
//test negative offset
for (int i = 0; i < d; i++){
ns_64_bit diff = 0;
for (unsigned int y = d; y < h-d; y++)
diff += (ns_64_bit)ns_64_bit_abs((ns_s64_bit)r[y]-(ns_s64_bit)a[y-i]);
// o << -i << "," << diff << "\n";
if (minimum_offset_difference > diff){
minimum_offset_difference = diff;
minimum_offset = -i;
}
}
}
return minimum_offset;
}
template<class profile_storage_type>
static void write_profile(const std::string & name, const ns_image_registration_profile<profile_storage_type> & profile, std::ostream & out){
for (unsigned long i = 0; i < profile.horizontal_profile.size();i++)
out << name << ",horiz," << i << "," << profile.horizontal_profile[i] << "," << profile.horizontal_profile[i]/(double)profile.average << "\n";
for (unsigned long i = 0; i < profile.vertical_profile.size();i++)
out << name << ",vertical," << i << "," << profile.vertical_profile[i] << "," << profile.vertical_profile[i]/(double)profile.average << "\n";
}
static std::string ns_registration_method_string(const ns_registration_method & reg){
switch(reg){
case ns_no_registration: return "none";
case ns_threshold_registration: return "threshold";
case ns_sum_registration: return "sum";
case ns_full_registration: return "full";
case ns_compound_registration: return "compound";
default: throw ns_ex("Unknown");
}
}
};
#endif
|
5c0fcf87f3c2ed3e7b9d151be1793761266acd0b | da1500e0d3040497614d5327d2461a22e934b4d8 | /third_party/skia/src/gpu/gl/GrGLBuffer.cpp | 516c10ea348366b7ff004936896abb0df77e9c6e | [
"BSD-3-Clause",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"Apache-2.0",
"MIT"
] | permissive | youtube/cobalt | 34085fc93972ebe05b988b15410e99845efd1968 | acefdaaadd3ef46f10f63d1acae2259e4024d383 | refs/heads/main | 2023-09-01T13:09:47.225174 | 2023-09-01T08:54:54 | 2023-09-01T08:54:54 | 50,049,789 | 169 | 80 | BSD-3-Clause | 2023-09-14T21:50:50 | 2016-01-20T18:11:34 | null | UTF-8 | C++ | false | false | 11,032 | cpp | GrGLBuffer.cpp | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkTraceMemoryDump.h"
#include "src/gpu/GrGpuResourcePriv.h"
#include "src/gpu/gl/GrGLBuffer.h"
#include "src/gpu/gl/GrGLGpu.h"
#define GL_CALL(X) GR_GL_CALL(this->glGpu()->glInterface(), X)
#define GL_CALL_RET(RET, X) GR_GL_CALL_RET(this->glGpu()->glInterface(), RET, X)
#if GR_GL_CHECK_ALLOC_WITH_GET_ERROR
#define CLEAR_ERROR_BEFORE_ALLOC(iface) GrGLClearErr(iface)
#define GL_ALLOC_CALL(iface, call) GR_GL_CALL_NOERRCHECK(iface, call)
#define CHECK_ALLOC_ERROR(iface) GR_GL_GET_ERROR(iface)
#else
#define CLEAR_ERROR_BEFORE_ALLOC(iface)
#define GL_ALLOC_CALL(iface, call) GR_GL_CALL(iface, call)
#define CHECK_ALLOC_ERROR(iface) GR_GL_NO_ERROR
#endif
#ifdef SK_DEBUG
#define VALIDATE() this->validate()
#else
#define VALIDATE() do {} while(false)
#endif
sk_sp<GrGLBuffer> GrGLBuffer::Make(GrGLGpu* gpu, size_t size, GrGpuBufferType intendedType,
GrAccessPattern accessPattern, const void* data) {
if (gpu->glCaps().transferBufferType() == GrGLCaps::kNone_TransferBufferType &&
(GrGpuBufferType::kXferCpuToGpu == intendedType ||
GrGpuBufferType::kXferGpuToCpu == intendedType)) {
return nullptr;
}
sk_sp<GrGLBuffer> buffer(new GrGLBuffer(gpu, size, intendedType, accessPattern, data));
if (0 == buffer->bufferID()) {
return nullptr;
}
return buffer;
}
// GL_STREAM_DRAW triggers an optimization in Chromium's GPU process where a client's vertex buffer
// objects are implemented as client-side-arrays on tile-deferred architectures.
#define DYNAMIC_DRAW_PARAM GR_GL_STREAM_DRAW
inline static GrGLenum gr_to_gl_access_pattern(GrGpuBufferType bufferType,
GrAccessPattern accessPattern) {
auto drawUsage = [](GrAccessPattern pattern) {
switch (pattern) {
case kDynamic_GrAccessPattern:
// TODO: Do we really want to use STREAM_DRAW here on non-Chromium?
return DYNAMIC_DRAW_PARAM;
case kStatic_GrAccessPattern:
return GR_GL_STATIC_DRAW;
case kStream_GrAccessPattern:
return GR_GL_STREAM_DRAW;
}
SK_ABORT("Unexpected access pattern");
};
auto readUsage = [](GrAccessPattern pattern) {
switch (pattern) {
case kDynamic_GrAccessPattern:
return GR_GL_DYNAMIC_READ;
case kStatic_GrAccessPattern:
return GR_GL_STATIC_READ;
case kStream_GrAccessPattern:
return GR_GL_STREAM_READ;
}
SK_ABORT("Unexpected access pattern");
};
auto usageType = [&drawUsage, &readUsage](GrGpuBufferType type, GrAccessPattern pattern) {
switch (type) {
case GrGpuBufferType::kVertex:
case GrGpuBufferType::kIndex:
case GrGpuBufferType::kXferCpuToGpu:
return drawUsage(pattern);
case GrGpuBufferType::kXferGpuToCpu:
return readUsage(pattern);
}
SK_ABORT("Unexpected gpu buffer type.");
};
return usageType(bufferType, accessPattern);
}
GrGLBuffer::GrGLBuffer(GrGLGpu* gpu, size_t size, GrGpuBufferType intendedType,
GrAccessPattern accessPattern, const void* data)
: INHERITED(gpu, size, intendedType, accessPattern)
, fIntendedType(intendedType)
, fBufferID(0)
, fUsage(gr_to_gl_access_pattern(intendedType, accessPattern))
, fGLSizeInBytes(0)
, fHasAttachedToTexture(false) {
GL_CALL(GenBuffers(1, &fBufferID));
if (fBufferID) {
GrGLenum target = gpu->bindBuffer(fIntendedType, this);
CLEAR_ERROR_BEFORE_ALLOC(gpu->glInterface());
// make sure driver can allocate memory for this buffer
GL_ALLOC_CALL(gpu->glInterface(), BufferData(target,
(GrGLsizeiptr) size,
data,
fUsage));
if (CHECK_ALLOC_ERROR(gpu->glInterface()) != GR_GL_NO_ERROR) {
GL_CALL(DeleteBuffers(1, &fBufferID));
fBufferID = 0;
} else {
fGLSizeInBytes = size;
}
}
VALIDATE();
this->registerWithCache(SkBudgeted::kYes);
if (!fBufferID) {
this->resourcePriv().removeScratchKey();
}
}
inline GrGLGpu* GrGLBuffer::glGpu() const {
SkASSERT(!this->wasDestroyed());
return static_cast<GrGLGpu*>(this->getGpu());
}
inline const GrGLCaps& GrGLBuffer::glCaps() const {
return this->glGpu()->glCaps();
}
void GrGLBuffer::onRelease() {
TRACE_EVENT0("skia.gpu", TRACE_FUNC);
if (!this->wasDestroyed()) {
VALIDATE();
// make sure we've not been abandoned or already released
if (fBufferID) {
GL_CALL(DeleteBuffers(1, &fBufferID));
fBufferID = 0;
fGLSizeInBytes = 0;
}
fMapPtr = nullptr;
VALIDATE();
}
INHERITED::onRelease();
}
void GrGLBuffer::onAbandon() {
fBufferID = 0;
fGLSizeInBytes = 0;
fMapPtr = nullptr;
VALIDATE();
INHERITED::onAbandon();
}
void GrGLBuffer::onMap() {
SkASSERT(fBufferID);
SkASSERT(!this->wasDestroyed());
VALIDATE();
SkASSERT(!this->isMapped());
// TODO: Make this a function parameter.
bool readOnly = (GrGpuBufferType::kXferGpuToCpu == fIntendedType);
// Handling dirty context is done in the bindBuffer call
switch (this->glCaps().mapBufferType()) {
case GrGLCaps::kNone_MapBufferType:
return;
case GrGLCaps::kMapBuffer_MapBufferType: {
GrGLenum target = this->glGpu()->bindBuffer(fIntendedType, this);
if (!readOnly) {
// Let driver know it can discard the old data
if (this->glCaps().useBufferDataNullHint() || fGLSizeInBytes != this->size()) {
GL_CALL(BufferData(target, this->size(), nullptr, fUsage));
}
}
GL_CALL_RET(fMapPtr, MapBuffer(target, readOnly ? GR_GL_READ_ONLY : GR_GL_WRITE_ONLY));
break;
}
case GrGLCaps::kMapBufferRange_MapBufferType: {
GrGLenum target = this->glGpu()->bindBuffer(fIntendedType, this);
// Make sure the GL buffer size agrees with fDesc before mapping.
if (fGLSizeInBytes != this->size()) {
GL_CALL(BufferData(target, this->size(), nullptr, fUsage));
}
GrGLbitfield access;
if (readOnly) {
access = GR_GL_MAP_READ_BIT;
} else {
access = GR_GL_MAP_WRITE_BIT;
if (GrGpuBufferType::kXferCpuToGpu != fIntendedType) {
// TODO: Make this a function parameter.
access |= GR_GL_MAP_INVALIDATE_BUFFER_BIT;
}
}
GL_CALL_RET(fMapPtr, MapBufferRange(target, 0, this->size(), access));
break;
}
case GrGLCaps::kChromium_MapBufferType: {
GrGLenum target = this->glGpu()->bindBuffer(fIntendedType, this);
// Make sure the GL buffer size agrees with fDesc before mapping.
if (fGLSizeInBytes != this->size()) {
GL_CALL(BufferData(target, this->size(), nullptr, fUsage));
}
GL_CALL_RET(fMapPtr, MapBufferSubData(target, 0, this->size(),
readOnly ? GR_GL_READ_ONLY : GR_GL_WRITE_ONLY));
break;
}
}
fGLSizeInBytes = this->size();
VALIDATE();
}
void GrGLBuffer::onUnmap() {
SkASSERT(fBufferID);
VALIDATE();
SkASSERT(this->isMapped());
if (0 == fBufferID) {
fMapPtr = nullptr;
return;
}
// bind buffer handles the dirty context
switch (this->glCaps().mapBufferType()) {
case GrGLCaps::kNone_MapBufferType:
SkDEBUGFAIL("Shouldn't get here.");
return;
case GrGLCaps::kMapBuffer_MapBufferType: // fall through
case GrGLCaps::kMapBufferRange_MapBufferType: {
GrGLenum target = this->glGpu()->bindBuffer(fIntendedType, this);
GL_CALL(UnmapBuffer(target));
break;
}
case GrGLCaps::kChromium_MapBufferType:
this->glGpu()->bindBuffer(fIntendedType, this); // TODO: Is this needed?
GL_CALL(UnmapBufferSubData(fMapPtr));
break;
}
fMapPtr = nullptr;
}
bool GrGLBuffer::onUpdateData(const void* src, size_t srcSizeInBytes) {
SkASSERT(fBufferID);
if (this->wasDestroyed()) {
return false;
}
SkASSERT(!this->isMapped());
VALIDATE();
if (srcSizeInBytes > this->size()) {
return false;
}
SkASSERT(srcSizeInBytes <= this->size());
// bindbuffer handles dirty context
GrGLenum target = this->glGpu()->bindBuffer(fIntendedType, this);
if (this->glCaps().useBufferDataNullHint()) {
if (this->size() == srcSizeInBytes) {
GL_CALL(BufferData(target, (GrGLsizeiptr) srcSizeInBytes, src, fUsage));
} else {
// Before we call glBufferSubData we give the driver a hint using
// glBufferData with nullptr. This makes the old buffer contents
// inaccessible to future draws. The GPU may still be processing
// draws that reference the old contents. With this hint it can
// assign a different allocation for the new contents to avoid
// flushing the gpu past draws consuming the old contents.
// TODO I think we actually want to try calling bufferData here
GL_CALL(BufferData(target, this->size(), nullptr, fUsage));
GL_CALL(BufferSubData(target, 0, (GrGLsizeiptr) srcSizeInBytes, src));
}
fGLSizeInBytes = this->size();
} else {
// Note that we're cheating on the size here. Currently no methods
// allow a partial update that preserves contents of non-updated
// portions of the buffer (map() does a glBufferData(..size, nullptr..))
GL_CALL(BufferData(target, srcSizeInBytes, src, fUsage));
fGLSizeInBytes = srcSizeInBytes;
}
VALIDATE();
return true;
}
void GrGLBuffer::setMemoryBacking(SkTraceMemoryDump* traceMemoryDump,
const SkString& dumpName) const {
SkString buffer_id;
buffer_id.appendU32(this->bufferID());
traceMemoryDump->setMemoryBacking(dumpName.c_str(), "gl_buffer",
buffer_id.c_str());
}
#ifdef SK_DEBUG
void GrGLBuffer::validate() const {
SkASSERT(0 != fBufferID || 0 == fGLSizeInBytes);
SkASSERT(nullptr == fMapPtr || fGLSizeInBytes <= this->size());
}
#endif
|
3eccfa4d1c8cc6db08ab39de570657a57117178e | 574ceb7088c8f3e87f77af496a0fc47a00a2d8e0 | /src/CommandQueue.cpp | fcd79216808c3af27890994b7724a545d461554e | [] | no_license | dentou/EEIT2015_Group4_ACertainSideScrollingGame | 11dcb328507893f0ac5c1858c761fbbe59d00b49 | e5e610f6074ee0670969474581de6f960b3848e9 | refs/heads/master | 2021-06-19T04:53:16.906650 | 2017-06-10T10:35:51 | 2017-06-10T10:35:51 | 93,761,183 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | CommandQueue.cpp | /***********************************************************************************
* CommandQueue.cpp
* C++ Final Project - A Certain Side Scrolling Game
* Vietnamese-German University
* Authors: Tran Tien Huy, Nguyen Huy Thong - EEIT2015
************************************************************************************
* Description:
* Implementation file for class CommandQueue.
************************************************************************************/
#include "include/CommandQueue.hpp"
void CommandQueue::push(const Command& command)
{
mQueue.push(command);
}
Command CommandQueue::pop()
{
Command command = mQueue.front();
mQueue.pop();
return command;
}
bool CommandQueue::isEmpty() const
{
return mQueue.empty();
}
|
6221c281c5428ede439935997d95cf3fa3303a56 | 27270a8a96986f7ddc38834a498faaf486b471fb | /MFCApplication1/DBOperation.cpp | 4ded33c580f572670cd3f414a5f1dd9ac807b945 | [] | no_license | photoqiu/private_IOTProject | a7b1259e984ea9ab78b72e99aa35d24ecd7becec | fb96a11c9cf5768f8b528e051b4db56b29184023 | refs/heads/master | 2020-12-01T13:58:27.946218 | 2020-01-05T21:30:39 | 2020-01-05T21:30:39 | 230,650,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,864 | cpp | DBOperation.cpp | #include "stdafx.h"
#include "DBOperation.h"
DBOperation::DBOperation()
{
}
DBOperation::~DBOperation()
{
}
int DBOperation::setLaserCamerasResult()
{
return 0;
}
int DBOperation::setVideoCamerasResult()
{
try {
sql::Driver *driver;
sql::PreparedStatement *pstmt;
/* Create a connection */
driver = get_driver_instance();
/* Connect to the MySQL test database */
std::auto_ptr< sql::Connection > con(driver->connect("tcp://127.0.0.1:3306", "root", "123456"));
con->setSchema("laser_datas");
// std::auto_ptr< sql::PreparedStatement > pstmt;
pstmt = con->prepareStatement("INSERT INTO laser_datas(id) VALUES (?)");
pstmt->setInt(1, 0);
pstmt->executeUpdate();
delete pstmt;
/*
TRUNCATE `hg_detection_db`.`camerasinfo`
TRUNCATE `hg_detection_db`.`laserinfo`
ANALYZE TABLE `camerasinfo`, `laserinfo`, `steelpipeinfo`
CHECK TABLE `camerasinfo`, `laserinfo`, `steelpipeinfo`
CHECKSUM TABLE `camerasinfo`, `laserinfo`, `steelpipeinfo`
OPTIMIZE TABLE `camerasinfo`, `laserinfo`, `steelpipeinfo`
REPAIR TABLE `camerasinfo`, `laserinfo`, `steelpipeinfo`
pstmt.reset(con->prepareStatement("CALL add_country(?,?,?)"));
pstmt->setString(1, code_vector[i]);
pstmt->setString(2, name_vector[i]);
pstmt->setString(3, cont_vector[i]);
pstmt->execute();
*/
}
catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line » " << __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
int DBOperation::getVideoCamerasResult()
{
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "123456");
/* Connect to the MySQL test database */
con->setSchema("laser_datas");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column data by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
}
catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line » "<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
int DBOperation::getLaserCamerasResult()
{
return EXIT_SUCCESS;
}
|
67f176447ddfeae80d373459d74c254309840157 | 3d15826fc8c937aec0be4fcf4b8edc06bb413fc7 | /src/utils.cpp | e22856b0a859ce8d3056791d5313ce651fd507a0 | [
"Zlib"
] | permissive | Parad0xPl/SimplePlayer | 38ddd50ebfd2945b3fdee53796eba33eede38eb7 | f6bad66881fa3cb5bf379fceed8c993b56c526a4 | refs/heads/master | 2022-11-27T22:04:52.751642 | 2020-07-27T17:39:30 | 2020-07-27T17:39:30 | 282,969,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | utils.cpp | #include "utils.hpp"
#include <cstdio>
#include <cstdint>
#include <cstring>
void PrintBuffer(void *data, int len){
const auto p = static_cast<uint8_t*>(data);
int i;
for (i = 0; i < len; i++)
{
if (i > 0) printf(":");
printf("%02X", p[i]);
}
printf("\n");
}
void PrintBufferMax(void *data, int len1, int len2){
int len = len1>len2 ? len2 : len1;
PrintBuffer(data, len);
}
void PrintAudioFloat(void *data, int len){
const auto p = static_cast<float*>(data);
int i;
for (i = 0; i < len; i++)
{
if (i > 0) printf(":");
printf("%F", p[i]);
}
printf("\n");
}
void MixPlanarAudio(uint8_t** src, uint8_t* dst,
int sampleSize, int nb){
int i;
uint8_t *pt = dst;
for(i=0;i<nb;i++){
memcpy(pt, src[0]+i*sampleSize, sampleSize);
pt+=sampleSize;
memcpy(pt, src[1]+i*sampleSize, sampleSize);
pt+=sampleSize;
}
// for(i=0;i<linesizes[0];i++){
// ((uint32_t*) dst)[i] = ((uint32_t*) src[0])[i];
// // ((uint32_t*) dst)[i << 1] = ((uint32_t*) src[0])[i];
// }
} |
0c23fbcbc30c4ed00750a43a75eeed312ed21bcb | d1ec47ff6acacb9f5368064e4c87f8d3770b016b | /contests/雑多/old_rep/cfnob.cpp | bbdca46f053ed8d72bbf0d313328f0f1473b59ad | [] | no_license | fj0rdingz/Competive_Programming | 8bca0870311b348ea4c38d134f73346edceadf15 | 3dc42a85b7c9f4e77ba8c5488d84fb0f1f3ac75c | refs/heads/master | 2021-10-29T02:25:52.820526 | 2021-10-25T06:23:29 | 2021-10-25T06:23:29 | 252,177,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,295 | cpp | cfnob.cpp | #include <cstdio>
#include <queue>
#include <iostream>
#include <bits/stdc++.h>
#include<stdio.h>
#include<string.h>
#include<fstream>
#define F first
#define S second
#define R cin>>
#define Z class
#define ll long long
#define ln cout<<'\n'
#define in(a) insert(a)
#define pb(a) push_back(a)
#define pd(a) printf("%.10f\n",a)
#define mem(a) memset(a,0,sizeof(a))
#define all(c) (c).begin(),(c).end()
#define iter(c) __typeof((c).begin())
#define rrep(i,n) for(ll i=(ll)(n)-1;i>=0;i--)
#define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++)
#define rep(i,n) REP(i,0,n)
#define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++)
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int i,j,k,q=1;
long n,tmp;
double m;
double moji;
string s[200000];
ll sum=0;
int strr[200005];
cin>>n;
rep(i,n){
int wins=0;
int pw,rw,sw;
int ar,ap,as;
int br=0,bp=0,bs=0;
string str;
cin>>m;
moji=m;
m=m/2;
m=round(m);
cin>>ar>>ap>>as;
cin>>str;
for(j=0;j<str.length();j++){
if(str[j]=='R') br++;
else if(str[j]=='P') bp++;
else if(str[j]=='S') bs++;
}
//cout<<br<<bp<<bs;
if(br<=ap){
wins=br;
pw=br;
}else{
wins=ap;
pw=ap;
}
if(bp<=as){
wins+=bp;
sw=bp;
}else{
wins+=as;
sw=as;
}
if(bs<=ar){
wins+=bs;
rw=bs;
}else{
wins+=ar;
rw=ar;
}
//cout<<wins;
if(m>wins){
cout<<"NO"<<endl;
}else{
cout<<"YES"<<endl;
int py,ry,sy;
py=ap-pw;
ry=ar-rw;
sy=as-sw;
rep(l,moji){
if(str[l]=='R') {
if(pw>0){
pw--;
cout<<"P";
}else{
if(ry>0){
ry--;
cout<<"R";
}else{
sy--;
cout<<"S";
}
}
}
else if(str[l]=='P') {
if(sw>0){
sw--;
cout<<"S";
}else{
if(ry>0){
ry--;
cout<<"R";
}else{
py--;
cout<<"P";
}
}
}
else if(str[l]=='S') {
if(rw>0){
rw--;
cout<<"R";
}else{
if(sy>0){
sy--;
cout<<"S";
}else{
py--;
cout<<"P";
}
}
}
}
cout<<endl;
}
}
return 0;
} |
6998296022af570cf9b04fe611d312f5bef4f104 | f15ba67850dceb5df5250deffa95cde64ec9d1aa | /CS116/File Diagram/main.cpp | 77ae2c538e54356dae9f582045f0a56969eeb9aa | [] | no_license | Syilun/SlopBukkit | f0b48af0ecc17c670653f1147065a84876248f8d | 6faac40f00915cfb9499ec59228bf8eb259a34ab | refs/heads/master | 2023-03-18T23:02:56.965863 | 2014-05-21T21:10:09 | 2014-05-21T21:10:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,136 | cpp | main.cpp | /*! Chris Miller (cmiller@fsdev.net), CS116
*! Copyright (C) 2009 FSDEV. Aw richts pitten by.
*! Academic endorsement. This code is not licensed for commercial use.
*! 20091010, Ch. 12 Asgn
*/
#include "Simple_window.h"
#include "Graph.h"
int main (int argc, char * const argv[]) {
using namespace Graph_lib;
int d,x;
fl_measure("foo",d,x);
Point t1(100,100);
Simple_window win(t1,780,620,"File Diagram");
// cheap hack
Image ii(Point(50,50),"../../filegraph.jpg");
win.attach(ii);
win.wait_for_button();
// Point.h
// title text origin: (74,49) +50 = (124,99)
// box origin: (73,54) +50 = (123,104)
// box dimensions: (138,29)
// internal text origin: (80,74) +50 = (130,124)
Text point_h_title(Point(124,85),"Point.h:");
point_h_title.set_color(Color::black);
win.attach(point_h_title);
Rectangle point_h_box(Point(123,104),138,29);
point_h_box.set_fill_color(Color::dark_yellow);
win.attach(point_h_box);
Text point_h_content(Point(130,110), "struct Point { ... };");
point_h_content.set_color(Color::black);
win.attach(point_h_content);
// FLTK Headers
// box1 origin: (305,10) +50 = (355,60)
// box2 origin: (310,15) +50 = (360,65)
// box3 origin: (315,20) +50 = (365,70)
// box dimensions: (100,35)
// FLTK Headers label origin: (325,25) +50 = (375,75)
Rectangle fltk_headers_box1(Point(355,60),100,35); Rectangle fltk_headers_box2(Point(360,65),100,35);
Rectangle fltk_headers_box3(Point(365,70),100,35); fltk_headers_box1.set_fill_color(Color::dark_yellow);
fltk_headers_box2.set_fill_color(Color::dark_yellow); fltk_headers_box3.set_fill_color(Color::dark_yellow);
win.attach(fltk_headers_box1); win.attach(fltk_headers_box2); win.attach(fltk_headers_box3);
Text fltk_headers_label1(Point(369,75),"FLTK Headers"); fltk_headers_label1.set_color(Color::black);
win.attach(fltk_headers_label1);
// FLTK Code
// box1 origin: (468,55) +50 = (518,105)
// box2 origin: (472,60) +50 = (522,110)
// box3 origin: (477,65) +50 = (527,115)
// box dimensions: (81,37)
// FLTK Code label origin: (484,71) +50 = (534,121)
// arrow1 origin: (465,76) +50 = (515,126)
// arrow1 terminus: (414,40) +50 = (464,90)
// arrow1 point1: (418,45) +50 = (468,95)
// arrow1 point2: (420,40) +50 = (469,90)
Rectangle fltk_code_box1(Point(518,105),81,37); Rectangle fltk_code_box2(Point(522,110),81,37);
Rectangle fltk_code_box3(Point(527,115),81,37); fltk_code_box1.set_fill_color(Color::dark_yellow);
fltk_code_box2.set_fill_color(Color::dark_yellow); fltk_code_box3.set_fill_color(Color::dark_yellow);
win.attach(fltk_code_box1); win.attach(fltk_code_box2); win.attach(fltk_code_box3);
Text fltk_code_label1(Point(532,121),"FLTK Code"); fltk_code_label1.set_color(Color::black);
win.attach(fltk_code_label1);
Open_polyline arrow1;
arrow1.set_color(Color::black);
arrow1.add(Point(518,126)); arrow1.add(Point(464,90)); arrow1.add(Point(468,97));
arrow1.add(Point(469,90)); arrow1.add(Point(464,90)); win.attach(arrow1);
// Window.h
// box origin: (284,126) +50 = (334,176)
// box dimensions: (143,61)
// title label origin: (282,106) +50 = (332,156)
// window interface label origin: (292,132) +50 = (342,182)
// class window label origin: (292,148) +50 = (342,198)
// em dash label origin: (292,166) +50 = (342,216)
// arrow2 origin: (300,126) +50 = (350,176)
// arrow2 terminus: (185,82) +50 = (235,132)
// arrow2 point1: (190,88) +50 = (240,138)
// arrow2 point2: (192,82) +50 = (242,132)
// arrow3 origin: (362,126) +50 = (412,176)
// arrow3 terminus: (361,58) +50 = (412,108)
// arrow3 point1: (359,64) +50 = (409,114)
// arrow3 point2: (364,64) +50 = (414,114)
Rectangle window_h_box(Point(334,176),143,61);
window_h_box.set_fill_color(Color::dark_yellow); win.attach(window_h_box);
Text window_h_title(Point(332,156),"Window.h:");
window_h_title.set_color(Color::black); win.attach(window_h_title);
Text window_h_label1(Point(342,182),"// window interface:");
window_h_label1.set_color(Color::black); win.attach(window_h_label1);
Text window_h_label2(Point(342,198),"class Window {...};");
window_h_label2.set_color(Color::black); win.attach(window_h_label2);
Text window_h_label3(Point(342,214),"...");
window_h_label3.set_color(Color::black); win.attach(window_h_label3);
Open_polyline arrow2;
arrow2.set_color(Color::black);
arrow2.add(Point(350,176)); arrow2.add(Point(235,132)); arrow2.add(Point(240,138));
arrow2.add(Point(242,132)); arrow2.add(Point(235,132)); win.attach(arrow2);
Open_polyline arrow3;
arrow3.set_color(Color::black);
arrow3.add(Point(412,176)); arrow3.add(Point(412,108)); arrow3.add(Point(409,114));
arrow3.add(Point(414,114)); arrow3.add(Point(412,108)); win.attach(arrow3);
// Graph.h
// title '(Graph.h:) origin: (70,148) +50 = (120,198)
// box origin: (72,168) +50 = (122,218)
// box dimensions: (150,60)
// label1 '(// graphing interface:) origin: (80,174) +50 = (130,224)
// label2 '(struct Shape {...};) origin: (80,190) +50 = (130,240)
// label3 '(...) origin: (80,206) +50 = (130,256)
// arrow4 origin: (145,168) +50 = (195,218)
// arrow4 terminus: (145,84) +50 = (195,134)
// arrow4 point1: (142,89) +50 = (192,139)
// arrow4 point2: (148,90) +50 = (198,140)
// arrow5 origin: (145,168) +50 = (195,218)
// arrow5 terminus: (322,58) +50 = (372,108)
// arrow5 point1: (314,60) +50 = (364,110)
// arrow5 point2: (318,64) +50 = (368,114)
Text graph_h_title(Point(120,198),"Graph.h:"); graph_h_title.set_color(Color::black);
win.attach(graph_h_title);
Rectangle graph_h_box(Point(122,218),150,60); graph_h_box.set_fill_color(Color::dark_yellow);
win.attach(graph_h_box);
Text graph_h_label1(Point(130,224),"// graphing interface:"); graph_h_label1.set_color(Color::black);
win.attach(graph_h_label1);
Text graph_h_label2(Point(130,240),"struct Shape {...};"); graph_h_label2.set_color(Color::black);
win.attach(graph_h_label2);
Text graph_h_label3(Point(130,256),"..."); graph_h_label3.set_color(Color::black);
win.attach(graph_h_label3);
Open_polyline arrow4; arrow4.set_color(Color::black);
arrow4.add(Point(195,218)); arrow4.add(Point(195,134)); arrow4.add(Point(192,139));
arrow4.add(Point(198,140)); arrow4.add(Point(195,134)); win.attach(arrow4);
Open_polyline arrow5; arrow5.set_color(Color::black);
arrow5.add(Point(195,218)); arrow5.add(Point(372,108)); arrow5.add(Point(364,110));
arrow5.add(Point(368,114)); arrow5.add(Point(372,108)); win.attach(arrow5);
// GUI.h
// title '(GUI.h:) origin: (405,206) +50 = (455,256)
// box origin: (407,225) +50 = (457,275)
// box dimensions: (145,60)
// label1 '(// GUI interface:) origin: (414,230) +50 = (464,280)
// label2 '(struct In_box {...};) origin: (414,246) +50 = (464,296)
// label3 '(...) origin: (414,262) +50 = (464,312)
// arrow6 origin: (506,225) +50 = (556,275)
// arrow6 terminus: (422,186) +50 = (472,236)
// arrow6 point1: (425,192) +50 = (475,242)
// arrow6 point2: (428,188) +50 = (478,238)
// arrow7 origin: (506,225) +50 = (556,275)
// arrow7 terminus: (390,58) +50 = (440,108)
// arrow7 point1: (392,65) +50 = (442,115)
// arrow7 point2: (398,62) +50 = (448,112)
Text gui_h_title(Point(455,256),"GUI.h:"); gui_h_title.set_color(Color::black);
win.attach(gui_h_title);
Rectangle gui_h_box(Point(457,275),145,60); gui_h_box.set_fill_color(Color::dark_yellow);
win.attach(gui_h_box);
Text gui_h_label1(Point(464,280),"// GUI interface:"); gui_h_label1.set_color(Color::black);
Text gui_h_label2(Point(464,296),"struct In_box {...};"); gui_h_label2.set_color(Color::black);
Text gui_h_label3(Point(464,312),"..."); gui_h_label3.set_color(Color::black);
win.attach(gui_h_label1); win.attach(gui_h_label2); win.attach(gui_h_label3);
Open_polyline arrow6; Open_polyline arrow7;
arrow6.set_color(Color::black); arrow7.set_color(Color::black);
arrow6.add(Point(556,275)); arrow6.add(Point(472,236)); arrow6.add(Point(475,242));
arrow6.add(Point(478,236)); arrow6.add(Point(472,236)); win.attach(arrow6);
arrow7.add(Point(556,275)); arrow7.add(Point(440,108)); arrow7.add(Point(442,115));
arrow7.add(Point(448,112)); arrow7.add(Point(440,108)); win.attach(arrow7);
// window.cpp
// title '(window.cpp:) origin: (190,248) +50 = (240,298)
// box origin: (193,266) +50 = (243,316)
// box dimensions: (114,28)
// label1 '(Window code) origin: (200,270) +50 = (250,320)
// arrow8 origin: (282,266) +50 = (332,316)
// arrow8 terminus: (337,187) +50 = (387,237)
// arrow8 point1: (330,192) +50 = (380,242)
// arrow8 point2: (336,194) +50 = (386,244)
Text window_cpp_title(Point(240,298),"window.cpp:"); window_cpp_title.set_color(Color::black);
win.attach(window_cpp_title);
Rectangle window_cpp_box(Point(243,316),114,28); window_cpp_box.set_fill_color(Color::dark_yellow);
win.attach(window_cpp_box);
Text window_cpp_label1(Point(250,320),"Window code"); window_cpp_label1.set_color(Color::black);
win.attach(window_cpp_label1);
Open_polyline arrow8; arrow8.set_color(Color::black);
arrow8.add(Point(332,316)); arrow8.add(Point(387,237)); arrow8.add(Point(380,242));
arrow8.add(Point(386,244)); arrow8.add(Point(387,237)); win.attach(arrow8);
// Graph.cpp
// title '(Graph.cpp:) origin: (21,313) +50 = (71,363)
// box origin: (22,330) +50 = (72,380)
// box dimensions: (97,27)
// label1 '(Graph code) origin: (30,336) +50 = (80,386)
// arrow9 origin: (102,330) +50 = (152,380)
// arrow9 terminus: (142,230) +50 = (192,280)
// arrow9 point1: (136,234) +50 = (186,284)
// arrow9 point2: (142,237) +50 = (192,287)
Text graph_cpp_title(Point(71,363),"Graph.cpp:"); graph_cpp_title.set_color(Color::black);
win.attach(graph_cpp_title);
Rectangle graph_cpp_box(Point(72,380),97,27); graph_cpp_box.set_fill_color(Color::dark_yellow);
win.attach(graph_cpp_box);
Text graph_cpp_label1(Point(80,386),"Graph code"); graph_cpp_label1.set_color(Color::black);
win.attach(graph_cpp_label1);
Open_polyline arrow9; arrow9.set_color(Color::black);
arrow9.add(Point(152,380)); arrow9.add(Point(192,280)); arrow9.add(Point(186,284));
arrow9.add(Point(192,287)); arrow9.add(Point(192,280)); win.attach(arrow9);
// GUI.cpp
// title '(GUI.cpp:) origin: (432,312) +50 = (482,362)
// box origin: (433,330) +50 = (483,380)
// box dimensions: (85,25)
// label1 '(GUI code) origin: (440,335) +50 = (490,385)
// arrow10 origin: (500,330) +50 = (550,380)
// arrow10 terminus: (483,286) +50 = (533,336)
// arrow10 point1: (483,291) +50 = (533,341)
// arrow10 point2: (489,291) +50 = (539,341)
Text gui_cpp_title(Point(482,362),"GUI.cpp:"); gui_cpp_title.set_color(Color::black);
win.attach(gui_cpp_title);
Rectangle gui_cpp_box(Point(483,380),85,25); gui_cpp_box.set_fill_color(Color::dark_yellow);
win.attach(gui_cpp_box);
Text gui_cpp_label1(Point(490,385),"GUI code"); gui_cpp_label1.set_color(Color::black);
win.attach(gui_cpp_label1);
Open_polyline arrow10; arrow10.set_color(Color::black);
arrow10.add(Point(550,380)); arrow10.add(Point(533,336)); arrow10.add(Point(533,341));
arrow10.add(Point(539,341)); arrow10.add(Point(533,336)); win.attach(arrow10);
// Simple_window.h
// title '(Simple_window.h:) origin: (218,321) +50 = (268,371)
// box origin: (220,340) +50 = (270,390)
// box dimensions: (193,60)
// label1 '(// window interface:) origin: (227,344) +50 = (277,394)
// label2 '(class Simple_window {...};) origin: (227,360) +50 = (277,410)
// label3 '(...) origin: (227,376) +50 = (277,426)
// arrow11 origin: (360,340) +50 = (410,390)
// arrow11 terminus: (360,187) +50 = (410,237)
// arrow11 point1: (358,193) +50 = (408,243)
// arrow11 point2: (362,193) +50 = (412,243)
// arrow12 origin: (360,340) +50 = (410,390)
// arrow12 terminus: (422,286) +50 = (472,336)
// arrow12 point1: (415,288) +50 = (465,338)
// arrow12 point2: (419,293) +50 = (469,343)
Text simple_window_h_title(Point(268,371),"Simple_window.h"); simple_window_h_title.set_color(Color::black);
win.attach(simple_window_h_title);
Rectangle simple_window_h_box(Point(270,390),193,60); simple_window_h_box.set_fill_color(Color::dark_yellow);
win.attach(simple_window_h_box);
Text simple_window_h_label1(Point(277,394),"// window interface:"); simple_window_h_label1.set_color(Color::black);
Text simple_window_h_label2(Point(277,410),"class Simple_window {...};"); simple_window_h_label2.set_color(Color::black);
Text simple_window_h_label3(Point(277,426),"..."); simple_window_h_label3.set_color(Color::black);
win.attach(simple_window_h_label1); win.attach(simple_window_h_label2); win.attach(simple_window_h_label3);
Open_polyline arrow11; Open_polyline arrow12;
arrow11.set_color(Color::black); arrow12.set_color(Color::black);
arrow11.add(Point(410,390)); arrow11.add(Point(410,237)); arrow11.add(Point(408,243));
arrow11.add(Point(412,243)); arrow11.add(Point(410,237)); win.attach(arrow11);
arrow12.add(Point(410,390)); arrow12.add(Point(472,336)); arrow12.add(Point(465,338));
arrow12.add(Point(469,343)); arrow12.add(Point(472,336)); win.attach(arrow12);
// chapter12.cpp
// title '(chapter12.cpp:) origin: (89,426) +50 = (139,476)
// box origin: (92,446) +50 = (142,496)
// box dimensions: (210,60)
// label1 '(#include "Graph.h") origin: (100,448) +50 = (150,498)
// label2 '(#include "Simple_window.h") origin: (100,464) +50 = (150,514)
// label3 '(int main() {...}) origin: (100,480) +50 = (150,530)
// arrow13 origin: (200,446) +50 = (250,496)
// arrow13 terminus: (148,230) +50 = (198,280)
// arrow13 point1: (148,236) +50 = (198,286)
// arrow13 point2: (152,235) +50 = (202,285)
// arrow14 origin: (200,446) +50 = (250,496)
// arrow14 terminus: (244,402) +50 = (294,452)
// arrow14 point1: (237,404) +50 = (287,454)
// arrow14 point2: (240,407) +50 = (290,457)
Text chapter12_cpp_title(Point(139,476),"chapter12.cpp:"); chapter12_cpp_title.set_color(Color::black);
win.attach(chapter12_cpp_title);
Rectangle chapter12_cpp_box(Point(142,496),210,60); chapter12_cpp_box.set_fill_color(Color::dark_yellow);
win.attach(chapter12_cpp_box);
Text chapter12_cpp_label1(Point(150,498),"#include \"Graph.h\""); chapter12_cpp_label1.set_color(Color::black);
Text chapter12_cpp_label2(Point(150,514),"#include \"Simple_window.h\""); chapter12_cpp_label2.set_color(Color::black);
Text chapter12_cpp_label3(Point(150,530),"int main() {...}"); chapter12_cpp_label3.set_color(Color::black);
win.attach(chapter12_cpp_label1); win.attach(chapter12_cpp_label2); win.attach(chapter12_cpp_label3);
Open_polyline arrow13; Open_polyline arrow14;
arrow13.set_color(Color::black); arrow14.set_color(Color::black);
arrow13.add(Point(250,496)); arrow13.add(Point(198,280)); arrow13.add(Point(198,286));
arrow13.add(Point(202,285)); arrow13.add(Point(198,280)); win.attach(arrow13);
arrow14.add(Point(250,496)); arrow14.add(Point(294,452)); arrow14.add(Point(287,454));
arrow14.add(Point(290,457)); arrow14.add(Point(294,452)); win.attach(arrow14);
win.wait_for_button();
win.detach(ii);
win.wait_for_button();
return 0;
}
|
d47edaff9027ba3eac99c63dff24fc960c3476ac | b1f4b7f5d4345fb555f1a38f0b512aef25f68f0d | /Door Sensor.ino | d4913e803c284d1fdd04145b4df79e7af2e770b2 | [] | no_license | oliverbonner/Team-Challenge | b24b744c5407b66a6d49ce1210e63830a4f15ef0 | 42e24c2323c588e5b10f72adfa8a272e1543c9b2 | refs/heads/master | 2016-09-05T13:53:41.226502 | 2015-08-24T16:56:29 | 2015-08-24T16:56:29 | 41,271,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | ino | Door Sensor.ino | //SYSTEM_MODE(MANUAL);
int led = D7;
int sensor = D3;
volatile int door_state = LOW;
char publishString[255];
void setup()
{
pinMode(led, OUTPUT);
pinMode(sensor, INPUT);
}
void loop()
{
//when we turn on or finish publishing data, go to sleep
System.sleep(sensor, CHANGE);
//when we wake up check the sensor and (in debug mode) write to the LED
wakeup();
digitalWrite(led, door_state);
//connect to the cloud, we need to wait to be connected before publishing
Spark.connect();
while(!Spark.connected())
{
Spark.process();
delay(50);
}
delay(500);
//publish the door state
publish_data();
}
void wakeup(void)
{
if(digitalRead(sensor) == 1)
{
door_state = HIGH;
}
else
{
door_state = LOW;
}
}
void publish_data(void)
{
sprintf(publishString,"door_state: %d", door_state);
Spark.publish("Door State", publishString);
//delay(PUBLISH_DELAY);
}
|
1f6bb2408b125035fb640e4c8c8a59b75eced407 | aceaf048853cba0c0392ad089bea22f9e3528098 | /_tutorials/code/more-files/src/foo/foo.cpp | 8b07d9e36a694913260ba8c1541f9c1c0b028e63 | [
"MIT"
] | permissive | hutscape/hutscape.github.io | c5b640bbfda21b9bc7260b5d2f6164c60ff9158a | 27c5d8a79d48025d3270fea704df7a5e5cb43f5d | refs/heads/master | 2023-02-13T04:05:12.235290 | 2023-02-01T05:37:53 | 2023-02-01T05:37:53 | 176,517,102 | 40 | 38 | MIT | 2021-07-15T07:02:01 | 2019-03-19T13:23:46 | C++ | UTF-8 | C++ | false | false | 63 | cpp | foo.cpp | #include "foo.h"
void bar() {
SerialUSB.println("bar");
}
|
8b3d7465809ced7a1067fff93f51b7f950f04875 | 919ca405d742a4e97439f80196a267b3d86a4117 | /.history/src/tools_20200203111240.cpp | f48d12ee3a5e1bd3d9c079e068b2abf6e30b20c6 | [
"MIT"
] | permissive | fratullii/CarND-Extended-Kalman-Filter-Project | 62211acdd63d9f4555e74067b85d9898a41e75a6 | 919c015a465d51d91583e512253adff1a372c36c | refs/heads/master | 2020-12-26T08:02:19.984918 | 2020-02-10T11:24:39 | 2020-02-10T11:24:39 | 237,441,025 | 1 | 0 | MIT | 2020-01-31T13:58:46 | 2020-01-31T13:58:45 | null | UTF-8 | C++ | false | false | 691 | cpp | tools_20200203111240.cpp | #include "tools.h"
#include <iostream>
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
/**
* TODO: Calculate the RMSE here.
*/
}
MatrixXd Tools::CalculateProcNoiseCov(const long long &dt,
const long long &sigma_ax,
const long long &sigma_ay){
/**
* TODO: Calculate Q here
*/
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
/**
* TODO:
* Calculate a Jacobian here.
*/
}
|
011390eba5fd36815980a29d4a8d79c7526a51c2 | 6f3e4c3afc10728d2c3b5d771dbd5e09129f81cb | /src/main.cpp | 43851f796ac1a4a587a25270403015fc34decf98 | [] | no_license | AdamNEvans/colorSortingEA | c2781d77d1bb6260a00f64eb8c9dc71fd51000ee | 08c85fcabc0fecd57890d8f9d118c6a747dd409b | refs/heads/master | 2021-08-24T14:04:09.029337 | 2017-12-10T04:10:08 | 2017-12-10T04:10:08 | 113,683,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,431 | cpp | main.cpp | #include <stdio.h>
#include <stdlib.h>
#include "config.h"
#include "ea.h"
// ============================================================================
// Main function. If a configuration file is not given, then
// "configurations/default.cfg" is used
// @param argc Size of argv
// @param argv argv[0] = program name
// argv[1] = config file (optional)
// ============================================================================
int main(int argc, char* argv[])
{
// ---------------------------------------
// command line argument validation
// ---------------------------------------
char defaultConfigFile[] = "configurations/default.cfg";
char* configFilename = NULL;
switch (argc)
{
case 1: configFilename = &defaultConfigFile[0]; break;
case 2: configFilename = argv[1]; break;
default:
printf("Usage: %s [configFile]\n", argv[0]);
return 1;
}
// ---------------------------------------
// load the config
// ---------------------------------------
Config config = Config(configFilename);
config.print(stdout);
srandom(config.seed);
// ---------------------------------------
// run the EA
// ---------------------------------------
executeEA(&config);
// ---------------------------------------
return 0;
}
// ============================================================================
|
eb5b35083ee045fb57c3f5d403103cc322c341f7 | bb5a0a09e3835f187a3a3cf6b2dc0e476056744c | /src/bin2cpp/Win32ResourceGenerator.h | b6fba405f9dfee0998abb4d750d4391804608f0b | [
"MIT"
] | permissive | evxio/bin2cpp | 75d4b0b081d53df0ef13afb70fe5a4c1d3c1c13f | 53d046ca7bfb0b0ac902d7bfecf07e04f07d75a0 | refs/heads/master | 2020-03-28T23:54:28.205442 | 2018-05-27T01:06:09 | 2018-05-27T01:06:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | h | Win32ResourceGenerator.h | #pragma once
#include "BaseGenerator.h"
namespace bin2cpp
{
///<summary>
///This generator stores data in a single string of a maximum of 65535 bytes.
///</summary>
class Win32ResourceGenerator : public BaseGenerator
{
public:
Win32ResourceGenerator();
virtual ~Win32ResourceGenerator();
virtual const char * getName() const;
virtual bool createCppSourceFile(const char * iCppFilePath);
protected:
virtual std::string getResourceFilePath(const char * iCppFilePath);
virtual bool createResourceFile(const char * iCppFilePath);
virtual std::string getRandomIdentifier(const char * iCppFilePath);
};
}; //bin2cpp
|
b8a2951df737bb9f738c8a103ecb4f5b4d7b1ef7 | ece30e7058d8bd42bc13c54560228bd7add50358 | /DataCollector/mozilla/xulrunner-sdk/include/nsIClipboardCommands.h | 87312f1ebb20f3fde336460e771eaca81a59e81f | [
"Apache-2.0"
] | permissive | andrasigneczi/TravelOptimizer | b0fe4d53f6494d40ba4e8b98cc293cb5451542ee | b08805f97f0823fd28975a36db67193386aceb22 | refs/heads/master | 2022-07-22T02:07:32.619451 | 2018-12-03T13:58:21 | 2018-12-03T13:58:21 | 53,926,539 | 1 | 0 | Apache-2.0 | 2022-07-06T20:05:38 | 2016-03-15T08:16:59 | C++ | UTF-8 | C++ | false | false | 8,644 | h | nsIClipboardCommands.h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsIClipboardCommands.idl
*/
#ifndef __gen_nsIClipboardCommands_h__
#define __gen_nsIClipboardCommands_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIClipboardCommands */
#define NS_ICLIPBOARDCOMMANDS_IID_STR "b8100c90-73be-11d2-92a5-00105a1b0d64"
#define NS_ICLIPBOARDCOMMANDS_IID \
{0xb8100c90, 0x73be, 0x11d2, \
{ 0x92, 0xa5, 0x00, 0x10, 0x5a, 0x1b, 0x0d, 0x64 }}
class NS_NO_VTABLE nsIClipboardCommands : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICLIPBOARDCOMMANDS_IID)
/* boolean canCutSelection (); */
NS_IMETHOD CanCutSelection(bool *_retval) = 0;
/* boolean canCopySelection (); */
NS_IMETHOD CanCopySelection(bool *_retval) = 0;
/* boolean canCopyLinkLocation (); */
NS_IMETHOD CanCopyLinkLocation(bool *_retval) = 0;
/* boolean canCopyImageLocation (); */
NS_IMETHOD CanCopyImageLocation(bool *_retval) = 0;
/* boolean canCopyImageContents (); */
NS_IMETHOD CanCopyImageContents(bool *_retval) = 0;
/* boolean canPaste (); */
NS_IMETHOD CanPaste(bool *_retval) = 0;
/* void cutSelection (); */
NS_IMETHOD CutSelection(void) = 0;
/* void copySelection (); */
NS_IMETHOD CopySelection(void) = 0;
/* void copyLinkLocation (); */
NS_IMETHOD CopyLinkLocation(void) = 0;
/* void copyImageLocation (); */
NS_IMETHOD CopyImageLocation(void) = 0;
/* void copyImageContents (); */
NS_IMETHOD CopyImageContents(void) = 0;
/* void paste (); */
NS_IMETHOD Paste(void) = 0;
/* void selectAll (); */
NS_IMETHOD SelectAll(void) = 0;
/* void selectNone (); */
NS_IMETHOD SelectNone(void) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIClipboardCommands, NS_ICLIPBOARDCOMMANDS_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSICLIPBOARDCOMMANDS \
NS_IMETHOD CanCutSelection(bool *_retval) override; \
NS_IMETHOD CanCopySelection(bool *_retval) override; \
NS_IMETHOD CanCopyLinkLocation(bool *_retval) override; \
NS_IMETHOD CanCopyImageLocation(bool *_retval) override; \
NS_IMETHOD CanCopyImageContents(bool *_retval) override; \
NS_IMETHOD CanPaste(bool *_retval) override; \
NS_IMETHOD CutSelection(void) override; \
NS_IMETHOD CopySelection(void) override; \
NS_IMETHOD CopyLinkLocation(void) override; \
NS_IMETHOD CopyImageLocation(void) override; \
NS_IMETHOD CopyImageContents(void) override; \
NS_IMETHOD Paste(void) override; \
NS_IMETHOD SelectAll(void) override; \
NS_IMETHOD SelectNone(void) override;
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSICLIPBOARDCOMMANDS(_to) \
NS_IMETHOD CanCutSelection(bool *_retval) override { return _to CanCutSelection(_retval); } \
NS_IMETHOD CanCopySelection(bool *_retval) override { return _to CanCopySelection(_retval); } \
NS_IMETHOD CanCopyLinkLocation(bool *_retval) override { return _to CanCopyLinkLocation(_retval); } \
NS_IMETHOD CanCopyImageLocation(bool *_retval) override { return _to CanCopyImageLocation(_retval); } \
NS_IMETHOD CanCopyImageContents(bool *_retval) override { return _to CanCopyImageContents(_retval); } \
NS_IMETHOD CanPaste(bool *_retval) override { return _to CanPaste(_retval); } \
NS_IMETHOD CutSelection(void) override { return _to CutSelection(); } \
NS_IMETHOD CopySelection(void) override { return _to CopySelection(); } \
NS_IMETHOD CopyLinkLocation(void) override { return _to CopyLinkLocation(); } \
NS_IMETHOD CopyImageLocation(void) override { return _to CopyImageLocation(); } \
NS_IMETHOD CopyImageContents(void) override { return _to CopyImageContents(); } \
NS_IMETHOD Paste(void) override { return _to Paste(); } \
NS_IMETHOD SelectAll(void) override { return _to SelectAll(); } \
NS_IMETHOD SelectNone(void) override { return _to SelectNone(); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSICLIPBOARDCOMMANDS(_to) \
NS_IMETHOD CanCutSelection(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CanCutSelection(_retval); } \
NS_IMETHOD CanCopySelection(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CanCopySelection(_retval); } \
NS_IMETHOD CanCopyLinkLocation(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CanCopyLinkLocation(_retval); } \
NS_IMETHOD CanCopyImageLocation(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CanCopyImageLocation(_retval); } \
NS_IMETHOD CanCopyImageContents(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CanCopyImageContents(_retval); } \
NS_IMETHOD CanPaste(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CanPaste(_retval); } \
NS_IMETHOD CutSelection(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CutSelection(); } \
NS_IMETHOD CopySelection(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CopySelection(); } \
NS_IMETHOD CopyLinkLocation(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CopyLinkLocation(); } \
NS_IMETHOD CopyImageLocation(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CopyImageLocation(); } \
NS_IMETHOD CopyImageContents(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CopyImageContents(); } \
NS_IMETHOD Paste(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Paste(); } \
NS_IMETHOD SelectAll(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SelectAll(); } \
NS_IMETHOD SelectNone(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SelectNone(); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsClipboardCommands : public nsIClipboardCommands
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICLIPBOARDCOMMANDS
nsClipboardCommands();
private:
~nsClipboardCommands();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS(nsClipboardCommands, nsIClipboardCommands)
nsClipboardCommands::nsClipboardCommands()
{
/* member initializers and constructor code */
}
nsClipboardCommands::~nsClipboardCommands()
{
/* destructor code */
}
/* boolean canCutSelection (); */
NS_IMETHODIMP nsClipboardCommands::CanCutSelection(bool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean canCopySelection (); */
NS_IMETHODIMP nsClipboardCommands::CanCopySelection(bool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean canCopyLinkLocation (); */
NS_IMETHODIMP nsClipboardCommands::CanCopyLinkLocation(bool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean canCopyImageLocation (); */
NS_IMETHODIMP nsClipboardCommands::CanCopyImageLocation(bool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean canCopyImageContents (); */
NS_IMETHODIMP nsClipboardCommands::CanCopyImageContents(bool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean canPaste (); */
NS_IMETHODIMP nsClipboardCommands::CanPaste(bool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void cutSelection (); */
NS_IMETHODIMP nsClipboardCommands::CutSelection()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void copySelection (); */
NS_IMETHODIMP nsClipboardCommands::CopySelection()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void copyLinkLocation (); */
NS_IMETHODIMP nsClipboardCommands::CopyLinkLocation()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void copyImageLocation (); */
NS_IMETHODIMP nsClipboardCommands::CopyImageLocation()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void copyImageContents (); */
NS_IMETHODIMP nsClipboardCommands::CopyImageContents()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void paste (); */
NS_IMETHODIMP nsClipboardCommands::Paste()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void selectAll (); */
NS_IMETHODIMP nsClipboardCommands::SelectAll()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void selectNone (); */
NS_IMETHODIMP nsClipboardCommands::SelectNone()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIClipboardCommands_h__ */
|
393c3b97d1a2859b3c4a62a7a9619fbecaf3ca4d | a0bb0915d389a3c7b193d61a7a56d21448d89600 | /tp5/Emission.cpp | 83127d253d619a627bda4bd03fa9372fd9c5116e | [] | no_license | julienlegault96/log1000 | 61868c69fb45cdf2f441ef919e933b31bcce2759 | 62764cecc18ba26a77f9cde312f2422ca59c36da | refs/heads/master | 2021-03-24T13:01:35.805103 | 2017-12-19T21:36:41 | 2017-12-19T21:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,356 | cpp | Emission.cpp | #include "Emission.h"
#include <fstream>
#include <iostream>
// Constructeur
Emission::Emission(){
titre = "";
animateur = "";
chaine = new Chaine();
}
Emission::Emission (string titre,
string animateur,
string chaineName,
string chaineCodePostal,
string chaineAddress) {
// Emission information
this->titre = titre;
this->animateur = animateur;
this->chaine = new Chaine (chaineName, chaineCodePostal, chaineAddress);
}
// Setters
void Emission::setTitre(string titre) {
this->titre = titre;
}
void Emission::setAnimateur(string animateur) {
this->animateur = animateur;
}
// Associer une Chaine à l'Emission
void Emission::associerChaine (Chaine* chaine) {
this -> chaine = chaine;
}
// Getters
string Emission::getTitre() {
return this->titre;
}
string Emission::getAnimateur() {
return this->animateur;
}
Chaine* Emission::getChaine(){
return chaine;
}
// Enregistrer l'Emission dans un fichier
void Emission::saveEmission (string fileName) {
ofstream outfile (fileName.c_str(), std::ofstream::binary | std::fstream::app);
// write to outfile
outfile<<this->titre <<","
<<this->animateur <<"\n";
outfile.close();
}
string Emission::trouverInfo(string line, int& index) {
if (index != 0)
index++;
string info;
for (index; index < line.length(); index++) {
if (line[index] != ',') {
info += line[index];
}
else {
break;
}
}
return info;
}
// Trouver un Emission avec son nom dans la base de données DB
Emission* Emission::trouverEmission(string DB, string titre) {
ifstream fichier(DB.c_str(), ios::in); // Ouvrir le fichier "DB.txt"
Emission*tmp = NULL;
if (fichier)
{
string line;
// Lire les Emissions, un Emission par ligne dans la base de données (DB.txt)
while (getline(fichier, line)) {
// Récupérer le nom de l'Emission
int i = 0;
string titreDB = trouverInfo(line, i);
// Si l'Emission qu'on lit actuellement est celui qu'on cherche
if (titreDB == titre) {
// Récupérer le nom de l'animateur
string animateurDB = trouverInfo(line, i);
// Récupérer le nom de l'éditeur
string chaineNameDB = trouverInfo(line, i);
// Récupérer le code postale de l'éditeur
string chaineCodePostalDB = trouverInfo(line, i);
// Récupérer l'addresse de l'éditeur
string chaineAddressDB = trouverInfo(line, i);
// Créer un objet de type Emission avec les informations récupérées
Emission *a = new Emission(titreDB, animateurDB, chaineNameDB, chaineCodePostalDB, chaineAddressDB);
// Fermer la base de données
fichier.close();
// Retourner l'Emission sélectionné
return a;
}
}
// Fermer la base de données
fichier.close();
}
// Si l'Emission est innexistant, on retourne NULL
return NULL;
}
// Afficher l'Emission
void Emission::afficher() {
std::cout << "Titre : " << this->titre << std::endl;
std::cout << "Animateur : " << this->animateur << std::endl;
std::cout << "Chaine name : " << (this->chaine)->getChaineName() << std::endl;
std::cout << "Chaine code postale : " << (this->chaine)->getChaineCodePostal() << std::endl;
std::cout << "Chaine address : " << (this->chaine)->getChaineAddress() << std::endl;
}
|
1f1c7013285beec4e874ffebef933449bde7e5fe | 6982a4d2feab96fb36e64066ff27f4c8d2838097 | /MainKnapsack.h | 8d766f9d39ef5dd911a793bebb3f564cbe8b7c45 | [] | no_license | akheireddine/P-TL | 1fa5d16b7a1b392ded0f05f86890d9d5bf023d93 | 27921c5b7437ea204fd6138d60055f503d022879 | refs/heads/master | 2022-02-16T05:13:03.523433 | 2019-08-29T07:27:50 | 2019-08-29T07:27:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,710 | h | MainKnapsack.h |
#ifndef __KNAPSACK_STRUCT__
#define __KNAPSACK_STRUCT__
class MainKnapsack;
#include "LSStructure.h"
#include "AlternativeKnapsack.h"
extern list<set<int>> init_population;
extern string INFO;
extern int k_replication;
extern float Ta;
class MainKnapsack : public LSStructure{
protected:
float Backpack_capacity = 0; // capacity ofthe backpack
int n_items; // number of items
map<string, shared_ptr< AlternativeKnapsack > > dic_Alternative;
public :
vector< tuple<float, vector< float> > > Items_information; //information about each item : (key:weight : value:utility list for each criteria)
//constructor
MainKnapsack( shared_ptr< Evaluator > evaluator, int population_size_init, string filename, bool generate_population=false);
~MainKnapsack(){
for(map<string, shared_ptr< AlternativeKnapsack > > ::iterator it = dic_Alternative.begin(); it != dic_Alternative.end(); ++it){
dic_Alternative[(*it).first].reset();
dic_Alternative.erase((*it).first);
}
for(vector< tuple<float, vector< float> > >::iterator i = Items_information.begin(); i != Items_information.end(); ++i){
get<1>(*i).shrink_to_fit();
}
Items_information.shrink_to_fit();
};
//GETTERS
int get_n_items(){ return n_items; };
float get_weight_of(int i) { return std::get<0>(Items_information[i]); };
float get_utility(int i, int j) { return std::get<1>(Items_information[i])[j]; };
float get_capacity(){ return Backpack_capacity; };
//SETTERS
void set_WS_matrix(vector< vector< float > > new_ws){
n_objective = new_ws[0].size();
p_criteria = new_ws.size();
WS_matrix.resize(p_criteria);
for(int i = 0 ; i < p_criteria; i++)
WS_matrix[i] = new_ws[i];
};
vector< float > OPT_Alternative_PLNE(vector<float> WS_vector);
vector< float > get_extrem_points();
bool reached_limit(vector< float > extrem_point);
//READ FILES
// void readInitPopulationFile(string filename);
//RESOLUTION
bool Update_Archive(shared_ptr< Alternative > p, list< shared_ptr< Alternative > > &set_SOL);
bool Update_LocalArchive(shared_ptr< Alternative > p, list< string > &set_SOL);
bool Update_Archive(shared_ptr< Alternative > p, list< shared_ptr< Alternative > > &set_SOL, list<string> & population);
void update_alternatives(list< string > &set_Alt, bool Pareto);
void update_WS_matrix_Population();
void HYBRID_WS_PLS(double starting_time_sec, int ITER);
void HYBRID_PLS_WS(double starting_time_sec, int ITER);
void SWITCH_PLS_WS(double starting_time_sec, int ITER_PLS, int ITER_WS);
void MOLS_DYN_PSize(double starting_time_sec, vector< int > UB_Population, vector< string > Informations);
void MOLS_DYN_PSize_OS(double starting_time_sec, vector< int > UB_Population_list, vector< string > Informations);
void MOLS_DYN_INFO(double starting_time_sec, vector< int > UB_Population_list, vector< string > Informations);
void MOLS_DYN_MULTIPLE_PARAM(int Budget, vector< int > UB_Population_list, int inst_name, vector< string > Informations);
void MOLS_DYNAMIC(double starting_time_sec, vector< int > UB_Population_list, vector< string > Informations);
void MOLS_Cst_PSize(double starting_time_sec, int UB_Population_size);
void MOLS_local_Archive(double starting_time_sec);
void MOLS_Cst_PSize_RS(double starting_time_sec, int UB_Population_size);
void MOLS_Cst_PSize_OS(double starting_time_sec, int UB_Population_size);
void MOLS_OPT_PARAMETERS(double starting_time_sec, vector< map<string, float > > OPT_Params,
map<float,int> id_info, string information_file);
void MOLS_ML_RegLin(int Budget, vector<int> UB_Population_list, int inst_name, vector< float > Info_rate);
void Random_Selection(list< string > & dominated_solutions, list< string > & population, int upper_bound);
void Ordered_Selection(list< string > & dominated_solutions, list< string > & population, int upper_bound);
void LTA(list< string > & dominated_solutions, list< string > & population, int upper_bound);
void TA(list< string > & dominated_solutions, list< string > & population, int upper_bound);
//EVALUATION
void save_information(string filename, vector< float > criteria_vect, float time_cpu, int index);
void save_information(string filename, vector< float > criteria_vect, float time_cpu, int index, int ub);
//STATIC METHOD
static void Generate_random_Population(shared_ptr< Evaluator > evaluator, int number_of_individu);
void update_extrem_point(vector< float > extrem1, float & epsi, vector< float > point_eval, vector< float > & extrem2);
//functions to overload
void initializeInformation(shared_ptr< Evaluator > evaluator);
void MOLS(double starting_time_sec);
void GenerateInitialPopulation(int size_population);
};
#endif
|
4322466f71309260ceb8f6342297df7089a406f7 | 5d185145d374d637b52ea4d3724f57f49832bd13 | /高一實習課/判斷平閏年.cpp | 4871998f21e7df6b7f4a209c853a5f52db41c6ba | [] | no_license | TKLabStudio/C-plus-plus | acaaa5c1575930d89259f3efe41208180c47b610 | 44a80147dfe025c784a6700de9acb975a9c14eba | refs/heads/master | 2021-05-25T14:42:22.765108 | 2020-04-07T13:11:16 | 2020-04-07T13:11:16 | 253,793,424 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 565 | cpp | 判斷平閏年.cpp | #include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
int main()
{
int a,a4,a100,a400;
cout<<"請輸入年分:";
cin>>a;
a4=a%4;
a100=a%100;
a400=a%400;
if(a4!=0)
{
cout<<"這是平年!!\n";
}
else if(a100!=0)
{
cout<<"這是閏年!!\n";
}
else if(a400!=0)
{
cout<<"這是平年!!\n";
}
else
{
cout<<"這是閏年!!\n";
}
system("PAUSE");
return 0;
}
|
7f2f80b4a1e4ef2a57cf38fb15a57b2f57f2fa39 | 8b868abed373e47df8fa76e68d7958a7e026fd15 | /DFS/DFS/dfs.cpp | 9663f96047a08675f0144d733e29523fe473ee1b | [] | no_license | dinesh032/Graph-Algorithms | 8cc8eade5cfba633ce7029c8a6c8ab290c02c670 | 9912ed88b202a97c1c62f8eb1cddb144bf947182 | refs/heads/master | 2020-03-16T03:11:47.731694 | 2018-05-07T15:59:32 | 2018-05-07T15:59:32 | 132,482,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | cpp | dfs.cpp | #include<iostream>
#include "dfs.h"
#include<stdio.h>
using namespace std;
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V+1];
}
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
}
void Graph::DFSUtil(int s, bool visited[]) {
//s node visited
visited[s] = true;
cout << s << "->";
//Depth first search recursive calls and printing it in that order
for (list<int>::iterator i = adj[s].begin(); i != adj[s].end(); i++)
if (!visited[*i])
DFSUtil(*i, visited);
}
void Graph::DFS(int s) {
bool *visited = new bool[V];
for (int i = 1; i <= V; i++) //mark all nodes as not visited
visited[i] = false;
DFSUtil(s, visited); //Helper function
}
|
beb97155c842c9b592404a461c1b356a8f4b94a4 | 82ef5875651151271a4d2ff786222dc42c96703b | /VS2013/ucp.cpp | 16c7f9755e41e16470643b7a2694fa7f569a1f40 | [] | no_license | XiaoxingChen/Uart-Calibration-Protocol | d42c48acdfa19729fa31239dfcc6a5396998eb54 | 6ce657ebf10eda0eeb8a746b371db11b84d6b9d2 | refs/heads/master | 2021-01-18T21:18:37.880659 | 2016-05-14T11:54:16 | 2016-05-14T11:54:16 | 52,843,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,891 | cpp | ucp.cpp | /**
******************************************************************************
* @file ucp.cpp
* @author Chenxx
* @version V1.0
* @date 2016-02-18
* @brief This file achieve the uart calibration protocol.
* This version is for PC.
******************************************************************************/
#include "ucp.h"
#include "CUart.h"
#include <iostream>
#include <vector>
/******************************************************************************
* @brief This part for ucp
******************************************************************************/
//
// static variable
//
const uint8_t ucp::REG_SIZE = 24;
//ucp::CAccs_base* Registry[ucp::REG_SIZE] = {(ucp::CAccs_base*)0xaa55};
uint32_t ucp::TimeStamp_ = 0x000000;
uint8_t ucp::RxdBuf_[sizeof(ucp::RxdPkgTyp)];
ucp::TxdPkgTyp ucp::TxdBuf_ = { 0x5AA5 };
list<ucp::RxdPkgTyp> ucp::RxdQue_;
uint16_t ucp::sendPeriod_ = 0;
ucp::CAccs_base* ucp::Registry_[ucp::REG_SIZE] = { (ucp::CAccs_base*)0xaa55 };
ucp::CAccs_base** ucp::DataIdx_ = Registry_;
ucp* ucp::instance_ = NULL;
CUsart ucp_Usart("COM2");
//
//local
//
ucp::CAccs_base accs_empty;
CAccs_dataIdx accs_dataIdx[4];
//
// instance()
//
ucp* ucp::instance()
{
if (instance_ == NULL)
{
instance_ = new ucp;
}
return instance_;
}
//
// constructor
//
ucp::ucp():
Usart_(&ucp_Usart)
{
CUsart_Init();
for (int i = 0; i < 4; i++)
{
ucp::DataIdx_[i] = &(accs_dataIdx[i]);
// ucp::DataIdx_[i] = accs_dataIdx+i;
}
for (int i = 4; i < REG_SIZE; i++)
{
if (Registry_[i] == NULL)
Registry_[i] = &accs_empty;
}
HANDLE hThread_1 = CreateThread(NULL, 0, run, 0, 0, NULL);
CloseHandle(hThread_1);
}
//
// CUsart_Init
//
void ucp::CUsart_Init()
{
if (Usart_ == NULL) std::cout << "Usart_ is NULL" << std::endl;
Usart_->Init(115200);
}
//
// updata()
//
void ucp::update(uint8_t send_period)
{
TimeStamp_++;
sendPeriod_ = send_period;
//ucp::instance()->send_Message(send_period);
/*ucp::instance()->pop_RxdQue_();*/
}
//
//void run()
//
DWORD WINAPI ucp::run(LPVOID lpParameter)
{
static uint32_t prevTime = 0;
while (true)
{
while (prevTime == TimeStamp_) Sleep(1);
prevTime = TimeStamp_;
ucp::instance()->send_Message(sendPeriod_);
ucp::instance()->pop_RxdQue_();
}
}
//
// OnMessageReceive()
//
//RSV
//
// pop_RxdQue_()
//
#if 0
uint8_t ucp::pop_RxdQue_()
{
static std::vector<char> temp;
uint16_t tempsize = temp.size();
#if 1
if (ucp_Usart.Get_cbInQue() > 0)
{
temp.resize(tempsize + Usart_->Get_cbInQue(), 0);
ucp_Usart.PopRxdQueue(&(temp[0]) + tempsize);
}
#else
if (Usart_->Get_cbInQue() > 0)
{
//temp.resize(tempsize + Usart_->Get_cbInQue(), 0);
//Usart_->PopRxdQueue(&(temp[0]) + tempsize);
Usart_->PopRxdQueue((char*)RxdBuf_);
for (int i = 0; i < min(test, 20); i++)
{
std::cout << std::hex << (uint16_t)(uint8_t)RxdBuf_[i] << " ";
}
std::cout << std::endl;
}
#endif
RxdPkgTyp tempPack;
if (temp.size() < sizeof(tempPack))
return 0;
while (true)
{
if ((uint8_t)temp[0] == 0x55 &&
(uint8_t)temp[1] == 0xAA &&
(uint8_t)temp[sizeof(tempPack)-1] == 0x00)
{
/* copy full pack data */
for (uint16_t i = 0; i < sizeof(tempPack); i++)
{
((uint8_t*)&tempPack)[i] = temp[i];
}
temp.erase(temp.begin(), temp.begin() + sizeof(tempPack) - 1);
/* execute */
Registry_[tempPack.DataIdx]->set(tempPack.Data);
}
if (temp.size() <= sizeof(tempPack))
{
break;
// unpack finished
}
temp.erase(temp.begin()); // pop front
}
if (temp.capacity() > 1)
{
std::vector<char> rls = temp; //release the memory that allocated by temp
temp.swap(rls);
#if 0
if (temp.size() > 0)
{
std::cout << (int)&temp[0] << std::endl;
}
#endif
}
return 1;
}
#endif
uint8_t ucp::pop_RxdQue_()
{
enum unpackMode_Type
{
CHECK_SIZE = 0, //check left array size
SRCH_HEAD = 1, //search pack head
CHECK_END = 2, //check pack end
RSERCH_TO_CHECK = 3, //re-search pack head
UNPACK = 4
}unpackMode;
unpackMode = RSERCH_TO_CHECK;
static RxdPkgTyp tempPack;
while (true) //unpack state machine
{
/* CHECK_SIZE */
if (unpackMode == CHECK_SIZE) //to "break" or "SRCH_HEAD"
{
if (ucp_Usart.Get_cbInQue() < sizeof(tempPack))
break;
else
unpackMode = SRCH_HEAD;
}
/* SRCH_HEAD */
else if (unpackMode == SRCH_HEAD) //to "SRCH_HEAD" or "CHECK_END"
{
ucp_Usart.PopRxdQueue((char*)&tempPack, 1);
if (*((uint8_t*)&tempPack) == 0x55) unpackMode = CHECK_END;
}
/* CHECK_END */
else if (unpackMode == CHECK_END) // to "UNPACK" or "RSERCH_TO_CHECK"
{
ucp_Usart.PopRxdQueue((char*)&tempPack + 1, sizeof(tempPack)-1);
if (tempPack.PackHead == 0xAA55 && tempPack.PackEnd == 0x00)
unpackMode = UNPACK;
else
unpackMode = RSERCH_TO_CHECK;
}
/* RSERCH_TO_CHECK */
else if (unpackMode == RSERCH_TO_CHECK)
{
uint8_t i;
/* re-search the head in tempPack */
for (i = 1; i < sizeof(tempPack); i++)
{
if (((uint8_t*)&tempPack)[i] == 0x55) break;
}
char* leftPartAddr = ((char*)&tempPack) + sizeof(tempPack)-1 - i;
uint16_t leftPartSize = sizeof(tempPack)-i;
if (leftPartSize > 0)
{
/* check size */
if (ucp_Usart.Get_cbInQue() < leftPartSize) break;
/* check pack end */
memmove(&tempPack, ((uint8_t*)&tempPack) + i, sizeof(tempPack)-i);
ucp_Usart.PopRxdQueue(leftPartAddr, leftPartSize);
if (tempPack.PackHead == 0xAA55 && tempPack.PackEnd == 0x00)
unpackMode = UNPACK;
else
unpackMode = RSERCH_TO_CHECK;
}
else //leftPartSize == 0, no pack head in tempPack
unpackMode = CHECK_SIZE;
}
/* UNPACK */
else if (unpackMode == UNPACK) // to "break"
{
Registry_[tempPack.DataIdx]->set(tempPack.Data);
break;
}
else std::cout << "unpack enum error" << std::endl;
}
return 1;
}
//
// send_Message()
//
uint8_t ucp::send_Message(uint8_t period)
{
static uint16_t counter = 0;
if ((++counter) % period != 0)
return 0;
if (true) //judge the buff
{
TxdBuf_.TimeStamp_H = TimeStamp_ >> 16;
TxdBuf_.TimeStamp_L = TimeStamp_ & 0xffff;
TxdBuf_.ErrorCode = 0;
uint16_t temp;
TxdBuf_.DataSign = 0x00;
for (int i = 0; i < 4; i++)
{
temp = DataIdx_[i]->get();
TxdBuf_.DataIdx[i] = (uint8_t)temp;
TxdBuf_.Data[i] = Registry_[temp]->get();
TxdBuf_.DataSign |= (Registry_[temp]->get_sign()) << i;
}
/*Usart_->DmaSendArray((u8*)&TxdBuf_, sizeof(TxdBuf_));*/
Usart_->SendArray((uint8_t*)&TxdBuf_, sizeof(TxdBuf_));
}
return 1;
}
//
// Get_Usart_()
//
//RSV
ucp::~ucp()
{
}
/******************************************************************************
* @brief This part for ucp::access
******************************************************************************/
uint16_t ucp::CAccs_base::get() const
{
return 0x0001;
}
void ucp::CAccs_base::set(uint16_t)
{}
uint8_t ucp::CAccs_base::get_sign() const
{
return 1;
}
//end of file
|
efffb2503c8f19d1a10639ec9ebcd97992a8294b | 8e0c952b04b9f3f5d6e21682f3efb9621a47a62d | /tests/chat/NetMessage.h | 9c62332353a7ee0806cfc06a994e35329864e92f | [
"Apache-2.0"
] | permissive | Neomer/binc | 687a57b02e1a7a6f3fb8535c946513cb7c9b8606 | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | refs/heads/Dev | 2021-09-06T14:13:54.296983 | 2018-02-07T10:59:31 | 2018-02-07T10:59:31 | 113,421,980 | 0 | 0 | Apache-2.0 | 2018-02-07T10:59:31 | 2017-12-07T08:13:27 | C++ | UTF-8 | C++ | false | false | 469 | h | NetMessage.h | #ifndef NETMESSAGE_H
#define NETMESSAGE_H
#include <core/JsonSerializableIdentifyedEntity.h>
class NetMessage : public JsonSerializableIdentifyedEntity
{
QString _msg;
public:
NetMessage();
QString getMessage() { return _msg; }
void setMessage(QString value) { _msg = value; }
// IJsonSerializable interface
public:
void toJsonObject(QJsonObject &out) override;
void fromJsonObject(QJsonObject &in) override;
};
#endif // NETMESSAGE_H
|
10da438c3d336356b56d85ea968915e71b768754 | 2d5100b882aba165f6706f88b23c38977a7825f3 | /2019-2020/contests/december/silver/meetings/main.cpp | b7d63094660ec436f63073fe13069a57e6f2d1e2 | [] | no_license | anish-lakkapragada/USACO-Solutions | ac8b8857e7a66dfacc3561ee5ca61a5f8be2430a | 74383af923cbdb0c54c8a9cddaa1a0ab8117e816 | refs/heads/master | 2023-02-03T04:25:43.432418 | 2020-12-19T07:18:45 | 2020-12-19T07:18:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,011 | cpp | main.cpp | // Test case path: [path]
// meetings - Silver - December 2019-2020
// http://usaco.org/index.php?page=viewproblem&cpid=955
#include <bits/stdc++.h>
using namespace std;
struct Cow {
int position;
int velocity;
int weight;
};
int N, L;
vector<Cow> cows;
int getTimeNeeded() {
vector<int> left, right;
for (int i = 0; i < N; i++) {
if (cows[i].velocity == -1) {
left.push_back(i);
} else {
right.push_back(i);
}
}
vector<pair<int, int>> arrivals;
for (int i = 0; i < left.size(); i++) {
arrivals.push_back(make_pair(cows[left[i]].position, cows[i].weight));
}
for (int i = 0; i < right.size(); i++) {
arrivals.push_back(make_pair(L - cows[right[i]].position, cows[left.size() + i].weight));
}
sort(arrivals.begin(), arrivals.end(), [](pair<int, int> a, pair<int, int> b) {
return a.first < b.first;
});
int totalWeight = 0;
for (int i = 0; i < N; i++) {
totalWeight += cows[i].weight;
}
for (int i = 0; i < N; i++) {
totalWeight -= 2 * arrivals[i].second;
if (totalWeight <= 0) {
return arrivals[i].first;
}
}
}
int main() {
ifstream fin("meetings.in");
ofstream fout("meetings.out");
fin >> N >> L;
cows = vector<Cow>(N);
for (int i = 0; i < N; i++) {
fin >> cows[i].weight >> cows[i].position >> cows[i].velocity;
}
sort(cows.begin(), cows.end(), [](Cow a, Cow b) {
return a.position < b.position;
});
int timeNeeded = getTimeNeeded();
queue<int> right;
int totalCollisions = 0;
for (int i = 0; i < N; i++) {
if (cows[i].velocity == 1) {
right.push(i);
} else {
while (right.size() > 0 && cows[right.front()].position + 2 * timeNeeded < cows[i].position) {
right.pop();
}
totalCollisions += right.size();
}
}
fout << totalCollisions << endl;
return 0;
} |
ed8e16dd77230d404008699bee108a51a8ed5a7e | 11f6ea22eb1520fa3e62bf1554f530c2d8cc5e34 | /src/rendering/pass.cpp | aec3930c392d6a5199d1fd8d88c45f035ed4392c | [
"MIT"
] | permissive | spencer-melnick/simple-render | bb6ad7509e8c6b030129dfbb91389825bf3ba215 | c150d6056c1dccf33d8ba26408a284286189b39e | refs/heads/master | 2022-08-31T15:12:24.304982 | 2020-05-22T17:30:20 | 2020-05-22T17:30:20 | 263,089,453 | 0 | 0 | MIT | 2020-05-22T17:30:21 | 2020-05-11T15:55:57 | CMake | UTF-8 | C++ | false | false | 1,685 | cpp | pass.cpp | #include "pass.hpp"
#include <spdlog/spdlog.h>
#include "context.hpp"
namespace Rendering
{
Pass::Pass()
{
// Right now this is a very simple render pass, just base color
vk::AttachmentDescription colorAttachment;
colorAttachment.format = Context::get().getDevice().getSurfaceFormat().format;
colorAttachment.samples = vk::SampleCountFlagBits::e1;
colorAttachment.loadOp = vk::AttachmentLoadOp::eClear;
colorAttachment.storeOp = vk::AttachmentStoreOp::eStore;
colorAttachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
colorAttachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
colorAttachment.initialLayout = vk::ImageLayout::eUndefined;
colorAttachment.finalLayout = vk::ImageLayout::ePresentSrcKHR;
// Fragment color is layout = 0!
vk::AttachmentReference colorAttachmentReference;
colorAttachmentReference.layout = vk::ImageLayout::eColorAttachmentOptimal;
colorAttachmentReference.attachment = 0;
// Single subpass
vk::SubpassDescription colorPass;
colorPass.colorAttachmentCount = 1;
colorPass.pColorAttachments = &colorAttachmentReference;
// Creation info
vk::RenderPassCreateInfo createInfo;
createInfo.attachmentCount = 1;
createInfo.pAttachments = &colorAttachment;
createInfo.subpassCount = 1;
createInfo.pSubpasses = &colorPass;
spdlog::info("Creating rendering pass");
m_renderPass = Context::getVulkanDevice().createRenderPassUnique(createInfo);
}
Pass::~Pass()
{
spdlog::info("Destroying render pass");
}
}
|
98b98db6560fb211944e3a6c350e007a65797b8d | 6de3f9867defe975dbd05500a888bbb4010f49ec | /2D_COLLISION/scene_parser_IMP.cpp | 628972b5fac423e10a6fb16b6793c329b7c17b88 | [] | no_license | MathNerd/Mathematics | fe5b9373cd82a0dfe49fdc97b5463e77207b00b8 | 403302cd22116c27e25be65e0385daebf964b3b8 | refs/heads/master | 2021-06-15T01:30:05.562885 | 2019-10-04T19:58:58 | 2019-10-04T19:58:58 | 144,030,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,195 | cpp | scene_parser_IMP.cpp |
#include <octave/oct.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <string>
#define CSTRING const char*
#define CONV_CHAR_DIGIT_TO_INT(c) ((c)-'0')
typedef enum Parse2DDoubleVectorReturnCodeEnum
{
Parse2DDoubleVectorReturnCode_SUCCESS,
Parse2DDoubleVectorReturnCode_ERROR__EXPECTS_OPENING_BRACKET,
Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT,
Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT,
Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTERS_AT_LINE_END
} Parse2DDoubleVectorReturnCodeEnum;
static CSTRING Parse2DDoubleVectorString(Parse2DDoubleVectorReturnCodeEnum return_code)
{
static CSTRING return_code_names[] = {
"Parse2DDoubleVectorReturnCode_SUCCESS",
"Parse2DDoubleVectorReturnCode_ERROR__EXPECTS_OPENING_BRACKET",
"Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT",
"Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT",
"Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTERS_AT_LINE_END"
};
return return_code_names[return_code];
}
static Parse2DDoubleVectorReturnCodeEnum Parse2DDoubleVector(const std::string& str, double& x, double& y)
{
typedef enum STATES {
STATE_START, // Starting state
STATE_0,
STATE_1,
STATE_2,
STATE_3,
STATE_4,
STATE_5,
STATE_6,
STATE_7,
STATE_8,
STATE_9,
STATE_10,
STATE_11,
STATE_12,
STATE_FINISH // Finish state
} STATES;
STATES state = STATE_START;
Parse2DDoubleVectorReturnCodeEnum return_code = Parse2DDoubleVectorReturnCode_SUCCESS;
x = 0;
y = 0;
int sign = 1;
double frac = 0;
double expo = 1;
for (size_t i = 0; state != STATE_FINISH && i < str.length(); i++)
{
char c = str[i];
switch(state)
{
case STATE_START:
if (c == '[')
state = STATE_0;
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__EXPECTS_OPENING_BRACKET;
}
break;
case STATE_0:
if (isspace(c))
{
// Do not change the state:
// state = STATE_0;
}
else if (isdigit(c))
{
state = STATE_2;
x = 10 * x + CONV_CHAR_DIGIT_TO_INT(c);
}
else if (c == '.')
{
state = STATE_3;
}
else if (c == '+')
{
state = STATE_1;
}
else if (c == '-')
{
state = STATE_1;
sign = -1;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT;
}
break;
case STATE_1:
if (isspace(c))
{
// Do not change the state:
// state = STATE_1;
}
else if (isdigit(c))
{
state = STATE_2;
x = 10 * x + CONV_CHAR_DIGIT_TO_INT(c);
}
else if (c == '.')
{
state = STATE_3;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT;
}
break;
case STATE_2:
if (isdigit(c))
{
// Do not change the state:
// state = STATE_2;
x = 10 * x + CONV_CHAR_DIGIT_TO_INT(c);
}
else if (c == '.')
{
state = STATE_4;
}
else if (isspace(c))
{
state = STATE_5;
x *= sign;
sign = 1;
}
else if (c == ',')
{
state = STATE_6;
x *= sign;
sign = 1;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT;
}
break;
case STATE_3:
if (isdigit(c))
{
state = STATE_4;
expo /= 10.0;
frac += CONV_CHAR_DIGIT_TO_INT(c) * expo;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT;
}
break;
case STATE_4:
if (isdigit(c))
{
// Do not change the state:
// state = STATE_4;
expo /= 10.0;
frac += CONV_CHAR_DIGIT_TO_INT(c) * expo;
}
else if (isspace(c))
{
state = STATE_5;
x += frac;
x *= sign;
sign = 1;
expo = 1.0;
frac = 0.0;
}
else if (c == ',')
{
state = STATE_6;
x += frac;
x *= sign;
sign = 1;
expo = 1.0;
frac = 0.0;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT;
}
break;
case STATE_5:
if (isspace(c))
{
// Do not change the state:
// state = STATE_5;
}
else if (c == ',')
{
state = STATE_6;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_FIRST_COMPONENT;
}
break;
case STATE_6:
if (isspace(c))
{
// Do not change the state:
// state = STATE_6;
}
else if (isdigit(c))
{
state = STATE_8;
y = 10 * y + CONV_CHAR_DIGIT_TO_INT(c);
}
else if (c == '+')
{
state = STATE_7;
}
else if (c == '-')
{
state = STATE_7;
sign = -1;
}
else if (c == '.')
{
state = STATE_9;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT;
}
break;
case STATE_7:
if (isspace(c))
{
// Do not change the state:
// state = STATE_7;
}
else if (isdigit(c))
{
state = STATE_8;
y = 10 * y + CONV_CHAR_DIGIT_TO_INT(c);
}
else if (c == '.')
{
state = STATE_9;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT;
}
break;
case STATE_8:
if (isdigit(c))
{
// Do not change the state:
// state = STATE_8;
y = 10 * y + CONV_CHAR_DIGIT_TO_INT(c);
}
else if (c == '.')
{
state = STATE_10;
}
else if (isspace(c))
{
state = STATE_11;
}
else if (c == ']')
{
state = STATE_12;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT;
}
break;
case STATE_9:
if (isdigit(c))
{
state = STATE_10;
expo /= 10.0;
frac += CONV_CHAR_DIGIT_TO_INT(c) * expo;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT;
}
break;
case STATE_10:
if (isdigit(c))
{
// Do not change the state:
// state = STATE_10;
expo /= 10.0;
frac += CONV_CHAR_DIGIT_TO_INT(c) * expo;
}
else if (isspace(c))
{
state = STATE_11;
y += frac;
y *= sign;
}
else if (c == ']')
{
state = STATE_12;
y += frac;
y *= sign;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT;
}
break;
case STATE_11:
if (isspace(c))
{
// Do not change the state:
// state = STATE_11;
}
else if (c == ']')
{
state = STATE_12;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTER_WHILE_READING_SECOND_COMPONENT;
}
break;
case STATE_12:
if (isspace(c))
{
// Do not change the state:
// state = STATE_12;
}
else
{
state = STATE_FINISH;
return_code = Parse2DDoubleVectorReturnCode_ERROR__UNRECOGNIZED_CHARACTERS_AT_LINE_END;
}
break;
}
}
return return_code;
}
DEFUN_DLD(scene_parser_IMP, args, nargout, "Reads a '.scene' file.")
{
int nargin = args.length();
if (nargin != 1)
octave_stdout << "Expects exactly one parameter of string type that will hold the full path to the '.scene' file.\n";
else
{
if (args(0).is_string())
{
std::string file_full_path = args(0).string_value();
if (!error_state)
{
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(file_full_path, pt);
//------------------------------------------------------------------------------
std::string str_point_0 = pt.get<std::string>("point_0");
std::string str_point_velocity = pt.get<std::string>("point_velocity");
std::string str_point_radius = pt.get<std::string>("point_radius");
std::string str_point_drag_acceleration = pt.get<std::string>("point_drag_acceleration");
std::string str_rectangle_bottom_left_corner = pt.get<std::string>("rectangle_bottom_left_corner");
std::string str_rectangle_size = pt.get<std::string>("rectangle_size");
std::string str_rectangle_velocity = pt.get<std::string>("rectangle_velocity");
std::string str_rectangle_drag_acceleration = pt.get<std::string>("rectangle_drag_acceleration");
//------------------------------------------------------------------------------
dim_vector dv(1, 13);
NDArray array(dv);
double x, y;
Parse2DDoubleVectorReturnCodeEnum return_code;
return_code = Parse2DDoubleVector(str_point_0, x, y);
if (return_code != Parse2DDoubleVectorReturnCode_SUCCESS)
{
octave_stdout << "Error while parsing value of \'" << "point_0" << "\'.\n";
octave_stdout << "Error details: " << Parse2DDoubleVectorString(return_code) << "\n";
}
else
{
array(0,0) = x;
array(0,1) = y;
}
return_code = Parse2DDoubleVector(str_point_velocity, x, y);
if (return_code != Parse2DDoubleVectorReturnCode_SUCCESS)
{
octave_stdout << "Error while parsing value of \'" << "point_velocity" << "\'.\n";
octave_stdout << "Error details: " << Parse2DDoubleVectorString(return_code) << "\n";
}
else
{
array(0,2) = x;
array(0,3) = y;
}
array(0,4) = std::stod(str_point_radius);
array(0,5) = std::stoi(str_point_drag_acceleration);
//------------------------------------------------------------------------------
return_code = Parse2DDoubleVector(str_rectangle_bottom_left_corner, x, y);
if (return_code != Parse2DDoubleVectorReturnCode_SUCCESS)
{
octave_stdout << "Error while parsing value of \'" << "rectangle_bottom_left_corner" << "\'.\n";
octave_stdout << "Error details: " << Parse2DDoubleVectorString(return_code) << "\n";
}
else
{
array(0,6) = x;
array(0,7) = y;
}
return_code = Parse2DDoubleVector(str_rectangle_size, x, y);
if (return_code != Parse2DDoubleVectorReturnCode_SUCCESS)
{
octave_stdout << "Error while parsing value of \'" << "rectangle_size" << "\'.\n";
octave_stdout << "Error details: " << Parse2DDoubleVectorString(return_code) << "\n";
}
else
{
array(0,8) = x;
array(0,9) = y;
}
return_code = Parse2DDoubleVector(str_rectangle_velocity, x, y);
if (return_code != Parse2DDoubleVectorReturnCode_SUCCESS)
{
octave_stdout << "Error while parsing value of \'" << "rectangle_velocity" << "\'.\n";
octave_stdout << "Error details: " << Parse2DDoubleVectorString(return_code) << "\n";
}
else
{
array(0,10) = x;
array(0,11) = y;
}
array(0,12) = std::stoi(str_rectangle_drag_acceleration);
return octave_value(array);
}
else
{
octave_stdout << "Octave error.\n";
}
}
else
{
octave_stdout << "Expects a string argument.\n";
}
}
return octave_value_list();
} |
ce8890c25a1e9af09fc3f5bb7c15565bdb6531a0 | 1a95063080e2da230750bfcb7f9b7adaa87bc9b9 | /main.cpp | da13f56fca2eb703bb7310e8cd6b2accc2a33725 | [] | no_license | mosdeo/StateMachinePattern | 8e73cf8538cc89bcbaff4f6b33083365817ddf37 | 6afa08eae83a5322ab8b2997015982e57e62083a | refs/heads/master | 2020-07-01T10:10:02.840299 | 2016-11-30T05:23:41 | 2016-11-30T05:23:41 | 74,086,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | cpp | main.cpp | #include "LockNoBike.hpp"
#include "LockHaveBike.hpp"
#include "State.hpp"
#include "Context.hpp"
#include <iostream>
#include <memory>
using namespace std;
int main(int argc, char *argv[])
{
shared_ptr<Context> c = make_shared<Context>(new LockNoBike());
c->Request();
c->Request();
c->Request();
c->Request();
} |
6d167873a87c445b152faab43e9b65e1af64bf68 | 5dbad1807774211488ee305fb408fde9956634f0 | /Src/IDACSharp/IDC.h | a2753d059703373931310bcee6a6b7a3d9e1be5a | [] | no_license | sailor-hb/IDACSharp | 1f1a66f2d769c734e3a1e6c6d87880d9c0f194b8 | 77410a19bb9af15c94a8930fa9bbf42650583a1d | refs/heads/master | 2022-03-28T17:05:26.273346 | 2012-10-01T22:38:35 | 2012-10-01T22:38:35 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 867 | h | IDC.h |
#pragma once
using namespace System;
#include <bytes.hpp>
#include "Bytes.h"
namespace IDACSharp {
// ½Å±¾
public ref class IDC
{
public:
static property ulong BadAddress { ulong get(){ return Bytes::BadAddress; }}
static property ulong BadSelect { ulong get(){ return Bytes::BadSelect; }}
static property ulong MaxAddress { ulong get(){ return Bytes::MaxAddress; }}
static bool HasValue(flags_t ea){ return Bytes::HasValue(ea); }
static bool MakeName(ea_t ea, String^ name, int flag){ return set_name(ea, IdaHelper::CastStringToChar(name), flag); }
static bool MakeName(ea_t ea, String^ name){ return set_name(ea, IdaHelper::CastStringToChar(name), SN_CHECK); }
static int MakeCode(ea_t ea){ return create_insn(ea); }
static int AnalyzeArea(ea_t start, ea_t end){ return analyze_area(start, end); }
};
} |
39951196102d187487042cdcb4c2c906008810d7 | 434342003036a93e9745d12a1c89b3e1c1b2c83d | /mailbox/lib/mbx/mbx_version.cpp | 602488f0ac11dbf896bbf9a9b39ba7f9460d3167 | [
"MIT"
] | permissive | fgrando/lib-skeleton | 563d2b9207492c07c0d82f196b852ba9ea45d66e | 8ffa63f2ab0b960d17182a4cb3cccb1df594602d | refs/heads/main | 2023-01-01T13:04:25.442356 | 2020-10-18T01:25:56 | 2020-10-18T01:25:56 | 304,767,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | mbx_version.cpp | #include <mbxlib.h>
// Versions
uint32_t mbx_get_version(void)
{
return MBX_VERSION;
}
int32_t mbx_is_compatible_dll(void)
{
uint32_t major = mbx_get_version() >> 24;
return major == MBX_VERSION_MAJOR;
}
|
f431f3c4166de3e127363e0ab93fe249e9cd2c57 | 2e94470a6fed74272b807bc33ba52987bffcf6f5 | /src/object.h | 0d4bb9609cf1eecfbbcece5dc1c7449402fa99c8 | [] | no_license | AdrianTanTeckKeng/ToyRenderer | ce3f77dc14cfad4221e4a080eb442452153634fd | 2d3a9d674e3cc6df2a47a3b761713904212e56d4 | refs/heads/main | 2023-09-03T18:35:13.983959 | 2021-11-01T20:10:08 | 2021-11-01T20:10:08 | 423,587,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,763 | h | object.h | #ifndef OBJECT_H
#define OBJECT_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <Eigen/Dense>
#include "utilities.h"
struct Material{
Eigen::Vector3d diffuse;
Eigen::Vector3d ambient;
Eigen::Vector3d specular;
double shininess;
};
class object{
public:
// Variables that determine objects(vertices, normals, faces, and indexes to determine which normals)
std::vector<double> vertices;
std::vector<double> normals;
std::vector<int> faces;
std::vector<int> normalIdx; //Store index for normals
int numOfVertices, numOfFaces, numOfNorms;
// Variables that determine lighting properties
Material properties;
// Variable to tag names
std::string objectName;
int copyIdx;
public:
// Constructors
object() {}
object(std::string name, const char* filename) {
properties.ambient << 0., 0., 0.;
properties.diffuse << 0., 0., 0.;
properties.specular << 0., 0., 0.;
properties.shininess = 0.;
load_data(name, filename);}
// Copy constructor
object(const object &o1) {vertices = o1.vertices;
normals = o1.normals;
faces = o1.faces;
normalIdx = o1.normalIdx;
numOfVertices = o1.numOfVertices;
numOfFaces = o1.numOfFaces;
numOfNorms = o1.numOfNorms;
properties = o1.properties;
objectName = o1.objectName;
copyIdx = o1.copyIdx;}
// Function to load data
void load_data(std::string name, const char* filename);
// Function to write out data
void writeData();
void writeVertices();
void writeFaces();
void writeNormal();
void writeFaceNormal();
void writeMaterial();
// Function to apply linear operation on the object
void applyOperationsOnObject(Eigen::Matrix4d operations);
void applyOperationsOnNormal(Eigen::Matrix4d operations);
// Function to change lighting properties
void changeAmbient(double x0, double x1, double x2){
properties.ambient[0] = x0;
properties.ambient[1] = x1;
properties.ambient[2] = x2;
}
void changeDiffuse(double x0, double x1, double x2){
properties.diffuse[0] = x0;
properties.diffuse[1] = x1;
properties.diffuse[2] = x2;
}
void changeSpecular(double x0, double x1, double x2){
properties.specular[0] = x0;
properties.specular[1] = x1;
properties.specular[2] = x2;
}
void changeShininess(double x0){
properties.shininess = x0;
}
// Return the name of the object
std::string getName(){
return objectName;
}
// Return face
int getFace(int idx){
return faces[idx];
}
// Return vertices
int getVertices(int idx){
return vertices[idx];
}
// Return component of vertices
Eigen::Vector3d getVertexComponent(int idx){
Eigen::Vector3d tmp;
tmp << vertices[3*(idx-1)], vertices[3*(idx-1) + 1], vertices[3*(idx-1) + 2];
return tmp;
}
// Return component of normal
Eigen::Vector3d getNormalComponent(int idx){
Eigen::Vector3d tmp;
tmp << normals[3*(idx-1)], normals[3*(idx-1) + 1], normals[3*(idx-1) + 2];
return tmp;
}
// Change copy index
void changeCopyIdx(int idx){
copyIdx = idx;
}
};
void object::load_data(std::string name, const char* filename){
objectName = name;
copyIdx = 0;
std::string directory = "data/";
directory += filename;
const char *fileLocation = directory.c_str();
// Opening file
std::ifstream file(fileLocation);
if (!file.is_open()){
std::cout << "error: " << filename << " does not exist." << std::endl;
exit(1);
}
// Parsing data
std::string line;
numOfVertices = 0;
numOfFaces = 0;
numOfNorms = 0;
while(std::getline(file, line)){
// Initialize a stringstream to parse the contents of the line.
std::stringstream ss(line);
// Declare variable to store the string, int, and double values.
std::string type;
// Parse string
ss >> type;
if(ss.fail()){
std::cout << "Error: unable to parse line." << std::endl;
}
if (type == "v"){
double x0, x1, x2;
ss >> x0 >> x1 >> x2;
numOfVertices += 1;
vertices.push_back(x0);
vertices.push_back(x1);
vertices.push_back(x2);
}
else if (type == "vn"){
double x0, x1, x2;
ss >> x0 >> x1 >> x2;
numOfNorms += 1;
normals.push_back(x0);
normals.push_back(x1);
normals.push_back(x2);
}
else{
std::string tmp1, tmp2, tmp3;
ss >> tmp1 >> tmp2 >> tmp3;
std::string regex_str = "//";
auto tokens_tmp1 = split(tmp1, regex_str);
auto tokens_tmp2 = split(tmp2, regex_str);
auto tokens_tmp3 = split(tmp3, regex_str);
faces.push_back(stoi(tokens_tmp1[0]));
faces.push_back(stoi(tokens_tmp2[0]));
faces.push_back(stoi(tokens_tmp3[0]));
normalIdx.push_back(stoi(tokens_tmp1[1]));
normalIdx.push_back(stoi(tokens_tmp2[1]));
normalIdx.push_back(stoi(tokens_tmp3[1]));
numOfFaces += 1;
}
}
file.close();
}
void object::writeData(){
if (copyIdx==0)
std::cout << objectName << std::endl;
else{
std::cout << objectName << "_copy" << copyIdx << std::endl;
}
writeVertices();
writeFaces();
}
void object::writeMaterial(){
std::cout << "ambient: " << properties.ambient[0] << " " << properties.ambient[1] << " " << properties.ambient[2] << std::endl;
std::cout << "diffuse: " << properties.diffuse[0] << " " << properties.diffuse[1] << " " << properties.diffuse[2] << std::endl;
std::cout << "specular: " << properties.specular[0] << " " << properties.specular[1] << " " << properties.specular[2] << std::endl;
std::cout << "shininess: " << properties.shininess << std::endl;
}
void object::writeVertices(){
for (int i=0; i<numOfVertices; i++){
std::cout << "v " << vertices[3*i] << " " << vertices[3*i + 1] << " " << vertices[3*i +2] << std::endl;
}
std::cout << std::endl;
}
void object::writeFaces(){
for (int i=0; i<numOfFaces; i++){
std::cout << "f " << faces[3*i] << " " << faces[3*i+1] << " " << faces[3*i+2] << std::endl;
}
std::cout << std::endl;
}
void object::writeNormal(){
for (int i=0; i<numOfNorms; i++){
std::cout << normals[3*i] << " " << normals[3*i+1] << " " << normals[3*i+2] << std::endl;
}
std::cout << std::endl;
}
void object::writeFaceNormal(){
for (int i=0; i<numOfFaces; i++){
std::cout << "f " << faces[3*i] << "//" << normalIdx[3*i]
<< " " << faces[3*i+1] << "//" << normalIdx[3*i+1]
<< " " << faces[3*i+2] << "//" << normalIdx[3*i+2] << std::endl;
}
std::cout << std::endl;
}
void object::applyOperationsOnObject(Eigen::Matrix4d operations){
// Obtain w of the operations
// Loop through all the vertices
for(int i=0; i<numOfVertices; i++){
//std::cout << "Checking multiplication " << std:endl;
// Construct Homogeneous coordinates
Eigen::Vector4d v(vertices[3*i], vertices[3*i+1], vertices[3*i+2], 1);
// Apply operations
Eigen::Vector4d new_v = operations * v;
// Update vertices value
vertices[3*i ] = new_v[0] / new_v[3];
vertices[3*i+1] = new_v[1] / new_v[3];
vertices[3*i+2] = new_v[2] / new_v[3];
}
}
void object::applyOperationsOnNormal(Eigen::Matrix4d operations){
// First construct the correct operations by taking inverse and then transpose
Eigen::Matrix4d tmp1 = operations.inverse();
Eigen::Matrix4d tmp2 = tmp1.transpose();
// Loop through all the normals
for(int i=0; i<numOfNorms; i++){
// Construct coordinates
Eigen::Vector4d n(normals[3*i], normals[3*i+1], normals[3*i+2], 1);
// Apply operations
Eigen::Vector4d new_n = tmp2 * n;
// Find the norm of the normsl to normalize
double norm = sqrt(new_n[0] * new_n[0] + new_n[1] * new_n[1] + new_n[2] * new_n[2]);
// Update normal value
normals[3*i ] = new_n[0] / norm;
normals[3*i+1] = new_n[1] / norm;
normals[3*i+2] = new_n[2] / norm;
}
}
#endif |
309aa6cf8f4bb9cd8015c8540e969d9b9cf74c6f | 2a7692d961a899e84fedb17c7e9d77a7b068cbc4 | /DP/minimum cost path.cpp | 8841ccb1576630d19eb90dd0484988df33e1bbfd | [] | no_license | deepanshuv23/DS-Algo | 2b48776767fb037a8b270ad3f48a54537afd713c | c28071d1e3dc8658e56182f779f2058d04b75e0e | refs/heads/master | 2018-10-16T14:19:55.498817 | 2018-07-21T16:22:53 | 2018-07-21T16:22:53 | 120,011,278 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,328 | cpp | minimum cost path.cpp | /* Dynamic Programming implementation of MCP problem */
#include<stdio.h>
#include<limits.h>
#define R 3
#define C 3
// apply a greedy approach
int min(int x, int y, int z);
int minCost(int cost[R][C], int m, int n)
{
int result[R][C]={0};
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0&&j==0)
{
result[i][j]=cost[i][j]; // no way to go
}
else if(i==0)
{
result[i][j]=cost[i][j]+result[i][j-1]; // can only move right
}
else if(j==0)
{
result[i][j]=cost[i][j]+result[i-1][j]; // can only move down
}
else
{
result[i][j]=cost[i][j]+min(result[i][j-1],result[i-1][j],result[i-1][j-1]); //minimum of the three path options
}
}
}
return result[m-1][n-1];
}
/* A utility function that returns minimum of 3 integers */
int min(int x, int y, int z)
{
if (x < y)
return (x < z)? x : z;
else
return (y < z)? y : z;
}
/* Driver program to test above functions */
int main()
{
int cost[R][C] = { {1, 2, 3},
{4, 8, 2},
{1, 5, 3} };
printf(" %d ", minCost(cost, 3, 3));
return 0;
}
|
0cfd73e7b84b3283c6748160562904dd28b38ec7 | e331c668a1e8f4024b542083c9adc44d5f8b423e | /문자열/17249.cpp | 2be3bc73b64702fca8593a1734fe82c1ecf525db | [] | no_license | ssy02060/basis | 76c3651b41d45a4718b0e3a1aa72b5b887b7fac3 | ab5856ae55b37be4121687a0821dded1234edf6c | refs/heads/master | 2023-05-04T03:01:44.710246 | 2021-05-13T11:41:07 | 2021-05-13T11:41:07 | 367,017,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | cpp | 17249.cpp | #include <stdio.h>
// 17249
int main()
{
char str[1500];
scanf("%s", str);
int left = 0;
int right = 0;
bool face = false;
for(int i = 0; str[i] != 0; i++)
{
if(str[i] == '0')
face = true;
if(str[i] == '@' && face == false)
left++;
else if(str[i] == '@' &&face == true)
right++;
}
printf("%d %d", left, right);
return 0;
}
|
e77afb403a8fd265a21dfeb610fba19208dc48ab | 06726bb031816046fe2175e483981e5f6e2ece82 | /contest/APCS/apcs0304-3.cpp | e36f0a14dbd1cc440b5f76dde2ed75398145bf1f | [] | no_license | a37052800/c | 2390f07c77131fbe01fc26943cb544edebc1726a | e966460b617dbfdeca324a6b4e845a62c70631bb | refs/heads/master | 2023-01-11T11:49:06.463615 | 2022-12-26T08:14:27 | 2022-12-26T08:14:27 | 150,870,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,228 | cpp | apcs0304-3.cpp | #include <iostream>
#define add for(i=0;i<n;i++) for(j=0;j<n;j++)
#define f for(j=1;j<=i*2;j++)
#define c(n) ((n-1)/2)
using namespace std;
int main()
{
int n,s,i,j,c;
cin>>n>>s;
int a[n][n];
add cin>>a[j][i];
cout<<a[c(n)][c(n)];
for(i=1;i<=c(n);i++)
{
switch (s)
{
case 0:
{
f cout<<a[c(n)-i][c(n)+i-j]; //U
f cout<<a[c(n)-i+j][c(n)-i]; //R
f cout<<a[c(n)+i][c(n)-i+j]; //D
f cout<<a[c(n)+i-j][c(n)+i]; //L
break;
}
case 1:
{
f cout<<a[c(n)-i+j][c(n)-i]; //R
f cout<<a[c(n)+i][c(n)-i+j]; //D
f cout<<a[c(n)+i-j][c(n)+i]; //L
f cout<<a[c(n)-i][c(n)+i-j]; //U
break;
}
case 2:
{
f cout<<a[c(n)+i][c(n)-i+j]; //D
f cout<<a[c(n)+i-j][c(n)+i]; //L
f cout<<a[c(n)-i][c(n)+i-j]; //U
f cout<<a[c(n)-i+j][c(n)-i]; //R
break;
}
case 3:
{
f cout<<a[c(n)+i-j][c(n)+i]; //L
f cout<<a[c(n)-i][c(n)+i-j]; //U
f cout<<a[c(n)-i+j][c(n)-i]; //R
f cout<<a[c(n)+i][c(n)-i+j]; //D
break;
}
}
}
cout<<endl;
return 0;
}
/*
7
0
8 5 4 1 3 7 6
9 8 2 4 3 6 5
7 5 2 3 5 8 1
1 7 8 2 3 9 5
6 7 2 3 8 6 4
8 0 5 2 9 3 1
9 7 3 6 0 5 4
*/
/*
5
3
3 4 2 1 4
4 2 3 8 9
2 1 9 5 6
4 2 3 7 8
1 2 6 4 3
*/
|
6bc32c0a38b4339b8bf084ec7e0977f3d61d37bf | e035cab6a135308464f8762f283a7bb79ee256bc | /Engine/Source/Runtime/System/Application.cpp | 315bc8c1c928fef7f2db76235192f1b863eae0ba | [] | no_license | corefan/EtherealEngine | 9d08a9e732618655ad3af9491d74095d3cdf28b5 | 7713e48af8f7be556a3f133d79210ddff16a0a4a | refs/heads/master | 2021-01-12T04:26:43.147169 | 2016-12-27T00:35:39 | 2016-12-27T00:35:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,265 | cpp | Application.cpp | #include "Application.h"
#include "Core/core.h"
#include "Graphics/graphics.h"
#include "../System/Singleton.h"
#include "../System/Timer.h"
#include "../System/FileSystem.h"
#include "../System/MessageBox.h"
#include "../Threading/ThreadPool.h"
#include "../Assets/AssetManager.h"
#include "../Assets/AssetReader.h"
#include "../Assets/AssetWriter.h"
#include "../Rendering/RenderPass.h"
#include "../Rendering/Debug/DebugDraw.h"
#include "../Rendering/RenderWindow.h"
#include "../Input/InputContext.h"
#include "../Ecs/World.h"
#include "../Ecs/Prefab.h"
#include "../Ecs/Systems/TransformSystem.h"
#include "../Ecs/Systems/CameraSystem.h"
#include "../Ecs/Systems/RenderingSystem.h"
struct GfxCallback : public gfx::CallbackI
{
virtual ~GfxCallback()
{
}
virtual void traceVargs(const char* _filePath, std::uint16_t _line, const char* _format, std::va_list _argList) BX_OVERRIDE
{
auto logger = logging::get("Log");
logger->trace() << string_utils::format(_format, _argList).c_str();
}
virtual void fatal(gfx::Fatal::Enum _code, const char* _str) BX_OVERRIDE
{
auto logger = logging::get("Log");
logger->error() << _str;
}
virtual uint32_t cacheReadSize(uint64_t /*_id*/) BX_OVERRIDE
{
return 0;
}
virtual bool cacheRead(uint64_t /*_id*/, void* /*_data*/, uint32_t /*_size*/) BX_OVERRIDE
{
return false;
}
virtual void cacheWrite(uint64_t /*_id*/, const void* /*_data*/, uint32_t /*_size*/) BX_OVERRIDE
{
}
virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip) BX_OVERRIDE
{
BX_UNUSED(_filePath, _width, _height, _pitch, _data, _size, _yflip);
}
virtual void captureBegin(uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, gfx::TextureFormat::Enum /*_format*/, bool /*_yflip*/) BX_OVERRIDE
{
BX_TRACE("Warning: using capture without callback (a.k.a. pointless).");
}
virtual void captureEnd() BX_OVERRIDE
{
}
virtual void captureFrame(const void* /*_data*/, uint32_t /*_size*/) BX_OVERRIDE
{
}
};
static GfxCallback sGfxCallback;
Application::Application()
{
// Set members to sensible defaults
mWorld = std::make_unique<World>();
mAssetManager = std::make_unique<AssetManager>();
mTimer = std::make_unique<Timer>();
mThreadPool = std::make_unique<ThreadPool>();
mActionMapper = std::make_unique<ActionMapper>();
}
Application::~Application()
{
}
InputContext& Application::getInput()
{
return getWindow().getInput();
}
RenderWindow& Application::getWindow()
{
Expects(mWindow);
return *mWindow.get();
}
RenderWindow& Application::getMainWindow()
{
Expects(!mWindows.empty());
return *(mWindows[0].get());
}
bool Application::initInstance(const std::string& strCmdLine)
{
// Create and initialize the logging system
if (!initLogging()) { shutDown(); return false; }
// Create and initialize the input mappings
if (!initInputMappings()) { shutDown(); return false; }
// Create and initialize the primary display device
if (!initDisplay()) { shutDown(); return false; }
// Create and initialize the logging system
if (!initAssetManager()) { shutDown(); return false; }
// Create and initialize the systems
if (!initSystems()) { shutDown(); return false; }
// Initialize the application systems
if (!initApplication()) { shutDown(); return false; }
// Success!
return true;
}
void Application::setCopyrightData(const std::string & copyright)
{
mCopyright = copyright;
}
void Application::setVersionData(const std::string & version)
{
mVersion = version;
}
bool Application::registerMainWindow(RenderWindow& window)
{
gfx::PlatformData pd
{
nullptr,
window.getSystemHandle(),
nullptr,
nullptr,
nullptr
};
gfx::setPlatformData(pd);
if (!gfx::init(gfx::RendererType::Count, 0, 0, &sGfxCallback))
return false;
auto onClosed = [this](RenderWindow& wnd)
{
mRunning = false;
};
window.setMain(true);
window.onClosed.addListener(onClosed);
return true;
}
void Application::registerWindow(std::shared_ptr<RenderWindow> window)
{
auto onClosed = [this](RenderWindow& wnd)
{
mWindows.erase(std::remove_if(std::begin(mWindows), std::end(mWindows),
[this, &wnd](std::shared_ptr<RenderWindow>& other)
{
return (&wnd == other.get());
}), std::end(mWindows));
};
window->getInput().setActionMapper(mActionMapper.get());
window->prepareSurface();
window->onClosed.addListener(onClosed);
mWindows.emplace_back(window);
}
std::shared_ptr<RenderWindow> Application::createMainWindow()
{
sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
return std::make_shared<RenderWindow>(sf::VideoMode{ 1280, 720, desktop.bitsPerPixel }, "App", sf::Style::Default);
}
bool Application::initLogging()
{
auto logger = logging::create("Log",
{
std::make_shared<logging::sinks::platform_sink_mt>(),
std::make_shared<logging::sinks::daily_file_sink_mt>("Log", "log", 23, 59),
});
//logger->set_level(logging::level::trace);
if (!logger)
{
misc::messageBox(
"Failed to initialize the logging system!\n"
"Application will terminate now.",
"Initialization Error",
misc::Style::Error,
misc::Buttons::OK);
return false;
}
logger->info() << "Logging System Initialized!";
return true;
}
bool Application::initAssetManager()
{
auto& manager = getAssetManager();
{
auto storage = manager.add<Shader>();
storage->loadFromFile = AssetReader::loadShaderFromFile;
storage->loadFromMemory = AssetReader::loadShaderFromMemory;
storage->subdir = "runtime/";
switch (gfx::getRendererType())
{
case gfx::RendererType::Direct3D9:
storage->platform = "dx9/";
break;
case gfx::RendererType::Direct3D11:
case gfx::RendererType::Direct3D12:
storage->platform = "dx11/";
break;
case gfx::RendererType::OpenGL:
storage->platform = "glsl/";
break;
case gfx::RendererType::Metal:
storage->platform = "metal/";
break;
case gfx::RendererType::OpenGLES:
storage->platform = "gles/";
break;
default:
break;
}
}
{
auto storage = manager.add<Texture>();
storage->subdir = "runtime/";
storage->loadFromFile = AssetReader::loadTextureFromFile;
//storage->loadFromMemory = AssetReader::loadTextureFromMemory;
}
{
auto storage = manager.add<Mesh>();
storage->subdir = "runtime/";
storage->loadFromFile = AssetReader::loadMeshFromFile;
//storage->loadFromMemory = AssetReader::loadMeshFromMemory;
}
{
auto storage = manager.add<Material>();
storage->subdir = "";
storage->loadFromFile = AssetReader::loadMaterialFromFile;
//storage->loadFromMemory = AssetReader::loadMaterialFromMemory;
}
{
auto storage = manager.add<Prefab>();
storage->subdir = "";
storage->loadFromFile = AssetReader::loadPrefabFromFile;
}
return true;
}
bool Application::initInputMappings()
{
auto logger = logging::get("Log");
return true;
}
bool Application::initDisplay()
{
auto logger = logging::get("Log");
auto window = createMainWindow();
if (!registerMainWindow(*window))
{
// Write debug info
logger->critical() << "Failed to initialize render driver.";
// Failure to initialize!
misc::messageBox(
"Failed to initialize rendering hardware. The application must now exit.",
"Fatal Error",
misc::Style::Error,
misc::Buttons::OK
);
return false;
}
registerWindow(window);
// Success!!
return true;
}
bool Application::initSystems()
{
auto& world = getWorld();
world.systems.add<TransformSystem>();
world.systems.add<CameraSystem>();
world.systems.add<RenderingSystem>();
// Success!!
return true;
}
bool Application::initApplication()
{
auto& world = getWorld();
world.systems.configure();
ddInit();
// Success!!
return true;
}
int Application::begin()
{
// Get access to required systems
auto logger = logging::get("Log");
// 'Ping' the timer for the first frame
mTimer->tick();
// Write debug info
logger->info() << "Entered main application processing loop.";
// Start main loop
while (mRunning)
{
// Advance and render frame.
frameAdvance();
} // Until quit message is received
return 0;
}
bool Application::frameAdvance(bool bRunSimulation /* = true */)
{
// Advance Game Frame.
if (frameBegin(bRunSimulation))
{
{
// Did we receive a message, or are we idling ?
// Copy window container to prevent iterator invalidation
auto windows = mWindows;
for (auto sharedWindow : windows)
{
mWindow = sharedWindow;
processWindow(*sharedWindow);
mWindow.reset();
}
}
frameEnd();
return true;
} // End if frame rendering can commence
return false;
}
bool Application::shutDown()
{
ddShutdown();
auto logger = logging::get("Log");
logger->info() << "Shutting down main application.";
mWindows.clear();
mWorld.reset();
mThreadPool.reset();
mAssetManager.reset();
mTimer.reset();
gfx::shutdown();
// Shutdown Success
return true;
}
void Application::quit()
{
mRunning = false;
}
bool Application::frameBegin(bool bRunSimulation /* = true */)
{
// Allowing simulation to run?
if (bRunSimulation)
{
// In order to help avoid input lag when VSync is enabled, it is sometimes
// recommended that the application cap its frame-rate manually where possible.
// This helps to ensure that there is a consistent delay between input polls
// rather than the variable time when the hardware is waiting to draw.
auto fCap = mMaximumFPS;
bool vsync = mVsync;
if (vsync)
{
float fSmoothedCap = mMaximumSmoothedFPS;
if (fSmoothedCap < fCap || fCap == 0)
{
fCap = fSmoothedCap;
}
} // End if cap frame rate
// Advance timer.
mTimer->tick(fCap);
} // End if bRunSimulation
else
{
// Do not advance simulation time.
auto fOldSimulationSpeed = mTimer->getSimulationSpeed();
mTimer->setSimulationSpeed(0.0);
mTimer->tick();
mTimer->setSimulationSpeed(fOldSimulationSpeed);
} // End if !bRunSimulation
// Increment the frame counter
mTimer->incrementFrameCounter();
mThreadPool->poll();
// Success, continue on to render
return true;
}
void Application::processWindow(RenderWindow& window)
{
if (window.isOpen())
{
frameWindowBegin(window);
frameWindowUpdate(window);
frameWindowRender(window);
frameWindowEnd(window);
}
}
void Application::frameWindowBegin(RenderWindow& window)
{
window.frameBegin();
sf::Event e;
while (window.pollEvent(e))
{
}
if (window.hasFocus())
getWorld().systems.frameBegin(static_cast<float>(mTimer->getDeltaTime()));
}
void Application::frameWindowUpdate(RenderWindow& window)
{
window.frameUpdate(static_cast<float>(mTimer->getDeltaTime()));
if (window.hasFocus())
getWorld().systems.frameUpdate(static_cast<float>(mTimer->getDeltaTime()));
}
void Application::frameWindowRender(RenderWindow& window)
{
window.frameRender();
if (window.hasFocus())
getWorld().systems.frameRender(static_cast<float>(mTimer->getDeltaTime()));
}
void Application::frameWindowEnd(RenderWindow& window)
{
window.frameEnd();
if (window.hasFocus())
getWorld().systems.frameEnd(static_cast<float>(mTimer->getDeltaTime()));
}
void Application::frameEnd()
{
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
mRenderFrame = gfx::frame();
RenderPass::reset();
} |
c732c0f8be074be29d1bef4e780cd439a6710622 | ffdde4ab8f73fb3ff97fdbc5a0ff637d023a0a98 | /KM_Lab_3/mainwindow.cpp | 3e2e7e922f99602fb568cdc4761b14f99e0cfb15 | [] | no_license | Koskop/KM_Labs | a94e81dfd4ab64abfdbd772f1054d6cd3c789c0a | 33c387b5de722d62e09ddea8c0e3ef09f50867e1 | refs/heads/master | 2021-01-24T02:30:33.588855 | 2018-06-03T17:21:48 | 2018-06-03T17:21:48 | 122,851,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,672 | cpp | mainwindow.cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->horizontalSlider->setMinimum(0);
ui->horizontalSlider->setMaximum(86);
ui->horizontalScrollBar->setRange(0,0);
ui->verticalScrollBar->setRange(0,0);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_horizontalSlider_sliderMoved(int position)
{
if(position < 4){
ui->numberLine->setText(QString::number(position*3));
}else{
ui->numberLine->setText(QString::number((position-3)*12));
}
this->check_the_condition();
}
void MainWindow::on_toolButtonPlus_clicked()
{
if(ui->numberLine->toPlainText().toInt() < 996){
if(ui->numberLine->toPlainText().toInt() < 12){
ui->numberLine->setText(QString::number(ui->numberLine->toPlainText().toInt() + 3));
}else{
ui->numberLine->setText(QString::number(ui->numberLine->toPlainText().toInt() + 12));
}
this->synchronization();
}
}
void MainWindow::on_toolButtonMinus_clicked()
{
if(ui->numberLine->toPlainText().toInt() > 0){
if(ui->numberLine->toPlainText().toInt() < 13){
ui->numberLine->setText(QString::number(ui->numberLine->toPlainText().toInt() - 3));
}else{
ui->numberLine->setText(QString::number(ui->numberLine->toPlainText().toInt() - 12));
}
this->synchronization();
}
}
void MainWindow::synchronization()
{
if(ui->numberLine->toPlainText().toInt() < 13){
ui->horizontalSlider->setValue((int)((ui->numberLine->toPlainText().toInt())/3));
}else{
ui->horizontalSlider->setValue((int)((ui->numberLine->toPlainText().toInt())/12)+3);
}
this->check_the_condition();
}
void MainWindow::check_the_condition()
{
ui->pushButton->setEnabled(false);
if(ui->numberLine->toPlainText().toInt()%3 == 0 || ui->numberLine->toPlainText().toInt()%12 == 0){
//enable
ui->pushButton->setEnabled(true);
}else{
//disable
ui->pushButton->setEnabled(false);
}
}
void MainWindow::on_numberLine_textChanged()
{
this->check_the_condition();
}
void MainWindow::on_pushButton_clicked() //draw element
{
this->on_pushButton_2_clicked(); //clear memory
if(ui->numberLine->toPlainText().toInt() < 12){
for(int i = 0; i < ui->numberLine->toPlainText().toInt()/3; i++){
for(int j = 0; j < 3; j ++){
int nl = 300; // зміщення на новий шар
if(1){ //vertical
QPixmap tmp(100,50); // ширина, висота
tmp.fill(QColor(0,0,0,0));
QPainter painter(&tmp);
QPen pen(QBrush (QColor(230,30,116), Qt::SolidPattern), 5 );
painter.setPen(pen);
QFont f("Myriad Pro", 12);
f.setBold(true);
painter.setFont(f);
painter.drawText((int)tmp.size().width()/1.7, (int)tmp.size().height()-7, QString::number(1+j+3*i));
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width(), 0);
painter.drawLine(tmp.size().width()-2.5, 5, tmp.size().width()-2.5, tmp.size().height());
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width()-2.5, tmp.size().height()-2.5);
this->vertical_triangle << new QLabel(ui->scrollAreaWidgetContents);
this->vertical_triangle.last()->setPixmap(tmp);
this->vertical_triangle.last()->move(10, 50+75*j+nl*i);
this->vertical_triangle.last()->show();
this->vertical_triangle_coords_Y << this->vertical_triangle.last()->geometry().y();
this->vertical_triangle_coords_X << this->vertical_triangle.last()->geometry().x();
}
if(1){ //horyzontal
QPixmap tmp(100,50); // ширина, висота
tmp.fill(QColor(0,0,0,0));
QPainter painter(&tmp);
QPen pen(QBrush (QColor(230,30,116), Qt::SolidPattern), 5 );
painter.setPen(pen);
QFont f("Myriad Pro", 12);
f.setBold(true);
painter.setFont(f);
painter.drawText(10, (int)tmp.size().height()-7, QString::number(3-j+3*i));
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawLine(2.5, 0, tmp.size().width()-2.5, tmp.size().height()-5);
painter.drawLine(2.5, 0, 2.5, tmp.size().height());
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width() + 5, tmp.size().height()-2.5);
this->horyzontal_triangle << new QLabel(ui->scrollAreaWidgetContents);
this->horyzontal_triangle.last()->setPixmap(tmp);
this->horyzontal_triangle.last()->move(250+100*j, 275 + nl*i);
this->horyzontal_triangle.last()->show();
this->horyzontal_triangle_coords_Y << this->horyzontal_triangle.last()->geometry().y();
this->horyzontal_triangle_coords_X << this->horyzontal_triangle.last()->geometry().x();
}
if(1){ //lines vertical
QPixmap tmp(5,30+75*j); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(250+100*j, 275 + nl*i - tmp.height());
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
if(1){ //lines horyzontal
QPixmap tmp(140+100*j,5); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(250+100*j - tmp.width(), 270 + nl*i-(25+75*j));
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("ПГ"+QString::number(i+1));
this->rl.last()->move(200, 300 + nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("0,3");
this->rl.last()->move(10, 50+55+75*j+nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("3,4");
this->rl.last()->move(90, 50+55+75*j+nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(12+4*j));
this->rl.last()->move(130, 50+25+75*j+nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(20.3-4*j));
this->rl.last()->move(250+100*j, 325 + nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(23.4-4*j));
this->rl.last()->move(325+100*j, 325 + nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
}
}
}else{
for(int i = 0; i < ui->numberLine->toPlainText().toInt()/12; i++){
for(int j = 0; j < 12; j ++){
int nl = 1000; // зміщення на новий шар
if(1){ //vertical
QPixmap tmp(100,50); // ширина, висота
tmp.fill(QColor(0,0,0,0));
QPainter painter(&tmp);
QPen pen(QBrush (QColor(230,30,116), Qt::SolidPattern), 5);
painter.setPen(pen);
QFont f("Myriad Pro", 12);
f.setBold(true);
painter.setFont(f);
painter.drawText((int)tmp.size().width()/1.7, (int)tmp.size().height()-7, QString::number(1+j+12*i));
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width(), 0);
painter.drawLine(tmp.size().width()-2.5, 5, tmp.size().width()-2.5, tmp.size().height());
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width()-2.5, tmp.size().height()-2.5);
this->vertical_triangle << new QLabel(ui->scrollAreaWidgetContents);
this->vertical_triangle.last()->setPixmap(tmp);
this->vertical_triangle.last()->move(10, 50+75*j+nl*i);
this->vertical_triangle.last()->show();
this->vertical_triangle_coords_Y << this->vertical_triangle.last()->geometry().y();
this->vertical_triangle_coords_X << this->vertical_triangle.last()->geometry().x();
}
if(1){ //horyzontal
QPixmap tmp(100,50); // ширина, висота
tmp.fill(QColor(0,0,0,0));
QPainter painter(&tmp);
QPen pen(QBrush (QColor(230,30,116), Qt::SolidPattern), 5 );
painter.setPen(pen);
QFont f("Myriad Pro", 12);
f.setBold(true);
painter.setFont(f);
painter.drawText(10, (int)tmp.size().height()-7, QString::number(12-j+12*i));
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawLine(2.5, 0, tmp.size().width()-2.5, tmp.size().height()-5);
painter.drawLine(2.5, 0, 2.5, tmp.size().height());
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width() + 5, tmp.size().height()-2.5);
this->horyzontal_triangle << new QLabel(ui->scrollAreaWidgetContents);
this->horyzontal_triangle.last()->setPixmap(tmp);
this->horyzontal_triangle.last()->move(250+100*j, 950 + nl*i);
this->horyzontal_triangle.last()->show();
this->horyzontal_triangle_coords_Y << this->horyzontal_triangle.last()->geometry().y();
this->horyzontal_triangle_coords_X << this->horyzontal_triangle.last()->geometry().x();
}
if(1){ //lines vertical
QPixmap tmp(5,30+75*j); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(250+100*j, 950 + nl*i - tmp.height());
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
if(1){ //lines horyzontal
QPixmap tmp(140+100*j,5); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(250+100*j - tmp.width(), 945 + nl*i-(25+75*j));
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("ПГ "+QString::number(i+1));
this->rl.last()->move(200, 975 + nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("0,3");
this->rl.last()->move(10, 50+55+75*j+nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("3,4");
this->rl.last()->move(90, 50+55+75*j+nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(108-4*j));
this->rl.last()->move(130, 50+25+75*j+nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(104.3-4*j));
this->rl.last()->move(250+100*j, 1000 + nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(107.4-4*j));
this->rl.last()->move(325+100*j, 1000 + nl*i);
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
}
if((i+1)%5 == 0){ // draw VG
for(int ij = 0; ij < 5; ij++){
if(1){
QPixmap tmp(100,50); // ширина, висота
tmp.fill(QColor(0,0,0,0));
QPainter painter(&tmp);
QPen pen(QBrush (QColor(230,30,116), Qt::SolidPattern), 5);
painter.setPen(pen);
QFont f("Myriad Pro", 12);
f.setBold(true);
painter.setFont(f);
painter.drawText((int)tmp.size().width()/1.7, (int)tmp.size().height()-7, QString::number(5-ij+5*(((i+1)/5)-1)));
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width(), 0);
painter.drawLine(tmp.size().width()-2.5, 5, tmp.size().width()-2.5, tmp.size().height());
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width()-2.5, tmp.size().height()-2.5);
this->horyzontal_triangle << new QLabel(ui->scrollAreaWidgetContents);
this->horyzontal_triangle.last()->setPixmap(tmp);
this->horyzontal_triangle.last()->move(1600+100*ij, 5050 + 5000*(((i+1)/5)-1));
this->horyzontal_triangle.last()->show();
this->horyzontal_triangle_coords_Y << this->horyzontal_triangle.last()->geometry().y();
this->horyzontal_triangle_coords_X << this->horyzontal_triangle.last()->geometry().x();
}
if(1){ //lines vertical
QPixmap tmp(5,50+1000*ij); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(1695+100*ij, 5050 + 5000*(((i+1)/5)-1) - tmp.height());
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
if(1){ //lines horyzontal
QPixmap tmp(300+100*ij,5); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(1700+100*ij - tmp.width(), 5020 + 5000*(((i+1)/5)-1)-(25+1000*ij));
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(540.3-4*ij));
this->rl.last()->move(1600+100*ij, 5100 + 5000*(((i+1)/5)-1));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(551.4-4*ij));
this->rl.last()->move(1665+100*ij, 5100 + 5000*(((i+1)/5)-1));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(612-48*ij));
this->rl.last()->move(1500, 5005 + 5000*(((i+1)/5)-1)-(25+1000*ij));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
}
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("ВГ "+QString::number((i+1)/5));
this->rl.last()->move(1575, 5055 + 5000*(((i+1)/5)-1));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
}
if((i+1)%25 == 0){ // draw TG
for(int ijj = 0; ijj < 5; ijj++){
if(1){
QPixmap tmp(100,50); // ширина, висота
tmp.fill(QColor(0,0,0,0));
QPainter painter(&tmp);
QPen pen(QBrush (QColor(230,30,116), Qt::SolidPattern), 5);
painter.setPen(pen);
QFont f("Myriad Pro", 12);
f.setBold(true);
painter.setFont(f);
painter.drawText(15, (int)tmp.size().height()-7, QString::number(5-ijj+5*(((i+1)/25)-1)));
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawLine(2.5, 0, tmp.size().width()-2.5, tmp.size().height()-5);
painter.drawLine(2.5, 0, 2.5, tmp.size().height());
painter.drawLine(0, tmp.size().height()-2.5, tmp.size().width() + 5, tmp.size().height()-2.5);
this->horyzontal_triangle << new QLabel(ui->scrollAreaWidgetContents);
this->horyzontal_triangle.last()->setPixmap(tmp);
this->horyzontal_triangle.last()->move(2200+100*ijj, 5150 + 5000*(((i+1)/5)-1));
this->horyzontal_triangle.last()->show();
this->horyzontal_triangle_coords_Y << this->horyzontal_triangle.last()->geometry().y();
this->horyzontal_triangle_coords_X << this->horyzontal_triangle.last()->geometry().x();
}
if(1){ //lines vertical
QPixmap tmp(5,50+5000*ijj); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(2200+100*ijj, 5150 + 5000*(((i+1)/5)-1) - tmp.height());
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
if(1){ //lines horyzontal
QPixmap tmp(300+100*ijj,5); // ширина, висота
tmp.fill(Qt::black);
this->lines << new QLabel(ui->scrollAreaWidgetContents);
this->lines.last()->setPixmap(tmp);
this->lines.last()->move(2205+100*ijj - tmp.width(), 25095 + 25000*(((i+1)/25)-1)-(5000*ijj));
this->lines.last()->show();
this->lines_coords_Y << this->lines.last()->geometry().y();
this->lines_coords_X << this->lines.last()->geometry().x();
}
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(1804.6-248*ijj));
this->rl.last()->move(2205+100*ijj, 5200 + 5000*(((i+1)/5)-1));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(2103.7-128*ijj));
this->rl.last()->move(2265+100*ijj, 5200 + 5000*(((i+1)/5)-1));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText(QString::number(2356-248*ijj));
this->rl.last()->move(2120, 5105 + 5000*(((i+1)/5)-1)-(25+1000*ijj));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
}
this->rl << new QLabel(ui->scrollAreaWidgetContents);
this->rl.last()->setText("ТГ "+QString::number((i+1)/25));
this->rl.last()->move(2170, 5165 + 5000*(((i+1)/5)-1));
this->rl.last()->show();
this->rl_coords_Y << this->rl.last()->geometry().y();
this->rl_coords_X << this->rl.last()->geometry().x();
}
}
}
this->setVerticalScrollBarRange();
this->setHorizontalScrollBarRange();
}
void MainWindow::setVerticalScrollBarRange()
{
if(!this->vertical_triangle_coords_Y.isEmpty())
if(this->vertical_triangle_coords_Y.last() > 300)
ui->verticalScrollBar->setRange(0,this->vertical_triangle_coords_Y.last() - 300);
else
ui->verticalScrollBar->setRange(0,0);
else
ui->horizontalScrollBar->setRange(0,0);
}
void MainWindow::setHorizontalScrollBarRange()
{
if(!this->horyzontal_triangle_coords_X.isEmpty())
if(this->horyzontal_triangle_coords_X.last() > 300)
ui->horizontalScrollBar->setRange(0,this->horyzontal_triangle_coords_X.last()+500);
else
ui->horizontalScrollBar->setRange(0,0);
else
ui->horizontalScrollBar->setRange(0,0);
}
void MainWindow::on_pushButton_2_clicked() //clear memory
{
for(auto i : this->vertical_triangle) delete i;
this->vertical_triangle.clear();
this->vertical_triangle_coords_X.clear();
this->vertical_triangle_coords_Y.clear();
for(auto i : horyzontal_triangle) delete i;
this->horyzontal_triangle.clear();
this->horyzontal_triangle_coords_X.clear();
this->horyzontal_triangle_coords_Y.clear();
for(auto i : this->lines) delete i;
this->lines.clear();
this->lines_coords_X.clear();
this->lines_coords_Y.clear();
for(auto i : this->rl) delete i;
this->rl.clear();
this->rl_coords_X.clear();
this->rl_coords_Y.clear();
}
void MainWindow::on_verticalScrollBar_sliderMoved(int p)
{
for(int i = 0; i < this->vertical_triangle.size(); i++){
this->vertical_triangle.at(i)->move(this->vertical_triangle.at(i)->geometry().x(), this->vertical_triangle_coords_Y.at(i)-p);
}
for(int i = 0; i < this->horyzontal_triangle.size(); i++){
this->horyzontal_triangle.at(i)->move(this->horyzontal_triangle.at(i)->geometry().x(), this->horyzontal_triangle_coords_Y.at(i)-p);
}
for(int i = 0; i < this->lines.size(); i++){
this->lines.at(i)->move(this->lines.at(i)->geometry().x(), this->lines_coords_Y.at(i)-p);
}
for(int i = 0; i < this->rl.size(); i++){
this->rl.at(i)->move(this->rl.at(i)->geometry().x(), this->rl_coords_Y.at(i)-p);
}
}
void MainWindow::on_horizontalScrollBar_sliderMoved(int p)
{
for(int i = 0; i < this->vertical_triangle.size(); i++){
this->vertical_triangle.at(i)->move(this->vertical_triangle_coords_X.at(i)-p, this->vertical_triangle.at(i)->geometry().y());
}
for(int i = 0; i < this->horyzontal_triangle.size(); i++){
this->horyzontal_triangle.at(i)->move(this->horyzontal_triangle_coords_X.at(i)-p, this->horyzontal_triangle.at(i)->geometry().y());
}
for(int i = 0; i < this->lines.size(); i++){
this->lines.at(i)->move(this->lines_coords_X.at(i)-p, this->lines.at(i)->geometry().y());
}
for(int i = 0; i < this->rl.size(); i++){
this->rl.at(i)->move(this->rl_coords_X.at(i)-p, this->rl.at(i)->geometry().y());
}
}
|
9ad7165921a2d856163058923ee34bad47d67d53 | 4e0590ddf391d3b70e01e332b9bb61b644d4312d | /code/pm/src/ode_solv.cpp | a57f9ffa51c69d0efe27c5f19e89de1eb548a363 | [] | no_license | ktbolt/ProteinMechanica | 8724f2f12ba892a32b69423fd4dbb52b169a4981 | e02effec46550b1a91061dd052af54ae56a7546f | refs/heads/master | 2020-06-22T04:41:28.728730 | 2020-06-09T04:21:36 | 2020-06-09T04:21:36 | 197,635,184 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60,875 | cpp | ode_solv.cpp | /* -------------------------------------------------------------------------- *
* Protein Mechanica *
* -------------------------------------------------------------------------- *
* This is part of the Protein Mechanica coarse-grained molecular motor *
* modeling application originating from Simbios, the NIH National Center for *
* Physics-Based Simulation of Biological Structures at Stanford, funded *
* under the NIH Roadmap for Medical Research, grant U54 GM072970. *
* See https://simtk.org. *
* *
* Portions copyright (c) 2010 Stanford University and the Authors. *
* Authors: David Parker *
* Contributors: *
* *
* 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, CONTRIBUTORS 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. *
* -------------------------------------------------------------------------- */
//*============================================================*
//* ode_solv: O D E s o l v e r *
//*============================================================*
// interface to the OpenDynamicsEngine.
#include "ode_solv.h"
#include "pm/mth.h"
// debug symbols //
//#define dbg_PmOdeSolver
namespace ProteinMechanica {
static int vel_param[] = { dParamVel, dParamVel2, dParamVel3 };
static int force_param[] = { dParamFMax, dParamFMax2, dParamFMax3 };
//*============================================================*
//*========== constructors / destructor ==========*
//*============================================================*
PmOdeSolver::PmOdeSolver(const string name)
{
#ifdef dbg_PmOdeSolver
fprintf (stderr, ">>>>>> PmOdeSolver: ctor [%s] \n", name.c_str());
#endif
this->name = name;
initialzed = false;
}
//*============================================================*
//*========== initialize ==========*
//*============================================================*
void
PmOdeSolver::initialize(PmRigidSimulation *sim, double time_step)
{
#ifdef dbg_PmOdeSolver
fprintf (stderr, "\n-------------------------------\n");
fprintf (stderr, ">>>>>> ODE Solver: initialize \n");
fprintf (stderr, " >>> size of dReal[%d]\n", sizeof(dReal));
#endif
simulation = sim;
#ifdef PM_ODE_SOLVER
if (initialzed) {
return;
}
dInitODE();
// get bodies from simulation //
vector<PmBody*> bodies;
sim->getBodies(bodies);
int num_bodies = bodies.size();
#ifdef dbg_PmOdeSolver
fprintf (stderr, " >>> num bodies [%d] \n", num_bodies);
#endif
if (num_bodies == 0) {
return;
}
PmOdeSolverData *prvd = new PmOdeSolverData;
prv_data = prvd;
// get joints //
vector<PmJoint*> joints;
sim->getJoints(joints);
int num_joints = joints.size();
#ifdef dbg_PmOdeSolver
fprintf (stderr, " >>> num joints [%d] \n", num_joints);
#endif
// check to make sure the bodies defined for the joints //
// have been added to the simualtion. //
if (!checkBodies(joints, bodies)) {
return;
}
// create ode world //
prvd->world = dWorldCreate();
#ifdef dbg_PmOdeSolver
fprintf (stderr, " >>> size of ODE real [%d] \n", sizeof(dReal));
#endif
// set error control //
//dReal erp, cfm;
//dWorldSetERP (prvd->world, erp);
//dWorldSetCFM (prvd->world, cfm);
// set quick step option //
prvd->quick_step = false;
// add bodies //
addBodies(bodies);
// add joints //
if (!addJoints(joints)) {
return;
}
prvd->num_bodies = num_bodies;
prvd->num_joints = num_joints;
prvd->time = 0.0;
prvd->time_step = time_step;
prvd->step = 0;
initialzed = true;
// add initial state //
update();
#else
#endif
}
//*============================================================*
//*========== setParam ==========*
//*============================================================*
// set an ode solver parameter.
bool
PmOdeSolver::setParam(const string name, const string val)
{
#ifdef dbg_PmOdeSolver
fprintf (stderr, "\n-------------------------------\n");
fprintf (stderr, ">>>>>> ODE Solver: set parameter \n");
#endif
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
if (name == "finite_rotation") {
return true;
}
else if (name == "momentum") {
return true;
}
else if (name == "quick_step") {
prvd->quick_step = (val == "true");
return true;
}
return false;
}
//*============================================================*
//*========== step ==========*
//*============================================================*
// step the ode solver.
void
PmOdeSolver::step()
{
#ifdef PM_ODE_SOLVER
#ifdef dbg_PmOdeSolver
fprintf (stderr, "\n-------------------------------\n");
fprintf (stderr, ">>>>>> ODE Solver: step \n");
#endif
if (!initialzed) {
return;
}
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
#ifdef dbg_PmOdeSolver
fprintf (stderr, " time step [%g] \n", prvd->time_step);
#endif
// step motors //
stepMotors();
// add forces to bodies //
addForces();
// step dynamics //
#ifdef dbg_PmOdeSolver
fprintf (stderr, " step dynamics \n" );
#endif
if (prvd->quick_step) {
dWorldQuickStep (prvd->world, prvd->time_step);
}
else {
dWorldStep (prvd->world, prvd->time_step);
}
prvd->step += 1;
prvd->time += prvd->time_step;
// if momentum is off then zero velocities //
if (simulation->getMomentumOff()) {
//fprintf (stderr, ">>> momentum off \n");
for (unsigned int i = 0; i < prvd->bodies.size(); i++) {
dBodyID obody = prvd->bodies[i].ode;
if (obody) {
dBodySetLinearVel (obody, 0.0, 0.0, 0.0);
dBodySetAngularVel (obody, 0.0, 0.0, 0.0);
}
}
}
// update objects state //
update();
#endif
}
//*============================================================*
//*========== setState ==========*
//*============================================================*
// set the state for the bodies in the simulation.
void
PmOdeSolver::setState(vector<string>& body_names, vector<PmRigidBodyState>& states)
{
//fprintf (stderr, ">>>>>> PmOdeSolver::setState \n");
PmBody *body;
dBodyID obody;
const dReal *pos;
dMatrix3 R;
PmVector3 disp, rot, new_pos, vel, avel;
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
for (int i = 0; i < body_names.size(); i++) {
//fprintf (stderr, "--- body %s --- \n", body_names[i].c_str());
pmSystem.getBody(body_names[i], &body);
if (!body) {
continue;
}
ode_getBody(prvd, body, &obody);
pos = dBodyGetPosition (obody);
//fprintf (stderr, ">>> pos = %f %f %f \n", pos[0], pos[1], pos[2]);
disp = states[i].displacement;
// set position //
for (int j = 0; j < 3; j++) {
new_pos[j] = pos[j] + disp[j];
}
dBodySetPosition (obody, new_pos[0], new_pos[1], new_pos[2]);
// set rotation //
R[0] = states[i].rotation_matrix(0,0);
R[1] = states[i].rotation_matrix(0,1);
R[2] = states[i].rotation_matrix(0,2);
R[3] = 0.0;
R[4] = states[i].rotation_matrix(1,0);
R[5] = states[i].rotation_matrix(1,1);
R[6] = states[i].rotation_matrix(1,2);
R[7] = 0.0;
R[8] = states[i].rotation_matrix(2,0);
R[9] = states[i].rotation_matrix(2,1);
R[10] = states[i].rotation_matrix(2,2);
R[11] = 0.0;
dBodySetRotation (obody, R);
// set velocity //
/*
fprintf (stderr, ">> vel = %f %f %f \n", states[i].velocity[0],
states[i].velocity[1], states[i].velocity[2]);
*/
dBodySetLinearVel (obody, states[i].velocity[0], states[i].velocity[1],
states[i].velocity[2]);
dBodySetAngularVel (obody, states[i].angular_velocity[0],
states[i].angular_velocity[1], states[i].angular_velocity[2]);
}
update();
}
//*============================================================*
//*========== setTimeStep ==========*
//*============================================================*
// set time step.
void
PmOdeSolver::setTimeStep(const double step)
{
#ifdef PM_ODE_SOLVER
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
prvd->time_step = step;
#endif
}
////////////////////////////////////////////////////////////////
// p r i v a t e //
//////////////////////////////////////////////////////////////
//*============================================================*
//*========== addBodies ==========*
//*============================================================*
// add bodies to ode solver.
void
PmOdeSolver::addBodies(vector<PmBody*> bodies)
{
#ifdef PM_ODE_SOLVER
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
int num_bodies = bodies.size();
PmOdeBody obody;
PmBody *body;
PmMassProperties props;
dMass omass_props;
PmBodyType type;
string name;
dReal xp, yp, zp;
#ifdef dbg_PmOdeSolver
fprintf (stderr, " --- add bodies --- \n");
#endif
for (int i = 0; i < num_bodies; i++) {
body = bodies[i];
body->getName(name);
//body->setRotOrderZYX(true);
type = body->getType();
#ifdef dbg_PmOdeSolver
fprintf (stderr, " >>> body[%s] type[%d] \n", name.c_str(), type);
#endif
if (type != PM_BODY_GROUND) {
// create an ode body //
obody.ode = dBodyCreate (prvd->world);
// set mass properties //
body->getMassProps(props);
xp = props.com[0];
yp = props.com[1];
zp = props.com[2];
dBodySetPosition (obody.ode, xp, yp, zp);
#ifdef dbg_PmOdeSolver
fprintf (stderr, " mass[%g] \n", props.mass);
fprintf (stderr, " com (%g %g %g) \n", xp, yp, zp);
fprintf (stderr, " I (%g %g %g) \n", props.inertia(0,0),
props.inertia(1,1),
props.inertia(2,2));
fprintf (stderr, " (%g %g %g) \n", props.inertia(0,1),
props.inertia(0,2),
props.inertia(1,2));
#endif
// center of mass in body frame //
props.com[0] = 0.0;
props.com[1] = 0.0;
props.com[2] = 0.0;
dMassSetParameters (&omass_props, props.mass,
props.com[0], props.com[1], props.com[2],
props.inertia(0,0), props.inertia(1,1),
props.inertia(2,2), props.inertia(0,1),
props.inertia(0,2), props.inertia(1,2));
dBodySetMass (obody.ode, &omass_props);
dBodySetFiniteRotationMode (obody.ode, 1);
dBodySetFiniteRotationAxis (obody.ode, 0.0, 0.0, 0.0);
}
else {
obody.ode = 0;
}
#ifdef dbg_PmOdeSolver
fprintf (stderr, " map pmbody[%x] to ode body[%x] \n", body, obody.ode);
#endif
obody.pm = body;
prvd->bodies.push_back(obody);
}
#endif
}
//*============================================================*
//*========== checkBodies ==========*
//*============================================================*
// check bodies.
bool
PmOdeSolver::checkBodies(vector<PmJoint*> joints, vector<PmBody*> bodies)
{
#ifdef PM_ODE_SOLVER
//PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
int num_bodies = bodies.size();
int num_joints = joints.size();
PmBody *body1, *body2;
// check to make sure the bodies defined for the joints //
// have been added to the simualtion. //
for (int i = 0; i < num_joints; i++) {
PmJoint *joint = joints[i];
joint->getBodies(&body1, &body2);
if (!body1 || !body2) {
string name;
joint->getName(name);
pm_ErrorReport ("pm> ", "joint \"%s\" bodies not defined.", "*", name.c_str());
return false;
}
bool body_found = false;
for (int j = 0; j < num_bodies; j++) {
if (body1 == bodies[j]) {
body_found = true;
break;
}
}
if (!body_found) {
string name;
body1->getName(name);
pm_ErrorReport ("PM", "body \"%s\" not defined.", "*", name.c_str());
return false;
}
body_found = false;
for (int j = 0; j < num_bodies; j++) {
if (body2 == bodies[j]) {
body_found = true;
break;
}
}
if (!body_found) {
string name;
body2->getName(name);
pm_ErrorReport ("PM", "body \"%s\" not defined.", "*", name.c_str());
return false;
}
}
return true;
#endif
}
//*============================================================*
//*========== addForces ==========*
//*============================================================*
// add forces to the bodies.
//#define dbg_PmOdeSolver
void
PmOdeSolver::addForces()
{
#ifdef PM_ODE_SOLVER
#ifdef dbg_PmOdeSolver
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
fprintf (stderr, ">>> ODE Solver: addForces time [%g] \n", prvd->time);
#endif
if (!initialzed) {
return;
}
// reset forces //
vector<PmBody*> bodies;
simulation->getBodies(bodies);
for (unsigned int i = 0; i < bodies.size(); i++) {
bodies[i]->resetForces();
}
// add joint forces //
addJointForces();
// add restraint forces //
addRestraintForces();
// add explicit forces //
addExplicitForces();
// add random forces //
addRandomForces();
// add damping forces //
addDampingForces();
// add interaction forces //
addInteractionForces();
}
//*============================================================*
//*========== addExplcitForces ==========*
//*============================================================*
// add explicit forces.
void
PmOdeSolver::addExplicitForces()
{
#ifdef dbg_PmOdeSolver
fprintf (stderr, ">>>>>> PmOdeSolver::addExplcitForces \n");
#endif
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
vector<PmExplicitForce*> forces;
simulation->getForces(forces);
int num = forces.size();
#ifdef dbg_PmOdeSolver
fprintf (stderr, " num forces[%d] \n", num);
#endif
if (!num) {
return;
}
dBodyID obody;
PmVector3 com, force, loc, vec, floc;
bool global_frame = false;
// ODE types //
const dReal *pos, *r;
dVector3 gvec;
double global_pt[3];
PmBody *body;
float time = prvd->time;
// apply each force to the appropriate body //
for (int i = 0; i < num; i++) {
if (!forces[i]->isActive(time)) {
continue;
}
forces[i]->getGlobalFrame(global_frame);
forces[i]->getObj((void**)&body);
#ifdef dbg_PmOdeSolver
fprintf (stderr, "--- %d body[%x] --- \n", i, body);
#endif
ode_getBody(prvd, body, &obody);
body->getCenterOfMass(com);
forces[i]->getDirection(time, force);
#ifdef dbg_PmOdeSolver
fprintf (stderr, "com (%g %g %g) \n", com[0], com[1], com[2]);
fprintf (stderr, "force (%g %g %g) \n", force[0], force[1], force[2]);
#endif
// apply a torque //
if (forces[i]->isTorque()) {
dBodyAddTorque(obody, force[0], force[1], force[2]);
dBodyGetRelPointPos (obody, 0, 0, 0, gvec);
for (int j = 0; j < 3; j++) {
floc[j] = gvec[j];
}
forces[i]->display(floc);
}
// apply force in global frame //
else if (global_frame) {
forces[i]->getPoint(loc);
pos = dBodyGetPosition (obody);
r = dBodyGetRotation (obody);
vec = loc - com;
dBodyVectorToWorld (obody, vec[0], vec[1], vec[2], gvec);
#ifdef dbg_PmOdeSolver
fprintf (stderr, "pos (%g %g %g) \n", pos[0], pos[1], pos[2]);
#endif
for (int j = 0; j < 3; j++) {
global_pt[j] = pos[j] + gvec[j];
floc[j] = pos[j] + gvec[j];
}
dBodyAddForceAtPos (obody, force[0], force[1], force[2], global_pt[0],
global_pt[1], global_pt[2]);
/*
fprintf (stderr, " global_pt (%g %g %g) \n", global_pt[0], global_pt[1],
global_pt[2]);
*/
//simulation->displayForce(forces[i], floc);
PmMatrix3x3 m;
PmXform body_xform;
m(0,0) = r[0]; m(1,0) = r[4]; m(2,0) = r[8];
m(0,1) = r[1]; m(1,1) = r[5]; m(2,1) = r[9];
m(0,2) = r[2]; m(1,2) = r[6]; m(2,2) = r[10];
body_xform.translation[0] = pos[0] - com[0];
body_xform.translation[1] = pos[1] - com[1];
body_xform.translation[2] = pos[2] - com[2];
body->getCenterOfMass (com);
body_xform.center = com;
body_xform.setRotation(m);
forces[i]->setXform(body_xform);
forces[i]->display(floc);
}
// apply force in local frame //
else {
forces[i]->getPoint(loc);
dBodyAddForceAtRelPos (obody, force[0], force[1], force[2], loc[0], loc[1], loc[2]);
dBodyGetRelPointPos (obody, loc[0], loc[1], loc[2], gvec);
for (int j = 0; j < 3; j++) {
floc[j] = gvec[j];
}
forces[i]->display(floc);
}
}
#endif
}
//*============================================================*
//*========== addRandomForces ==========*
//*============================================================*
// add random forces.
void
PmOdeSolver::addRandomForces()
{
#ifdef dbg_PmOdeSolver
fprintf (stderr, ">>>>>> PmOdeSolver::addRandomForces \n");
#endif
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
vector<PmRandomForce*> forces;
simulation->getForces(forces);
int num = forces.size();
#ifdef dbg_PmOdeSolver
fprintf (stderr, " num forces[%d] \n", num);
#endif
if (!num) {
return;
}
dBodyID obody;
PmVector3 com, force, loc, vec, floc;
// ODE types //
dVector3 gvec;
PmBody *body;
float time = prvd->time;
// apply each random force to the appropriate body //
for (int i = 0; i < num; i++) {
if (!forces[i]->isActive(time)) {
continue;
}
forces[i]->getObj((void**)&body);
#ifdef dbg_PmOdeSolver
fprintf (stderr, "--- %d body[%x] --- \n", i, body);
#endif
ode_getBody(prvd, body, &obody);
body->getCenterOfMass(com);
// generate and apply a random force //
forces[i]->genForce(force);
#ifdef dbg_PmOdeSolver
fprintf (stderr, "com (%g %g %g) \n", com[0], com[1], com[2]);
fprintf (stderr, "force (%g %g %g) \n", force[0], force[1], force[2]);
#endif
loc.set(0,0,0);
dBodyAddForceAtRelPos (obody, force[0], force[1], force[2], loc[0], loc[1], loc[2]);
dBodyGetRelPointPos (obody, loc[0], loc[1], loc[2], gvec);
for (int j = 0; j < 3; j++) {
floc[j] = gvec[j];
}
forces[i]->display(floc);
// generate and apply a random torque //
forces[i]->genForce(force);
dBodyAddTorque(obody, force[0], force[1], force[2]);
}
}
//*============================================================*
//*========== addDampingForces ==========*
//*============================================================*
// add damping forces.
void
PmOdeSolver::addDampingForces()
{
#ifdef dbg_PmOdeSolver
fprintf (stderr, ">>>>>> PmOdeSolver::addDampingForces\n");
#endif
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
if (!simulation->getDamping()) {
return;
}
const dReal *vel, *avel;
PmBody *body;
dBodyID obody;
PmVector3 com, force;
float c, factor, length;
vector<PmBody*> bodies;
simulation->getBodies(bodies);
for (unsigned int i = 0; i < bodies.size(); i++) {
body = bodies[i];
if (body->isGround()) {
continue;
}
if (!body->getDampingFactor(factor, length)) {
continue;
}
// generate and apply a damping force //
ode_getBody(prvd, body, &obody);
vel = dBodyGetLinearVel(obody);
c = factor;
force[0] = -c*vel[0];
force[1] = -c*vel[1];
force[2] = -c*vel[2];
dBodyAddForce (obody, force[0], force[1], force[2]);
//fprintf (stderr, " >>> force = %g %g %g \n", force[0], force[1], force[2]);
// generate and apply a damping torque //
avel = dBodyGetAngularVel(obody);
length /= 2.0;
if (length > 0.1) {
c = factor*length*length;
force[0] = -c*avel[0];
force[1] = -c*avel[1];
force[2] = -c*avel[2];
dBodyAddTorque(obody, force[0], force[1], force[2]);
}
}
}
//*============================================================*
//*========== addInteractionForces ==========*
//*============================================================*
// add interaction forces.
void
PmOdeSolver::addInteractionForces()
{
#ifdef dbg_PmOdeSolver_addInteractionForces
fprintf (stderr, "\n------ addInteractionForces ------\n");
#endif
vector<PmInteraction*> interactions;
string intr_name;
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
float time = prvd->time;
//===== get the interactions defined for a simulation =====//
simulation->getInteractions(interactions);
bool upd = simulation->checkUpdateState();
//===== compute interaction forces =====//
for (unsigned int i = 0; i < interactions.size(); i++) {
//fprintf (stderr, "--- interaction[%s] ---\n", intr_name.c_str());
//if (interactions[i]->isActive(time)) {
interactions[i]->compForces(upd, time);
}
//===== apply forces generated from interactions =====//
vector<PmBody*> bodies;
vector<PmForceVector> forces;
string bname;
PmVector3 dir, loc;
dBodyID obody;
simulation->getBodies(bodies);
for (unsigned int i = 0; i < bodies.size(); i++) {
bodies[i]->getForces(forces);
ode_getBody(prvd, bodies[i], &obody);
//bodies[i]->getName(bname);
//fprintf (stderr, ">>> body[%s] num forces[%d]\n", bname.c_str(), forces.size());
for (unsigned int j = 0; j < forces.size(); j++) {
loc = forces[j].point;
dir = forces[j].direction;
dBodyAddForceAtPos (obody, dir[0], dir[1], dir[2], loc[0], loc[1], loc[2]);
#ifdef dbg_PmOdeSolver_addInteractionForces
fprintf (stderr, "-------------------\n");
fprintf (stderr, ">>> loc (%g %g %g) \n", loc[0], loc[1], loc[2]);
fprintf (stderr, ">>> dir (%g %g %g) \n", dir[0], dir[1], dir[2]);
#endif
}
}
// now apply any torques generated from the interactions //
for (unsigned int i = 0; i < bodies.size(); i++) {
bodies[i]->getTorques(forces);
ode_getBody(prvd, bodies[i], &obody);
for (unsigned int j = 0; j < forces.size(); j++) {
dir = forces[j].direction;
dBodyAddTorque(obody, dir[0], dir[1], dir[2]);
//fprintf (stderr, ">>> add torque (%g %g %g) \n", dir[0], dir[1], dir[2]);
}
}
}
//*============================================================*
//*========== addJointForces ==========*
//*============================================================*
// add joint forces.
void
PmOdeSolver::addJointForces()
{
#ifdef PM_ODE_SOLVER
#ifdef dbg_PmOdeSolver_addInteractionForces
fprintf (stderr, "\n------ addJointForces ------\n");
#endif
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
PmBody *body1, *body2;
PmJoint *joint;
PmJointType jtype;
dJointID ojoint;
float energy;
bool upd = simulation->checkUpdateState();
// for each joint type add torque if it has a non-zero force constant //
int num_joints = prvd->joints.size();
for (int i = 0; i < num_joints; i++) {
joint = prvd->joints[i].pm;
if (joint->hasMotors()) {
continue;
}
ojoint = prvd->joints[i].ode;
jtype = joint->getType();
joint->getBodies(&body1, &body2);
// universal joint //
if (jtype == PM_JOINT_UNIVERSAL) {
PmUniversalJoint *ujoint = dynamic_cast<PmUniversalJoint*>(joint);
float k1, k2, ang1, ang2, dang, torque1, torque2;
ujoint->getForceConst(1,k1);
ujoint->getForceConst(2,k2);
//fprintf (stderr, " >>> ujoint k1[%f] k2[%f] \n", k1, k2);
if (k1 + k2 == 0.0) {
continue;
}
ang1 = dJointGetUniversalAngle1(ojoint);
ang2 = dJointGetUniversalAngle2(ojoint);
//fprintf (stderr, " >>> ang1[%f] ang2[%f] \n", ang1, ang2);
dang = ang1;
if (dang > M_PI) dang -= 2*M_PI;
if (dang < -M_PI) dang += 2*M_PI;
torque1 = dang*k1;
dang = ang2;
if (dang > M_PI) dang -= 2*M_PI;
if (dang < -M_PI) dang += 2*M_PI;
torque2 = dang*k2;
dJointAddUniversalTorques (ojoint, -torque1, -torque2);
}
// ball joint //
else if (jtype == PM_JOINT_BALL) {
PmBallJoint *bjoint = dynamic_cast<PmBallJoint*>(joint);
float k1, k2, k3, ang1, ang2, ang3, dang, torque1, torque2, torque3;
PmVector3 axis1, axis2, axis3, u1, v1, w1, u2, v2, w2, dir, u, v, w;
dBodyID obody1, obody2, obody;
const dReal *r1, *r2;
PmMatrix3x3 m1, m2, rmat;
float dcm[3][3], rang[3];
bjoint->getForceConst(1,k1);
bjoint->getAxis(1,axis1);
bjoint->getForceConst(2,k2);
bjoint->getAxis(2,axis2);
bjoint->getForceConst(3,k3);
bjoint->getAxis(3,axis3);
/*
fprintf (stderr, "\n");
fprintf (stderr, ">>> axis1 = %f %f %f \n", axis1[0], axis1[1], axis1[2]);
fprintf (stderr, ">>> axis2 = %f %f %f \n", axis2[0], axis2[1], axis2[2]);
fprintf (stderr, ">>> axis3 = %f %f %f \n", axis3[0], axis3[1], axis3[2]);
fprintf (stderr, ">>> k1 = %f k2 = %f k3 = %f \n", k1, k2, k3);
*/
if (k1 + k2 + k3 == 0.0) {
continue;
}
ode_getBody(prvd, body1, &obody1);
ode_getBody(prvd, body2, &obody2);
// obody1 is 0 then it is the ground //
if (obody1) {
r1 = dBodyGetRotation(obody1);
m1(0,0) = r1[0]; m1(1,0) = r1[4]; m1(2,0) = r1[8];
m1(0,1) = r1[1]; m1(1,1) = r1[5]; m1(2,1) = r1[9];
m1(0,2) = r1[2]; m1(1,2) = r1[6]; m1(2,2) = r1[10];
u1 = m1*axis1;
v1 = m1*axis2;
w1 = m1*axis3;
obody = obody1;
}
else {
m1.diag(1.0);
u1 = axis1;
v1 = axis2;
w1 = axis3;
}
if (obody2) {
r2 = dBodyGetRotation(obody2);
m2(0,0) = r2[0]; m2(1,0) = r2[4]; m2(2,0) = r2[8];
m2(0,1) = r2[1]; m2(1,1) = r2[5]; m2(2,1) = r2[9];
m2(0,2) = r2[2]; m2(1,2) = r2[6]; m2(2,2) = r2[10];
u2 = m2*axis1;
v2 = m2*axis2;
w2 = m2*axis3;
obody = obody2;
}
else {
m2.diag(1.0);
u2 = axis1;
v2 = axis2;
w2 = axis3;
}
/*
fprintf (stderr, ">>> u1 = %f %f %f \n", u1[0], u1[1], u1[2]);
fprintf (stderr, " v1 = %f %f %f \n", v1[0], v1[1], v1[2]);
fprintf (stderr, " w1 = %f %f %f \n", w1[0], w1[1], w1[2]);
fprintf (stderr, "\n");
fprintf (stderr, ">>> u2 = %f %f %f \n", u2[0], u2[1], u2[2]);
fprintf (stderr, " v2 = %f %f %f \n", v2[0], v2[1], v2[2]);
fprintf (stderr, " w2 = %f %f %f \n", w2[0], w2[1], w2[2]);
*/
// compute rotation from one axes to the other //
pm_MathFrameRotation(u1, v1, w1, u2, v2, w2, rmat);
/*
u = rmat*u1 - u2;
v = rmat*v1 - v2;
w = rmat*w1 - w2;
fprintf (stderr, ">>> diff vec = %f %f %f\n", u.length(), v.length(), w.length());
*/
// extract angles from rotation matrix //
dcm[0][0] = rmat(0,0); dcm[0][1] = rmat(0,1); dcm[0][2] = rmat(0,2);
dcm[1][0] = rmat(1,0); dcm[1][1] = rmat(1,1); dcm[1][2] = rmat(1,2);
dcm[2][0] = rmat(2,0); dcm[2][1] = rmat(2,1); dcm[2][2] = rmat(2,2);
pm_MathExtractRotations(dcm, rang);
//fprintf (stderr, ">>> rang = %f %f %f \n", rang[0], rang[1], rang[2]);
// axis 1 //
if (k1 != 0.0) {
ang1 = rang[0];
dang = ang1;
if (dang > M_PI) dang -= 2*M_PI;
if (dang < -M_PI) dang += 2*M_PI;
torque1 = dang*k1;
dir = axis1;
dir.set(1,0,0);
if (obody1) {
//dir = u1;
//dBodyAddRelTorque(obody1, torque1*dir[0], torque1*dir[1], torque1*dir[2]);
dBodyAddTorque(obody1, torque1*dir[0], torque1*dir[1], torque1*dir[2]);
}
if (obody2) {
//dir = u2;
torque1 = -torque1;
//dBodyAddRelTorque(obody2, torque1*dir[0], torque1*dir[1], torque1*dir[2]);
dBodyAddTorque(obody2, torque1*dir[0], torque1*dir[1], torque1*dir[2]);
}
}
// axis 2 //
if (k2 != 0.0) {
ang2 = rang[1];
dang = ang2;
if (dang > M_PI) dang -= 2*M_PI;
if (dang < -M_PI) dang += 2*M_PI;
torque2 = dang*k2;
dir = axis2;
dir.set(0,1,0);
if (obody1) {
//dir = v1;
//dBodyAddRelTorque(obody1, torque2*dir[0], torque2*dir[1], torque2*dir[2]);
dBodyAddTorque(obody1, torque2*dir[0], torque2*dir[1], torque2*dir[2]);
}
if (obody2) {
//dir = v2;
torque2 = -torque2;
//dBodyAddRelTorque(obody2, torque2*dir[0], torque2*dir[1], torque2*dir[2]);
dBodyAddTorque(obody2, torque2*dir[0], torque2*dir[1], torque2*dir[2]);
}
}
// axis 3 //
if (k3 != 0.0) {
ang3 = rang[2];
dang = ang3;
if (dang > M_PI) dang -= 2*M_PI;
if (dang < -M_PI) dang += 2*M_PI;
torque3 = dang*k3;
dir = axis3;
dir.set(0,0,1);
if (obody1) {
//dir = w1;
//dBodyAddRelTorque(obody1, torque3*dir[0], torque3*dir[1], torque3*dir[2]);
dBodyAddTorque(obody1, torque3*dir[0], torque3*dir[1], torque3*dir[2]);
}
if (obody2) {
//dir = w2;
torque3 = -torque3;
//dBodyAddRelTorque(obody2, torque3*dir[0], torque3*dir[1], torque3*dir[2]);
dBodyAddTorque(obody2, torque3*dir[0], torque3*dir[1], torque3*dir[2]);
}
}
}
// hinge joint //
else if (jtype == PM_JOINT_HINGE) {
PmHingeJoint *hjoint = dynamic_cast<PmHingeJoint*>(joint);
float k, ang, dang, torque;
hjoint->getForceConst(k);
if (k == 0.0) {
continue;
}
ang = dJointGetHingeAngle(ojoint);
dang = ang;
if (dang > M_PI) dang -= 2*M_PI;
if (dang < -M_PI) dang += 2*M_PI;
torque = -dang*k;
dJointAddHingeTorque (ojoint, torque);
energy = 0.5*k*dang*dang;
joint->addEnergy(upd, energy);
/*
fprintf (stderr, ">>> joint %d ang = %f dang = %f torq = %f \n", i, ang,
dang, torque);
*/
}
}
#endif
}
//*============================================================*
//*========== stepMotors ==========*
//*============================================================*
// advance any motors attached to joints.
void
PmOdeSolver::stepMotors()
{
#ifdef PM_ODE_SOLVER
//fprintf (stderr, ">>> PmOdeSolver::stepMotors \n");
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
PmJoint *joint;
vector<PmMotor*> motors;
dJointID mjoint;
float avel, ang, ainc, max_angle;
int num_axes, axes[3], axis;
float time = prvd->time;
float dt = prvd->time_step;
// check each joint for motors //
int num_joints = prvd->joints.size();
for (int i = 0; i < num_joints; i++) {
joint = prvd->joints[i].pm;
if (!joint->hasMotors()) {
continue;
}
joint->getMotors(motors);
//fprintf (stderr, "---- joint[%d] %d motors ---- \n", i, motors.size());
for (unsigned int j = 0; j < motors.size(); j++) {
PmMotor *motor = motors[j];
PmAngularMotor *amotor = dynamic_cast<PmAngularMotor*>(motor);
amotor->getAxes(num_axes, axes);
mjoint = prvd->joints[i].motors[j];
if (!motor->isEnabled()) {
continue;
}
if (!motor->isActive(time)) {
if (motor->isActive()) {
ode_activateJointMotor(prvd, prvd->joints[i], false);
//fprintf (stderr, "---- joint[%d] time[%f] de-activate \n", i, time);
motor->setActive(false);
}
continue;
}
else if (!motor->isActive()) {
ode_activateJointMotor(prvd, prvd->joints[i], true);
motor->setActive(true);
//fprintf (stderr, "---- joint[%d] time[%f] activate \n", i, time);
}
// the angle increment is determined by the //
// velocity (degs/radians) and time step //
for (int k = 0; k < num_axes; k++) {
axis = axes[k] - 1;
amotor->getMaxVelocity(k+1, avel);
ainc = avel * dt;
//amotor->getAngleInc(k+1, ainc);
ang = dJointGetAMotorAngle (mjoint, axis);
ang += ainc;
amotor->addAngleData(ang);
amotor->getMaxAngle(k+1, max_angle);
max_angle = max_angle * (M_PI / 180.0);
//fprintf (stderr, "\n---- joint[%d] ang[%f] max_angle[%f]\n", i, ang, max_angle);
if (fabs(ang) <= max_angle) {
dJointSetAMotorAngle (mjoint, axis, ang);
}
else {
dJointSetAMotorParam (mjoint, vel_param[k], 0.0);
dJointSetAMotorParam (mjoint, force_param[k], 0.0);
motor->setEnabled(false);
}
}
}
}
#endif
}
//*============================================================*
//*========== addRestraintForces ==========*
//*============================================================*
// add restraint forces.
void
PmOdeSolver::addRestraintForces()
{
#ifdef dbg_addRestraintForces
fprintf (stderr, ">>> addRestraintForces \n");
#endif
//===== get the restraints defined for a simulation =====//
vector<PmRestraint*> restraints;
simulation->getRestraints(restraints);
int num = restraints.size();
if (num == 0) {
return;
}
bool upd = simulation->checkUpdateState();
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
float time = prvd->time;
PmVector3 center1, center2;
float power_params[2];
#ifdef dbg_addRestraintForces
fprintf (stderr, ">>> num restraints [%d] \n", num);
#endif
//===== compute restraint forces =====//
for (unsigned int i = 0; i < restraints.size(); i++) {
restraints[i]->compForces(upd, time);
}
}
//*============================================================*
//*========== ode_attach_joints ==========*
//*============================================================*
// attach bodies to joints.
void
ode_AttachJoints (PmOdeJoint& ojoint, PmBody *body1, dBodyID obody1, PmBody *body2,
dBodyID obody2)
{
//fprintf (stderr, "\n###### ode_AttachJoints body1[%x] body2[%x] \n", body1, body2);
//fprintf (stderr, "\n###### ode_AttachJoints obody1[%x] obody2[%x] \n", obody1, obody2);
#ifdef PM_ODE_SOLVER
if (body1->isGround()) {
dJointAttach (ojoint.ode, obody2, 0);
}
else if (body2->isGround()) {
dJointAttach (ojoint.ode, obody1, 0);
}
else {
dJointAttach (ojoint.ode, obody1, obody2);
}
#endif
}
//*============================================================*
//*============================================================*
// add joints to ode solver.
bool
PmOdeSolver::addJoints(vector<PmJoint*> joints)
{
#ifdef PM_ODE_SOLVER
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
int num_joints = joints.size();
PmBody *body1, *body2;
#ifdef dbg_PmOdeSolver
fprintf (stderr, "\n --- add joints --- \n");
#endif
for (int i = 0; i < num_joints; i++) {
string jname;
PmOdeJoint ojoint;
PmVector3 pos;
dBodyID obody1, obody2;
vector<PmMotor*> motors;
PmJoint *joint = joints[i];
ojoint.pm = joint;
joint->getName(jname);
PmJointType jtype = joint->getType();
// get joint data //
joint->getPosition (pos);
joint->getBodies(&body1, &body2);
joint->getMotors(motors);
// get ode body associated with pm bodies //
ode_getBody(prvd, body1, &obody1);
ode_getBody(prvd, body2, &obody2);
#ifdef dbg_PmOdeSolver
fprintf (stderr, " >>> joint [%s]\n", jname.c_str());
fprintf (stderr, " >>> num motors [%d]\n", motors.size());
#endif
// create a two-axis universal joint //
if (jtype == PM_JOINT_UNIVERSAL) {
#ifdef dbg_PmOdeSolver
fprintf (stderr, " type universal \n");
#endif
ojoint.ode = dJointCreateUniversal (prvd->world, 0);
ode_AttachJoints (ojoint, body1, obody1, body2, obody2);
dJointSetUniversalAnchor (ojoint.ode, pos[0], pos[1], pos[2]);
PmUniversalJoint *ujoint = dynamic_cast<PmUniversalJoint*>(joint);
if (!ujoint) {
pm_ErrorReport ("pm> ", "joint \"%s\" failed conversion.", "*", name.c_str());
return false;
}
PmVector3 axis1, axis2;
ujoint->getAxis(1,axis1);
dJointSetUniversalAxis1 (ojoint.ode, axis1[0], axis1[1], axis1[2]);
ujoint->getAxis(2,axis2);
dJointSetUniversalAxis2 (ojoint.ode, axis2[0], axis2[1], axis2[2]);
#ifdef dbg_PmOdeSolver
fprintf (stderr, " axes: 1 (%g %g %g)\n",axis1[0],axis1[1],axis1[2]);
fprintf (stderr, " axes: 2 (%g %g %g)\n",axis2[0],axis2[1],axis2[2]);
#endif
ode_addJointStop(prvd, ojoint);
}
// create a single-axis hinge joint //
else if (jtype == PM_JOINT_HINGE) {
#ifdef dbg_PmOdeSolver
fprintf (stderr, " type hinge \n");
#endif
ojoint.ode = dJointCreateHinge(prvd->world, 0);
ode_AttachJoints (ojoint, body1, obody1, body2, obody2);
dJointSetHingeAnchor(ojoint.ode, pos[0], pos[1], pos[2]);
PmHingeJoint *hjoint = dynamic_cast<PmHingeJoint*>(joint);
if (!hjoint) {
pm_ErrorReport ("pm> ", "joint \"%s\" failed conversion.", "*", name.c_str());
return false;
}
PmVector3 axis;
hjoint->getAxis(axis);
dJointSetHingeAxis (ojoint.ode, axis[0], axis[1], axis[2]);
ode_addJointStop(prvd, ojoint);
}
// three-axis ball joint //
else if (jtype == PM_JOINT_BALL) {
//PmBallJoint *bjoint = dynamic_cast<PmBallJoint*>(joint);
#ifdef dbg_PmOdeSolver
fprintf (stderr, " type ball \n");
fprintf (stderr, " anchor (%g %g %g) \n", pos[0], pos[1], pos[2]);
#endif
ojoint.ode = dJointCreateBall(prvd->world, 0);
ode_AttachJoints (ojoint, body1, obody1, body2, obody2);
dJointSetBallAnchor (ojoint.ode, pos[0], pos[1], pos[2]);
ode_addJointStop(prvd, ojoint);
}
else if (jtype == PM_JOINT_WELD) {
ojoint.ode = dJointCreateFixed(prvd->world, 0);
ode_AttachJoints (ojoint, body1, obody1, body2, obody2);
dJointSetFixed (ojoint.ode);
}
else {
string name;
joint->getName(name);
pm_ErrorReport ("pm> ", "joint \"%s\" type not supported.", "*", name.c_str());
return false;
}
#ifdef dbg_PmOdeSolver
fprintf (stderr, " bodies: [%x] [%x] \n", obody1, obody2);
#endif
prvd->joints.push_back(ojoint);
}
// create motors for the joints //
addJointMotors();
return true;
#endif
}
//*============================================================*
//*========== addJointMotors ==========*
//*============================================================*
// add a motor to a joint.
void
PmOdeSolver::addJointMotors()
{
#ifdef PM_ODE_SOLVER
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
PmBody *body1, *body2;
PmJoint *joint;
dBodyID obody1, obody2;
vector<PmMotor*> motors;
for (unsigned int i = 0; i < prvd->joints.size(); i++) {
joint = prvd->joints[i].pm;
if (!joint->hasMotors()) {
continue;
}
joint->getMotors(motors);
PmJointType jtype = joint->getType();
joint->getBodies(&body1, &body2);
joint->getMotors(motors);
ode_getBody(prvd, body1, &obody1);
ode_getBody(prvd, body2, &obody2);
// create motors for the joint //
for (unsigned int j = 0; j < motors.size(); j++) {
int num_axes, axes[3];
PmOdeJoint mjoint;
PmVector3 jaxis;
float force, vel;
PmMotor *motor = motors[j];
PmAngularMotor *amotor = dynamic_cast<PmAngularMotor*>(motor);
amotor->getAxes(num_axes, axes);
// create ode motor //
mjoint.ode = dJointCreateAMotor(prvd->world, 0);
#ifdef PmOdeSolver_addJointMotors_use_euler
dJointSetAMotorMode (mjoint.ode, dAMotorEuler);
#else
dJointSetAMotorMode (mjoint.ode, dAMotorUser);
ode_AttachJoints (mjoint, body1, obody1, body2, obody2);
dJointSetAMotorNumAxes (mjoint.ode, num_axes);
prvd->joints[i].motors[j] = mjoint.ode;
for (int k = 0; k < num_axes; k++) {
if (jtype == PM_JOINT_BALL) {
PmBallJoint *bjoint = dynamic_cast<PmBallJoint*>(joint);
bjoint->getAxis(axes[k], jaxis);
}
dJointSetAMotorAxis (mjoint.ode, k, 2, jaxis[0], jaxis[1], jaxis[2]);
//dJointSetAMotorAxis (mjoint.ode, k, axes[k]-1, jaxis[0], jaxis[1], jaxis[2]);
// set max vel and max force //
if (amotor->isEnabled()) {
amotor->getMaxVelocity(k+1, vel);
amotor->getMaxForce(k+1, force);
dJointSetAMotorParam (mjoint.ode, vel_param[k], vel);
dJointSetAMotorParam (mjoint.ode, force_param[k], force);
}
}
if (jtype == PM_JOINT_HINGE) {
PmHingeJoint *hjoint = dynamic_cast<PmHingeJoint*>(joint);
float range, hi_ang, low_ang;
if (hjoint->getRange(range)) {
hi_ang = range*M_PI / 180.0;
low_ang = -range*M_PI / 180.0;
dJointSetAMotorParam(mjoint.ode, dParamLoStop, low_ang);
dJointSetAMotorParam(mjoint.ode, dParamHiStop, hi_ang);
//dJointSetHingeParam (mjoint.ode, dParamLoStop, low_ang);
//dJointSetHingeParam (mjoint.ode, dParamHiStop, hi_ang);
//fprintf (stderr, ">>> add hinge stop. range = %f \n", range);
}
}
#endif
}
}
#endif
}
//*============================================================*
//*========== addJointStop ==========*
//*============================================================*
// add a stop to a joint.
static void
ode_addJointStop(PmOdeSolverData *prvd, PmOdeJoint& ojoint)
{
#ifdef PM_ODE_SOLVER
PmJoint *joint = ojoint.pm;
PmJointType jtype = joint->getType();
PmOdeJoint mjoint;
// joint stops for a ball joint are implemented //
// using an angular motor. //
if (jtype == PM_JOINT_BALL) {
PmBallJoint *bjoint = dynamic_cast<PmBallJoint*>(joint);
int num_axes = 0;
for (int i = 0; i < 3; i++) {
if (bjoint->hasRange(i+1)) {
num_axes += 1;
break;
}
}
if (!num_axes) {
return;
}
//fprintf (stderr, ">>> add stop \n");
PmBody *body1, *body2;
dBodyID obody1, obody2;
PmVector3 jaxis;
float hi_ang, fmax, low_ang, val;
// get joint information //
joint->getBodies(&body1, &body2);
ode_getBody(prvd, body1, &obody1);
ode_getBody(prvd, body2, &obody2);
mjoint.ode = dJointCreateAMotor(prvd->world, 0);
dJointSetAMotorNumAxes(mjoint.ode, 3);
ode_AttachJoints(mjoint, body1, obody1, body2, obody2);
fmax = 1.0;
// set axis 1 //
bjoint->getAxis(1, jaxis);
if (bjoint->hasRange(1)) {
bjoint->getRange(1, val);
hi_ang = val*M_PI / 180.0;
low_ang = -val*M_PI / 180.0;
}
else {
hi_ang = 0.0;
low_ang = 0.0;
}
dJointSetAMotorAxis(mjoint.ode, 0, 1, jaxis[0], jaxis[1], jaxis[2]);
dJointSetAMotorParam(mjoint.ode, dParamFMax, fmax);
dJointSetAMotorParam(mjoint.ode, dParamLoStop, low_ang);
dJointSetAMotorParam(mjoint.ode, dParamHiStop, hi_ang);
dJointSetAMotorParam(mjoint.ode, dParamVel, 0.0);
//dJointSetAMotorParam(mjoint.ode, dParamStopERP, 0.8);
//dJointSetAMotorParam(mjoint.ode, dParamStopCFM, 0.0);
// axis 2 //
if (bjoint->hasRange(2)) {
bjoint->getRange(2, val);
hi_ang = val*M_PI / 180.0;
low_ang = -val*M_PI / 180.0;
}
else {
hi_ang = 0.0;
low_ang = 0.0;
}
dJointSetAMotorParam(mjoint.ode, dParamFMax2, fmax);
dJointSetAMotorParam(mjoint.ode, dParamLoStop2, low_ang);
dJointSetAMotorParam(mjoint.ode, dParamHiStop2, hi_ang);
dJointSetAMotorParam(mjoint.ode, dParamVel2, 0.0);
//dJointSetAMotorParam(mjoint.ode, dParamStopERP2, 0.8);
//dJointSetAMotorParam(mjoint.ode, dParamStopCFM2, 0.0);
// axis 3 //
if (bjoint->hasRange(3)) {
bjoint->getRange(3, val);
hi_ang = val*M_PI / 180.0;
low_ang = -val*M_PI / 180.0;
}
else {
hi_ang = 0.0;
low_ang = 0.0;
}
bjoint->getAxis(2, jaxis);
dJointSetAMotorAxis(mjoint.ode, 2, 2, jaxis[0], jaxis[1], jaxis[2]);
dJointSetAMotorParam(mjoint.ode, dParamFMax3, fmax);
dJointSetAMotorParam(mjoint.ode, dParamLoStop3, low_ang);
dJointSetAMotorParam(mjoint.ode, dParamHiStop3, hi_ang);
dJointSetAMotorParam(mjoint.ode, dParamVel3, 0.0);
//dJointSetAMotorParam(mjoint.ode, dParamStopERP3, 0.8);
//dJointSetAMotorParam(mjoint.ode, dParamStopCFM3, 0.0);
dJointSetAMotorMode(mjoint.ode, dAMotorEuler);
/*
for (int i = 0; i < 3; i++) {
if (bjoint->hasRange(i+1)) {
bjoint->getRange(i+1, val);
val = val*M_PI / 180.0;
bjoint->getAxis(i+1, jaxis);
dJointSetAMotorAxis(mjoint.ode, num_axes, 2, jaxis[0], jaxis[1], jaxis[2]);
fprintf (stderr, ">>> add stop %f \n", val);
fprintf (stderr, ">>> axis %f %f %f \n", jaxis[0], jaxis[1], jaxis[2]);
if (num_axes == 0) {
dJointSetAMotorParam(mjoint.ode, dParamHiStop, val);
dJointSetAMotorParam(mjoint.ode, dParamFMax, fmax);
dJointSetAMotorParam(mjoint.ode, dParamVel, 0.0);
}
else if (num_axes == 1) {
dJointSetAMotorParam(mjoint.ode, dParamHiStop2, val);
dJointSetAMotorParam(mjoint.ode, dParamFMax2, fmax);
dJointSetAMotorParam(mjoint.ode, dParamVel2, 0.0);
}
else if (num_axes == 2) {
dJointSetAMotorParam(mjoint.ode, dParamHiStop3, val);
dJointSetAMotorParam(mjoint.ode, dParamFMax3, fmax);
dJointSetAMotorParam(mjoint.ode, dParamVel3, 0.0);
}
num_axes += 1;
}
}
*/
}
else if (jtype == PM_JOINT_HINGE) {
PmHingeJoint *hjoint = dynamic_cast<PmHingeJoint*>(joint);
float range, hi_ang, low_ang;
if (hjoint->getRange(range)) {
hi_ang = range*M_PI / 180.0;
low_ang = -range*M_PI / 180.0;
dJointSetHingeParam (ojoint.ode, dParamLoStop, low_ang);
dJointSetHingeParam (ojoint.ode, dParamHiStop, hi_ang);
}
}
else if (jtype == PM_JOINT_UNIVERSAL) {
//PmUniversalJoint *ujoint = dynamic_cast<PmUniversalJoint*>(joint);
}
#endif
}
//*============================================================*
//*========== activateJointMotor ==========*
//*============================================================*
// activate/deactivate a joint motor.
static void
ode_activateJointMotor(PmOdeSolverData *prv_data, PmOdeJoint& ojoint, bool activate)
{
#ifdef PM_ODE_SOLVER
float force, vel;
int num_axes, axes[3];
vector<PmMotor*> motors;
PmJoint *joint = ojoint.pm;
joint->getMotors(motors);
for (unsigned int j = 0; j < motors.size(); j++) {
dJointID mjoint = ojoint.motors[j];
PmMotor *motor = motors[j];
if (!motor->isEnabled()) {
continue;
}
PmAngularMotor *amotor = dynamic_cast<PmAngularMotor*>(motor);
amotor->getAxes(num_axes, axes);
for (int k = 0; k < num_axes; k++) {
if (activate) {
amotor->getMaxVelocity(k+1, vel);
amotor->getMaxForce(k+1, force);
dJointSetAMotorParam (mjoint, vel_param[k], vel);
dJointSetAMotorParam (mjoint, force_param[k], force);
}
else {
dJointSetAMotorParam (mjoint, vel_param[k], 0.0);
dJointSetAMotorParam (mjoint, force_param[k], 0.0);
}
}
}
#endif
}
//*============================================================*
//*========== getBody ==========*
//*============================================================*
// get an ode body id for the given PmBody.
static void
ode_getBody(PmOdeSolverData *prvd, PmBody *body, dBodyID *obody)
{
#ifdef PM_ODE_SOLVER
int num_bodies = prvd->bodies.size();
for (int i = 0; i < num_bodies; i++) {
if (body == prvd->bodies[i].pm) {
*obody = prvd->bodies[i].ode;
return;
}
}
*obody = NULL;
#endif
}
//*============================================================*
//*========== getJoint ==========*
//*============================================================*
// get an ode joint id for the given PmJoint.
static void
ode_getJoint(PmOdeSolverData *prvd, PmJoint *joint, dJointID *ojoint)
{
#ifdef PM_ODE_SOLVER
int num_joints = prvd->joints.size();
for (int i = 0; i < num_joints; i++) {
if (joint == prvd->joints[i].pm) {
*ojoint = prvd->joints[i].ode;
return;
}
}
*ojoint = NULL;
#endif
}
//*============================================================*
//*========== update ==========*
//*============================================================*
// update body, joints and trace states. note that we still need
// to update the transformation for a body to update the geoemtry
// of any potentials defined for the body.
void
PmOdeSolver::update()
{
#ifdef PM_ODE_SOLVER
#define ndbg_PmOdeSolver
#ifdef dbg_PmOdeSolver
PmOdeSolverData *prvddbg = (PmOdeSolverData*)prv_data;
fprintf (stderr, "\n-------------------------------\n");
fprintf (stderr, ">>>>>> ODE Solver: update\n");
fprintf (stderr, " >>> num bodies[%d]\n", prvddbg->bodies.size());
fprintf (stderr, " >>> num joints[%d]\n", prvddbg->joints.size());
#endif
if (!initialzed) {
return;
}
const dReal *pos, *r, *vel, *avel;
PmVector3 com, rvec, disp, vec, linvel, angvel;
bool upd;
PmMatrix3x3 m;
PmQuaternion q;
PmMassProperties props;
float ke, total_ke;
PmOdeSolverData *prvd = (PmOdeSolverData*)prv_data;
float time = prvd->time;
// check to see if we should update state //
// for storing results and display. //
upd = simulation->checkUpdateState();
// update bodies //
total_ke = 0.0;
for (unsigned int i = 0; i < prvd->bodies.size(); i++) {
#ifdef dbg_PmOdeSolver
fprintf (stderr, "------ body [%d] ------ \n", i);
#endif
PmBody *body = prvd->bodies[i].pm;
dBodyID obody = prvd->bodies[i].ode;
if ((body->getType() == PM_BODY_GROUND) || (body->getType() == PM_BODY_STATIC)) {
#ifdef dbg_PmOdeSolver
fprintf (stderr, ">>> ground \n");
#endif
continue;
}
body->getCenterOfMass(com);
pos = dBodyGetPosition (obody);
r = dBodyGetRotation (obody);
disp[0] = pos[0] - com[0];
disp[1] = pos[1] - com[1];
disp[2] = pos[2] - com[2];
#ifdef PmOdeSolver_update_comp_other_rot
rot[0][0] = r[0]; rot[0][1] = r[4]; rot[0][2] = r[8];
rot[1][0] = r[1]; rot[1][1] = r[5]; rot[1][2] = r[9];
rot[2][0] = r[2]; rot[2][1] = r[6]; rot[2][2] = r[10];
pm_MathExtractRotations(rot, ang);
rvec[0] = 180.0*ang[0] / M_PI;
rvec[1] = 180.0*ang[1] / M_PI;
rvec[2] = 180.0*ang[2] / M_PI;
#ifdef dbg_PmOdeSolver
fprintf (stderr, ">>> pos (%g %g %g) \n", pos[0], pos[1], pos[2]);
fprintf (stderr, ">>> disp (%g %g %g) \n", disp[0], disp[1], disp[2]);
fprintf (stderr, ">>> ang (%g %g %g) \n", ang[0], ang[1], ang[2]);
#endif
#endif
m(0,0) = r[0]; m(1,0) = r[4]; m(2,0) = r[8];
m(0,1) = r[1]; m(1,1) = r[5]; m(2,1) = r[9];
m(0,2) = r[2]; m(1,2) = r[6]; m(2,2) = r[10];
// convert the rotation matrix into a quaternion //
//pm_MathMatrixToQuaternion(m, q);
// set kinetic energy //
body->getMassProps(props);
vel = dBodyGetLinearVel(obody);
linvel[0] = vel[0];
linvel[1] = vel[1];
linvel[2] = vel[2];
ke = 0.5*props.mass*linvel*linvel;
avel = dBodyGetAngularVel(obody);
angvel[0] = avel[0];
angvel[1] = avel[1];
angvel[2] = avel[2];
rvec = props.inertia * angvel;
ke += 0.5*rvec*rvec;
total_ke += ke;
body->addKineticEnergy(upd, ke);
// set the simulation results //
body->addSimResults(upd, time, disp, rvec, linvel, angvel, m, q);
// set body state //
PmRigidBodyState state;
for (int i = 0; i < 3; i++) {
state.velocity[i] = vel[i];
state.angular_velocity[i] = avel[i];
state.displacement[i] = disp[i];
}
state.rotation_matrix = m;
body->setState(state);
}
//fprintf (stderr, ">>>> total ke = %g \n", total_ke);
// update joints //
PmBody *body1, *body2, *body;
dBodyID obody;
PmVector3 jpos, xjpos;
PmXform body_xform;
dJointID ojoint;
for (unsigned int i = 0; i < prvd->joints.size(); i++) {
//fprintf (stderr, "------ joint[%d] ------ \n", i);
PmJoint *joint = prvd->joints[i].pm;
PmJointType jtype = joint->getType();
joint->getPosition (jpos);
joint->getBodies(&body1, &body2);
ojoint = prvd->joints[i].ode;
if (body1->isGround()) {
body = body2;
}
else {
body = body1;
}
ode_getBody(prvd, body, &obody);
ode_xformPoint(body, obody, jpos, xjpos);
/*
fprintf (stderr, ">>> jpos=%g %g %g -> xjpos=%g %g %g\n", jpos[0], jpos[1], jpos[2],
xjpos[0], xjpos[1], xjpos[2]);
*/
r = dBodyGetRotation (obody);
PmMatrix3x3 m;
m(0,0) = r[0]; m(1,0) = r[4]; m(2,0) = r[8];
m(0,1) = r[1]; m(1,1) = r[5]; m(2,1) = r[9];
m(0,2) = r[2]; m(1,2) = r[6]; m(2,2) = r[10];
body_xform.translation = xjpos;
body->getCenterOfMass (com);
body_xform.center = com;
body_xform.setRotation(m);
joint->update(xjpos);
joint->update(body_xform);
//dReal a = dJointGetHingeAngle(mjoint);
//fprintf (stderr, "---- joint[%d] ang[%f] \n", i, ang);
if (jtype == PM_JOINT_HINGE) {
PmHingeJoint *hjoint = dynamic_cast<PmHingeJoint*>(joint);
dReal a = dJointGetHingeAngle(ojoint);
hjoint->updateAngle(a);
}
}
// update objects not needed for the //
// simulation every saved state upate. //
if (!upd) {
return;
}
// update geometies //
vector<PmGeometry*> geoms;
simulation->getGeometries(geoms);
int ngeoms = geoms.size();
for (int i = 0; i < ngeoms; i++) {
geoms[i]->getBody(&body);
ode_getBody(prvd, body, &obody);
body->getCenterOfMass(com);
pos = dBodyGetPosition (obody);
if (!obody) {
fprintf (stderr, "\n**** WARNING: geometry does not have an obody. \n");
continue;
}
r = dBodyGetRotation (obody);
//ode_xformPoint(body, obody, com, xjpos);
PmMatrix3x3 m;
m(0,0) = r[0]; m(1,0) = r[4]; m(2,0) = r[8];
m(0,1) = r[1]; m(1,1) = r[5]; m(2,1) = r[9];
m(0,2) = r[2]; m(1,2) = r[6]; m(2,2) = r[10];
body_xform.translation[0] = pos[0] - com[0];
body_xform.translation[1] = pos[1] - com[1];
body_xform.translation[2] = pos[2] - com[2];
body->getCenterOfMass (com);
body_xform.center = com;
body_xform.setRotation(m);
geoms[i]->update(body_xform);
geoms[i]->display(true);
}
// update traces //
vector<PmTrace*> traces;
PmVector3 loc, tloc;
bool global_frame = false;
dVector3 gvec;
simulation->getTraces(traces);
int num = traces.size();
//fprintf (stderr, ">>>>>> PmOdeSolver::update ntraces %d \n", num);
for (int i = 0; i < num; i++) {
traces[i]->getGlobalFrame(global_frame);
traces[i]->getObj((void**)&body);
ode_getBody(prvd, body, &obody);
body->getCenterOfMass(com);
traces[i]->getPoint(loc);
//fprintf (stderr, " >>> loc %f %f %f \n", loc[0], loc[1], loc[2]);
//fprintf (stderr, " >>> com %f %f %f \n", com[0], com[1], com[2]);
if (global_frame) {
pos = dBodyGetPosition (obody);
//r = dBodyGetRotation (obody);
vec = loc - com;
dBodyVectorToWorld (obody, vec[0], vec[1], vec[2], gvec);
for (int j = 0; j < 3; j++) {
tloc[j] = pos[j] + gvec[j];
}
}
else {
dBodyGetRelPointPos (obody, loc[0], loc[1], loc[2], gvec);
for (int j = 0; j < 3; j++) {
tloc[j] = gvec[j];
}
}
traces[i]->addPoint(tloc);
traces[i]->display(true);
}
// update measurements //
vector<PmMeasurement*> msr;
vector<PmVector3> points;
vector<PmVector3> upd_points;
vector<void*> pobjs;
PmVector3 ploc;
global_frame = true;
simulation->getMeasurements(msr);
num = msr.size();
//fprintf (stderr, ">>>>>> PmOdeSolver::update nmsr %d \n", num);
for (int i = 0; i < num; i++) {
//msr[i]->getGlobalFrame(global_frame);
msr[i]->getObjs(pobjs);
msr[i]->getPoints(points);
upd_points.clear();
for (unsigned int j = 0; j < points.size(); j++) {
loc = points[j];
body = (PmBody*)pobjs[j];
ode_getBody(prvd, body, &obody);
body->getCenterOfMass(com);
if (global_frame) {
pos = dBodyGetPosition (obody);
r = dBodyGetRotation (obody);
vec = loc - com;
dBodyVectorToWorld (obody, vec[0], vec[1], vec[2], gvec);
for (int k = 0; k < 3; k++) {
ploc[k] = pos[k] + gvec[k];
}
}
else {
dBodyGetRelPointPos (obody, loc[0], loc[1], loc[2], gvec);
for (int k = 0; k < 3; k++) {
ploc[k] = gvec[k];
}
}
//fprintf (stderr, "ploc %f %f %f \n", ploc[0], ploc[1], ploc[2]);
upd_points.push_back(ploc);
}
msr[i]->updatePoints(upd_points);
msr[i]->display();
}
}
//*============================================================*
//*========== XformPoint ==========*
//*============================================================*
// transform a point on a body.
static void
ode_xformPoint(PmBody *body, dBodyID obody, PmVector3& pt, PmVector3& xpt)
{
#ifdef PM_ODE_SOLVER
const dReal *pos;
dReal gvec[3];
PmVector3 com, vec;
if (body->getType() == PM_BODY_GROUND) {
xpt = pt;
return;
}
//fprintf (stderr, ">>>>>> ode_xformPoint \n");
body->getCenterOfMass(com);
pos = dBodyGetPosition (obody);
vec = pt - com;
dBodyVectorToWorld (obody, vec[0], vec[1], vec[2], gvec);
//fprintf (stderr, " >>> gvec=%g %g %g\n", gvec[0], gvec[1], gvec[2]);
//fprintf (stderr, " >>> pos=%g %g %g\n", pos[0], pos[1], pos[2]);
for (int i = 0; i < 3; i++) {
xpt[i] = pos[i] + gvec[i];
}
#endif
}
#endif
}
|
484abddb2f4c1166c8f5e7fcc8eb4a5cf94b732a | 4fa90d778e9cf823179a885e0de0ea235abce06a | /PathTracing/CSphere.h | 1e58c0a94ae66b01129bf82da7f018de2e3cee18 | [] | no_license | zhuisa/PathTracing | b8342c0adde0c31626c3b7376319dee8c26c0667 | ab615779328a0f070225b667a7c01a0fa897c5fa | refs/heads/master | 2022-12-08T16:22:31.245730 | 2020-09-06T13:09:58 | 2020-09-06T13:09:58 | 292,211,252 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | h | CSphere.h | #pragma once
#include<glm/glm.hpp>
using namespace glm;
class CSphere
{
public:
struct SMaterial
{
float Absorption;
float Disperse;
float Reflection;
vec3 Color;
};
CSphere(float vRadius, vec3 vCenter, SMaterial vMaterial);
const float getRadius() const;
const vec3 getColor() const;
const vec3 getCenter() const;
private:
vec3 m_Center;
float m_Radius;
SMaterial m_Material;
};
|
a9419a4d293b9587520032652d8e40d7f8503391 | 20bb1ae805cd796a7c377e55966633441d1d9fd5 | /hackerrank/University CodeSprint 2/March of the King/march.cpp | ffa5bcf6756e714d39aae9693c204492837af715 | [] | no_license | nathantheinventor/solved-problems | 1791c9588aefe2ebdc9293eb3d58317346d88e83 | c738e203fa77ae931b0ec613e5a00f9a8f7ff845 | refs/heads/master | 2022-10-27T08:58:23.860159 | 2022-10-13T20:18:43 | 2022-10-13T20:18:43 | 122,110,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,370 | cpp | march.cpp | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
char secret[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
char board[8][8] = {0};
int neighbors[8][2] = {{-1, -1}, {-1, 0}, {-1, 1},
{ 0, -1}, { 0, 1},
{ 1, -1}, { 1, 0}, { 1, 1}};
ull mask(ull i, ull j) {
return 1 << (8 * i + j);
}
bool inBounds(int x, int y) {
return x >= 0 and y >= 0 and x < 8 and y < 8;
}
ull recurse(int x, int y, int pos, ull taken) {
if (secret[pos] == 0) {
return 1;
}
ull ans = 0;
for (int k = 0; k < 8; k ++) {
int i = neighbors[k][0] + x;
int j = neighbors[k][1] + y;
if (inBounds(i, j) and board[i][j] == secret[pos] and !(taken & mask(i, j))) {
ans += recurse(i, j, pos + 1, taken | mask(i, j));
}
}
return ans;
}
int main() {
int k;
cin >> k;
for (int i = 0; i < k; i ++) {
cin >> secret[i];
}
for (int i = 0; i < 8; i ++) {
for (int j = 0; j < 8; j ++) {
cin >> board[i][j];
}
}
ull ans = 0;
for (int i = 0; i < 8; i ++) {
for (int j = 0; j < 8; j ++) {
if (board[i][j] == secret[0]) {
ans += recurse(i, j, 1, mask(i, j));
}
}
}
cout << ans << endl;
return 0;
}
|
5bf3b8752662b8994a94834c09cc80f19b4fc166 | 076d699d2ad3c97603a514224634b774271647fb | /2017.11.11/D1.cpp | 2a47b18a3b8ee51e7997f6e491f9f432273f2940 | [] | no_license | siberiy4/comp_prog | 2d3e612561239cc48226c572cb67187eddd9e952 | 3ca7070f9ae4ef1aff6d1a39ce8492a076204793 | refs/heads/master | 2022-12-06T21:23:35.191599 | 2019-08-18T14:52:02 | 2019-08-18T14:52:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | D1.cpp | #include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
int main(){
int N,Z,W,i=1,b=1;
cin >>N >>Z >>W;
vector<int> a(N);
for(i=b;i<N;i++){
cin >>a[i];
}
while(i<N){
for(i=b;i<N;i++){
if(a[i-1]>a[i]&&a[i-1]>Z){
Z=a[i-1];
b=i+2;
break;
}
}
for(i=b;i<N;i++){
if(a[i-1]<a[i]&&a[i-1]<W){
Z=a[i-1];
b=i+2;
break;
}
}
}
cout << abs(W-Z) <<endl;
} |
f9f22ea704ee205e6ff5c72b0490333b07789b12 | bb097f5bc86785cd8c448f290b66d2fe092e0218 | /comparator.cpp | e58e37e8b591901b3648d35951068e183c352170 | [] | no_license | YBelikov/spreadsheet-app-qt | b41be108d62636afcd7c654fd4f83339b3cff7f8 | b7259c744d2bc1c1342718d6ec9749e7b1208fc5 | refs/heads/master | 2020-08-28T03:33:27.443802 | 2019-11-07T22:20:20 | 2019-11-07T22:20:20 | 217,575,806 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | comparator.cpp | #include "comparator.h"
Comparator::Comparator(){}
bool Comparator::operator()(const QStringList &row1, const QStringList &row2){
for(int i = 0; i < numberOfKeys; ++i){
int column = keys[i];
if(column != -1){
if(ascendingOrder[i]){
return row1[i] > row2[i];
}else{
return row1[i] < row2[i];
}
}
}
return false;
}
|
102f8d279f12de70d3b1680dfbdd476891b1eb1f | 1ffa1eddd3e57d5696971d636f7c5abfdeb8cce7 | /vp/src/core/common/timer.cpp | 844e66c4f1f0077eae36bce11d38c9cc78beb4d1 | [
"MIT"
] | permissive | agra-uni-bremen/riscv-vp | fc933564e2616821798d478c6a3fbbc3ac7817d5 | 9418b8abb5e22d586a222ebebd5e9b12051e475b | refs/heads/master | 2023-08-17T12:55:47.669700 | 2023-07-04T08:57:11 | 2023-07-04T08:57:11 | 137,900,431 | 116 | 64 | MIT | 2023-01-22T12:01:54 | 2018-06-19T14:09:48 | C++ | UTF-8 | C++ | false | false | 2,959 | cpp | timer.cpp | #include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <err.h>
#include "timer.h"
/* As defined in nanosleep(3) */
#define NS_MAX 999999999UL
#define US_MAX (NS_MAX / 1000)
/* Signal used to unblock nanosleep in thread */
#define SIGNUM SIGUSR1
static int
xnanosleep(const struct timespec *timespec) {
if (nanosleep(timespec, NULL) == 0)
return 0; /* success */
if (errno == EINTR)
return -1; /* received signal via pthread_kill, terminate */
err(EXIT_FAILURE, "nanosleep failed"); /* EFAULT, EINVAL, … */
}
static void *
callback(void *arg)
{
struct timespec timespec;
Timer::Context *ctx = (Timer::Context*)arg;
/* Initialize the seconds field, we use nanoseconds though */
timespec.tv_sec = 0;
auto count = ctx->duration.count();
while (count > US_MAX) {
timespec.tv_nsec = NS_MAX;
if (xnanosleep(×pec))
return NULL; /* pthread_kill */
count -= US_MAX;
}
// Convert remaining us → ns with overflow check
uint64_t ns = count * 1000;
assert(ns > count);
assert(ns <= LONG_MAX); // tv_nsec is a long
timespec.tv_nsec = ns;
if (xnanosleep(×pec))
return NULL; /* pthread_kill */
ctx->fn(ctx->arg);
return NULL;
}
Timer::Timer(Callback fn, void *arg)
: ctx(usecs(0), fn, arg) {
running = false;
}
Timer::~Timer(void) {
pause();
}
void Timer::start(usecs duration) {
if (running && (errno = pthread_join(thread, NULL)))
throw std::system_error(errno, std::generic_category());
/* Update duration for new callback */
ctx.duration = duration;
if ((errno = pthread_create(&thread, NULL, callback, &ctx)))
throw std::system_error(errno, std::generic_category());
running = true;
}
void Timer::pause(void) {
struct sigaction sa;
if (!running)
return;
sa.sa_handler = SIG_IGN;
sa.sa_flags = SA_RESTART;
if (sigemptyset(&sa.sa_mask) == -1)
throw std::system_error(errno, std::generic_category());
if (sigaction(SIGNUM, &sa, NULL) == -1)
throw std::system_error(errno, std::generic_category());
/* Signal is ignored in main thread, send it to background
* thread and restore the default handler afterwards. */
stop_thread();
sa.sa_handler = SIG_DFL;
if (sigaction(SIGNUM, &sa, NULL) == -1)
throw std::system_error(errno, std::generic_category());
}
void Timer::stop_thread(void) {
/* Attempt to cancel thread first, for the event that it hasn't
* invoked nanosleep yet. The nanosleep function is a
* cancelation point, as per pthreads(7). If the thread is
* blocked in nanosleep the signal should interrupt the
* nanosleep system call and cause thread termination. */
assert(running);
// Either pthread_cancel or pthread_kill will stop the thread, in
// which case the other one will error out thus the error is ignored.
pthread_cancel(thread);
pthread_kill(thread, SIGNUM);
if ((errno = pthread_join(thread, NULL)))
throw std::system_error(errno, std::generic_category());
running = false;
}
|
5aa58569c5bc227f60f6eddee920253307cd4be7 | f332acd61b060ebb53a2a9a15de1ef39f9ae2b0d | /include/kernel.hpp | a94db25c78b34859005ab6a56263a8574f7e622c | [
"MIT"
] | permissive | PierreMarchand20/htool_benchmarks | a7b780a5ff856f0b9471205493f2df656223118a | 32f78503839e793b4a270aa7f71be2c08c2e7423 | refs/heads/main | 2023-07-15T13:33:26.418328 | 2021-09-03T14:05:06 | 2021-09-03T14:05:06 | 296,685,145 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,829 | hpp | kernel.hpp | #ifndef HTOOL_BENCHMARKS_KERNEL_HPP
#define HTOOL_BENCHMARKS_KERNEL_HPP
#include <complex>
#include <htool/htool.hpp>
#include <iomanip>
#include <omp.h>
#ifndef __INTEL_COMPILER
# include <vectorclass.h>
# include "vectormath_exp.h"
# include "vectormath_trig.h"
# include <complexvec1.h>
#endif
#include "misc.hpp"
#include "xsimd/xsimd.hpp"
template <typename T>
class MyVirtualGenerator : public htool::VirtualGenerator<T> {
protected:
htool::underlying_type<T> freq;
public:
// Constructor
MyVirtualGenerator(int space_dim0, int nr, int nc, htool::underlying_type<T> freq0)
: htool::VirtualGenerator<T>(nr, nc), freq(freq0) {}
// Virtual function to overload
T get_coef(const int &k, const int &j) const {}
// Virtual function to overload
virtual void copy_submatrix(int M, int N, const int *const rows, const int *const cols, T *ptr) const = 0;
T sanity_check(int line_number) {
std::vector<T> line(this->nc);
std::vector<int> col_numbers(this->nc);
std::iota(col_numbers.begin(), col_numbers.end(), int(0));
this->copy_submatrix(1, this->nc, &line_number, col_numbers.data(), line.data());
return std::accumulate(line.begin(), line.end(), T(0)) / T(this->nc);
}
htool::underlying_type<T> normFrob() {
std::vector<T> mat(this->nr * this->nc);
std::vector<int> line_numbers(this->nr), col_numbers(this->nc);
std::iota(col_numbers.begin(), col_numbers.end(), int(0));
std::iota(line_numbers.begin(), line_numbers.end(), int(0));
this->copy_submatrix(this->nr, this->nc, line_numbers.data(), col_numbers.data(), mat.data());
return htool::norm2(mat);
}
htool::underlying_type<T> get_freq() const { return this->freq; };
};
template <typename T, int vectorized>
class MyGenerator : public MyVirtualGenerator<T> {
std::vector<double, allocator_type<double, vectorized>> points_target;
std::vector<double, allocator_type<double, vectorized>> points_source;
int space_dim;
int inct;
int incs;
public:
// Constructor
MyGenerator(int space_dim0, int nr, int nc, const std::vector<double, allocator_type<double, vectorized>> &p10, const std::vector<double, allocator_type<double, vectorized>> &p20, htool::underlying_type<T> freq0, std::size_t inct0 = 0, std::size_t incs0 = 0)
: MyVirtualGenerator<T>(space_dim0, nr, nc, freq0), points_target(p10), points_source(p20), space_dim(space_dim0), inct(inct0), incs(incs0) {
}
// Virtual function to overload
T get_coef(const int &k, const int &j) const {}
// Virtual function to overload
void copy_submatrix(int M, int N, const int *const rows, const int *const cols, T *ptr) const {};
};
// No vectorization
template <>
void MyGenerator<float, 0>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, float *ptr) const {
double dx, dy, dz;
for (int k = 0; k < N; k++) {
for (int j = 0; j < M; j++) {
dx = this->points_target[this->space_dim * rows[j] + 0] - this->points_source[this->space_dim * cols[k] + 0];
dy = this->points_target[this->space_dim * rows[j] + 1] - this->points_source[this->space_dim * cols[k] + 1];
dz = this->points_target[this->space_dim * rows[j] + 2] - this->points_source[this->space_dim * cols[k] + 2];
ptr[j + k * M] = 1.f / ((4 * 3.14159265358979f) * (sqrt(dx * dx + dy * dy + dz * dz)));
}
}
}
template <>
void MyGenerator<double, 0>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, double *ptr) const {
double dx, dy, dz;
for (int k = 0; k < N; k++) {
for (int j = 0; j < M; j++) {
dx = this->points_target[space_dim * rows[j] + 0] - this->points_source[space_dim * cols[k] + 0];
dy = this->points_target[space_dim * rows[j] + 1] - this->points_source[space_dim * cols[k] + 1];
dz = this->points_target[space_dim * rows[j] + 2] - this->points_source[space_dim * cols[k] + 2];
ptr[j + k * M] = 1. / ((4 * 3.141592653589793238463) * (sqrt(dx * dx + dy * dy + dz * dz)));
}
}
}
template <>
void MyGenerator<std::complex<float>, 0>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, std::complex<float> *ptr) const {
double dx, dy, dz;
float d;
for (int k = 0; k < N; k++) {
for (int j = 0; j < M; j++) {
dx = this->points_target[space_dim * rows[j] + 0] - this->points_source[space_dim * cols[k] + 0];
dy = this->points_target[space_dim * rows[j] + 1] - this->points_source[space_dim * cols[k] + 1];
dz = this->points_target[space_dim * rows[j] + 2] - this->points_source[space_dim * cols[k] + 2];
d = sqrt(dx * dx + dy * dy + dz * dz);
ptr[j + k * M] = (1.f / (4 * 3.14159265358979f)) * exp(std::complex<float>(0, 1) * freq * d) / (d);
}
}
}
template <>
void MyGenerator<std::complex<double>, 0>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, std::complex<double> *ptr) const {
double dx, dy, dz, d;
for (int k = 0; k < N; k++) {
for (int j = 0; j < M; j++) {
dx = this->points_target[space_dim * rows[j] + 0] - this->points_source[space_dim * cols[k] + 0];
dy = this->points_target[space_dim * rows[j] + 1] - this->points_source[space_dim * cols[k] + 1];
dz = this->points_target[space_dim * rows[j] + 2] - this->points_source[space_dim * cols[k] + 2];
d = sqrt(dx * dx + dy * dy + dz * dz);
ptr[j + k * M] = (1.f / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
}
// vector-class-library Agner Fog's library
#ifndef __INTEL_COMPILER
template <>
void MyGenerator<float, 1>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, float *ptr) const {
double ddx, ddy, ddz;
Vec8d charge(1. / (4 * 3.141592653589793238463));
Vec8d Xt_vec, Yt_vec, Zt_vec;
Vec8f pot_vec(0);
Vec8d dx, dy, dz, r2;
if (M >= 8) {
std::size_t vec_size = M - M % 8;
for (std::size_t j = 0; j < vec_size; j += 8) {
// load
Xt_vec.load(this->points_target.data() + rows[0] + 0 * this->nr + j);
Yt_vec.load(this->points_target.data() + rows[0] + 1 * this->nr + j);
Zt_vec.load(this->points_target.data() + rows[0] + 2 * this->nr + j);
for (std::size_t k = 0; k < N; k++) {
dx = Vec8d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec8d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec8d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = to_float(charge / sqrt(r2));
pot_vec.store(&(ptr[j + k * M]));
}
}
if (vec_size < M) {
int padding = M - vec_size;
// load
Xt_vec.load_partial(padding, this->points_target.data() + rows[0] + 0 * this->nr + vec_size);
Yt_vec.load_partial(padding, this->points_target.data() + rows[0] + 1 * this->nr + vec_size);
Zt_vec.load_partial(padding, this->points_target.data() + rows[0] + 2 * this->nr + vec_size);
for (std::size_t k = 0; k < N; k++) {
dx = Vec8d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec8d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec8d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = to_float(charge / sqrt(r2));
pot_vec.store_partial(padding, &(ptr[vec_size + k * M]));
}
}
} else if (N >= 8) {
std::size_t vec_size = N - N % 8;
std::vector<float> tmp(8);
for (std::size_t k = 0; k < vec_size; k += 8) {
// load
Xt_vec.load(this->points_source.data() + cols[0] + 0 * this->nc + k);
Yt_vec.load(this->points_source.data() + cols[0] + 1 * this->nc + k);
Zt_vec.load(this->points_source.data() + cols[0] + 2 * this->nc + k);
for (std::size_t j = 0; j < M; j++) {
dx = Vec8d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec8d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec8d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = to_float(charge / sqrt(r2));
pot_vec.store(tmp.data());
for (int i = 0; i < 8; i++) {
ptr[j + (k + i) * M] = tmp[i];
}
}
}
if (vec_size < N) {
int padding = N - vec_size;
// load
Xt_vec.load_partial(padding, this->points_source.data() + cols[0] + 0 * this->nc + vec_size);
Yt_vec.load_partial(padding, this->points_source.data() + cols[0] + 1 * this->nc + vec_size);
Zt_vec.load_partial(padding, this->points_source.data() + cols[0] + 2 * this->nc + vec_size);
for (std::size_t j = 0; j < M; j++) {
dx = Vec8d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec8d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec8d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = to_float(charge / sqrt(r2));
pot_vec.store(tmp.data());
for (std::size_t i = 0; i < padding; i++) {
ptr[j + (vec_size + i) * M] = tmp[i];
}
}
}
} else {
for (std::size_t k = 0; k < N; k++) {
for (std::size_t j = 0; j < M; j++) {
ddx = this->points_target[this->space_dim * rows[j] + 0] - this->points_source[this->space_dim * cols[k] + 0];
ddy = this->points_target[this->space_dim * rows[j] + 1] - this->points_source[this->space_dim * cols[k] + 1];
ddz = this->points_target[this->space_dim * rows[j] + 2] - this->points_source[this->space_dim * cols[k] + 2];
ptr[j + k * M] = 1.f / ((4 * 3.14159265358979f) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
}
}
template <>
void MyGenerator<double, 1>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, double *ptr) const {
double ddx, ddy, ddz;
Vec8d charge(1. / (4 * 3.141592653589793238463));
Vec8d Xt_vec, Yt_vec, Zt_vec, pot_vec, r2;
Vec8d dx, dy, dz;
if (M >= 8) {
std::size_t vec_size = M - M % 8;
for (std::size_t j = 0; j < vec_size; j += 8) {
// load
Xt_vec.load(this->points_target.data() + rows[0] + 0 * this->nr + j);
Yt_vec.load(this->points_target.data() + rows[0] + 1 * this->nr + j);
Zt_vec.load(this->points_target.data() + rows[0] + 2 * this->nr + j);
for (std::size_t k = 0; k < N; k++) {
dx = Vec8d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec8d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec8d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
pot_vec.store(&(ptr[j + k * M]));
}
}
if (vec_size < M) {
int padding = M - vec_size;
// load
Xt_vec.load_partial(padding, this->points_target.data() + rows[0] + 0 * this->nr + vec_size);
Yt_vec.load_partial(padding, this->points_target.data() + rows[0] + 1 * this->nr + vec_size);
Zt_vec.load_partial(padding, this->points_target.data() + rows[0] + 2 * this->nr + vec_size);
for (std::size_t k = 0; k < N; k++) {
dx = Vec8d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec8d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec8d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
pot_vec.store_partial(padding, &(ptr[vec_size + k * M]));
}
}
} else if (N >= 8) {
std::vector<double> tmp(8);
std::size_t vec_size = N - N % 8;
for (std::size_t k = 0; k < vec_size; k += 8) {
// load
Xt_vec.load(this->points_source.data() + cols[0] + 0 * this->nc + k);
Yt_vec.load(this->points_source.data() + cols[0] + 1 * this->nc + k);
Zt_vec.load(this->points_source.data() + cols[0] + 2 * this->nc + k);
for (std::size_t j = 0; j < M; j++) {
dx = Vec8d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec8d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec8d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
pot_vec.store(tmp.data());
for (int i = 0; i < 8; i++) {
ptr[j + (k + i) * M] = tmp[i];
}
}
}
if (vec_size < N) {
int padding = N - vec_size;
// load
Xt_vec.load_partial(padding, this->points_source.data() + cols[0] + 0 * this->nc + vec_size);
Yt_vec.load_partial(padding, this->points_source.data() + cols[0] + 1 * this->nc + vec_size);
Zt_vec.load_partial(padding, this->points_source.data() + cols[0] + 2 * this->nc + vec_size);
for (std::size_t j = 0; j < M; j++) {
dx = Vec8d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec8d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec8d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
pot_vec.store(tmp.data());
for (std::size_t i = 0; i < padding; i++) {
ptr[j + (vec_size + i) * M] = tmp[i];
}
}
}
} else {
for (std::size_t k = 0; k < N; k++) {
for (std::size_t j = 0; j < M; j++) {
ddx = this->points_target[this->space_dim * rows[j] + 0] - this->points_source[this->space_dim * cols[k] + 0];
ddy = this->points_target[this->space_dim * rows[j] + 1] - this->points_source[this->space_dim * cols[k] + 1];
ddz = this->points_target[this->space_dim * rows[j] + 2] - this->points_source[this->space_dim * cols[k] + 2];
ptr[j + k * M] = 1 / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
}
}
template <>
void MyGenerator<std::complex<float>, 1>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, std::complex<float> *ptr) const {
double ddx, ddy, ddz;
Vec4d charge = Vec4d(1. / (4 * 3.141592653589793238463));
Vec4d Xt_vec, Yt_vec, Zt_vec;
Complex4f pot_vec;
Vec4d dx, dy, dz, r, aux, cos, sin;
float d;
if (M >= 4) {
std::size_t vec_size = M - M % 4;
for (std::size_t j = 0; j < vec_size; j += 4) {
// load
Xt_vec.load(this->points_target.data() + rows[0] + 0 * this->nr + j);
Yt_vec.load(this->points_target.data() + rows[0] + 1 * this->nr + j);
Zt_vec.load(this->points_target.data() + rows[0] + 2 * this->nr + j);
for (std::size_t k = 0; k < N; k++) {
dx = Vec4d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec4d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec4d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = to_float(Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin))));
pot_vec.store(reinterpret_cast<float *>(&(ptr[j + k * M])));
}
}
if (vec_size < M) {
int padding = M - vec_size;
// load
Xt_vec.load_partial(padding, this->points_target.data() + rows[0] + 0 * this->nr + vec_size);
Yt_vec.load_partial(padding, this->points_target.data() + rows[0] + 1 * this->nr + vec_size);
Zt_vec.load_partial(padding, this->points_target.data() + rows[0] + 2 * this->nr + vec_size);
for (int k = 0; k < N; k++) {
dx = Vec4d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec4d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec4d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = to_float(Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin))));
pot_vec.to_vector().store_partial(2 * padding, reinterpret_cast<float *>(&(ptr[vec_size + k * M])));
}
}
} else if (N >= 4) {
std::size_t vec_size = N - N % 4;
std::vector<std::complex<float>> tmp(4);
for (std::size_t k = 0; k < vec_size; k += 4) {
// load
Xt_vec.load(this->points_source.data() + cols[0] + 0 * this->nc + k);
Yt_vec.load(this->points_source.data() + cols[0] + 1 * this->nc + k);
Zt_vec.load(this->points_source.data() + cols[0] + 2 * this->nc + k);
for (std::size_t j = 0; j < M; j++) {
dx = Vec4d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec4d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec4d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = to_float(Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin))));
pot_vec.store(reinterpret_cast<float *>(tmp.data()));
for (int i = 0; i < 4; i++) {
ptr[j + (k + i) * M] = tmp[i];
}
}
}
if (vec_size < N) {
int padding = N - vec_size;
// load
Xt_vec.load_partial(padding, this->points_source.data() + cols[0] + 0 * this->nc + vec_size);
Yt_vec.load_partial(padding, this->points_source.data() + cols[0] + 1 * this->nc + vec_size);
Zt_vec.load_partial(padding, this->points_source.data() + cols[0] + 2 * this->nc + vec_size);
for (int j = 0; j < M; j++) {
dx = Vec4d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec4d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec4d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = to_float(Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin))));
pot_vec.store(reinterpret_cast<float *>(tmp.data()));
for (int i = 0; i < padding; i++) {
ptr[j + (vec_size + i) * M] = tmp[i];
}
}
}
} else {
for (int k = 0; k < N; k++) {
for (int j = 0; j < M; j++) {
dx = this->points_target[space_dim * rows[j] + 0] - this->points_source[space_dim * cols[k] + 0];
dy = this->points_target[space_dim * rows[j] + 1] - this->points_source[space_dim * cols[k] + 1];
dz = this->points_target[space_dim * rows[j] + 2] - this->points_source[space_dim * cols[k] + 2];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1.f / (4 * 3.14159265358979f)) * exp(std::complex<float>(0, 1) * freq * d) / (d);
}
}
}
}
template <>
void MyGenerator<std::complex<double>, 1>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, std::complex<double> *ptr) const {
double ddx, ddy, ddz, d;
Vec4d charge = Vec4d(1. / (4 * 3.141592653589793238463)), r, aux;
Vec4d cos, sin;
Vec4d Xt_vec, Yt_vec, Zt_vec;
Complex4d pot_vec;
Vec4d dx, dy, dz;
if (M >= 4) {
std::size_t vec_size = M - M % 4;
for (std::size_t j = 0; j < vec_size; j += 4) {
// load
Xt_vec.load(this->points_target.data() + rows[0] + 0 * this->nr + j);
Yt_vec.load(this->points_target.data() + rows[0] + 1 * this->nr + j);
Zt_vec.load(this->points_target.data() + rows[0] + 2 * this->nr + j);
for (std::size_t k = 0; k < N; k++) {
dx = Vec4d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec4d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec4d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin)));
pot_vec.store(reinterpret_cast<double *>(&(ptr[j + k * M])));
}
}
if (vec_size < M) {
int padding = M - vec_size;
// load
Xt_vec.load_partial(padding, this->points_target.data() + rows[0] + 0 * this->nr + vec_size);
Yt_vec.load_partial(padding, this->points_target.data() + rows[0] + 1 * this->nr + vec_size);
Zt_vec.load_partial(padding, this->points_target.data() + rows[0] + 2 * this->nr + vec_size);
for (int k = 0; k < N; k++) {
dx = Vec4d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = Vec4d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = Vec4d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin)));
pot_vec.to_vector().store_partial(2 * padding, reinterpret_cast<double *>(&(ptr[vec_size + k * M])));
}
}
} else if (N >= 4) {
std::size_t vec_size = N - N % 4;
std::vector<std::complex<double>> tmp(4);
for (std::size_t k = 0; k < vec_size; k += 4) {
// load
Xt_vec.load(this->points_source.data() + cols[0] + 0 * this->nc + k);
Yt_vec.load(this->points_source.data() + cols[0] + 1 * this->nc + k);
Zt_vec.load(this->points_source.data() + cols[0] + 2 * this->nc + k);
for (std::size_t j = 0; j < M; j++) {
dx = Vec4d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec4d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec4d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin)));
pot_vec.store(reinterpret_cast<double *>(tmp.data()));
for (int i = 0; i < 4; i++) {
ptr[j + (k + i) * M] = tmp[i];
}
}
}
if (vec_size < N) {
int padding = N - vec_size;
// load
Xt_vec.load_partial(padding, this->points_source.data() + cols[0] + 0 * this->nc + vec_size);
Yt_vec.load_partial(padding, this->points_source.data() + cols[0] + 1 * this->nc + vec_size);
Zt_vec.load_partial(padding, this->points_source.data() + cols[0] + 2 * this->nc + vec_size);
for (int j = 0; j < M; j++) {
dx = Vec4d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = Vec4d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = Vec4d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
sin = sincos(&cos, freq * r);
pot_vec = Complex4d(permute8<0, 4, 1, 5, 2, 6, 3, 7>(Vec8d(aux * cos, aux * sin)));
pot_vec.store(reinterpret_cast<double *>(tmp.data()));
for (int i = 0; i < padding; i++) {
ptr[j + (vec_size + i) * M] = tmp[i];
}
}
}
} else {
for (int k = 0; k < N; k++) {
for (int j = 0; j < M; j++) {
ddx = this->points_target[space_dim * rows[j] + 0] - this->points_source[space_dim * cols[k] + 0];
ddy = this->points_target[space_dim * rows[j] + 1] - this->points_source[space_dim * cols[k] + 1];
ddz = this->points_target[space_dim * rows[j] + 2] - this->points_source[space_dim * cols[k] + 2];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1.f / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
}
}
#endif
// xsimd library (unaligned)
template <>
void MyGenerator<double, 2>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, double *ptr) const {
using b_type_d = xsimd::simd_type<double>;
constexpr std::size_t simd_size = b_type_d::size;
b_type_d charge(1. / (4 * 3.141592653589793238463)), r2;
b_type_d dx, dy, dz;
b_type_d Xt_vec, Yt_vec, Zt_vec;
b_type_d pot_vec;
double ddx, ddy, ddz;
if (M >= simd_size) {
std::size_t vec_size = M - M % simd_size;
for (std::size_t j = 0; j < vec_size; j += simd_size) {
// load
Xt_vec.load_unaligned(this->points_target.data() + rows[0] + 0 * this->nr + j);
Yt_vec.load_unaligned(this->points_target.data() + rows[0] + 1 * this->nr + j);
Zt_vec.load_unaligned(this->points_target.data() + rows[0] + 2 * this->nr + j);
for (std::size_t k = 0; k < N; k++) {
dx = b_type_d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = b_type_d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = b_type_d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
pot_vec.store_unaligned(&(ptr[j + k * M]));
}
}
for (std::size_t j = vec_size; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->nr] - this->points_source[cols[k] + 0 * this->nc];
ddy = this->points_target[rows[j] + 1 * this->nr] - this->points_source[cols[k] + 1 * this->nc];
ddz = this->points_target[rows[j] + 2 * this->nr] - this->points_source[cols[k] + 2 * this->nc];
ptr[j + k * M] = 1 / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
} else if (N >= simd_size) {
// std::vector<double> tmp(simd_size);
std::size_t vec_size = N - N % simd_size;
for (std::size_t k = 0; k < vec_size; k += simd_size) {
// load
Xt_vec.load_unaligned(this->points_source.data() + cols[0] + 0 * this->nc + k);
Yt_vec.load_unaligned(this->points_source.data() + cols[0] + 1 * this->nc + k);
Zt_vec.load_unaligned(this->points_source.data() + cols[0] + 2 * this->nc + k);
for (std::size_t j = 0; j < M; j++) {
dx = b_type_d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = b_type_d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = b_type_d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
// pot_vec.store_aligned(tmp.data());
for (int i = 0; i < simd_size; i++) {
ptr[j + (k + i) * M] = pot_vec[i];
}
}
}
for (std::size_t k = vec_size; k < N; k++) {
for (std::size_t j = 0; j < M; ++j) {
ddx = this->points_target[rows[j] + 0 * this->nr] - this->points_source[cols[k] + 0 * this->nc];
ddy = this->points_target[rows[j] + 1 * this->nr] - this->points_source[cols[k] + 1 * this->nc];
ddz = this->points_target[rows[j] + 2 * this->nr] - this->points_source[cols[k] + 2 * this->nc];
ptr[j + k * M] = 1. / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
} else {
for (std::size_t j = 0; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->nr] - this->points_source[cols[k] + 0 * this->nc];
ddy = this->points_target[rows[j] + 1 * this->nr] - this->points_source[cols[k] + 1 * this->nc];
ddz = this->points_target[rows[j] + 2 * this->nr] - this->points_source[cols[k] + 2 * this->nc];
ptr[j + k * M] = 1. / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
}
}
template <>
void MyGenerator<std::complex<double>, 2>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, std::complex<double> *ptr) const {
using b_type_d = xsimd::simd_type<double>;
using b_type_c_d = xsimd::simd_type<std::complex<double>>;
constexpr std::size_t simd_size = b_type_d::size;
b_type_d charge(1. / (4 * 3.141592653589793238463));
b_type_d cos, sin, r, aux;
b_type_d Xt_vec, Yt_vec, Zt_vec;
b_type_c_d pot_vec;
b_type_d dx, dy, dz;
double ddx, ddy, ddz;
double d;
if (M >= simd_size) {
std::size_t vec_size = M - M % simd_size;
for (std::size_t j = 0; j < vec_size; j += simd_size) {
// load
Xt_vec.load_unaligned(this->points_target.data() + rows[0] + 0 * this->nr + j);
Yt_vec.load_unaligned(this->points_target.data() + rows[0] + 1 * this->nr + j);
Zt_vec.load_unaligned(this->points_target.data() + rows[0] + 2 * this->nr + j);
for (std::size_t k = 0; k < N; k++) {
dx = b_type_d(this->points_source[cols[0] + k + this->nc * 0]) - Xt_vec;
dy = b_type_d(this->points_source[cols[0] + k + this->nc * 1]) - Yt_vec;
dz = b_type_d(this->points_source[cols[0] + k + this->nc * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
xsimd::sincos(freq * r, sin, cos);
pot_vec = b_type_c_d(aux * cos, aux * sin);
pot_vec.store_unaligned(&(ptr[j + k * M]));
// for (int i = 0; i < simd_size; i++) {
// ptr[j + i + k * M] = pot_vec[i];
// }
}
}
for (std::size_t j = vec_size; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->nr] - this->points_source[cols[k] + 0 * this->nc];
ddy = this->points_target[rows[j] + 1 * this->nr] - this->points_source[cols[k] + 1 * this->nc];
ddz = this->points_target[rows[j] + 2 * this->nr] - this->points_source[cols[k] + 2 * this->nc];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
} else if (N >= simd_size) {
std::size_t vec_size = N - N % simd_size;
for (std::size_t k = 0; k < vec_size; k += simd_size) {
// load
Xt_vec.load_unaligned(this->points_source.data() + cols[0] + 0 * this->nc + k);
Yt_vec.load_unaligned(this->points_source.data() + cols[0] + 1 * this->nc + k);
Zt_vec.load_unaligned(this->points_source.data() + cols[0] + 2 * this->nc + k);
for (std::size_t j = 0; j < M; j++) {
dx = b_type_d(this->points_target[rows[0] + j + this->nr * 0]) - Xt_vec;
dy = b_type_d(this->points_target[rows[0] + j + this->nr * 1]) - Yt_vec;
dz = b_type_d(this->points_target[rows[0] + j + this->nr * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
xsimd::sincos(freq * r, sin, cos);
pot_vec = b_type_c_d(aux * cos, aux * sin);
for (int i = 0; i < simd_size; i++) {
ptr[j + (k + i) * M] = pot_vec[i];
}
}
}
for (std::size_t k = vec_size; k < N; k++) {
for (std::size_t j = 0; j < M; ++j) {
ddx = this->points_target[rows[j] + 0 * this->nr] - this->points_source[cols[k] + 0 * this->nc];
ddy = this->points_target[rows[j] + 1 * this->nr] - this->points_source[cols[k] + 1 * this->nc];
ddz = this->points_target[rows[j] + 2 * this->nr] - this->points_source[cols[k] + 2 * this->nc];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
} else {
for (std::size_t j = 0; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->nr] - this->points_source[cols[k] + 0 * this->nc];
ddy = this->points_target[rows[j] + 1 * this->nr] - this->points_source[cols[k] + 1 * this->nc];
ddz = this->points_target[rows[j] + 2 * this->nr] - this->points_source[cols[k] + 2 * this->nc];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
}
}
// xsimd library (aligned)
template <>
void MyGenerator<double, 3>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, double *ptr) const {
using b_type_d = xsimd::simd_type<double>;
constexpr std::size_t simd_size = b_type_d::size;
b_type_d charge(1. / (4 * 3.141592653589793238463)), r2;
b_type_d Xt_vec, Yt_vec, Zt_vec;
b_type_d pot_vec;
b_type_d dx, dy, dz;
double ddx, ddy, ddz;
if (M >= simd_size) {
std::size_t vec_start = simd_size - rows[0] % simd_size;
for (std::size_t j = 0; j < vec_start; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
ptr[j + k * M] = 1 / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
std::size_t vec_size = (M - vec_start) - (M - vec_start) % simd_size;
for (std::size_t j = vec_start; j < vec_size; j += simd_size) {
// load
Xt_vec.load_aligned(this->points_target.data() + rows[0] + 0 * this->inct + j);
Yt_vec.load_aligned(this->points_target.data() + rows[0] + 1 * this->inct + j);
Zt_vec.load_aligned(this->points_target.data() + rows[0] + 2 * this->inct + j);
for (std::size_t k = 0; k < N; k++) {
dx = b_type_d(this->points_source[cols[0] + k + this->incs * 0]) - Xt_vec;
dy = b_type_d(this->points_source[cols[0] + k + this->incs * 1]) - Yt_vec;
dz = b_type_d(this->points_source[cols[0] + k + this->incs * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
pot_vec.store_unaligned(&(ptr[j + k * M]));
}
}
for (std::size_t j = vec_size; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
ptr[j + k * M] = 1 / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
} else if (N >= simd_size) {
// std::vector<double, xsimd::aligned_allocator<double>> tmp(8);
std::size_t vec_start = simd_size - cols[0] % simd_size;
for (std::size_t k = 0; k < vec_start; k++) {
for (std::size_t j = 0; j < M; ++j) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
ptr[j + k * M] = 1. / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
std::size_t vec_size = (N - vec_start) - (N - vec_start) % simd_size;
for (std::size_t k = vec_start; k < vec_size; k += simd_size) {
// load
Xt_vec.load_aligned(this->points_source.data() + cols[0] + 0 * this->incs + k);
Yt_vec.load_aligned(this->points_source.data() + cols[0] + 1 * this->incs + k);
Zt_vec.load_aligned(this->points_source.data() + cols[0] + 2 * this->incs + k);
for (std::size_t j = 0; j < M; j++) {
dx = b_type_d(this->points_target[rows[0] + j + this->inct * 0]) - Xt_vec;
dy = b_type_d(this->points_target[rows[0] + j + this->inct * 1]) - Yt_vec;
dz = b_type_d(this->points_target[rows[0] + j + this->inct * 2]) - Zt_vec;
r2 = dx * dx + dy * dy + dz * dz;
pot_vec = charge / sqrt(r2);
// pot_vec.store_aligned(tmp.data());
for (int i = 0; i < simd_size; i++) {
ptr[j + (k + i) * M] = pot_vec[i];
}
}
}
for (std::size_t k = vec_size; k < N; k++) {
for (std::size_t j = 0; j < M; ++j) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
ptr[j + k * M] = 1. / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
} else {
for (std::size_t j = 0; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
ptr[j + k * M] = 1. / ((4 * 3.141592653589793238463) * (sqrt(ddx * ddx + ddy * ddy + ddz * ddz)));
}
}
}
}
template <>
void MyGenerator<std::complex<double>, 3>::copy_submatrix(int M, int N, const int *const rows, const int *const cols, std::complex<double> *ptr) const {
using b_type_d = xsimd::simd_type<double>;
using b_type_c_d = xsimd::simd_type<std::complex<double>>;
constexpr std::size_t simd_size = b_type_d::size;
b_type_d charge(1. / (4 * 3.141592653589793238463));
b_type_d cos, sin, r, aux;
b_type_d Xt_vec, Yt_vec, Zt_vec;
b_type_c_d pot_vec;
b_type_d dx, dy, dz;
double d, ddx, ddy, ddz;
if (M >= simd_size) {
std::size_t vec_start = simd_size - rows[0] % simd_size;
for (std::size_t j = 0; j < vec_start; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
std::size_t vec_size = (M - vec_start) - (M - vec_start) % simd_size;
for (std::size_t j = vec_start; j < vec_size; j += simd_size) {
// load
Xt_vec.load_aligned(this->points_target.data() + rows[0] + 0 * this->inct + j);
Yt_vec.load_aligned(this->points_target.data() + rows[0] + 1 * this->inct + j);
Zt_vec.load_aligned(this->points_target.data() + rows[0] + 2 * this->inct + j);
for (std::size_t k = 0; k < N; k++) {
dx = b_type_d(this->points_source[cols[0] + k + this->incs * 0]) - Xt_vec;
dy = b_type_d(this->points_source[cols[0] + k + this->incs * 1]) - Yt_vec;
dz = b_type_d(this->points_source[cols[0] + k + this->incs * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
xsimd::sincos(freq * r, sin, cos);
pot_vec = b_type_c_d(aux * cos, aux * sin);
pot_vec.store_unaligned(&(ptr[j + k * M]));
}
}
for (std::size_t j = vec_size; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
} else if (N >= simd_size) {
std::size_t vec_start = simd_size - cols[0] % simd_size;
for (std::size_t k = 0; k < vec_start; k++) {
for (std::size_t j = 0; j < M; ++j) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
std::size_t vec_size = (N - vec_start) - (N - vec_start) % simd_size;
for (std::size_t k = vec_start; k < vec_size; k += simd_size) {
// load
Xt_vec.load_aligned(this->points_source.data() + cols[0] + 0 * this->incs + k);
Yt_vec.load_aligned(this->points_source.data() + cols[0] + 1 * this->incs + k);
Zt_vec.load_aligned(this->points_source.data() + cols[0] + 2 * this->incs + k);
for (std::size_t j = 0; j < M; j++) {
dx = b_type_d(this->points_target[rows[0] + j + this->inct * 0]) - Xt_vec;
dy = b_type_d(this->points_target[rows[0] + j + this->inct * 1]) - Yt_vec;
dz = b_type_d(this->points_target[rows[0] + j + this->inct * 2]) - Zt_vec;
r = sqrt(dx * dx + dy * dy + dz * dz);
aux = charge / r;
xsimd::sincos(freq * r, sin, cos);
pot_vec = b_type_c_d(aux * cos, aux * sin);
for (int i = 0; i < simd_size; i++) {
ptr[j + (k + i) * M] = pot_vec[i];
}
}
}
for (std::size_t k = vec_size; k < N; k++) {
for (std::size_t j = 0; j < M; ++j) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
} else {
for (std::size_t j = 0; j < M; ++j) {
for (std::size_t k = 0; k < N; k++) {
ddx = this->points_target[rows[j] + 0 * this->inct] - this->points_source[cols[k] + 0 * this->incs];
ddy = this->points_target[rows[j] + 1 * this->inct] - this->points_source[cols[k] + 1 * this->incs];
ddz = this->points_target[rows[j] + 2 * this->inct] - this->points_source[cols[k] + 2 * this->incs];
d = sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ptr[j + k * M] = (1. / (4 * 3.141592653589793238463)) * exp(std::complex<double>(0, 1) * freq * d) / (d);
}
}
}
}
#endif |
49a426d0d9661c1d6d2661099c5f9e3165828624 | 354528d2bb33fe91245e44be181e880fb3874f5a | /NeuralNet/include/nn/layerset.h | 3cd9a298a469063c4444ebe870d5a20d27d00693 | [
"MIT"
] | permissive | nabla27/NeuralNet32 | e6b410db19d07caa332bb19afd50f3904b84277c | e35233adf2b52d9fcb8443dfe35bb8acf5187eb8 | refs/heads/master | 2023-07-15T17:08:38.595959 | 2021-08-26T14:46:15 | 2021-08-26T14:46:15 | 398,137,288 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,576 | h | layerset.h | /* LICENSE
Copyright (c) 2021, nabla All rights reserved.
Use of this source code is governed by a MIT license that can be found
in the LICENSE file.
*/
#ifndef NN_LAYERSET_H
#define NN_LAYERSET_H
#include <vector>
#include <string>
#include <random>
#include "vec/function.h"
#include "util/exchanding.h"
namespace nn {
enum class InitType
{
He, //前層のニューロン数をnとして、標準偏差sqrt{2/n}のガウス分布で初期化
Xavier, //前層のニューロン数をnとして、標準偏差sqrt{1/n}のガウス分布で初期化
Std, //引数で指定した標準偏差のガウス分布で初期化
Unify //引数で指定した値で一律に初期化
};
class LayerSet {
public:
size_t data_size = 0;
size_t label_size = 0;
vec::vector3d weights;
vec::vector2d bias;
std::vector<int> node;
public:
LayerSet(const size_t data_size, const size_t label_size) : data_size(data_size), label_size(label_size) {}
LayerSet() {}
inline void set_node(const std::vector<int>& node) { this->node = node; }
void initialize(const InitType type = InitType::He, const double val = 0);
};
void LayerSet::initialize(const InitType type, const double val)
{
//データがセットされていない場合の例外処理
if (data_size == 0) { exchandling::empty_data(__FILE__, __LINE__, "LayerSet::initialize"); }
weights.clear(); bias.clear(); //重みとバイアスをリセット
std::vector<size_t> index; //重みとバイアスのサイズを一時記憶する配列
index.push_back(data_size);
for (size_t i = 0; i < node.size(); i++) { index.push_back(node[i]); }
index.push_back(label_size);
//重みとバイアスのサイズを確保
const size_t layer_size = index.size() - 1;
for (size_t i = 0; i < layer_size; i++) {
weights.push_back(vec::vector2d(index[i], vec::vector1d(index[i + 1])));
bias.push_back(vec::vector1d(index[i + 1], 0));
}
//重みの各要素を初期化する
const size_t size = weights.size();
for (size_t i = 0; i < size; i++)
{
const size_t row = weights[i].size();
//標準偏差の指定
double variance = val;
switch ((int)type) {
case 0: variance = sqrt(2 / (double)index[i]); break;
case 1: variance = sqrt(1 / (double)index[i]); break;
case 2: variance = val; break;
default: break;
}
if (type != InitType::Unify) { vec::initgauss(weights[i], 0.0, variance); }
else if (type == InitType::Unify) { vec::initequal(weights, val); }
}
}
}
#endif //NN_LAYERSET_H |
d7319270cf35da111dd6b9ae8ab28360c37614d5 | 9e8649a48a4fb2fa001465bddbf7f820daf7b9a7 | /compiler/symbol_table.h | b357f457de9b6239eba7aa805dabef72e176842a | [] | no_license | igalakhov/mks66-mdl | 6c3f9e0977e29536b73ce713ccb95fb87ee8c2ff | 4c3b687069b0348fea9823998cab6a92fccb38cd | refs/heads/master | 2020-05-22T00:46:50.567993 | 2019-05-16T19:26:00 | 2019-05-16T19:26:00 | 186,180,420 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | h | symbol_table.h | //
// Created by Ivan Galakhov on 2019-05-10.
//
#ifndef WORK_01_LINE_SYMBOL_TABLE_H
#define WORK_01_LINE_SYMBOL_TABLE_H
#include <iostream>
#include <string.h>
#include "../matrix/transformation_matrix.h"
#include "../settings.h"
#define MAX_SYMBOLS 512
#define SYM_MATRIX 1
#define SYM_VALUE 2
#define SYM_CONSTANTS 3
#define SYM_LIGHT 4
#define SYM_FILE 5
#define SYM_STRING 5
#define AMBIENT_R 0
#define DIFFUSE_R 1
#define SPECULAR_R 2
// symbol table structures
struct constants
{
double r[4];
double g[4];
double b[4];
double red,green,blue;
};
struct light
{
double l[4];
double c[4];
};
typedef struct
{
char * name;
int type;
union {
TransformationMatrix * m;
struct constants * c;
struct light * l;
double val;
} s;
} SYMBOL;
// symbol table class
// used for keeping track of (you guessed it!) symbols!
class SymbolTable {
public:
SymbolTable();
~SymbolTable();
SYMBOL * lookup_symbol(const char *);
SYMBOL * add_symbol(const char *, int, void *);
void print();
private:
SYMBOL * symtab; // actual list of symbols
int lastsym; // number of symbols
void print_constants(struct constants *);
void print_light(struct light *);
};
#endif //WORK_01_LINE_SYMBOL_TABLE_H
|
a5f6e7ec13ce23e262992f06fb2a56e969bae6a1 | 8b42ecbf10596fe8cfc1efacd9c0d189d0d26a11 | /src/Parser.cpp | 0efac1242f253541473e108eef184f459ac5f89c | [] | no_license | itsmekate/abstract-vm | e040f4f88a158f06299fe724812edce419e4f164 | 1d796681295193da5df12696f887de6326f8395a | refs/heads/master | 2020-04-16T07:41:06.707190 | 2019-01-26T14:37:14 | 2019-01-26T14:37:14 | 165,395,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,567 | cpp | Parser.cpp | #include "../inc/Parser.hpp"
#include "../inc/Exception.hpp"
#include <limits.h>
#include <iostream>
Parser::Parser(){}
Parser::Parser(std::vector<std::map<std::string, std::string>> lexer_result){
try
{
checkExit(lexer_result);
}
catch (std::exception &e) {
std::cout << e.what() << '\n';
}
}
Parser::~Parser(){}
void Parser::checkExit(std::vector<std::map<std::string, std::string>> file){
int exit = 0;
for(auto &i : file){
if (i["cmd"] == "exit")
exit++;
else if (i["cmd"] == "push" || i["cmd"] == "assert")
checkValue(i);
}
if (exit != 1)
throw noExit();
}
void Parser::checkValue(std::map<std::string, std::string> i) const {
if (i["type"] == "int8")
checkInt8(i["value"]);
else if (i["type"] == "int16")
checkInt16(i["value"]);
else if (i["type"] == "int32")
checkInt32(i["value"]);
else if (i["type"] == "float")
checkFloat(i["value"]);
else if (i["type"] == "double")
checkDouble(i["value"]);
}
void Parser::checkInt8( std::string const & value ) const {
try {
int i = std::stoi(value);
if (CHAR_MIN > i || i > CHAR_MAX)
throw wrongValue();
} catch (std::exception &e) {
std::cout << e.what() << '\n';
}
}
void Parser::checkInt16( std::string const & value ) const {
try
{
int i = std::stoi(value);
if (SHRT_MIN > i || i > SHRT_MAX)
throw wrongValue();
}
catch (std::exception &e) {
std::cout << e.what() << '\n';
}
}
void Parser::checkInt32( std::string const & value ) const {
try
{
int i = std::stoi(value);
if (INT_MIN > i || i > INT_MAX)
throw wrongValue();
}
catch (std::exception &e) {
std::cout << e.what() << '\n';
}
}
void Parser::checkFloat( std::string const & value ) const {
try
{
// underflow 15
float i = std::stof(value);
if (std::numeric_limits<float>::max() < i || i < std::numeric_limits<float>::lowest())
throw wrongValue();
}
catch (std::exception &e) {
std::cout << e.what() << '\n';
}
}
void Parser::checkDouble( std::string const & value ) const {
try
{
// underflow 30
double i = std::stod(value);
if (std::numeric_limits<double>::max() < i || i < std::numeric_limits<double>::lowest())
throw wrongValue();
}
catch (std::exception &e) {
std::cout << e.what() << '\n';
}
} |
1c0951b2fcd218567a11f4341aa660ffe45f074b | dfd221943983d2d48fabf0c41064ba5714789bfc | /terepgen/code/renderer/dx_resource.cpp | 3b0aff896d00215091b30321b523c83b3cef9359 | [] | no_license | HMate/TerepGenProject | 8c878cf8164a24aed7649a18236f1e4dbfa4c230 | b8491db03b93805e7638026a178696d26651725a | refs/heads/master | 2020-05-21T04:33:53.602107 | 2017-03-17T11:17:54 | 2017-03-17T11:17:54 | 38,627,366 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 31,321 | cpp | dx_resource.cpp | /*
Terep generátor by Hidvégi Máté @2015
*/
#include "renderer.h"
internal HRESULT
LoadJPGFromFile(dx_resource *DXResources, char *Filename, ID3D11ShaderResourceView **ShaderResView)
{
HRESULT HResult = E_FAIL;
int32 ImgHeight;
int32 ImgWidth;
int32 SourcePxByteSize;
uint32 DestPxByteSize = 4;
uint8 *LoadedBitmap = stbi_load(Filename, &ImgWidth, &ImgHeight, &SourcePxByteSize, DestPxByteSize);
if(LoadedBitmap)
{
// NOTE: Get image info
D3D11_TEXTURE2D_DESC TextureDesc;
TextureDesc.Height = ImgHeight;
TextureDesc.Width = ImgWidth;
TextureDesc.MipLevels = 0;
TextureDesc.ArraySize = 1;
TextureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
TextureDesc.SampleDesc.Count = 1;
TextureDesc.SampleDesc.Quality = 0;
TextureDesc.Usage = D3D11_USAGE_DEFAULT;
TextureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
TextureDesc.CPUAccessFlags = 0;
TextureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
ID3D11Texture2D* Tex;
HResult = DXResources->Device->CreateTexture2D(&TextureDesc, NULL, &Tex);
if(FAILED(HResult))
{
stbi_image_free(LoadedBitmap);
return HResult;
}
// NOTE: Should use UpdateSubresource, if the resource isnt loaded every frame
uint32 RowPitch = ImgWidth * DestPxByteSize;
DXResources->DeviceContext->UpdateSubresource(Tex, 0, NULL, LoadedBitmap, RowPitch, 0);
D3D11_SHADER_RESOURCE_VIEW_DESC SrvDesc;
SrvDesc.Format = TextureDesc.Format;
SrvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SrvDesc.Texture2D.MostDetailedMip = 0;
SrvDesc.Texture2D.MipLevels = (unsigned int)-1;
HResult = DXResources->Device->CreateShaderResourceView(Tex, &SrvDesc, ShaderResView);
if(FAILED(HResult))
{
stbi_image_free(LoadedBitmap);
return HResult;
}
// NOTE: Generate mipmaps for this texture.
DXResources->DeviceContext->GenerateMips(*ShaderResView);
stbi_image_free(LoadedBitmap);
}
return HResult;
}
internal HRESULT
LoadBackground(dx_resource *DXResources, memory_arena *Arena, ID3D11ShaderResourceView **ShaderResView)
{
int32 ImgHeight = 512;
int32 ImgWidth = 512;
perlin_noise_generator Perlin;
SetSeed(&Perlin, 1000);
real32 PixelWidth = 2.0f/512.0f;
// NOTE: order: +X, -X, +Y, -Y, +Z, -Z
const uint32 Colors[6] = {0xFFFF0000, 0x00FF0000, 0x0000FF00, 0xFFFFFF00, 0xFF00FF00, 0xFF000000};
const v3 StartPositions[6] = {{1.0f, 1.0f, 1.0f},
{-1.0f, 1.0f, -1.0f},
{-1.0f, 1.0f, -1.0f},
{-1.0f, -1.0f, 1.0f},
{-1.0f, 1.0f, 1.0f},
{1.0f, 1.0f, -1.0f}};
const v3 ColumnDiffs[6] = {{0.0f, 0.0f, -PixelWidth},
{0.0f, 0.0f, PixelWidth},
{PixelWidth, 0.0f, 0.0f},
{PixelWidth, 0.0f, 0.0f},
{PixelWidth, 0.0f, 0.0f},
{-PixelWidth, 0.0f, 0.0f}};
const v3 RowDiffs[6] = {{0.0f, -PixelWidth, 0.0f},
{0.0f, -PixelWidth, 0.0f},
{0.0f, 0.0f, PixelWidth},
{0.0f, 0.0f, -PixelWidth},
{0.0f, -PixelWidth, 0.0f},
{0.0f, -PixelWidth, 0.0f}};
D3D11_SUBRESOURCE_DATA pData[6];
uint32 *Image = PushArray(Arena, uint32, ImgHeight*ImgWidth*6);
uint8* Ptr = (uint8*)Image;
for(int32 Side = 0;
Side < 6;
++Side)
{
uint32 Color = Colors[Side];
v3 StartPos = StartPositions[Side];
v3 ColumnDiff = ColumnDiffs[Side];
v3 RowDiff = RowDiffs[Side];
v3 PixelPos = StartPos;
for(int32 Y = 0;
Y < ImgHeight;
Y++)
{
for(int32 X = 0;
X < ImgWidth;
X++)
{
Assert(Color != 0);
v3 SkyPos = Normalize(PixelPos);
real32 Cloud = RandomFloat(&Perlin, 2.0f*SkyPos)*8.0f;
Cloud += RandomFloat(&Perlin, 8.0f*SkyPos)*4.0f;
Cloud += RandomFloat(&Perlin, 20.0f*SkyPos)*2.0f;
Cloud += RandomFloat(&Perlin, 40.0f*SkyPos)*1.0f;
// NOTE: clip to 0.0-1.0
Cloud = (Cloud / 30.0f) + 0.5f;
Cloud *= Abs(ClampReal32(SkyPos.Y+0.4f, 0.0f, 1.0f));
uint8 Red = (uint8)(Cloud*255);
uint8 Green = (uint8)(Cloud*255);
uint8 Blue = (uint8)(225);
*(Ptr++) = Red;
*(Ptr++) = Green;
*(Ptr++) = Blue;
*(Ptr++) = 0;
PixelPos = PixelPos + ColumnDiff;
}
PixelPos = PixelPos + ((real32)(-ImgWidth)*ColumnDiff);
PixelPos = PixelPos + RowDiff;
}
pData[Side].pSysMem = &Image[Side*ImgHeight*ImgWidth];
pData[Side].SysMemPitch = 4*ImgWidth;
pData[Side].SysMemSlicePitch = 0;
}
// NOTE: Get image info
D3D11_TEXTURE2D_DESC TextureDesc;
TextureDesc.Height = ImgHeight;
TextureDesc.Width = ImgWidth;
TextureDesc.MipLevels = 1;
TextureDesc.ArraySize = 6;
TextureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
TextureDesc.SampleDesc.Count = 1;
TextureDesc.SampleDesc.Quality = 0;
TextureDesc.Usage = D3D11_USAGE_DEFAULT;
TextureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
TextureDesc.CPUAccessFlags = 0;
TextureDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE | D3D11_RESOURCE_MISC_GENERATE_MIPS;
ID3D11Texture2D* Tex;
HRESULT HResult = DXResources->Device->CreateTexture2D(&TextureDesc, &pData[0], &Tex);
if(FAILED(HResult))
{
return HResult;
}
D3D11_SHADER_RESOURCE_VIEW_DESC SrvDesc;
SrvDesc.Format = TextureDesc.Format;
// SrvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SrvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
SrvDesc.TextureCube.MipLevels = TextureDesc.MipLevels;
SrvDesc.TextureCube.MostDetailedMip = 0;
HResult = DXResources->Device->CreateShaderResourceView(Tex, &SrvDesc, ShaderResView);
if(FAILED(HResult))
{
return HResult;
}
// NOTE: Generate mipmaps for this texture.
DXResources->DeviceContext->GenerateMips(*ShaderResView);
return HResult;
}
struct shader_code
{
uint8* Data;
uint32 Size;
};
internal shader_code
LoadShaderCode(memory_arena *Arena, char* FileName)
{
shader_code Result;
Result.Size = 0;
FileHandle Handle = PlatformOpenFileForRead(FileName);
Result.Size = GetFileSize(Handle, NULL);
Result.Data = PushArray(Arena, uint8, Result.Size);
bool32 EndOfFile = false;
uint32 BytesRead = PlatformReadFile(Handle, Result.Data, Result.Size);
CloseHandle(Handle);
return Result;
}
HRESULT dx_resource::Initialize(memory_arena *Arena, uint32 ScreenWidth, uint32 ScreenHeight)
{
HRESULT HResult;
ViewPortMinDepth = 0.0f;
ViewPortMaxDepth = 1.0f;
DefaultDepthValue = 1.0f;
// NOTE: Query hardware specs
IDXGIFactory *Factory;
IDXGIAdapter *Adapter;
IDXGIOutput *AdapterOutput;
DXGI_ADAPTER_DESC AdapterDesc;
uint32 NumModes, Numerator, Denominator;
size_t StringLength;
HResult = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&Factory);
if(FAILED(HResult))
return HResult;
HResult = Factory->EnumAdapters(0, &Adapter);
if(FAILED(HResult))
return HResult;
HResult = Adapter->EnumOutputs(0, &AdapterOutput);
if(FAILED(HResult))
return HResult;
HResult = AdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_ENUM_MODES_INTERLACED, &NumModes, NULL);
if(FAILED(HResult))
return HResult;
DXGI_MODE_DESC *DisplayModeList = PushArray(Arena, DXGI_MODE_DESC, NumModes);
if(!DisplayModeList)
return E_ABORT;
HResult = AdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_ENUM_MODES_INTERLACED, &NumModes, DisplayModeList);
if(FAILED(HResult))
return HResult;
for(uint32 i = 0; i < NumModes; ++i)
{
if(DisplayModeList[i].Width == (uint32)ScreenWidth)
{
if(DisplayModeList[i].Height == (uint32)ScreenHeight)
{
Numerator = DisplayModeList[i].RefreshRate.Numerator;
Denominator = DisplayModeList[i].RefreshRate.Denominator;
}
}
}
HResult = Adapter->GetDesc(&AdapterDesc);
if(FAILED(HResult))
return HResult;
VideoCardMemory = (int32)(AdapterDesc.DedicatedVideoMemory / 1024 / 1024);
wcstombs_s(&StringLength, VideoCardDescription, 128, AdapterDesc.Description, 128);
AdapterOutput->Release();
Adapter->Release();
Factory->Release();
DXGI_SWAP_CHAIN_DESC SwapChainDesc;
ZeroMemory(&SwapChainDesc, sizeof(SwapChainDesc));
SwapChainDesc.BufferCount = 1;
SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
SwapChainDesc.BufferDesc.Width = ScreenWidth;
SwapChainDesc.BufferDesc.Height = ScreenHeight;
SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
SwapChainDesc.BufferDesc.RefreshRate.Numerator = 0; // No VSync
SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
SwapChainDesc.OutputWindow = GetActiveWindow();
SwapChainDesc.SampleDesc.Count = 4;
SwapChainDesc.SampleDesc.Quality = 0;
SwapChainDesc.Windowed = true;
D3D_FEATURE_LEVEL FeatureLevels[4] = {D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0};
D3D_FEATURE_LEVEL UsedFeatureLevel;
uint32 DeviceFlags = NULL;
#if TEREPGEN_DEBUG
// NOTE: D3D11_CREATE_DEVICE_DEBUGGABLE flag does not work before win8.1
logger::DebugPrint("Device and SwapChain are created with DEBUG flag");
DeviceFlags = D3D11_CREATE_DEVICE_DEBUG;
#endif
HResult = D3D11CreateDeviceAndSwapChain(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
DeviceFlags,
(D3D_FEATURE_LEVEL *)FeatureLevels,
ArrayCount(FeatureLevels),
D3D11_SDK_VERSION,
&SwapChainDesc,
&SwapChain,
&Device,
&UsedFeatureLevel,
&DeviceContext);
if(FAILED(HResult))
return HResult;
D3D11_VIEWPORT Viewport;
ZeroMemory(&Viewport, sizeof(D3D11_VIEWPORT));
Viewport.TopLeftX = 0.0f;
Viewport.TopLeftY = 0.0f;
Viewport.Width = (real32)ScreenWidth;
Viewport.Height = (real32)ScreenHeight;
Viewport.MinDepth = ViewPortMinDepth;
Viewport.MaxDepth = ViewPortMaxDepth;
DeviceContext->RSSetViewports(1, &Viewport);
// NOTE: Create Render Target View
ID3D11Texture2D *BackBufferTexture;
HResult = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&BackBufferTexture);
if(FAILED(HResult))
return HResult;
HResult = Device->CreateRenderTargetView(BackBufferTexture, 0, &BackBuffer);
BackBufferTexture->Release();
if(FAILED(HResult))
return HResult;
// NOTE: Create Depth Stencil
// NOTE: SampleDesc have to be the same as the SwapChain's, or nothing will render
D3D11_TEXTURE2D_DESC DepthStencilDesc;
DepthStencilDesc.Width = ScreenWidth;
DepthStencilDesc.Height = ScreenHeight;
DepthStencilDesc.MipLevels = 1;
DepthStencilDesc.ArraySize = 1;
DepthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
DepthStencilDesc.SampleDesc.Count = 4;
DepthStencilDesc.SampleDesc.Quality = 0;
DepthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
DepthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
DepthStencilDesc.CPUAccessFlags = 0;
DepthStencilDesc.MiscFlags = 0;
HResult = Device->CreateTexture2D(&DepthStencilDesc, nullptr, &DepthStencilBuffer);
if(FAILED(HResult)) return HResult;
HResult = Device->CreateDepthStencilView(DepthStencilBuffer, nullptr, &DepthStencilView);
if(FAILED(HResult)) return HResult;
DeviceContext->OMSetRenderTargets(1, &BackBuffer, DepthStencilView);
// NOTE: Create DepthStencilState
D3D11_DEPTH_STENCIL_DESC dsDesc;
dsDesc.DepthEnable = true;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS;
dsDesc.StencilEnable = false;
dsDesc.StencilReadMask = 0xFF;
dsDesc.StencilWriteMask = 0xFF;
// Stencil operations if pixel is front-facing
dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Stencil operations if pixel is back-facing
dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create depth stencil state
Device->CreateDepthStencilState(&dsDesc, &DepthStencilState);
DeviceContext->OMSetDepthStencilState(DepthStencilState, 1);
// NOTE: Compile Terrain Shaders
shader_code VShader = LoadShaderCode(Arena, "terrain_vs.fxc");
HResult = Device->CreateVertexShader(VShader.Data, VShader.Size, 0, &TerrainVS);
shader_code PShader = LoadShaderCode(Arena, "terrain_ps.fxc");
Device->CreatePixelShader(PShader.Data, PShader.Size, 0, &TerrainPS);
PShader = LoadShaderCode(Arena, "line_ps.fxc");
Device->CreatePixelShader(PShader.Data, PShader.Size, 0, &LinePS);
// NOTE: Create Input Layout
D3D11_INPUT_ELEMENT_DESC ElementDesc[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
};
HResult = Device->CreateInputLayout(ElementDesc, ArrayCount(ElementDesc),
VShader.Data, VShader.Size, &TerrainInputLayout);
if(FAILED(HResult))
{
return HResult;
}
// NOTE: Background shaders
VShader = LoadShaderCode(Arena, "background_vs.fxc");
Device->CreateVertexShader(VShader.Data, VShader.Size, 0, &BackgroundVS);
PShader = LoadShaderCode(Arena, "background_ps.fxc");
Device->CreatePixelShader(PShader.Data, PShader.Size, 0, &BackgroundPS);
// NOTE: Create Background Input Layout
D3D11_INPUT_ELEMENT_DESC BGElementDesc[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}
};
HResult = Device->CreateInputLayout(BGElementDesc, ArrayCount(BGElementDesc),
VShader.Data, VShader.Size, &BackgroundInputLayout);
if(FAILED(HResult))
{
return HResult;
}
SetTransformations(v3{0,0,0});
ObjectConstants.WorldMatrix = DirectX::XMFLOAT4X4(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
ObjectConstants.CameraDir = DirectX::XMFLOAT4(1,0, 0, 1);
D3D11_BUFFER_DESC ObjectCBDesc = {};
ObjectCBDesc.ByteWidth = sizeof( object_constants );
ObjectCBDesc.Usage = D3D11_USAGE_DYNAMIC;
ObjectCBDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
ObjectCBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
ObjectCBDesc.MiscFlags = 0;
ObjectCBDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA ObjCBufferData;
ObjCBufferData.pSysMem = &ObjectConstants;
ObjCBufferData.SysMemPitch = 0;
ObjCBufferData.SysMemSlicePitch = 0;
HResult = Device->CreateBuffer(&ObjectCBDesc, &ObjCBufferData, &ObjectConstantBuffer);
if(FAILED(HResult)) return HResult;
// NOTE: Create RasterizerStates
D3D11_RASTERIZER_DESC RSDescDefault;
ZeroMemory(&RSDescDefault, sizeof(D3D11_RASTERIZER_DESC));
RSDescDefault.FillMode = D3D11_FILL_SOLID;
RSDescDefault.CullMode = D3D11_CULL_BACK;
RSDescDefault.DepthClipEnable = true;
HResult = Device->CreateRasterizerState(&RSDescDefault, &RSDefault);
if(FAILED(HResult)) return HResult;
D3D11_RASTERIZER_DESC RSDescWireFrame;
ZeroMemory(&RSDescWireFrame, sizeof(D3D11_RASTERIZER_DESC));
RSDescWireFrame.FillMode = D3D11_FILL_WIREFRAME;
RSDescWireFrame.CullMode = D3D11_CULL_NONE;
HResult = Device->CreateRasterizerState(&RSDescWireFrame, &RSWireFrame);
if(FAILED(HResult)) return HResult;
#if 1
this->MaxVertexCount = 150000;
#else
this->MaxVertexCount = RENDER_BLOCK_VERTEX_COUNT;
#endif
logger::DebugPrint("VertBuff Max Vertex Count: %d", MaxVertexCount);
// TODO: Instead of MaxVertexCount, i should use the count from CreateRenderVertices here.
// Its more precise, but then i cant change the number of vertices.
HResult = CreateVertexBuffer(&VertexBuffer, this->MaxVertexCount);
if(FAILED(HResult)) return HResult;
HResult = LoadJPGFromFile(this, "grass.jpg", &GrassTexture);
if(FAILED(HResult)) return HResult;
HResult = LoadJPGFromFile(this, "lichen_rock_by_darlingstock.jpg", &RockTexture);
if(FAILED(HResult)) return HResult;
// HResult = LoadJPGFromFile(this, "sky-texture.jpg", &SkyTexture);
// if(FAILED(HResult)) return HResult;
HResult = LoadBackground(this, Arena, &SkyTexture);
if(FAILED(HResult)) return HResult;
DeviceContext->PSSetShaderResources(0, 1, &GrassTexture);
DeviceContext->PSSetShaderResources(1, 1, &RockTexture);
DeviceContext->PSSetShaderResources(2, 1, &SkyTexture);
D3D11_SAMPLER_DESC SampDesc;
ZeroMemory( &SampDesc, sizeof(SampDesc) );
SampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
SampDesc.AddressU = D3D11_TEXTURE_ADDRESS_MIRROR;
SampDesc.AddressV = D3D11_TEXTURE_ADDRESS_MIRROR;
SampDesc.AddressW = D3D11_TEXTURE_ADDRESS_MIRROR;
SampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
SampDesc.MinLOD = 0;
SampDesc.MaxLOD = D3D11_FLOAT32_MAX;
HResult = Device->CreateSamplerState(&SampDesc, &TexSamplerState);
if(FAILED(HResult))
{
return HResult;
}
DeviceContext->PSSetSamplers(0, 1, &TexSamplerState);
D3D11_SAMPLER_DESC CubeSampDesc;
ZeroMemory( &CubeSampDesc, sizeof(CubeSampDesc) );
CubeSampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
CubeSampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
CubeSampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
CubeSampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
CubeSampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
CubeSampDesc.MinLOD = 0;
CubeSampDesc.MaxLOD = D3D11_FLOAT32_MAX;
HResult = Device->CreateSamplerState(&CubeSampDesc, &CubeTexSamplerState);
if(FAILED(HResult))
{
return HResult;
}
DeviceContext->PSSetSamplers(0, 1, &TexSamplerState);
return HResult;
}
void dx_resource::ClearViews()
{
v4 BackgroundColor = {0.0f, 0.2f, 0.4f, 1.0f};
DeviceContext->ClearDepthStencilView(DepthStencilView,
D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, DefaultDepthValue, 0);
DeviceContext->ClearRenderTargetView(BackBuffer, BackgroundColor.C);
}
void dx_resource::Release()
{
if(SwapChain)
{
SwapChain->SetFullscreenState(false, NULL);
}
if(RSDefault)
{
RSDefault->Release();
RSDefault = nullptr;
}
if(RSWireFrame)
{
RSWireFrame->Release();
RSWireFrame = nullptr;
}
if(ObjectConstantBuffer)
{
ObjectConstantBuffer->Release();
ObjectConstantBuffer = nullptr;
}
if(VertexBuffer)
{
VertexBuffer->Release();
VertexBuffer = nullptr;
}
if(TerrainVS)
{
TerrainVS->Release();
TerrainVS = nullptr;
}
if(TerrainPS)
{
TerrainPS->Release();
TerrainPS = nullptr;
}
if(LinePS)
{
LinePS->Release();
LinePS = nullptr;
}
if(BackgroundVS)
{
BackgroundVS->Release();
BackgroundVS = nullptr;
}
if(BackgroundPS)
{
BackgroundPS->Release();
BackgroundPS = nullptr;
}
if(DepthStencilView)
{
DepthStencilView->Release();
DepthStencilView = nullptr;
}
if(DepthStencilBuffer)
{
DepthStencilBuffer->Release();
DepthStencilBuffer = nullptr;
}
if(DepthStencilState)
{
DepthStencilState->Release();
DepthStencilState = nullptr;
}
if(BackBuffer)
{
BackBuffer->Release();
BackBuffer = nullptr;
}
if(Device)
{
Device->Release();
Device = nullptr;
}
if(DeviceContext)
{
DeviceContext->Release();
DeviceContext = nullptr;
}
if(SwapChain)
{
SwapChain->Release();
SwapChain = nullptr;
}
}
HRESULT dx_resource::Resize(uint32 ScreenWidth, uint32 ScreenHeight)
{
HRESULT HResult = S_OK;
if(SwapChain && ScreenWidth && ScreenHeight)
{
#if TEREPGEN_DEBUG
char DebugBuffer[256];
sprintf_s(DebugBuffer, "[TEREPGEN_DEBUG] Resize Width: %d\n", ScreenWidth);
OutputDebugStringA(DebugBuffer);
sprintf_s(DebugBuffer, "[TEREPGEN_DEBUG] Resize Height: %d\n", ScreenHeight);
OutputDebugStringA(DebugBuffer);
#endif
DeviceContext->OMSetRenderTargets(0, 0, 0);
BackBuffer->Release();
SwapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
ID3D11Texture2D* BackBufferTexture;
HResult = SwapChain->GetBuffer(0, __uuidof( ID3D11Texture2D), (void**) &BackBufferTexture);
if(FAILED(HResult)) return HResult;
HResult = Device->CreateRenderTargetView(BackBufferTexture, NULL, &BackBuffer);
BackBufferTexture->Release();
if(FAILED(HResult)) return HResult;
if(DepthStencilBuffer) DepthStencilBuffer->Release();
if(DepthStencilState) DepthStencilState->Release();
D3D11_TEXTURE2D_DESC DepthStencilDesc;
DepthStencilDesc.Width = ScreenWidth;
DepthStencilDesc.Height = ScreenHeight;
DepthStencilDesc.MipLevels = 1;
DepthStencilDesc.ArraySize = 1;
DepthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
DepthStencilDesc.SampleDesc.Count = 4;
DepthStencilDesc.SampleDesc.Quality = 0;
DepthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
DepthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
DepthStencilDesc.CPUAccessFlags = 0;
DepthStencilDesc.MiscFlags = 0;
HResult = Device->CreateTexture2D(&DepthStencilDesc, nullptr, &DepthStencilBuffer);
if(FAILED(HResult)) return HResult;
HResult = Device->CreateDepthStencilView(DepthStencilBuffer, nullptr, &DepthStencilView);
if(FAILED(HResult)) return HResult;
DeviceContext->OMSetRenderTargets(1, &BackBuffer, DepthStencilView);
D3D11_VIEWPORT Viewport;
ZeroMemory(&Viewport, sizeof(D3D11_VIEWPORT));
Viewport.TopLeftX = 0.0f;
Viewport.TopLeftY = 0.0f;
Viewport.Width = (real32)ScreenWidth;
Viewport.Height = (real32)ScreenHeight;
Viewport.MinDepth = ViewPortMinDepth;
Viewport.MaxDepth = ViewPortMaxDepth;
DeviceContext->RSSetViewports( 1, &Viewport);
}
return HResult;
}
char* dx_resource::GetDebugMessage(DWORD dwErrorMsgId)
{
DWORD ret; // Temp space to hold a return value.
char* pBuffer; // Buffer to hold the textual error description.
ret = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | // The function will allocate space for pBuffer.
FORMAT_MESSAGE_FROM_SYSTEM | // System wide message.
FORMAT_MESSAGE_IGNORE_INSERTS, // No inserts.
NULL, // Message is not in a module.
dwErrorMsgId, // Message identifier.
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language.
(LPTSTR)&pBuffer, // Buffer to hold the text string.
ERRMSGBUFFERSIZE, // The function will allocate at least this much for pBuffer.
NULL // No inserts.
);
return pBuffer;
}
void dx_resource::SetTransformations(v3 Translation)
{
ObjectConstants.WorldMatrix = DirectX::XMFLOAT4X4(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
Translation.X, Translation.Y, Translation.Z, 1);
}
void dx_resource::SetDrawModeDefault(void)
{
DeviceContext->RSSetState(RSDefault);
}
void dx_resource::SetDrawModeWireframe(void)
{
DeviceContext->RSSetState(RSWireFrame);
}
void dx_resource::DrawBackground(v3 *Vertices, uint32 VertCount)
{
LoadResource(ObjectConstantBuffer, &ObjectConstants, sizeof(ObjectConstants));
DeviceContext->VSSetConstantBuffers(1, 1, &ObjectConstantBuffer);
DeviceContext->PSSetConstantBuffers(1, 1, &ObjectConstantBuffer);
uint32 stride = sizeof(v3);
uint32 offset = 0;
LoadResource(VertexBuffer, Vertices, sizeof(v3) * VertCount);
DeviceContext->IASetVertexBuffers(0, 1, &VertexBuffer, &stride, &offset);
DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
DeviceContext->Draw(VertCount, 0);
}
void dx_resource::DrawTriangles(vertex *Vertices, uint32 VertCount)
{
LoadResource(VertexBuffer, Vertices, sizeof(vertex) * VertCount);
DrawVertices(&VertexBuffer, VertCount);
}
void dx_resource::DrawLines(vertex *Vertices, uint32 VertCount)
{
LoadResource(VertexBuffer, Vertices, sizeof(vertex) * VertCount);
DrawVertices(&VertexBuffer, VertCount);
}
void dx_resource::DrawDebugTriangle()
{
DeviceContext->RSSetState(RSDefault);
const uint32 FalseCount = 3;
v4 Color{1.0f, 0.0f, 0.0f, 1.0f};
v3 Normal{0.0f, 1.0f, 0.0f};
vertex FalseVertices[FalseCount]={Vertex(v3{1.0f , 0.55f, 1.0f}, Normal, Color),
Vertex(v3{-0.8f, -0.7f, 1.0f}, Normal, Color),
Vertex(v3{-1.0f, 0.0f , 1.0f}, Normal, Color)};
Assert(!"Curently not implemented!");
}
void dx_resource::DrawVertices(ID3D11Buffer** Buffer, uint32 VertexCount)
{
LoadResource(ObjectConstantBuffer, &ObjectConstants, sizeof(ObjectConstants));
DeviceContext->VSSetConstantBuffers(1, 1, &ObjectConstantBuffer);
uint32 stride = sizeof(vertex);
uint32 offset = 0;
DeviceContext->IASetVertexBuffers(0, 1, Buffer, &stride, &offset);
DeviceContext->Draw(VertexCount, 0);
}
HRESULT dx_resource::CreateVertexBuffer(ID3D11Buffer** Buffer, uint32 Size, void *Content)
{
D3D11_BUFFER_DESC BufferDesc;
ZeroMemory(&BufferDesc, sizeof(BufferDesc));
BufferDesc.Usage = D3D11_USAGE_DYNAMIC;
// NOTE: above 120MB vx buffer size dx11 crashes
// NOTE: at vertex size = 48 B, MaxVC = 2621440 is 120MB
// TODO: Need to profile if drawing is faster with lower buffer size.
// BufferDesc.ByteWidth = sizeof(vertex) * 2621440; // Max buffer size at 48B vertices
BufferDesc.ByteWidth = sizeof(vertex) * Size;
BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
Assert(BufferDesc.ByteWidth <= MEGABYTE(120));
HRESULT HResult;
if(Content != NULL)
{
D3D11_SUBRESOURCE_DATA Data;
Data.pSysMem = Content;
Data.SysMemPitch = 0;
Data.SysMemSlicePitch = 0;
HResult = Device->CreateBuffer(&BufferDesc, &Data, Buffer);
}else{
HResult = Device->CreateBuffer(&BufferDesc, NULL, Buffer);
}
if(FAILED(HResult))
{
logger::DebugPrint("Failed to create vertex buffer with size %d: %s", Size, GetDebugMessage(HResult));
}
return HResult;
}
HRESULT dx_resource::CreateVertexBufferImmutable(ID3D11Buffer** Buffer, uint32 Size, void *Content)
{
D3D11_BUFFER_DESC BufferDesc;
ZeroMemory(&BufferDesc, sizeof(BufferDesc));
BufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
// NOTE: above 120MB vx buffer size dx11 crashes
// NOTE: at vertex size = 48 B, MaxVC = 2621440 is 120MB
// TODO: Need to profile if drawing is faster with lower buffer size.
// BufferDesc.ByteWidth = sizeof(vertex) * 2621440; // Max buffer size at 48B vertices
BufferDesc.ByteWidth = sizeof(vertex) * Size;
BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
//BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
Assert(BufferDesc.ByteWidth <= MEGABYTE(120));
D3D11_SUBRESOURCE_DATA Data;
Data.pSysMem = Content;
Data.SysMemPitch = 0;
Data.SysMemSlicePitch = 0;
HRESULT HResult = Device->CreateBuffer(&BufferDesc, &Data, Buffer);
if(FAILED(HResult))
{
logger::DebugPrint("Failed to create vertex buffer with size %d: %s", Size, GetDebugMessage(HResult));
}
return HResult;
}
void dx_resource::LoadResource(ID3D11Resource *Buffer, void *Resource, uint32 ResourceSize)
{
// NOTE: This kind of resource mapping is optimized for per frame updating
// for resources with D3D11_USAGE_DYNAMIC
// SOURCE: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476259%28v=vs.85%29.aspx
// TODO: Conscutive calls for vertex buffers should use this: D3D11_MAP_WRITE_NO_OVERWRITE
HRESULT HResult;
D3D11_MAPPED_SUBRESOURCE MappedSubresource;
HResult = DeviceContext->Map(Buffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &MappedSubresource);
if(FAILED(HResult))
{
logger::DebugPrint("Load Resource failed: %s", GetDebugMessage(HResult));
}
memcpy(MappedSubresource.pData, Resource, ResourceSize);
DeviceContext->Unmap(Buffer, NULL);
} |
e37a7d02a340b3995340572cf418081e7b348a02 | d8f568633b985728d1a3bef7fea35341448ab34d | /TestStable/testmt.cpp | 4287477d5d8d4206310d94359d444cf300ac97fa | [] | no_license | zhkLearn/TestStable | 1100fbe37d2264dd387e68f6559aac6ec6a0b75c | 13f8f904e947e9c043619e8d927a3bbf5f7aba55 | refs/heads/master | 2020-04-13T12:02:56.212660 | 2019-08-10T07:14:25 | 2019-08-10T07:14:25 | 163,191,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,379 | cpp | testmt.cpp | #include "stdafx.h"
#include "stable.h"
#include <thread>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <inttypes.h>
#define MAX_THREAD 16
#define MAX_COUNT 1000
static struct STable* init()
{
struct STable * t = stable_create();
struct STable * sub1 = stable_create();
struct STable * sub2 = stable_create();
stable_settable(t, TKEY("number"), sub1);
stable_settable(t, TKEY("string"), sub2);
stable_setnumber(t, TKEY("count"), 0);
return t;
}
static void* thread_write(struct STable* ptr)
{
struct STable* t = ptr;
int i;
char buf[32];
struct STable * n = stable_table(t, TKEY("number"));
struct STable * s = stable_table(t, TKEY("string"));
assert(n && s);
for (i = 0; i < MAX_COUNT; i++)
{
sprintf_s(buf, "%d", i);
printf("Write: %6d ", i + 1);
stable_setstring(n, TINDEX(i), buf, strlen(buf));
printf("string ");
stable_setnumber(s, buf, strlen(buf), i);
printf("number ");
stable_setnumber(t, TKEY("count"), i + 1);
printf("count\n");
if ((i + 1) % 10 == 0)
{
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
}
return NULL;
}
static void* thread_read(int index, struct STable* ptr)
{
struct STable * t = ptr;
int lastCount = 0;
struct STable * n = stable_table(t, TKEY("number"));
struct STable * s = stable_table(t, TKEY("string"));
while (lastCount != MAX_COUNT)
{
int count = stable_number(t, TKEY("count"));
if (count == lastCount)
{
continue;
}
if (count >= lastCount + 1)
{
printf("Read thread%3d: %6d - %6d\n", index, lastCount, count);
}
lastCount = count;
count--;
char buf[32];
sprintf_s(buf, "%d", count);
char buffer[512];
size_t sz = 512;
stable_string(n, TINDEX(count), buffer, &sz);
int v = strtol(buffer, NULL, 10);
//assert(v == count);
double d = stable_number(s, buf, strlen(buf));
if ((int)d != count)
{
printf("key = %s i=%d d=%f\n", buf, count, d);
}
//assert((int)d == count);
}
return NULL;
}
static void test_read(struct STable *t)
{
struct STable * n = stable_table(t, TKEY("number"));
struct STable * s = stable_table(t, TKEY("string"));
char buf[32];
int i;
for (i = 0; i < MAX_COUNT; i++)
{
sprintf_s(buf, "%d", i);
char buffer[512];
size_t sz = 512;
stable_string(n, TINDEX(i), buffer, &sz);
int v = strtol(buffer, NULL, 10);
//assert(v == i);
double d = stable_number(s, buf, strlen(buf));
if ((int)d != i)
{
printf("key = %s i=%d d=%f\n", buf, i, d);
}
//assert((int)d == i);
}
}
int test_mt()
{
std::thread pid[MAX_THREAD];
struct STable *T = init();
printf("init\n");
pid[0] = std::thread(thread_write, T);
//pthread_create(&pid[0], NULL, thread_write, T);
int i;
for (i = 1; i < MAX_THREAD; i++)
{
pid[i] = std::thread(thread_read, i, T);
//pthread_create(&pid[i], NULL, thread_read, T);
}
for (i = 0; i < MAX_THREAD; i++)
{
pid[i].join();
//pthread_join(pid[i], NULL);
}
printf("main exit\n");
test_read(T);
stable_release(T);
return 0;
}
|
b5ef20ac31ec86ede8c58f576ae0b898e9050ed6 | a349dbf18493cd9bbb2bc9288671f2c981aa8233 | /All Other Topics/Smallest Positive missing number.cpp | cc3859f5e59676ec6e487c95bf17532a6774af33 | [] | no_license | Ashish-kumar7/geeks-for-geeks-solutions | dd67fb596162d866a8043460f07e2052dc38446d | 045dc4041323b4f912fcb50ae087eb5865fbacb3 | refs/heads/master | 2022-10-27T14:43:09.588551 | 2022-10-02T10:41:56 | 2022-10-02T10:41:56 | 228,147,267 | 38 | 50 | null | 2022-10-19T05:32:24 | 2019-12-15T07:40:36 | C++ | UTF-8 | C++ | false | false | 291 | cpp | Smallest Positive missing number.cpp | int missingNumber(int B[], int n) {
int A[n+2];
for(int i=0;i<n+2;i++){
A[i]=0;
}
for(int i=0;i<n;i++){
if(B[i]>0 && B[i]<n+2){
A[B[i]]++;
}
}
for(int i=1;i<n+2;i++){
if(A[i]==0){
return i;
}
}
} |
8aab6dc446468c7fc836c5eae00144d11882cf8b | 47750365686d097ade42f71ff1c00783672c8670 | /src/SynTree/CompoundStmt.cc | 6679ec561942b4ac92fa0d5e8639f063f23e83b2 | [
"BSD-3-Clause"
] | permissive | cforall/cforall | 5c380fe6b1dbb361acaca946afef420f322f30bd | 3d410dfa484515e634d1c902f9a88143b57a8a60 | refs/heads/master | 2023-08-18T09:22:22.954701 | 2023-08-16T04:30:20 | 2023-08-16T04:30:20 | 139,628,817 | 56 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,430 | cc | CompoundStmt.cc | //
// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// XXX.cc --
//
// Author : Richard C. Bilson
// Created On : Mon May 18 07:44:20 2015
// Last Modified By : Rob Schluntz
// Last Modified On : Mon May 02 15:19:17 2016
// Update Count : 3
//
#include <cassert> // for assert, strict_dynamic_cast
#include <list> // for list, _List_const_iterator, lis...
#include <ostream> // for operator<<, ostream, basic_ostream
#include <string> // for operator==, string
#include "Common/utility.h" // for cloneAll, deleteAll, printAll
#include "Declaration.h" // for DeclarationWithType, Declaration
#include "Statement.h" // for CompoundStmt, Statement, DeclStmt
#include "SynTree/Label.h" // for Label
#include "SynTree/DeclReplacer.h" // for DeclReplacer
using std::string;
using std::endl;
CompoundStmt::CompoundStmt() : Statement() {
}
CompoundStmt::CompoundStmt( std::list<Statement *> stmts ) : Statement(), kids( stmts ) {
}
CompoundStmt::CompoundStmt( const CompoundStmt &other ) : Statement( other ) {
cloneAll( other.kids, kids );
// when cloning a compound statement, we may end up cloning declarations which
// are referred to by VariableExprs throughout the block. Cloning a VariableExpr
// does a shallow copy, so the VariableExpr will end up pointing to the original
// declaration. If the original declaration is deleted, e.g. because the original
// CompoundStmt is deleted, then we have a dangling pointer. To avoid this case,
// find all DeclarationWithType nodes (since a VariableExpr must point to a
// DeclarationWithType) in the original CompoundStmt and map them to the cloned
// node in the new CompoundStmt ('this'), then replace the Declarations referred to
// by each VariableExpr according to the constructed map. Note that only the declarations
// in the current level are collected into the map, because child CompoundStmts will
// recursively execute this routine. There may be more efficient ways of doing
// this.
DeclReplacer::DeclMap declMap;
std::list< Statement * >::const_iterator origit = other.kids.begin();
for ( Statement * s : kids ) {
assert( origit != other.kids.end() );
Statement * origStmt = *origit++;
if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( s ) ) {
DeclStmt * origDeclStmt = strict_dynamic_cast< DeclStmt * >( origStmt );
if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * > ( declStmt->get_decl() ) ) {
DeclarationWithType * origdwt = strict_dynamic_cast< DeclarationWithType * > ( origDeclStmt->get_decl() );
assert( dwt->get_name() == origdwt->get_name() );
declMap[ origdwt ] = dwt;
} else assert( ! dynamic_cast< DeclarationWithType * > ( origDeclStmt->get_decl() ) );
} else assert( ! dynamic_cast< DeclStmt * > ( s ) );
}
if ( ! declMap.empty() ) {
DeclReplacer::replace( this, declMap );
}
}
CompoundStmt::~CompoundStmt() {
deleteAll( kids );
}
void CompoundStmt::print( std::ostream &os, Indenter indent ) const {
os << "CompoundStmt" << endl;
printAll( kids, os, indent+1 );
}
// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
|
ed4261d7177994235bfac860f6b703e5271c149a | abb28a62de39d806d5a63f5b94305069ee5950ca | /src/cppsim/general_quantum_operator.cpp | d8f06fd75cf5ee7862215bf85076b8e7fc0c9136 | [
"MIT"
] | permissive | qulacs/qulacs | 0d79074b83b8cc0faa3c31135178b08771be9987 | 413bcd3d02c01e2ad85a711abad252daadd5b832 | refs/heads/main | 2023-08-16T21:25:57.217422 | 2023-07-31T01:53:48 | 2023-07-31T01:53:48 | 151,675,481 | 349 | 121 | MIT | 2023-09-14T01:53:34 | 2018-10-05T05:39:51 | C++ | UTF-8 | C++ | false | false | 36,921 | cpp | general_quantum_operator.cpp | #include "general_quantum_operator.hpp"
#include <Eigen/Dense>
#include <csim/stat_ops.hpp>
#include <csim/update_ops.hpp>
#include <csim/update_ops_dm.hpp>
#include <csim/utility.hpp>
#include <cstring>
#include <fstream>
#include <numeric>
#include <unsupported/Eigen/KroneckerProduct>
#include "exception.hpp"
#include "gate_factory.hpp"
#include "pauli_operator.hpp"
#include "state.hpp"
#include "type.hpp"
#include "utility.hpp"
#ifdef _USE_GPU
#include <gpusim/update_ops_cuda.h>
#endif
GeneralQuantumOperator::GeneralQuantumOperator(const UINT qubit_count)
: _qubit_count(qubit_count), _is_hermitian(true) {}
GeneralQuantumOperator::~GeneralQuantumOperator() {
for (auto& term : this->_operator_list) {
delete term;
}
}
GeneralQuantumOperator::GeneralQuantumOperator(
const GeneralQuantumOperator& obj)
: _qubit_count(obj._qubit_count), _is_hermitian(obj._is_hermitian) {
for (auto& pauli : obj._operator_list) {
this->add_operator_copy(pauli);
}
}
void GeneralQuantumOperator::add_operator(const PauliOperator* mpt) {
GeneralQuantumOperator::add_operator_copy(mpt);
}
void GeneralQuantumOperator::add_operator_copy(const PauliOperator* mpt) {
PauliOperator* _mpt = mpt->copy();
GeneralQuantumOperator::add_operator_move(_mpt);
}
void GeneralQuantumOperator::add_operator_move(PauliOperator* mpt) {
if (!check_Pauli_operator(this, mpt)) {
throw QubitIndexOutOfRangeException(
"Error: GeneralQuantumOperator::add_operator(const "
"PauliOperator*): pauli_operator applies target qubit of "
"which the index is larger than qubit_count");
}
if (this->_is_hermitian && std::abs(mpt->get_coef().imag()) > 0) {
this->_is_hermitian = false;
}
this->_operator_list.push_back(mpt);
}
void GeneralQuantumOperator::add_operator(
CPPCTYPE coef, std::string pauli_string) {
PauliOperator* _mpt = new PauliOperator(pauli_string, coef);
if (!check_Pauli_operator(this, _mpt)) {
throw QubitIndexOutOfRangeException(
"Error: "
"GeneralQuantumOperator::add_operator(double,std::string):"
" pauli_operator applies target qubit of which the index "
"is larger than qubit_count");
}
if (this->_is_hermitian && std::abs(coef.imag()) > 0) {
this->_is_hermitian = false;
}
this->add_operator_move(_mpt);
}
void GeneralQuantumOperator::add_operator(
const std::vector<UINT>& target_qubit_index_list,
const std::vector<UINT>& target_qubit_pauli_list, CPPCTYPE coef = 1.) {
PauliOperator* _mpt = new PauliOperator(
target_qubit_index_list, target_qubit_pauli_list, coef);
if (!check_Pauli_operator(this, _mpt)) {
throw QubitIndexOutOfRangeException(
"Error: "
"GeneralQuantumOperator::add_operator(double,std::string):"
" pauli_operator applies target qubit of which the index "
"is larger than qubit_count");
}
if (this->_is_hermitian && std::abs(coef.imag()) > 0) {
this->_is_hermitian = false;
}
this->add_operator(_mpt);
delete _mpt;
}
CPPCTYPE GeneralQuantumOperator::get_expectation_value(
const QuantumStateBase* state) const {
if (this->_qubit_count > state->qubit_count) {
throw InvalidQubitCountException(
"Error: GeneralQuantumOperator::get_expectation_value(const "
"QuantumStateBase*): invalid qubit count");
}
const size_t n_terms = this->_operator_list.size();
std::string device = state->get_device_name();
if (device == "gpu" || device == "multi-cpu") {
CPPCTYPE sum = 0;
for (UINT i = 0; i < n_terms; ++i) {
sum += _operator_list[i]->get_expectation_value(state);
}
return sum;
}
double sum_real = 0.;
double sum_imag = 0.;
CPPCTYPE tmp(0., 0.);
#ifdef _OPENMP
OMPutil::get_inst().set_qulacs_num_threads(n_terms, 0);
#pragma omp parallel for reduction(+ : sum_real, sum_imag) private(tmp)
#endif
for (int i = 0; i < (int)n_terms;
++i) { // this variable (i) has to be signed integer because of OpenMP
// of Windows compiler.
tmp = _operator_list[i]->get_expectation_value_single_thread(state);
sum_real += tmp.real();
sum_imag += tmp.imag();
}
#ifdef _OPENMP
OMPutil::get_inst().reset_qulacs_num_threads();
#endif
return CPPCTYPE(sum_real, sum_imag);
}
CPPCTYPE GeneralQuantumOperator::get_expectation_value_single_thread(
const QuantumStateBase* state) const {
if (this->_qubit_count > state->qubit_count) {
std::cerr
<< "Error: GeneralQuantumOperator::get_expectation_value(const "
"QuantumStateBase*): invalid qubit count"
<< std::endl;
return 0.;
}
auto sum = std::accumulate(this->_operator_list.cbegin(),
this->_operator_list.cend(), (CPPCTYPE)0.0,
[&](CPPCTYPE acc, PauliOperator* pauli) {
return acc + pauli->get_expectation_value_single_thread(state);
});
return sum;
}
CPPCTYPE GeneralQuantumOperator::get_transition_amplitude(
const QuantumStateBase* state_bra,
const QuantumStateBase* state_ket) const {
if (this->_qubit_count > state_bra->qubit_count ||
state_bra->qubit_count != state_ket->qubit_count) {
throw InvalidQubitCountException(
"Error: GeneralQuantumOperator::get_transition_amplitude(const "
"QuantumStateBase*, const QuantumStateBase*): invalid qubit "
"count");
}
auto sum = std::accumulate(this->_operator_list.cbegin(),
this->_operator_list.cend(), (CPPCTYPE)0.0,
[&](CPPCTYPE acc, PauliOperator* pauli) {
return acc + pauli->get_transition_amplitude(state_bra, state_ket);
});
return sum;
}
void GeneralQuantumOperator::add_random_operator(const UINT operator_count) {
const auto qubit_count = this->get_qubit_count();
for (UINT operator_index = 0; operator_index < operator_count;
operator_index++) {
auto target_qubit_index_list = std::vector<UINT>(qubit_count, 0);
auto target_qubit_pauli_list = std::vector<UINT>(qubit_count, 0);
for (UINT qubit_index = 0; qubit_index < qubit_count; qubit_index++) {
const UINT pauli_id = random.int32() % 4;
target_qubit_index_list.at(qubit_index) = qubit_index;
target_qubit_pauli_list.at(qubit_index) = pauli_id;
}
// -1.0 <= coef <= 1.0
const CPPCTYPE coef = random.uniform() * 2 - 1.0;
auto pauli_operator = PauliOperator(
target_qubit_index_list, target_qubit_pauli_list, coef);
this->add_operator(&pauli_operator);
}
}
void GeneralQuantumOperator::add_random_operator(
const UINT operator_count, UINT seed) {
random.set_seed(seed);
add_random_operator(operator_count);
}
CPPCTYPE
GeneralQuantumOperator::solve_ground_state_eigenvalue_by_arnoldi_method(
QuantumStateBase* state, const UINT iter_count, const CPPCTYPE mu) const {
if (this->get_term_count() == 0) {
throw InvalidQuantumOperatorException(
"Error: "
"GeneralQuantumOperator::solve_ground_state_eigenvalue_by_"
"arnoldi_method("
"QuantumStateBase * state, const UINT iter_count, const "
"CPPCTYPE mu): At least one PauliOperator is required.");
}
// Implemented based on
// https://files.transtutors.com/cdn/uploadassignments/472339_1_-numerical-linear-aljebra.pdf
const auto qubit_count = this->get_qubit_count();
auto present_state = QuantumState(qubit_count);
auto tmp_state = QuantumState(qubit_count);
auto multiplied_state = QuantumState(qubit_count);
auto mu_timed_state = QuantumState(qubit_count);
// Vectors composing Krylov subspace.
std::vector<QuantumStateBase*> state_list;
state_list.reserve(iter_count + 1);
state->normalize(state->get_squared_norm());
state_list.push_back(state->copy());
CPPCTYPE mu_;
if (mu == 0.0) {
// mu is not changed from default value.
mu_ = this->calculate_default_mu();
} else {
mu_ = mu;
}
ComplexMatrix hessenberg_matrix =
ComplexMatrix::Zero(iter_count, iter_count);
for (UINT i = 0; i < iter_count; i++) {
mu_timed_state.load(state_list[i]);
mu_timed_state.multiply_coef(-mu_);
this->apply_to_state(&tmp_state, *state_list[i], &multiplied_state);
multiplied_state.add_state(&mu_timed_state);
for (UINT j = 0; j < i + 1; j++) {
const auto coef = state::inner_product(
static_cast<QuantumState*>(state_list[j]), &multiplied_state);
hessenberg_matrix(j, i) = coef;
tmp_state.load(state_list[j]);
tmp_state.multiply_coef(-coef);
multiplied_state.add_state(&tmp_state);
}
const auto norm = multiplied_state.get_squared_norm();
if (i != iter_count - 1) {
hessenberg_matrix(i + 1, i) = std::sqrt(norm);
}
multiplied_state.normalize(norm);
state_list.push_back(multiplied_state.copy());
}
Eigen::ComplexEigenSolver<ComplexMatrix> eigen_solver(hessenberg_matrix);
const auto eigenvalues = eigen_solver.eigenvalues();
const auto eigenvectors = eigen_solver.eigenvectors();
// Find ground state eigenvalue and eigenvector.
UINT minimum_eigenvalue_index = 0;
auto minimum_eigenvalue = eigenvalues[0];
for (UINT i = 0; i < eigenvalues.size(); i++) {
if (eigenvalues[i].real() < minimum_eigenvalue.real()) {
minimum_eigenvalue_index = i;
minimum_eigenvalue = eigenvalues[i];
}
}
// Compose ground state vector and store it to `state`.
present_state.set_zero_norm_state();
for (UINT i = 0; i < state_list.size() - 1; i++) {
tmp_state.load(state_list[i]);
tmp_state.multiply_coef(eigenvectors(i, minimum_eigenvalue_index));
present_state.add_state(&tmp_state);
}
state->load(&present_state);
// Free states allocated by `QuantumState::copy()`.
for (auto used_state : state_list) {
delete used_state;
}
return minimum_eigenvalue + mu_;
}
CPPCTYPE GeneralQuantumOperator::solve_ground_state_eigenvalue_by_power_method(
QuantumStateBase* state, const UINT iter_count, const CPPCTYPE mu) const {
if (this->get_term_count() == 0) {
throw InvalidQuantumOperatorException(
"Error: "
"GeneralQuantumOperator::solve_ground_state_eigenvalue_by_"
"power_method("
"QuantumStateBase * state, const UINT iter_count, const "
"CPPCTYPE mu): At least one PauliOperator is required.");
}
CPPCTYPE mu_;
if (mu == 0.0) {
// mu is not changed from default value.
mu_ = this->calculate_default_mu();
} else {
mu_ = mu;
}
// Stores a result of A|a>
auto multiplied_state = QuantumState(state->qubit_count);
// Stores a result of -\mu|a>
auto mu_timed_state = QuantumState(state->qubit_count);
auto work_state = QuantumState(state->qubit_count);
for (UINT i = 0; i < iter_count; i++) {
mu_timed_state.load(state);
mu_timed_state.multiply_coef(-mu_);
multiplied_state.set_zero_norm_state();
this->apply_to_state(&work_state, *state, &multiplied_state);
state->load(&multiplied_state);
state->add_state(&mu_timed_state);
state->normalize(state->get_squared_norm());
}
return this->get_expectation_value(state) + mu;
}
void GeneralQuantumOperator::apply_to_state(QuantumStateBase* work_state,
const QuantumStateBase& state_to_be_multiplied,
QuantumStateBase* dst_state) const {
if (state_to_be_multiplied.qubit_count != dst_state->qubit_count) {
throw InvalidQubitCountException(
"Qubit count of state_to_be_multiplied and dst_state must be the "
"same");
}
dst_state->set_zero_norm_state();
const auto term_count = this->get_term_count();
for (UINT i = 0; i < term_count; i++) {
work_state->load(&state_to_be_multiplied);
const auto term = this->get_term(i);
_apply_pauli_to_state(
term->get_pauli_id_list(), term->get_index_list(), work_state);
dst_state->add_state_with_coef(term->get_coef(), work_state);
}
}
void GeneralQuantumOperator::apply_to_state(
QuantumStateBase* state, QuantumStateBase* dst_state) const {
if (state->qubit_count != dst_state->qubit_count) {
throw InvalidQubitCountException(
"Qubit count of state_to_be_multiplied and dst_state must be the "
"same");
}
dst_state->set_zero_norm_state();
const auto term_count = this->get_term_count();
for (UINT i = 0; i < term_count; i++) {
const auto term = this->get_term(i);
_apply_pauli_to_state(
term->get_pauli_id_list(), term->get_index_list(), state);
dst_state->add_state_with_coef(term->get_coef(), state);
_apply_pauli_to_state(
term->get_pauli_id_list(), term->get_index_list(), state);
}
}
void GeneralQuantumOperator::apply_to_state_single_thread(
QuantumStateBase* state, QuantumStateBase* dst_state) const {
if (state->qubit_count != dst_state->qubit_count) {
throw InvalidQubitCountException(
"Qubit count of state_to_be_multiplied and dst_state must be the "
"same");
}
dst_state->set_zero_norm_state();
const auto term_count = this->get_term_count();
for (UINT i = 0; i < term_count; i++) {
const auto term = this->get_term(i);
_apply_pauli_to_state_single_thread(
term->get_pauli_id_list(), term->get_index_list(), state);
dst_state->add_state_with_coef_single_thread(term->get_coef(), state);
_apply_pauli_to_state_single_thread(
term->get_pauli_id_list(), term->get_index_list(), state);
}
}
void GeneralQuantumOperator::_apply_pauli_to_state(
std::vector<UINT> pauli_id_list, std::vector<UINT> target_index_list,
QuantumStateBase* state) const {
// this function is same as the gate::Pauli update quantum state
if (state->is_state_vector()) {
#ifdef _USE_GPU
if (state->get_device_name() == "gpu") {
multi_qubit_Pauli_gate_partial_list_host(target_index_list.data(),
pauli_id_list.data(), (UINT)target_index_list.size(),
state->data(), state->dim, state->get_cuda_stream(),
state->device_number);
// _update_func_gpu(this->_target_qubit_list[0].index(), _angle,
// state->data(), state->dim);
return;
}
#endif
multi_qubit_Pauli_gate_partial_list(target_index_list.data(),
pauli_id_list.data(), (UINT)target_index_list.size(),
state->data_c(), state->dim);
} else {
dm_multi_qubit_Pauli_gate_partial_list(target_index_list.data(),
pauli_id_list.data(), (UINT)target_index_list.size(),
state->data_c(), state->dim);
}
}
void GeneralQuantumOperator::_apply_pauli_to_state_single_thread(
std::vector<UINT> pauli_id_list, std::vector<UINT> target_index_list,
QuantumStateBase* state) const {
// this function is same as the gate::Pauli update quantum state
if (state->is_state_vector()) {
#ifdef _USE_GPU
if (state->get_device_name() == "gpu") {
// TODO: make it single thread for this function
multi_qubit_Pauli_gate_partial_list_host(target_index_list.data(),
pauli_id_list.data(), (UINT)target_index_list.size(),
state->data(), state->dim, state->get_cuda_stream(),
state->device_number);
// _update_func_gpu(this->_target_qubit_list[0].index(), _angle,
// state->data(), state->dim);
return;
}
#endif
multi_qubit_Pauli_gate_partial_list_single_thread(
target_index_list.data(), pauli_id_list.data(),
(UINT)target_index_list.size(), state->data_c(), state->dim);
} else {
throw std::runtime_error(
"apply single thread is not implemented for density matrix");
}
}
CPPCTYPE GeneralQuantumOperator::calculate_default_mu() const {
double mu = 0.0;
const auto term_count = this->get_term_count();
for (UINT i = 0; i < term_count; i++) {
const auto term = this->get_term(i);
mu += std::abs(term->get_coef().real());
}
return static_cast<CPPCTYPE>(mu);
}
GeneralQuantumOperator* GeneralQuantumOperator::copy() const {
auto quantum_operator = new GeneralQuantumOperator(_qubit_count);
for (auto pauli : this->_operator_list) {
quantum_operator->add_operator_copy(pauli);
}
return quantum_operator;
}
SparseComplexMatrixRowMajor _tensor_product(
const std::vector<SparseComplexMatrixRowMajor>& _obs) {
std::vector<SparseComplexMatrixRowMajor> obs(_obs);
int sz = obs.size();
while (sz != 1) {
if (sz % 2 == 0) {
for (int i = 0; i < sz; i += 2) {
obs[i >> 1] =
Eigen::kroneckerProduct(obs[i], obs[i + 1]).eval();
}
sz >>= 1;
} else {
obs[sz - 2] =
Eigen::kroneckerProduct(obs[sz - 2], obs[sz - 1]).eval();
sz--;
}
}
return obs[0];
}
SparseComplexMatrixRowMajor GeneralQuantumOperator::get_matrix() const {
SparseComplexMatrixRowMajor sigma_x(2, 2), sigma_y(2, 2), sigma_z(2, 2),
sigma_i(2, 2);
sigma_x.insert(0, 1) = 1.0, sigma_x.insert(1, 0) = 1.0;
sigma_y.insert(0, 1) = -1.0i, sigma_y.insert(1, 0) = 1.0i;
sigma_z.insert(0, 0) = 1.0, sigma_z.insert(1, 1) = -1.0;
sigma_i.insert(0, 0) = 1.0, sigma_i.insert(1, 1) = 1.0;
std::vector<SparseComplexMatrixRowMajor> pauli_matrix_list = {
sigma_i, sigma_x, sigma_y, sigma_z};
int n_terms = this->get_term_count();
int n_qubits = this->get_qubit_count();
SparseComplexMatrixRowMajor hamiltonian_matrix(
1 << n_qubits, 1 << n_qubits);
hamiltonian_matrix.setZero();
#ifdef _OPENMP
#pragma omp declare reduction(+ : SparseComplexMatrixRowMajor : omp_out += \
omp_in) initializer(omp_priv = omp_orig)
#pragma omp parallel for reduction(+ : hamiltonian_matrix)
#endif
for (int i = 0; i < n_terms; i++) {
auto const pauli = this->get_term(i);
auto const pauli_id_list = pauli->get_pauli_id_list();
auto const pauli_target_list = pauli->get_index_list();
std::vector<SparseComplexMatrixRowMajor>
init_hamiltonian_pauli_matrix_list(
n_qubits, sigma_i); // initialize matrix_list I
for (int j = 0; j < (int)pauli_target_list.size(); j++) {
init_hamiltonian_pauli_matrix_list[pauli_target_list[j]] =
pauli_matrix_list[pauli_id_list[j]]; // ex) [X,X,I,I]
}
std::reverse(init_hamiltonian_pauli_matrix_list.begin(),
init_hamiltonian_pauli_matrix_list.end());
hamiltonian_matrix +=
pauli->get_coef() *
_tensor_product(init_hamiltonian_pauli_matrix_list);
}
hamiltonian_matrix.prune(CPPCTYPE(0, 0));
return hamiltonian_matrix;
}
GeneralQuantumOperator* GeneralQuantumOperator::get_dagger() const {
auto quantum_operator = new GeneralQuantumOperator(_qubit_count);
for (auto pauli : this->_operator_list) {
quantum_operator->add_operator(
std::conj(pauli->get_coef()), pauli->get_pauli_string());
}
return quantum_operator;
}
boost::property_tree::ptree GeneralQuantumOperator::to_ptree() const {
boost::property_tree::ptree pt;
pt.put("name", "GeneralQuantumOperator");
pt.put("qubit_count", _qubit_count);
std::vector<boost::property_tree::ptree> operator_list_pt;
std::transform(_operator_list.begin(), _operator_list.end(),
std::back_inserter(operator_list_pt),
[](const PauliOperator* po) { return po->to_ptree(); });
pt.put_child("operator_list", ptree::to_ptree(operator_list_pt));
return pt;
}
GeneralQuantumOperator GeneralQuantumOperator::operator+(
const GeneralQuantumOperator& target) const {
return GeneralQuantumOperator(*this) += target;
}
GeneralQuantumOperator GeneralQuantumOperator::operator+(
const PauliOperator& target) const {
return GeneralQuantumOperator(*this) += target;
}
GeneralQuantumOperator& GeneralQuantumOperator::operator+=(
const GeneralQuantumOperator& target) {
ITYPE i, j;
auto terms = target.get_terms();
// #pragma omp parallel for
for (i = 0; i < _operator_list.size(); i++) {
auto pauli_operator = _operator_list[i];
for (j = 0; j < terms.size(); j++) {
auto target_operator = terms[j];
auto pauli_x = pauli_operator->get_x_bits();
auto pauli_z = pauli_operator->get_z_bits();
auto target_x = target_operator->get_x_bits();
auto target_z = target_operator->get_z_bits();
if (pauli_x.size() != target_x.size()) {
UINT max_size = std::max(pauli_x.size(), target_x.size());
pauli_x.resize(max_size);
pauli_z.resize(max_size);
target_x.resize(max_size);
target_z.resize(max_size);
}
if (pauli_x == target_x && pauli_z == target_z) {
_operator_list[i]->change_coef(_operator_list[i]->get_coef() +
target_operator->get_coef());
}
}
}
for (j = 0; j < terms.size(); j++) {
auto target_operator = terms[j];
bool flag = true;
for (i = 0; i < _operator_list.size(); i++) {
auto pauli_operator = _operator_list[i];
auto pauli_x = pauli_operator->get_x_bits();
auto pauli_z = pauli_operator->get_z_bits();
auto target_x = target_operator->get_x_bits();
auto target_z = target_operator->get_z_bits();
if (pauli_x.size() != target_x.size()) {
UINT max_size = std::max(pauli_x.size(), target_x.size());
pauli_x.resize(max_size);
pauli_z.resize(max_size);
target_x.resize(max_size);
target_z.resize(max_size);
}
if (pauli_x == target_x && pauli_z == target_z) {
flag = false;
}
}
if (flag) {
this->add_operator_copy(target_operator);
}
}
return *this;
}
GeneralQuantumOperator& GeneralQuantumOperator::operator+=(
const PauliOperator& target) {
bool flag = true;
ITYPE i;
// #pragma omp parallel for
for (i = 0; i < _operator_list.size(); i++) {
auto pauli_operator = _operator_list[i];
auto pauli_x = pauli_operator->get_x_bits();
auto pauli_z = pauli_operator->get_z_bits();
auto target_x = target.get_x_bits();
auto target_z = target.get_z_bits();
if (pauli_x.size() != target_x.size()) {
UINT max_size = std::max(pauli_x.size(), target_x.size());
pauli_x.resize(max_size);
pauli_z.resize(max_size);
target_x.resize(max_size);
target_z.resize(max_size);
}
if (pauli_x == target_x && pauli_z == target_z) {
_operator_list[i]->change_coef(
_operator_list[i]->get_coef() + target.get_coef());
flag = false;
}
}
if (flag) {
this->add_operator_copy(&target);
}
return *this;
}
GeneralQuantumOperator GeneralQuantumOperator::operator-(
const GeneralQuantumOperator& target) const {
return GeneralQuantumOperator(*this) -= target;
}
GeneralQuantumOperator GeneralQuantumOperator::operator-(
const PauliOperator& target) const {
return GeneralQuantumOperator(*this) -= target;
}
GeneralQuantumOperator& GeneralQuantumOperator::operator-=(
const GeneralQuantumOperator& target) {
ITYPE i, j;
auto terms = target.get_terms();
// #pragma omp parallel for
for (i = 0; i < _operator_list.size(); i++) {
auto pauli_operator = _operator_list[i];
for (j = 0; j < terms.size(); j++) {
auto target_operator = terms[j];
auto pauli_x = pauli_operator->get_x_bits();
auto pauli_z = pauli_operator->get_z_bits();
auto target_x = target_operator->get_x_bits();
auto target_z = target_operator->get_z_bits();
if (pauli_x.size() != target_x.size()) {
UINT max_size = std::max(pauli_x.size(), target_x.size());
pauli_x.resize(max_size);
pauli_z.resize(max_size);
target_x.resize(max_size);
target_z.resize(max_size);
}
if (pauli_x == target_x && pauli_z == target_z) {
_operator_list[i]->change_coef(_operator_list[i]->get_coef() -
target_operator->get_coef());
}
}
}
for (j = 0; j < terms.size(); j++) {
auto target_operator = terms[j];
bool flag = true;
for (i = 0; i < _operator_list.size(); i++) {
auto pauli_operator = _operator_list[i];
auto pauli_x = pauli_operator->get_x_bits();
auto pauli_z = pauli_operator->get_z_bits();
auto target_x = target_operator->get_x_bits();
auto target_z = target_operator->get_z_bits();
if (pauli_x.size() != target_x.size()) {
UINT max_size = std::max(pauli_x.size(), target_x.size());
pauli_x.resize(max_size);
pauli_z.resize(max_size);
target_x.resize(max_size);
target_z.resize(max_size);
}
if (pauli_x == target_x && pauli_z == target_z) {
flag = false;
}
}
if (flag) {
auto copy = target_operator->copy();
copy->change_coef(-copy->get_coef());
this->add_operator_move(copy);
}
}
return *this;
}
GeneralQuantumOperator& GeneralQuantumOperator::operator-=(
const PauliOperator& target) {
bool flag = true;
ITYPE i;
for (i = 0; i < _operator_list.size(); i++) {
auto pauli_operator = _operator_list[i];
auto pauli_x = pauli_operator->get_x_bits();
auto pauli_z = pauli_operator->get_z_bits();
auto target_x = target.get_x_bits();
auto target_z = target.get_z_bits();
if (pauli_x.size() != target_x.size()) {
UINT max_size = std::max(pauli_x.size(), target_x.size());
pauli_x.resize(max_size);
pauli_z.resize(max_size);
target_x.resize(max_size);
target_z.resize(max_size);
}
if (pauli_x == target_x && pauli_z == target_z) {
_operator_list[i]->change_coef(
_operator_list[i]->get_coef() - target.get_coef());
flag = false;
}
}
if (flag) {
auto copy = target.copy();
copy->change_coef(-copy->get_coef());
this->add_operator_move(copy);
}
return *this;
}
GeneralQuantumOperator GeneralQuantumOperator::operator*(
const GeneralQuantumOperator& target) const {
return GeneralQuantumOperator(*this) *= target;
}
GeneralQuantumOperator GeneralQuantumOperator::operator*(
const PauliOperator& target) const {
return GeneralQuantumOperator(*this) *= target;
}
GeneralQuantumOperator GeneralQuantumOperator::operator*(
CPPCTYPE target) const {
return GeneralQuantumOperator(*this) *= target;
}
GeneralQuantumOperator& GeneralQuantumOperator::operator*=(
const GeneralQuantumOperator& target) {
auto this_copy = this->copy();
auto terms = this_copy->get_terms();
auto target_terms = target.get_terms();
// initialize (*this) operator to empty.
for (auto& term : _operator_list) {
delete term;
}
_operator_list.clear();
ITYPE i, j;
// #pragma omp parallel for
for (i = 0; i < terms.size(); i++) {
auto pauli_operator = terms[i];
for (j = 0; j < target_terms.size(); j++) {
auto target_operator = target_terms[j];
PauliOperator product = (*pauli_operator) * (*target_operator);
*this += product;
}
}
delete this_copy;
return *this;
}
GeneralQuantumOperator& GeneralQuantumOperator::operator*=(
const PauliOperator& target) {
auto this_copy = this->copy();
ITYPE i;
auto terms = this_copy->get_terms();
// initialize (*this) operator to empty.
for (auto& term : _operator_list) {
delete term;
}
_operator_list.clear();
// #pragma omp parallel for
for (i = 0; i < terms.size(); i++) {
auto pauli_operator = terms[i];
PauliOperator product = (*pauli_operator) * (target);
*this += product;
}
delete this_copy;
return *this;
}
GeneralQuantumOperator& GeneralQuantumOperator::operator*=(CPPCTYPE target) {
ITYPE i;
// #pragma omp parallel for
for (i = 0; i < _operator_list.size(); i++) {
*_operator_list[i] *= target;
}
return *this;
}
namespace quantum_operator {
GeneralQuantumOperator* create_general_quantum_operator_from_openfermion_file(
std::string file_path) {
UINT qubit_count = 0;
std::vector<CPPCTYPE> coefs;
std::vector<std::string> ops;
// loading lines and check qubit_count
std::string str_buf;
std::vector<std::string> index_list;
std::ifstream ifs;
std::string line;
ifs.open(file_path);
while (getline(ifs, line)) {
std::tuple<double, double, std::string> parsed_items =
parse_openfermion_line(line);
const auto coef_real = std::get<0>(parsed_items);
const auto coef_imag = std::get<1>(parsed_items);
str_buf = std::get<2>(parsed_items);
CPPCTYPE coef(coef_real, coef_imag);
coefs.push_back(coef);
ops.push_back(str_buf);
index_list = split(str_buf, "IXYZ ");
for (UINT i = 0; i < index_list.size(); ++i) {
UINT n = std::stoi(index_list[i]) + 1;
if (qubit_count < n) qubit_count = n;
}
}
if (!ifs.eof()) {
throw InvalidOpenfermionFormatException("ERROR: Invalid format");
}
ifs.close();
GeneralQuantumOperator* general_quantum_operator =
new GeneralQuantumOperator(qubit_count);
for (UINT i = 0; i < ops.size(); ++i) {
general_quantum_operator->add_operator(coefs[i], ops[i].c_str());
}
return general_quantum_operator;
}
GeneralQuantumOperator* create_general_quantum_operator_from_openfermion_text(
std::string text) {
UINT qubit_count = 0;
std::vector<CPPCTYPE> coefs;
std::vector<std::string> ops;
std::string str_buf;
std::vector<std::string> index_list;
std::vector<std::string> lines;
lines = split(text, "\n");
for (std::string line : lines) {
std::tuple<double, double, std::string> parsed_items =
parse_openfermion_line(line);
const auto coef_real = std::get<0>(parsed_items);
const auto coef_imag = std::get<1>(parsed_items);
str_buf = std::get<2>(parsed_items);
CPPCTYPE coef(coef_real, coef_imag);
coefs.push_back(coef);
ops.push_back(str_buf);
index_list = split(str_buf, "IXYZ ");
for (UINT i = 0; i < index_list.size(); ++i) {
UINT n = std::stoi(index_list[i]) + 1;
if (qubit_count < n) qubit_count = n;
}
}
GeneralQuantumOperator* general_quantum_operator =
new GeneralQuantumOperator(qubit_count);
for (UINT i = 0; i < ops.size(); ++i) {
general_quantum_operator->add_operator(coefs[i], ops[i].c_str());
}
return general_quantum_operator;
}
std::pair<GeneralQuantumOperator*, GeneralQuantumOperator*>
create_split_general_quantum_operator(std::string file_path) {
UINT qubit_count = 0;
std::vector<CPPCTYPE> coefs;
std::vector<std::string> ops;
std::ifstream ifs;
ifs.open(file_path);
if (!ifs) {
throw IOException("ERROR: Cannot open file");
}
// loading lines and check qubit_count
std::string str_buf;
std::vector<std::string> index_list;
std::string line;
while (getline(ifs, line)) {
std::tuple<double, double, std::string> parsed_items =
parse_openfermion_line(line);
const auto coef_real = std::get<0>(parsed_items);
const auto coef_imag = std::get<1>(parsed_items);
str_buf = std::get<2>(parsed_items);
if (str_buf == (std::string)NULL) {
continue;
}
CPPCTYPE coef(coef_real, coef_imag);
coefs.push_back(coef);
ops.push_back(str_buf);
index_list = split(str_buf, "IXYZ ");
for (UINT i = 0; i < index_list.size(); ++i) {
UINT n = std::stoi(index_list[i]) + 1;
if (qubit_count < n) qubit_count = n;
}
}
if (!ifs.eof()) {
throw InvalidOpenfermionFormatException("ERROR: Invalid format");
}
ifs.close();
GeneralQuantumOperator* general_quantum_operator_diag =
new GeneralQuantumOperator(qubit_count);
GeneralQuantumOperator* general_quantum_operator_non_diag =
new GeneralQuantumOperator(qubit_count);
for (UINT i = 0; i < ops.size(); ++i) {
if (ops[i].find("X") != std::string::npos ||
ops[i].find("Y") != std::string::npos) {
general_quantum_operator_non_diag->add_operator(
coefs[i], ops[i].c_str());
} else {
general_quantum_operator_diag->add_operator(
coefs[i], ops[i].c_str());
}
}
return std::make_pair(
general_quantum_operator_diag, general_quantum_operator_non_diag);
}
SinglePauliOperator* single_pauli_operator_from_ptree(
const boost::property_tree::ptree& pt) {
std::string name = pt.get<std::string>("name");
if (name != "SinglePauliOperator") {
throw UnknownPTreePropertyValueException(
"unknown value for property \"name\":" + name);
}
UINT index = pt.get<UINT>("index");
UINT pauli_id = pt.get<UINT>("pauli_id");
return new SinglePauliOperator(index, pauli_id);
}
PauliOperator* pauli_operator_from_ptree(
const boost::property_tree::ptree& pt) {
std::string name = pt.get<std::string>("name");
if (name != "PauliOperator") {
throw UnknownPTreePropertyValueException(
"unknown value for property \"name\":" + name);
}
std::vector<boost::property_tree::ptree> pauli_list_pt =
ptree::ptree_array_from_ptree(pt.get_child("pauli_list"));
CPPCTYPE coef = ptree::complex_from_ptree(pt.get_child("coef"));
PauliOperator* po = new PauliOperator(coef);
for (const boost::property_tree::ptree& pauli_pt : pauli_list_pt) {
SinglePauliOperator* spo = single_pauli_operator_from_ptree(pauli_pt);
po->add_single_Pauli(spo->index(), spo->pauli_id());
free(spo);
}
return po;
}
GeneralQuantumOperator* from_ptree(const boost::property_tree::ptree& pt) {
std::string name = pt.get<std::string>("name");
if (name != "GeneralQuantumOperator") {
throw UnknownPTreePropertyValueException(
"unknown value for property \"name\":" + name);
}
UINT qubit_count = pt.get<UINT>("qubit_count");
std::vector<boost::property_tree::ptree> operator_list_pt =
ptree::ptree_array_from_ptree(pt.get_child("operator_list"));
GeneralQuantumOperator* gqo = new GeneralQuantumOperator(qubit_count);
for (const boost::property_tree::ptree& operator_pt : operator_list_pt) {
gqo->add_operator_move(pauli_operator_from_ptree(operator_pt));
}
return gqo;
}
} // namespace quantum_operator
bool check_Pauli_operator(const GeneralQuantumOperator* quantum_operator,
const PauliOperator* pauli_operator) {
auto vec = pauli_operator->get_index_list();
UINT val = 0;
if (vec.size() > 0) {
val = std::max(val, *std::max_element(vec.begin(), vec.end()));
}
return val < (quantum_operator->get_qubit_count());
}
std::string GeneralQuantumOperator::to_string() const {
std::stringstream os;
auto term_count = this->get_term_count();
for (UINT index = 0; index < term_count; index++) {
os << this->get_term(index)->get_coef() << " ";
os << this->get_term(index)->get_pauli_string();
if (index != term_count - 1) {
os << " + ";
}
}
return os.str();
}
|
c4ca2494aab292fe44a67c8fb4b1d9b766c1fb8b | 32068408ebe4502d04045f6b70b1f540c0e153e2 | /src/Commands/Auto/CheckHeading.h | 89cad58b4e04c816af87a5b136a77d117e7303dd | [] | no_license | ZacharyCody/FRC-2018 | 2d90f83477e6bb92a3c685bcdbab86cf6810e23d | f551694a9f23edf3019da3af74e73272259f1356 | refs/heads/master | 2022-02-14T12:35:31.066235 | 2018-11-15T04:34:30 | 2018-11-15T04:34:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | h | CheckHeading.h | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include <Commands/Command.h>
#include "CommandBase.h"
class CheckHeading : public CommandBase {
public:
CheckHeading(double heading, double tolerance, double timeout);
void Initialize();
void Execute();
bool IsFinished();
void End();
void Interrupted();
private:
bool m_isFinished = false;
double m_timeOut = 0;
double m_tolerance = 0;
double m_heading = 0;
};
|
db442792df738e71fb0147d2c4cc2419a60f8e7d | 8cd27157aa08040bbf592a4a5bd52f1d6aef9219 | /PT Project Phase_2/Actions/AddComment.h | 210bc4b2d35d4ece18aec7dfc5cef5c3c31a1892 | [] | no_license | ayaibrahim44/testing2 | aa61e659279f93b5223a82a1a3d75f9d2b0d18fc | ee3d2110e20a856079eac59047e872b30b6e9fb1 | refs/heads/master | 2020-05-26T11:40:53.835776 | 2017-03-14T20:59:13 | 2017-03-14T20:59:13 | 84,996,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | h | AddComment.h | #include "..\Statements\SmplAssign.h"
#include"Action.h"
class Comment :public Action
{
string comment;
Statement*SelStat;
public:
Comment(ApplicationManager *pAppManager);
virtual void ReadActionParameters();
virtual void Execute();
}; |
05cbed514289a8fdf4ddf4df6a8cea66895f9b73 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2652486_1/C++/marcoskwkm/c.cpp | bcb12c63d53e0b58aa98270b406f4e392e5e8478 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,324 | cpp | c.cpp | #include <cmath>
#include <ctime>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <functional>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <iomanip>
#include <sstream>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <list>
#include <set>
#include <map>
using namespace std;
#define debug(args...) fprintf(stderr,args)
#define foreach(_it,_v) for(typeof(_v.begin()) _it = _v.begin(); _it != _v.end(); ++_it)
typedef long long lint;
typedef pair<int,int> pii;
typedef pair<lint,lint> pll;
const int INF = 0x3f3f3f3f;
const lint LINF = 0x3f3f3f3f3f3f3f3fll;
const int MAXK = 10, MAXN = 10;
int r,n=12,m=8,k=12;
lint v[MAXK];
int p[] = {2,3,4,5,6,7,8};
int qntd[7];
lint fact[15];
map< lint,set<string> > cj;
map< lint,map<string,lint> > cnt;
map< lint,lint > tot;
void go(int i,int q) {
if(i == 6) {
qntd[6] = q;
string s = "";
vector<int> vet;
for(int a=0;a<qntd[0];++a) {
s += '0'+p[0];
vet.push_back(p[0]);
}
for(int a=0;a<qntd[1];++a) {
s += '0'+p[1];
vet.push_back(p[1]);
}
for(int a=0;a<qntd[2];++a) {
s += '0'+p[2];
vet.push_back(p[2]);
}
for(int a=0;a<qntd[3];++a) {
s += '0'+p[3];
vet.push_back(p[3]);
}
for(int a=0;a<qntd[4];++a) {
s += '0'+p[4];
vet.push_back(p[4]);
}
for(int a=0;a<qntd[5];++a) {
s += '0'+p[5];
vet.push_back(p[5]);
}
for(int a=0;a<qntd[6];++a) {
s += '0'+p[6];
vet.push_back(p[6]);
}
lint add = fact[12]/(fact[qntd[0]]*fact[qntd[1]]*fact[qntd[2]]*fact[qntd[3]]*fact[qntd[4]]*fact[qntd[5]]*fact[qntd[6]]);
for(int mask=0;mask<(1<<n);++mask) {
lint prod = 1;
for(int a=0;a<n;++a) if(mask&(1<<a)) prod *= vet[a];
cj[prod].insert(s);
cnt[prod][s] += add;
tot[prod] += add;
}
return;
}
for(int a=0;a<=q;++a) {
qntd[i] = a;
go(i+1,q-a);
}
}
void generate_sets() { go(0,n); }
int main() {
fact[0] = 1;
for(int a=1;a<=12;++a) fact[a] = a*fact[a-1];
generate_sets();
scanf("%*d");
printf("Case #1:\n");
scanf("%d%*d%*d%*d",&r);
for(int a=0;a<r;++a) {
lint high = LINF;
int ind = 0;
for(int b=0;b<k;++b) {
scanf("%lld",&v[b]);
if(cj[v[b]].size() < high) {
high = cj[v[b]].size();
ind = b;
}
}
swap(v[0],v[ind]);
double best = 0;
string ans;
for(string s: cj[v[0]]) {
double prob = double(cnt[v[0]][s])/tot[v[0]];
bool ok = 1;
for(int b=1;b<k;++b) {
if(cj[v[b]].find(s) == cj[v[b]].end()) {
ok = 0;
break;
}
else prob *= double(cnt[v[b]][s])/tot[v[b]];
}
if(ok && prob > best) {
best = prob;
ans = s;
}
}
printf("%s\n",ans.c_str());
}
return 0;
}
|
83a9631f027ff45bd6b92b5f431f217d079f4c4f | 3819be3b7e24fae0bdaf644ad5971eaa4d9282b3 | /Coursera/week3/Realize.cpp | 0dbc59d22ca3c7fcfd0dd21fbbde9da22dc7c95b | [] | no_license | somerandomsymbols/Cubics_Labkees | b4b6daf51a13a43c25148f94bea78dd048b03414 | c86fadc86b13c50f1f70722bcccbb6c757ea9533 | refs/heads/master | 2022-04-26T21:08:06.006266 | 2020-04-28T14:39:13 | 2020-04-28T14:39:13 | 254,868,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | cpp | Realize.cpp | #include <bits/stdc++.h>
#include "sum_reverse_sort.h"
using namespace std;
int Sum(int x, int y)
{
return x + y;
}
string Reverse(string s)
{
string x = "";
for (int i = s.length() - 1; i >= 0; --i)
x += s.substr(i,1);
return x;
}
void Sort(vector<int>& nums)
{
sort(nums.begin(), nums.end());
}
|
935ff3cdcd0f5aa44147811efde96dd99af8ef81 | 2cb3829bca2b0b20c27699b636d52e170bcafe6b | /add.cpp | 00ea6e4307a53b9b918ff0bd544b9c6a423b456e | [] | no_license | dennisledford/gradebook | 8e25ab9197cb1793fd73554d3ac5ee691e91e6c4 | 7e7aea25a21e63319e72b949072a13e99f2d5004 | refs/heads/master | 2020-07-04T21:02:23.261124 | 2016-11-18T15:38:40 | 2016-11-18T15:38:40 | 74,142,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | add.cpp | #include"header.h"
void addstudent(SortedType& studentlist)
{
student person;
bool found;
person.getinfo();
studentlist.RetrieveItem(person, found);
if(!found)
{
studentlist.InsertItem(person);
}
else
cout<<"Student already entered"<<endl;
}
|
b2e9b2062684b87e2758f48a120016c1fcfead76 | 82646fb7fe40db6dcdf238548128f7b633de94c0 | /workspace/算法/1142.cpp | cc49045ff278d0ac0026dd47ead5e41d279914cd | [] | no_license | jtahstu/iCode | a7873618fe98e502c1e0e2fd0769d71b3adac756 | 42d0899945dbc1bab98092d21a1d946137a1795e | refs/heads/master | 2021-01-10T22:55:47.677615 | 2016-10-23T12:42:38 | 2016-10-23T12:42:38 | 70,316,051 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 777 | cpp | 1142.cpp | #include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
while(n--)
{
string a,b,c[27],d[27];
cin>>a>>b;
sort(a.begin(),a.end());
sort(b.begin(),b.end());
c[0]=a[0],d[0]=b[0];
int count1=1,count2=1;
for(int i=1; i<a.length(); i++)
if(a[i]!=a[i-1])
c[count1++]=a[i];
for(int i=1; i<b.length(); i++)
if(b[i]!=b[i-1])
d[count2++]=b[i];
if(count1!=count2)cout<<"No"<<endl;
else
{
bool flag=true;
for(int i=0;i<count1;i++)
if(c[i]!=d[i])
{
flag=false;
break;
}
if(flag)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}
|
7b22f9f0b290c4b2e6768ee84267014c03f290a6 | 18001b0aaf2b5365d0002b36bf96def23b21a4e9 | /MyLIP/algorithm.cpp | e5d0d571725771632796e614907cc5a54f0f8cd2 | [] | no_license | waterdr0p/BigInt | 7590903f35422711412c37c370dbd7d74097115f | 8ae682f3690179bd115ea80c0cf183b23d5fc4fa | refs/heads/master | 2021-01-15T16:52:19.952295 | 2013-11-26T16:05:30 | 2013-11-26T16:05:30 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 12,497 | cpp | algorithm.cpp | #include "algorithm.h"
#include <windows.h>
//计算蒙哥马利乘积,在ModExp里面进行二进制模幂时每一步都会使用
BigInt MonPro(const BigInt&a,const BigInt& b,const BigInt& r,const BigInt&n,const BigInt& n$)
{
BigInt t = a*b;
/*BigInt m = t*n$ % r; //蒙哥马利算法的精髓就是这一行和下一行。不需要过多的计算就可以进行,因为r是10...0形式, %r 或 /r 的计算超级容易!
BigInt u = (t+m*n)/r; //下面是对这两行代码经过改造成2进制的取模和除法
*/
BigInt m,u;
BigInt __;
BigDiv2N2(t*n$,r,__,m);
BigDiv2N2((t+m*n),r,u,__);
if (u>=n)
return u-n;
else
return u;
}
//n must be odd
BigInt ModExpWrapper(const BigInt& M,const BigInt& e,const BigInt& n)
{
BigInt R = BigInt("1");
R=R<<( n.m_value.GetNonZeroBitIdx()+1 );
return ModExp(M,e,R,n);
}
BigInt ModExp(const BigInt& M,const BigInt& e,const BigInt& r,const BigInt& n)//n is odd
{
BigInt r$,n$;
ExEuclid2(r,n,r$,n$);//16*-4 + 13*5 = 1 ->>> 16*9 - 13* 11 = 144 - 143 = 1
//因为扩展欧几里得算法求出来的不一定满足 r*r$ - n*n$ = 1,并且
while (r$ < BigInt("0"))
{
r$ = r$ + n;
}
n$ = (r*r$ - BigInt("1")) / n;
//计算第一次
BigInt M_ = M*r % n;
BigInt x_ = BigInt("1")*r % n;
BigInt ee = e;//13 == 1101 1010 == 10
int len = 0;
while (ee>BigInt("0"))
{
ee = ee >> 1;
len++;
}
while (--len>=0)
{
x_ = MonPro(x_,x_,r,n,n$);
BigInt tmp = e>>len;
int bit = tmp.m_value.GetRadixBits(0);
if (bit & 1)//e的 e>>len是不是1
{
x_ = MonPro(M_,x_,r,n,n$);
}
}
x_ = MonPro(x_,BigInt("1"),r,n,n$);
return x_;
}
//get the index bit of Number,1 or 0
int GetIndexBit(int index,int Number)
{
if (Number>>index)
{
return 1;
}
else
return 0;
}
int other_gcd(int a,int b,int&x,int &y)
{
int t,d;
if(b==0)
{
x=1;
y=0; //不明处1
return a;
}
d=other_gcd(b,a%b,x,y);
t=x;
x=y;
y=t-(a/b)*y; //不明处2
return d;
}
int modular_exp_test(int a,int b,int m);
// 11001
//test_v是测试用的值
int rabin_miller(int p,int test_v)
{
// 偶数
if ( (p&3) % 2 == 0)
{
return false;
}
int m = p-1;
int k = 0;
while(0==(m&1))
{
m = m >> 1;
k++;
}
int m_ = p-1;
while (k>=0)
{
int expmod = modular_exp_test(test_v,m_,p);
if (expmod == p-1)
{
return true;
}
else if (expmod!=1)
{
return false;
}
else
{
m_ = m_ >> 1;
}
k = k -1;
}
return true;
}
//用test_v来对p进行一次rabinmiller素数判断,test_v<p
bool rabin_miller(const BigUInt& p,const BigUInt& test_v)
{
uint32 v = p.GetRadixBits(0);
if( (p & 1) == BigUInt("0"))//偶数
{
return false;
}
BigUInt m = p - BigUInt("1");
BigUInt m_ = m;
int k = 0;
while ( (m&1) == BigUInt("0"))
{
if( (m&0xffffffff) == BigUInt("0") )
{
int continue_uin32 = 0;
while ( (m.GetRadixBits(continue_uin32) & 0xffffffff) == BigUInt("0"))
{
continue_uin32++;
}
m = m >> (32*continue_uin32);
k = k + 32*continue_uin32;
}
else
{
m = m >> 1;
k = k + 1;
}
}
while (k>=0)
{
//BigUInt expmod = ExpMod(test_v,m_,p);
//use more efficient Montgomery ModExp
BigInt expmod = ModExpWrapper(BigInt(test_v),BigInt(m_),BigInt(p));
//BigUInt expmod = ExpMod(test_v,m_,p);
if (expmod == p - BigUInt("1"))
{
return true;
}
else if (expmod == BigUInt("1"))
{
m_ = m_ >> 1;
}
else
{
return false;
}
k = k - 1;
}
return true;
}
/*
相求 a*x + b*y = 1的解
因为 gcd(a,b) = gcd(b,a%b) == 1
->设 a*x + b*y = 1 (1)
所以下一次递归有:
b*x' + (a%b)*y' = 1,
即 b*x' + (a- a/b * b) * y' = 1
即 a*y' + b(1-a/b)*y' = 1 (2)
由 (1) 和(2)恒成立得到:
x = y'
y = (1 - a/b) * y'
即,本地递归的x等于下一次递归的y,本次递归的y等于下一次递归的 (1-a/b)*y。
因为gcd(a,b) = gcd(b,a%b)
所以,最后一次递归,就是 a==b,即 a%b==0时,
对于gcd(a,b,x,y)
{
if(b==0)//此时b为0, b = a_upper % b_upper ,即a_upper == b_upper,此时等式为 a*x + 0*y == 1,可以令y=1,
{
y=1
}
}
*/
void ex_euclid( int a,int b,int& g_x,int & g_y )
{
int old_a = a;
int old_b = b;
int tmp = b;
b = a % b;
a = tmp;
if(b == 0)
{
g_x = 1;
g_y = 0;
//最后一次递归返回时,顺带把出了赋予初始值之外的
//第一层x y之间的递推也计算出来。
int tmp = g_x;
g_x = g_y;
g_y = tmp - (old_a/old_b)*g_y;
return;
}
ex_euclid(a,b,g_x,g_y);
//计算第一次
int old_x = g_x;
g_x = g_y;
g_y = old_x - (old_a/old_b)*g_y;
}
int GetR( int n )
{
int i = 0;
while (n>0)
{
i++;
n=n>>1;
}
return 1<<i;
}
int MonPro( int a,int b,int r,int n,int n$ )
{
int t = a*b;
int m = t*n$ % r;
int u = (t+m*n) / r;
if (u>= n)
return u - n;
else
return u;
}
//r 128 n 97 r$ 25 n$ 33
int ModMul( int a,int b,int r,int n )
{
int r$,n$;
int rr,nn;
ex_euclid(r,n,r$,n$);
other_gcd(r,n,rr,nn);
int a_ = (a*r) % n;
int b_ = (b*r) % n;
int x_ = MonPro(a_,b_,r,n,-n$);//扩展欧几里得算法求出来的n$ 是 r*r-1 + n*n$ =1 的解,蒙哥马利算法要的是r*r-1 - n*n$ =1 的 n$,所以n$要取负
int x = MonPro(x_,1,r,n,-n$);
return x;
}
int ModMul2(int a,int b,int r,int n)
{
int r$,n$;
ex_euclid(r,n,r$,n$);
int a_ = (a*r) % n;
int x = MonPro(a_,b,r,n,n$);
return x;
}
/*
*/
int ModExp(int M,int e,int r,int n)//n is odd
{
int r$,n$;
ex_euclid(r,n,r$,n$);//16*-4 + 13*5 = 1 ->>> 16*9 - 13* 11 = 144 - 143 = 1
//因为扩展欧几里得算法求出来的不一定满足 r*r$ - n*n$ = 1,并且
while (r$ < 0)
{
r$ = r$ + n;
}
n$ = (r*r$ - 1) / n;
//计算第一次
int M_ = M*r % n;
int x_ = 1*r % n;
int ee = e;//13 == 1101 1010 == 10
int len = 0;
while (ee)
{
ee = ee >> 1;
len++;
}
while (--len>=0)
{
x_ = MonPro(x_,x_,r,n,n$);
int bit = e>>len;
if (bit & 1)
{
x_ = MonPro(M_,x_,r,n,n$);
}
}
x_ = MonPro(x_,1,r,n,n$);
return x_;
}
int modular_exp_test(int a,int b,int m)
{
int res = 1;
int multiplier = a;
while(b!=0)
{
if(b & 1)
{
res = (res * multiplier)%m;
}
multiplier = (multiplier * multiplier)%m;
b >>=1;
}
return res;
}
/*
原理是:
gcd(a,b) == gcd(b,a%b) ==
*/
int test_gcd(int a,int b)
{
while (a)
{
int t = a;
a = a % b;
b = t;
}
return b;
}
//产生BitLen长度的素数
BigInt GetPrimeNumber(int BitLen)
{
srand(GetTickCount());
int complete_uint32 = BitLen/32;
int remainded_bits = BitLen % 32;
BigInt P;
for (int i=0;i<complete_uint32;i++)
{
uint32 v = rand();
P.m_value.SetRadixBits(v,i);
}
if (remainded_bits>0)
{
uint32 mask = 0xffffffff;
mask = mask >> (32-remainded_bits);
uint32 v = rand();
v = v & mask;
P.m_value.SetRadixBits(v,complete_uint32);
}
//保证为奇数
if ((P.m_value & 1) == BigUInt("0"))
{
P = P+BigInt("1");
}
//测试是否为素数
//选取N个数,对得到的res进行素数测试
BigInt test_array[5];
for (int i=0;i<5;i++)
{
//test_array[i] = P >>( i+1 +rand()%3 );
}
test_array[0] = BigInt("2");
test_array[1] = BigInt("3");
test_array[2] = BigInt("7");
test_array[3] = BigInt("11");
test_array[4] = BigInt("63");
TEST:
bool is_prime = true;
for (int cnt=0;cnt<5;cnt++)
{
int rabin_miller_res = rabin_miller(P.m_value,test_array[cnt].m_value);
if (!rabin_miller_res)
{
is_prime = false;
break;
}
}
if (is_prime)
{
return P;
}
else
{
P = P + BigInt("2");
goto TEST;
}
}
void RSA_GetKeys(BigInt& pri_key,BigInt& pub_key,BigInt&n)
{
//假设我们直接得到了p 和 q两个大素数
BigInt p = "1406070802479346900455332906838309029958477035142707599662569";
BigInt q = "282469596323172063934194036186019324374654117450376009511809";
BigInt n_ = (p-BigInt("1"))*(q-BigInt("1"));
n = p*q;
int shift = 1 + rand()%13;
pub_key = n_ >> shift + shift;
while(GCD2(pub_key,n_) != BigInt("1"))
{
pub_key = pub_key - BigInt("1");
}
BigInt no_use;
ExEuclid2(pub_key,n_,pri_key,no_use);
while (pri_key < BigInt("0"))
{
pri_key = pri_key + n_;
}
}
BigInt RSA_Encrytp(const BigInt&data,const BigInt& pub_key,const BigInt&n)
{
return ModExpWrapper(data,pub_key,n);
}
BigInt RSA_Decrypt(const BigInt&enc_data,const BigInt& pri_key,const BigInt&n)
{
return ModExpWrapper(enc_data,pri_key,n);
}
int main()
{
BigUInt aaaaa = "429496729542949672954294967295";
BigUInt bbbbb = "429496729542949672954294967295";
BigUInt ccccc = aaaaa*bbbbb;
DumpBits(ccccc,"ccc是:");
for (int cnt=0;cnt<10;cnt++)
{
BigInt test_v("2");
BigInt p = "2004653905828746675557769888253513977792761579701275150291694205533610983232156841836467530035758446764254060229316652896944522602127828818539627839153960484313960997942756721543937404419116855816035777244295711055004816809573190573516516637026063862644437345073890587452098383334497888766902324698711865737257821137875776339620685614649750524394098405016601713";
BigInt m_ = p - BigInt("1");
BigInt expmod = ModExpWrapper(BigInt(test_v),BigInt(m_),BigInt(p));
break;
}
return 0;
BigInt pub_key,pri_key,rsa_n;
RSA_GetKeys(pri_key,pub_key,rsa_n);
uint32 data = 'm';
BigInt enc_data = RSA_Encrytp(BigInt(data),pub_key,rsa_n);
BigInt data2 = RSA_Decrypt(enc_data,pri_key,rsa_n);
//return 0;
for (int i=0;i<2;i++)
{
BigInt PrimeNum = GetPrimeNumber(1201);
DumpBits(PrimeNum.m_value,"第%d个素数",i);
}
return 0;
BigUInt max_prime = "170141183460469231731687303715884105727";
//DumpBits(max_prime);
BigInt prime_array[8] = {
BigInt("B00000000000000000000000011100000000000000000000000100100110000100000000000000000000101111100101000000000000000000011101011100110000000000000000000000001111110000000000000000000011001100011001000000000000000000101110111101001"),
BigInt("B00000000000000000000000000101101000000000000000000110000101110100000000000000000001111110001011100000000000000000111001011010010000000000000000000000001001111110000000000000000001010101000011100000000000000000111001110000001"),
BigInt("B00000000000000000000000000100111000000000000000000011011000011110000000000000000010010100101001100000000000000000011010110001101000000000000000000110100011101100000000000000000010100000000111100000000000000000110011110011111"),
BigInt("B00000000000000000000000011011101000000000000000001100100010011010000000000000000001100010000010100000000000000000100110111000000000000000000000001011101001111110000000000000000001101010111101100000000000000000010000110010111"),
BigInt("B00000000000000000000000011110011000000000000000000100001100010100000000000000000011011100010010000000000000000000111001110001011000000000000000000010111010101000000000000000000011001111100101100000000000000000001110010011111"),
BigInt("B00000000000000000000000000101011000000000000000001101001001100100000000000000000000010110110111100000000000000000101000101011100000000000000000001101010101110010000000000000000010001001010001000000000000000000100011011100101"),
BigInt("B00000000000000000000000001111001000000000000000001000011001010110000000000000000010110101111000100000000000000000111011110001101000000000000000000000101100000110000000000000000001101101001111000000000000000000001000110100101"),
BigInt("B00000000000000000000000111011111000000000000000000100111000110010000000000000000001100101000110000000000000000000110101100101101000000000000000001010110111010010000000000000000011101101011000100000000000000000111000101101101")
};
//for (BigUInt p=BigUInt("3");p<BigUInt("2000");)
for (int i=0;i<8;i++)// /*+ BigUInt("2000")*/;)
{
BigUInt p = prime_array[i].m_value;
int is_prime = true;
for(BigUInt j="2";j<BigUInt("5");)
{
if( !rabin_miller(p,j))
{
is_prime = false;
break;
}
j = j + BigUInt("1");
}
if (is_prime)
{
DumpBits(p);
}
p = p + BigUInt("1");
}
BigInt QQ,RR;
BigDiv2N2(BigInt("7"),BigInt("2"),QQ,RR);
int gcd_v = test_gcd(24,24);
int a = 7,b=109999999,n=13; //a*b mod n = 14
int r = GetR(n);
int rr = r;
int len = 0;
int vvv = ModExp(a,b,r,n);
int vvvv = modular_exp_test(a,b,n);
BigInt A = "817263847623465716523745273645781652376548176523874658162537846518726354";
BigInt B = "76981762398764918762398576298376495876198237645987263478562398475";
BigInt C = "87619823764598726349865981763948765928364985762198376498576234986598768761987";
//蒙哥马利算法用到的R,是比模C要大的最小的2^n的值,
BigInt R = BigInt("1");
R=R<<( C.m_value.GetNonZeroBitIdx()+1 );
BigInt Result = ModExp(A,B,R,C);
DumpBits(Result.m_value,"结果:");
return 0;
} |
c2124d7b507eb727af315402dbb5f7ebf4e22b86 | b326e7396c67e0ebb13ab78f442accb4e3ccab88 | /MMC.h | 91b9836c1ad8e8698c45191e7158c19f98a9b4e9 | [] | no_license | karlajusten/DS1-MMC | 23e74c78e7470716af2a44a28ef45a55f2e6f239 | 892fe5375dfd5843eff93bf68da662bd6774d809 | refs/heads/master | 2020-03-26T12:27:19.912633 | 2018-08-29T19:30:23 | 2018-08-29T19:30:23 | 144,893,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | h | MMC.h | /*
* MMC.h
*
* Created on: 15 de ago de 2018
* Author: karla
* Author: bruno
*/
#ifndef MMC_H_
#define MMC_H_
#include <stdint.h>
#include <iostream>
#define _USE_MATH_DEFINES
#include <cmath>
#include "Sampler_if.h"
//discrete
#include <initializer_list>
#include <iterator>
#include <numeric>
#include <tuple>
#include <vector>
class MMC : public Sampler_if {
protected:
MMC *mmc;
public:
MMC();
MMC(const MMC& mmc_);
virtual ~MMC();
struct MyRNG_Parameters: public RNG_Parameters{
uint64_t seed;
uint64_t multiplier;
uint64_t increment; // Select a sequence in the 2^63 range. must be odd!
};
double random();
double sampleUniform(double min, double max);
double sampleExponential(double mean);
double sampleErlang(double mean, int M);
double sampleNormal(double mean, double stddev);
double sampleGamma(double mean, double alpha);
double sampleBeta(double alpha, double beta, double infLimit, double supLimit);
double sampleWeibull(double alpha, double scale);
double sampleLogNormal(double mean, double stddev);
double sampleTriangular(double min, double mode, double max);
double sampleDiscrete(const std::vector<double>& Prob );
void setRNGparameters(RNG_Parameters* param);
RNG_Parameters* getRNGparameters() const;
private:
uint32_t rotr32(uint32_t x, unsigned r);
MyRNG_Parameters* param = new MyRNG_Parameters();
};
#endif /* MMC_H_ */
|
e4ca7f6defa34b970156389a65e0baa83b986f90 | 1a76cb9fce384bbbb3e4c538d4be9b9b4197ec54 | /SVIEngine/jni/SVI/Animation/Transition/SVIUncoverEffector.h | f70b3adcfd9788dec85f0051b1ea8e3077971b47 | [
"Apache-2.0"
] | permissive | teeraporn39/SVIEngine | 8e231e9e8d5a2aa001539e96abc6355ee0edbb5d | 87e379a1e1906025660e9de8da8ff908faf0a976 | refs/heads/master | 2020-06-19T18:17:27.504208 | 2019-09-23T20:26:18 | 2019-09-23T20:26:18 | 196,818,062 | 1 | 0 | Apache-2.0 | 2019-07-14T09:33:39 | 2019-07-14T09:33:39 | null | UTF-8 | C++ | false | false | 329 | h | SVIUncoverEffector.h | #ifndef __SVI_UNCOVEREFFECTOR_H_
#define __SVI_UNCOVEREFFECTOR_H_
#include "SVITransitionEffector.h"
namespace SVI {
class SVIUncoverEffector : public SVITransitionEffector {
public:
SVIUncoverEffector(SVIGLSurface *surface);
virtual ~SVIUncoverEffector() {}
protected:
void setAnimation();
private:
};
}
#endif
|
94ad8c22b3bf15ceea7f963b177c9c5cc96b9943 | 5fbde59f61cdf490d03a46aa1361e49cfce118d7 | /wait.cc | c96a4ba5adc43b04169bf8288f209e5acb4e57ec | [] | no_license | kcir-notlob/wait | 1e9f520969315fbdcb8cc502a007e13becaf8ea5 | ee924e3511fde5a2158b1ec362dba27ab32e975e | refs/heads/master | 2020-03-28T00:01:03.843510 | 2018-09-04T15:37:56 | 2018-09-04T15:37:56 | 147,368,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cc | wait.cc | //file:wait.cc
//version:0.0.0.1
#include <iostream>
#include <thread>
using namespace std;
using namespace std::chrono;
float star(float previous,int current,int max){
int const DISPLAY_STEPS=80;
if(current==0){
cout << "[" << flush;
for(int i=0;i<DISPLAY_STEPS;i++){
cout << "-" << flush;
}
cout << "]" << endl << flush;
cout << "[" << flush;
return 0;
}
float steps=(float) max/(float)DISPLAY_STEPS;
float change=(float)current-(float)previous;
int step_count=change /steps;
if(step_count<1){
return previous;
}
for(int i=0;i<step_count;i++){
cout << "*" << flush;
}
previous+=(float) step_count * steps;
if(current==max){
cout << "]" << endl << flush;
}
return previous;
}
void wait(int seconds){
time_point<system_clock> start=system_clock::now();
time_point<system_clock> current=system_clock::now();
chrono::seconds sec=chrono::duration_cast<chrono::seconds>(current - start);
float last=0;
star(0,0,seconds);
while(sec.count() < seconds){
this_thread::sleep_for(1s);
current=chrono::system_clock::now();
sec=chrono::duration_cast<chrono::seconds>(current - start);
//cout << sec.count() << endl;
last=star(last,sec.count(),seconds);
}
}
int main(int argc,char* argv[]){
wait(3 * 60);
return 0;
}
|
871f1258d5043f1c802dfe20f8db57260092e09e | 60de2a41d7848c6933ccb94fce5f0961b56e2498 | /Examples/C++/Contents/SceneEntities/HelloPolycodeApp.h | daa5295fccd38096ab7642d8a3f0d622614cb323 | [
"MIT"
] | permissive | sbarisic/Polycode | 0e7e7dae031a91bc720bcff410fdd379046c8a8b | b6fe41c6123281db3caee3c11f655de79df6fbfb | refs/heads/master | 2018-12-12T23:23:15.311252 | 2018-09-13T13:42:04 | 2018-09-13T13:42:04 | 40,675,469 | 0 | 0 | MIT | 2018-09-13T13:42:05 | 2015-08-13T18:35:40 | C++ | UTF-8 | C++ | false | false | 349 | h | HelloPolycodeApp.h | #include <Polycode.h>
#include "PolycodeView.h"
using namespace Polycode;
class HelloPolycodeApp {
public:
HelloPolycodeApp(PolycodeView *view);
~HelloPolycodeApp();
bool Update();
private:
ScenePrimitive *sun;
ScenePrimitive *planet;
ScenePrimitive *moon;
Number planetRoll;
Number moonRoll;
Core *core;
};
|
480f86cd65e2e0717cd28ba882f3f6caee022247 | 530877d73360973288f8bd041230e9e566820b78 | /Figures/CRectangle.h | 562d7da396ca1f3f45da572c53cbb6727ddc9402 | [] | no_license | aymanElakwah/paint-for-kids | 888418fd028bcdb704cce4030604a233aad57a12 | 88319b2e9ac54d75a292dd61abc35cbeb22614e0 | refs/heads/master | 2021-10-08T04:29:51.308969 | 2018-12-07T18:12:26 | 2018-12-07T18:12:26 | 112,390,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | h | CRectangle.h | #ifndef CRECT_H
#define CRECT_H
#include "CFigure.h"
class CRectangle : public CFigure
{
private:
Point Corner1;
Point Corner2;
public:
CRectangle();
CRectangle(Point , Point, GfxInfo FigureGfxInfo);
virtual void Draw(Output* pOut) const;
virtual bool IsInside(Point P);
virtual void Save(ofstream &OutFile) const;
virtual void Load(ifstream &Infile);
virtual void PrintInfo(Output* pOut);
virtual CFigure*CopyFigure();
virtual Point GetCenter();
virtual void Move(Point);
virtual string getName() const;
virtual void rotate();
virtual bool isSame(CFigure* figChoose) const;
};
#endif |
bec8beca13b29bbfd2ec89184c34c28ca4dd78d0 | d287ed8bdb566b25b5e5fed9d635cb68a3687a88 | /rmf_traffic_ros2/src/rmf_traffic_ros2/schedule/convert_Patch.cpp | e5d77ed7c9baee973295d4f90b501fad139ad006 | [
"Apache-2.0"
] | permissive | jian-dong/rmf_ros2 | 3ebff8e2ff9e059b56baa59e21da4bbd1e596bfd | 87ce942d534b24da202c77efea5daf0fce47fe25 | refs/heads/main | 2023-07-20T07:28:20.357865 | 2021-09-02T06:34:01 | 2021-09-02T06:34:01 | 404,021,430 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,412 | cpp | convert_Patch.cpp | /*
* Copyright (C) 2019 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <rmf_traffic_ros2/schedule/Patch.hpp>
#include <rmf_traffic_ros2/schedule/Change.hpp>
#include <rmf_traffic_msgs/msg/schedule_participant_patch.hpp>
#include <rmf_traffic_msgs/msg/schedule_change_cull.hpp>
#include <rmf_traffic_msgs/msg/schedule_change_add.hpp>
#include <rmf_traffic_msgs/msg/schedule_change_delay.hpp>
using Time = rmf_traffic::Time;
using Duration = rmf_traffic::Duration;
namespace rmf_traffic_ros2 {
//==============================================================================
rmf_traffic::schedule::Patch::Participant convert(
const rmf_traffic_msgs::msg::ScheduleParticipantPatch& from);
//==============================================================================
//==============================================================================
template<typename T_out, typename T_in>
void convert_vector(
std::vector<T_out>& output,
const std::vector<T_in>& input)
{
output.reserve(input.size());
for (const auto& i : input)
output.emplace_back(convert(i));
}
//==============================================================================
template<typename T_out, typename T_in>
std::vector<T_out> convert_vector(
const std::vector<T_in>& input)
{
std::vector<T_out> output;
convert_vector(output, input);
return output;
}
//==============================================================================
rmf_traffic_msgs::msg::ScheduleParticipantPatch convert(
const rmf_traffic::schedule::Patch::Participant& from)
{
return
rmf_traffic_msgs::build<rmf_traffic_msgs::msg::ScheduleParticipantPatch>()
.participant_id(from.participant_id())
.itinerary_version(from.itinerary_version())
.erasures(from.erasures().ids())
.delays(convert_vector<rmf_traffic_msgs::msg::ScheduleChangeDelay>(
from.delays()))
.additions(convert_vector<rmf_traffic_msgs::msg::ScheduleChangeAdd>(
from.additions().items()));
}
//==============================================================================
rmf_traffic::schedule::Patch::Participant convert(
const rmf_traffic_msgs::msg::ScheduleParticipantPatch& from)
{
return rmf_traffic::schedule::Patch::Participant{
from.participant_id,
from.itinerary_version,
rmf_traffic::schedule::Change::Erase{from.erasures},
convert_vector<rmf_traffic::schedule::Change::Delay>(from.delays),
rmf_traffic::schedule::Change::Add{
convert_vector<rmf_traffic::schedule::Change::Add::Item>(from.additions)
}
};
}
//==============================================================================
rmf_traffic_msgs::msg::SchedulePatch convert(
const rmf_traffic::schedule::Patch& from)
{
rmf_traffic_msgs::msg::SchedulePatch output;
output.participants.reserve(from.size());
for (const auto& p : from)
output.participants.emplace_back(convert(p));
if (const auto& cull = from.cull())
output.cull.emplace_back(convert(*cull));
output.has_base_version = from.base_version().has_value();
if (from.base_version().has_value())
output.base_version = *from.base_version();
output.latest_version = from.latest_version();
return output;
}
//==============================================================================
rmf_traffic::schedule::Patch convert(
const rmf_traffic_msgs::msg::SchedulePatch& from)
{
std::optional<rmf_traffic::schedule::Change::Cull> cull;
if (!from.cull.empty())
cull = convert(from.cull.front());
std::optional<rmf_traffic::schedule::Version> base_version;
if (from.has_base_version)
base_version = from.base_version;
return rmf_traffic::schedule::Patch{
convert_vector<rmf_traffic::schedule::Patch::Participant>(
from.participants),
std::move(cull),
base_version,
from.latest_version
};
}
} // namespace rmf_traffic_ros2
|
19ae06a3187e117b606803742afbb5646eb50876 | 2137ad6d3e303cfc0dd4b24d27eb914514f442b3 | /test/testBig.cc | e898c95c6b290dc4c591546dc75a535dfa181f86 | [] | no_license | zacharysells/project_euler | 5e4e8d91ef9cfdd4aa51305f7bb57b9a09b7e68a | 526e39d00e448921072cbe3659c9389f21f9dc76 | refs/heads/master | 2016-09-06T11:28:16.655258 | 2014-12-08T07:08:26 | 2014-12-08T07:08:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cc | testBig.cc | #include <iostream>
#include <bigNumber.h>
#include <bigNumber.cpp>
using namespace std;
int main()
{
bigNumber x("5");
bigNumber y("11");
x = x * 2;
cout << x << endl;
}
|
ef97c9127886a5ede71f248fa6d5380eec9ca96f | 459fabe8dcc30a168034a9166f8931ceb986b21a | /atcoder/ABC-085/c.cpp | 16efd6e8830414a01e06c655875cbb2b02e2a920 | [
"MIT"
] | permissive | YusukeKato/ProgrammingContest | a04727472e4b3684d2928e7114f5bde0f517aa58 | d8ae46b936eaa4f8794ad333f5367c177c18d92f | refs/heads/master | 2022-12-02T15:53:47.032118 | 2019-08-28T14:04:59 | 2019-08-28T14:04:59 | 170,851,658 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | c.cpp | #include <iostream>
using namespace std;
int main()
{
int N, Y;
cin >> N >> Y;
int ans_a = -1;
int ans_b = -1;
int ans_c = -1;
for(int a = 0; a <= N; a++)
{
for(int b = 0; b <= N; b++)
{
int c = N - a - b;
if(c >= 0 and a+b+c == N and 10000*a+5000*b+1000*c == Y)
{
ans_a = a;
ans_b = b;
ans_c = c;
}
}
}
cout << ans_a << " " << ans_b << " " << ans_c << endl;
return 0;
}
|
8e726fbb36dc0d226cf6156ea9aa5fdbfac692ce | b8376621d63394958a7e9535fc7741ac8b5c3bdc | /lib/lib_mech/src/server/TServer/TCommonClient/protocal/PT_ChannelServer_Enum.cpp | a740d6423202bcadda782110d1858ded185e5895 | [] | no_license | 15831944/job_mobile | 4f1b9dad21cb7866a35a86d2d86e79b080fb8102 | ebdf33d006025a682e9f2dbb670b23d5e3acb285 | refs/heads/master | 2021-12-02T10:58:20.932641 | 2013-01-09T05:20:33 | 2013-01-09T05:20:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,890 | cpp | PT_ChannelServer_Enum.cpp |
//from(d:\svn\common\lib\windows\mech\src\server\tserver\doc\sequece\tserver\..\..\..\tcommonclient\protocal\pt_channel.xml)
#include "stdafx.h"
#include "interface/net/jPlugInHelpTable.h"
#include "PT_ChannelServer_Enum.h"
#include "../my_PT_TServer.h"
#ifndef ChannelServer_jNOTUSE_SQ_CODE
using namespace nMech::nNET::nChannelServer;
DECLARE_INSTANCE_TYPE(S_CH_ECHO);
DECLARE_INSTANCE_TYPE(S_X2CH_CHAT);
DECLARE_INSTANCE_TYPE(S_CH2X_CHAT);
DECLARE_INSTANCE_TYPE(S_X2CH_USER_LOGIN_CHANNEL);
DECLARE_INSTANCE_TYPE(S_CH2X_NEW_TOWN_OK);
DECLARE_INSTANCE_TYPE(S_X2CH_NEW_TOWN);
DECLARE_INSTANCE_TYPE(S_CH2X_SELECT_CASTLE);
DECLARE_INSTANCE_TYPE(S_X2CH_TOWN_SELECT);
DECLARE_INSTANCE_TYPE(S_X2CH_TOWN_DELETE);
DECLARE_INSTANCE_TYPE(S_CH2X_TOWN_DELETE_OK);
DECLARE_INSTANCE_TYPE(S_CH2X_TOWN_SELECT_RESULT);
DECLARE_INSTANCE_TYPE(S_CH2X_CREATE_NEW_TOWN);
DECLARE_INSTANCE_TYPE(S_X2CH_USER_EXIT);
DECLARE_INSTANCE_TYPE(S_CH2X_USER_EXIT);
DECLARE_INSTANCE_TYPE(S_X2CH_GOTO_CASTLE_MAP);
DECLARE_INSTANCE_TYPE(S_CH2X_GOTO_CASTLE_MAP);
DECLARE_INSTANCE_TYPE(S_X2CH_GOTO_WORLD_MAP);
DECLARE_INSTANCE_TYPE(S_CH2X_GOTO_WORLD_MAP);
DECLARE_INSTANCE_TYPE(S_CH2X_UPDATE_CASTLE_MAP);
DECLARE_INSTANCE_TYPE(S_CH2X_UDPATE_WORLD_MAP);
DECLARE_INSTANCE_TYPE(S_X2CH_GOTO_TOWN_MAP);
DECLARE_INSTANCE_TYPE(S_CH2X_GOTO_TOWN_MAP);
DECLARE_INSTANCE_TYPE(S_X2CH_NEW_BUILD);
DECLARE_INSTANCE_TYPE(S_X2CH_BUILD_UPGRADE);
DECLARE_INSTANCE_TYPE(S_CH2X_BUILD_UPGRADE_RESULT);
DECLARE_INSTANCE_TYPE(S_X2CH_BUILD_UPGRADE_CANCLE);
DECLARE_INSTANCE_TYPE(S_X2CH_BUILD_UPGRADE_CANCLE_OK);
DECLARE_INSTANCE_TYPE(S_X2CH_BUILD_UPGRADE_CHECK);
DECLARE_INSTANCE_TYPE(S_X2CH_BUILD_UPGRADE_CHECK_RESULT);
DECLARE_INSTANCE_TYPE(S_CH_ERROR);
DECLARE_INSTANCE_TYPE(S_CH_HELLO);
DECLARE_INSTANCE_TYPE(S_T2X_NOTICE);
DECLARE_INSTANCE_TYPE(S_X2L_NOTICE_TEST);
DECLARE_INSTANCE_TYPE(S_CH2X_USER_LOGIN_CHANNEL_OK);
DECLARE_INSTANCE_TYPE(S_CH2X_USER_LOGIN_CHANNEL_OK2);
DECLARE_INSTANCE_TYPE(S_CH2X_USER_LOGIN_CHANNEL_OK3);
#endif // ChannelServer_jNOTUSE_SQ_CODE
namespace nMech{ namespace nNET { namespace nChannelServer
{
PT_ChannelServer_LIB_API nMech::nNET::jNamedEventTable *g_pPlugInHelpTableList=0;
#ifndef ChannelServer_jNOTUSE_SQ_CODE
static void _S_CH_ECHO_WritePacket(S_CH_ECHO* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH_ECHO(sendBuf,*pThis));
}
static void _S_CH_ECHO_WriteToPacket(S_CH_ECHO* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH_ECHO(sendBuf,*pThis));
}
void call_sq_CH_ECHO(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH_ECHO param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH_ECHO"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_CH_ECHO , get_msg)(S_CH_ECHO* pThis)
{
fname_t buf;return (pThis->get_msg(buf));
}
static void _S_X2CH_CHAT_WritePacket(S_X2CH_CHAT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_CHAT(sendBuf,*pThis));
}
static void _S_X2CH_CHAT_WriteToPacket(S_X2CH_CHAT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_CHAT(sendBuf,*pThis));
}
void call_sq_X2CH_CHAT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_CHAT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_CHAT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_CHAT , get_msg)(S_X2CH_CHAT* pThis)
{
fname_t buf;return (pThis->get_msg(buf));
}
static void _S_CH2X_CHAT_WritePacket(S_CH2X_CHAT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_CHAT(sendBuf,*pThis));
}
static void _S_CH2X_CHAT_WriteToPacket(S_CH2X_CHAT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_CHAT(sendBuf,*pThis));
}
void call_sq_CH2X_CHAT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_CHAT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_CHAT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_CH2X_CHAT , get_msg)(S_CH2X_CHAT* pThis)
{
fname_t buf;return (pThis->get_msg(buf));
}
static void _S_X2CH_USER_LOGIN_CHANNEL_WritePacket(S_X2CH_USER_LOGIN_CHANNEL* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_USER_LOGIN_CHANNEL(sendBuf,*pThis));
}
static void _S_X2CH_USER_LOGIN_CHANNEL_WriteToPacket(S_X2CH_USER_LOGIN_CHANNEL* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_USER_LOGIN_CHANNEL(sendBuf,*pThis));
}
void call_sq_X2CH_USER_LOGIN_CHANNEL(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_USER_LOGIN_CHANNEL param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_USER_LOGIN_CHANNEL"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_USER_LOGIN_CHANNEL , get_id)(S_X2CH_USER_LOGIN_CHANNEL* pThis)
{
fname_t buf;return (pThis->get_id(buf));
}
static void _S_CH2X_NEW_TOWN_OK_WritePacket(S_CH2X_NEW_TOWN_OK* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_NEW_TOWN_OK(sendBuf,*pThis));
}
static void _S_CH2X_NEW_TOWN_OK_WriteToPacket(S_CH2X_NEW_TOWN_OK* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_NEW_TOWN_OK(sendBuf,*pThis));
}
void call_sq_CH2X_NEW_TOWN_OK(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_NEW_TOWN_OK param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_NEW_TOWN_OK"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_NEW_TOWN_WritePacket(S_X2CH_NEW_TOWN* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_NEW_TOWN(sendBuf,*pThis));
}
static void _S_X2CH_NEW_TOWN_WriteToPacket(S_X2CH_NEW_TOWN* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_NEW_TOWN(sendBuf,*pThis));
}
void call_sq_X2CH_NEW_TOWN(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_NEW_TOWN param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_NEW_TOWN"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_NEW_TOWN , get_name)(S_X2CH_NEW_TOWN* pThis)
{
fname_t buf;return (pThis->get_name(buf));
}
static void _S_CH2X_SELECT_CASTLE_WritePacket(S_CH2X_SELECT_CASTLE* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_SELECT_CASTLE(sendBuf,*pThis));
}
static void _S_CH2X_SELECT_CASTLE_WriteToPacket(S_CH2X_SELECT_CASTLE* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_SELECT_CASTLE(sendBuf,*pThis));
}
void call_sq_CH2X_SELECT_CASTLE(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_SELECT_CASTLE param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_SELECT_CASTLE"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_TOWN_SELECT_WritePacket(S_X2CH_TOWN_SELECT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_TOWN_SELECT(sendBuf,*pThis));
}
static void _S_X2CH_TOWN_SELECT_WriteToPacket(S_X2CH_TOWN_SELECT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_TOWN_SELECT(sendBuf,*pThis));
}
void call_sq_X2CH_TOWN_SELECT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_TOWN_SELECT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_TOWN_SELECT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_TOWN_DELETE_WritePacket(S_X2CH_TOWN_DELETE* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_TOWN_DELETE(sendBuf,*pThis));
}
static void _S_X2CH_TOWN_DELETE_WriteToPacket(S_X2CH_TOWN_DELETE* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_TOWN_DELETE(sendBuf,*pThis));
}
void call_sq_X2CH_TOWN_DELETE(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_TOWN_DELETE param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_TOWN_DELETE"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_TOWN_DELETE_OK_WritePacket(S_CH2X_TOWN_DELETE_OK* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_TOWN_DELETE_OK(sendBuf,*pThis));
}
static void _S_CH2X_TOWN_DELETE_OK_WriteToPacket(S_CH2X_TOWN_DELETE_OK* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_TOWN_DELETE_OK(sendBuf,*pThis));
}
void call_sq_CH2X_TOWN_DELETE_OK(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_TOWN_DELETE_OK param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_TOWN_DELETE_OK"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_TOWN_SELECT_RESULT_WritePacket(S_CH2X_TOWN_SELECT_RESULT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_TOWN_SELECT_RESULT(sendBuf,*pThis));
}
static void _S_CH2X_TOWN_SELECT_RESULT_WriteToPacket(S_CH2X_TOWN_SELECT_RESULT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_TOWN_SELECT_RESULT(sendBuf,*pThis));
}
void call_sq_CH2X_TOWN_SELECT_RESULT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_TOWN_SELECT_RESULT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_TOWN_SELECT_RESULT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_CREATE_NEW_TOWN_WritePacket(S_CH2X_CREATE_NEW_TOWN* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_CREATE_NEW_TOWN(sendBuf,*pThis));
}
static void _S_CH2X_CREATE_NEW_TOWN_WriteToPacket(S_CH2X_CREATE_NEW_TOWN* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_CREATE_NEW_TOWN(sendBuf,*pThis));
}
void call_sq_CH2X_CREATE_NEW_TOWN(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_CREATE_NEW_TOWN param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_CREATE_NEW_TOWN"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_USER_EXIT_WritePacket(S_X2CH_USER_EXIT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_USER_EXIT(sendBuf,*pThis));
}
static void _S_X2CH_USER_EXIT_WriteToPacket(S_X2CH_USER_EXIT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_USER_EXIT(sendBuf,*pThis));
}
void call_sq_X2CH_USER_EXIT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_USER_EXIT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_USER_EXIT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_USER_EXIT_WritePacket(S_CH2X_USER_EXIT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_USER_EXIT(sendBuf,*pThis));
}
static void _S_CH2X_USER_EXIT_WriteToPacket(S_CH2X_USER_EXIT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_USER_EXIT(sendBuf,*pThis));
}
void call_sq_CH2X_USER_EXIT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_USER_EXIT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_USER_EXIT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_GOTO_CASTLE_MAP_WritePacket(S_X2CH_GOTO_CASTLE_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_GOTO_CASTLE_MAP(sendBuf,*pThis));
}
static void _S_X2CH_GOTO_CASTLE_MAP_WriteToPacket(S_X2CH_GOTO_CASTLE_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_GOTO_CASTLE_MAP(sendBuf,*pThis));
}
void call_sq_X2CH_GOTO_CASTLE_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_GOTO_CASTLE_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_GOTO_CASTLE_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_GOTO_CASTLE_MAP_WritePacket(S_CH2X_GOTO_CASTLE_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_GOTO_CASTLE_MAP(sendBuf,*pThis));
}
static void _S_CH2X_GOTO_CASTLE_MAP_WriteToPacket(S_CH2X_GOTO_CASTLE_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_GOTO_CASTLE_MAP(sendBuf,*pThis));
}
void call_sq_CH2X_GOTO_CASTLE_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_GOTO_CASTLE_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_GOTO_CASTLE_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_GOTO_WORLD_MAP_WritePacket(S_X2CH_GOTO_WORLD_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_GOTO_WORLD_MAP(sendBuf,*pThis));
}
static void _S_X2CH_GOTO_WORLD_MAP_WriteToPacket(S_X2CH_GOTO_WORLD_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_GOTO_WORLD_MAP(sendBuf,*pThis));
}
void call_sq_X2CH_GOTO_WORLD_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_GOTO_WORLD_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_GOTO_WORLD_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_GOTO_WORLD_MAP_WritePacket(S_CH2X_GOTO_WORLD_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_GOTO_WORLD_MAP(sendBuf,*pThis));
}
static void _S_CH2X_GOTO_WORLD_MAP_WriteToPacket(S_CH2X_GOTO_WORLD_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_GOTO_WORLD_MAP(sendBuf,*pThis));
}
void call_sq_CH2X_GOTO_WORLD_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_GOTO_WORLD_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_GOTO_WORLD_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_UPDATE_CASTLE_MAP_WritePacket(S_CH2X_UPDATE_CASTLE_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_UPDATE_CASTLE_MAP(sendBuf,*pThis));
}
static void _S_CH2X_UPDATE_CASTLE_MAP_WriteToPacket(S_CH2X_UPDATE_CASTLE_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_UPDATE_CASTLE_MAP(sendBuf,*pThis));
}
void call_sq_CH2X_UPDATE_CASTLE_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_UPDATE_CASTLE_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_UPDATE_CASTLE_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_UDPATE_WORLD_MAP_WritePacket(S_CH2X_UDPATE_WORLD_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_UDPATE_WORLD_MAP(sendBuf,*pThis));
}
static void _S_CH2X_UDPATE_WORLD_MAP_WriteToPacket(S_CH2X_UDPATE_WORLD_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_UDPATE_WORLD_MAP(sendBuf,*pThis));
}
void call_sq_CH2X_UDPATE_WORLD_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_UDPATE_WORLD_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_UDPATE_WORLD_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_GOTO_TOWN_MAP_WritePacket(S_X2CH_GOTO_TOWN_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_GOTO_TOWN_MAP(sendBuf,*pThis));
}
static void _S_X2CH_GOTO_TOWN_MAP_WriteToPacket(S_X2CH_GOTO_TOWN_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_GOTO_TOWN_MAP(sendBuf,*pThis));
}
void call_sq_X2CH_GOTO_TOWN_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_GOTO_TOWN_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_GOTO_TOWN_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_GOTO_TOWN_MAP_WritePacket(S_CH2X_GOTO_TOWN_MAP* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_GOTO_TOWN_MAP(sendBuf,*pThis));
}
static void _S_CH2X_GOTO_TOWN_MAP_WriteToPacket(S_CH2X_GOTO_TOWN_MAP* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_GOTO_TOWN_MAP(sendBuf,*pThis));
}
void call_sq_CH2X_GOTO_TOWN_MAP(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_GOTO_TOWN_MAP param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_GOTO_TOWN_MAP"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_X2CH_NEW_BUILD_WritePacket(S_X2CH_NEW_BUILD* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_NEW_BUILD(sendBuf,*pThis));
}
static void _S_X2CH_NEW_BUILD_WriteToPacket(S_X2CH_NEW_BUILD* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_NEW_BUILD(sendBuf,*pThis));
}
void call_sq_X2CH_NEW_BUILD(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_NEW_BUILD param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_NEW_BUILD"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_NEW_BUILD , get_build_slot)(S_X2CH_NEW_BUILD* pThis)
{
fname_t buf;return (pThis->get_build_slot(buf));
}
static void _S_X2CH_BUILD_UPGRADE_WritePacket(S_X2CH_BUILD_UPGRADE* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_BUILD_UPGRADE(sendBuf,*pThis));
}
static void _S_X2CH_BUILD_UPGRADE_WriteToPacket(S_X2CH_BUILD_UPGRADE* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_BUILD_UPGRADE(sendBuf,*pThis));
}
void call_sq_X2CH_BUILD_UPGRADE(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_BUILD_UPGRADE param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_BUILD_UPGRADE"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_BUILD_UPGRADE , get_build_slot)(S_X2CH_BUILD_UPGRADE* pThis)
{
fname_t buf;return (pThis->get_build_slot(buf));
}
static void _S_CH2X_BUILD_UPGRADE_RESULT_WritePacket(S_CH2X_BUILD_UPGRADE_RESULT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_BUILD_UPGRADE_RESULT(sendBuf,*pThis));
}
static void _S_CH2X_BUILD_UPGRADE_RESULT_WriteToPacket(S_CH2X_BUILD_UPGRADE_RESULT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_BUILD_UPGRADE_RESULT(sendBuf,*pThis));
}
void call_sq_CH2X_BUILD_UPGRADE_RESULT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_BUILD_UPGRADE_RESULT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_BUILD_UPGRADE_RESULT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_CH2X_BUILD_UPGRADE_RESULT , get_build_slot)(S_CH2X_BUILD_UPGRADE_RESULT* pThis)
{
fname_t buf;return (pThis->get_build_slot(buf));
}
static void _S_X2CH_BUILD_UPGRADE_CANCLE_WritePacket(S_X2CH_BUILD_UPGRADE_CANCLE* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_BUILD_UPGRADE_CANCLE(sendBuf,*pThis));
}
static void _S_X2CH_BUILD_UPGRADE_CANCLE_WriteToPacket(S_X2CH_BUILD_UPGRADE_CANCLE* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_BUILD_UPGRADE_CANCLE(sendBuf,*pThis));
}
void call_sq_X2CH_BUILD_UPGRADE_CANCLE(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_BUILD_UPGRADE_CANCLE param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_BUILD_UPGRADE_CANCLE"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_BUILD_UPGRADE_CANCLE , get_build_slot)(S_X2CH_BUILD_UPGRADE_CANCLE* pThis)
{
fname_t buf;return (pThis->get_build_slot(buf));
}
static void _S_X2CH_BUILD_UPGRADE_CANCLE_OK_WritePacket(S_X2CH_BUILD_UPGRADE_CANCLE_OK* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_BUILD_UPGRADE_CANCLE_OK(sendBuf,*pThis));
}
static void _S_X2CH_BUILD_UPGRADE_CANCLE_OK_WriteToPacket(S_X2CH_BUILD_UPGRADE_CANCLE_OK* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_BUILD_UPGRADE_CANCLE_OK(sendBuf,*pThis));
}
void call_sq_X2CH_BUILD_UPGRADE_CANCLE_OK(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_BUILD_UPGRADE_CANCLE_OK param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_BUILD_UPGRADE_CANCLE_OK"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_BUILD_UPGRADE_CANCLE_OK , get_build_slot)(S_X2CH_BUILD_UPGRADE_CANCLE_OK* pThis)
{
fname_t buf;return (pThis->get_build_slot(buf));
}
static void _S_X2CH_BUILD_UPGRADE_CHECK_WritePacket(S_X2CH_BUILD_UPGRADE_CHECK* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_BUILD_UPGRADE_CHECK(sendBuf,*pThis));
}
static void _S_X2CH_BUILD_UPGRADE_CHECK_WriteToPacket(S_X2CH_BUILD_UPGRADE_CHECK* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_BUILD_UPGRADE_CHECK(sendBuf,*pThis));
}
void call_sq_X2CH_BUILD_UPGRADE_CHECK(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_BUILD_UPGRADE_CHECK param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_BUILD_UPGRADE_CHECK"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_BUILD_UPGRADE_CHECK , get_build_slot)(S_X2CH_BUILD_UPGRADE_CHECK* pThis)
{
fname_t buf;return (pThis->get_build_slot(buf));
}
static void _S_X2CH_BUILD_UPGRADE_CHECK_RESULT_WritePacket(S_X2CH_BUILD_UPGRADE_CHECK_RESULT* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2CH_BUILD_UPGRADE_CHECK_RESULT(sendBuf,*pThis));
}
static void _S_X2CH_BUILD_UPGRADE_CHECK_RESULT_WriteToPacket(S_X2CH_BUILD_UPGRADE_CHECK_RESULT* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2CH_BUILD_UPGRADE_CHECK_RESULT(sendBuf,*pThis));
}
void call_sq_X2CH_BUILD_UPGRADE_CHECK_RESULT(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2CH_BUILD_UPGRADE_CHECK_RESULT param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2CH_BUILD_UPGRADE_CHECK_RESULT"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_X2CH_BUILD_UPGRADE_CHECK_RESULT , get_build_slot)(S_X2CH_BUILD_UPGRADE_CHECK_RESULT* pThis)
{
fname_t buf;return (pThis->get_build_slot(buf));
}
static void _S_CH_ERROR_WritePacket(S_CH_ERROR* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH_ERROR(sendBuf,*pThis));
}
static void _S_CH_ERROR_WriteToPacket(S_CH_ERROR* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH_ERROR(sendBuf,*pThis));
}
void call_sq_CH_ERROR(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH_ERROR param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH_ERROR"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH_HELLO_WritePacket(S_CH_HELLO* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH_HELLO(sendBuf,*pThis));
}
static void _S_CH_HELLO_WriteToPacket(S_CH_HELLO* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH_HELLO(sendBuf,*pThis));
}
void call_sq_CH_HELLO(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH_HELLO param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH_HELLO"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_T2X_NOTICE_WritePacket(S_T2X_NOTICE* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_T2X_NOTICE(sendBuf,*pThis));
}
static void _S_T2X_NOTICE_WriteToPacket(S_T2X_NOTICE* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_T2X_NOTICE(sendBuf,*pThis));
}
void call_sq_T2X_NOTICE(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_T2X_NOTICE param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_T2X_NOTICE"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
jSQ_gfn_DEF2(SquirrelObject, S_T2X_NOTICE , get_msg)(S_T2X_NOTICE* pThis)
{
fname_t buf;return (pThis->get_msg(buf));
}
jSQ_gfn_DEF2(SquirrelObject, S_T2X_NOTICE , get_date)(S_T2X_NOTICE* pThis)
{
fname_t buf;return (pThis->get_date(buf));
}
static void _S_X2L_NOTICE_TEST_WritePacket(S_X2L_NOTICE_TEST* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_X2L_NOTICE_TEST(sendBuf,*pThis));
}
static void _S_X2L_NOTICE_TEST_WriteToPacket(S_X2L_NOTICE_TEST* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_X2L_NOTICE_TEST(sendBuf,*pThis));
}
void call_sq_X2L_NOTICE_TEST(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_X2L_NOTICE_TEST param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_X2L_NOTICE_TEST"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_USER_LOGIN_CHANNEL_OK_WritePacket(S_CH2X_USER_LOGIN_CHANNEL_OK* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_USER_LOGIN_CHANNEL_OK(sendBuf,*pThis));
}
static void _S_CH2X_USER_LOGIN_CHANNEL_OK_WriteToPacket(S_CH2X_USER_LOGIN_CHANNEL_OK* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_USER_LOGIN_CHANNEL_OK(sendBuf,*pThis));
}
void call_sq_CH2X_USER_LOGIN_CHANNEL_OK(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_USER_LOGIN_CHANNEL_OK param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_USER_LOGIN_CHANNEL_OK"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_USER_LOGIN_CHANNEL_OK2_WritePacket(S_CH2X_USER_LOGIN_CHANNEL_OK2* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_USER_LOGIN_CHANNEL_OK2(sendBuf,*pThis));
}
static void _S_CH2X_USER_LOGIN_CHANNEL_OK2_WriteToPacket(S_CH2X_USER_LOGIN_CHANNEL_OK2* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_USER_LOGIN_CHANNEL_OK2(sendBuf,*pThis));
}
void call_sq_CH2X_USER_LOGIN_CHANNEL_OK2(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_USER_LOGIN_CHANNEL_OK2 param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_USER_LOGIN_CHANNEL_OK2"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
static void _S_CH2X_USER_LOGIN_CHANNEL_OK3_WritePacket(S_CH2X_USER_LOGIN_CHANNEL_OK3* pThis, jIPacketSocket_IOCP* pS)
{
nswb1024_t sendBuf; pS->WritePacket(&WRITE_CH2X_USER_LOGIN_CHANNEL_OK3(sendBuf,*pThis));
}
static void _S_CH2X_USER_LOGIN_CHANNEL_OK3_WriteToPacket(S_CH2X_USER_LOGIN_CHANNEL_OK3* pThis, jIPacketSocket_IOCP* pS,jIP_Address* pIP)
{
nswb1024_t sendBuf; pS->WriteToPacket(pIP,&WRITE_CH2X_USER_LOGIN_CHANNEL_OK3(sendBuf,*pThis));
}
void call_sq_CH2X_USER_LOGIN_CHANNEL_OK3(void* v,jIPacketSocket_IOCP*pS,jPacket_Base* pk,jIP_Address* pIP)
{
SquirrelObject* pO = (SquirrelObject*)v;
S_CH2X_USER_LOGIN_CHANNEL_OK3 param;
SquirrelFunction<void> func(*pO,_T("jNET_EVENT_CH2X_USER_LOGIN_CHANNEL_OK3"));
if(!func.func.IsNull()) func(pS,pk,pIP,¶m);
}
#endif //ChannelServer_jNOTUSE_SQ_CODE
jONCE_RUN_CTOR(__ChannelServer__)
{
static jNamedEventTable_impl phtl;
phtl.Insert(CH_ECHO,jS(CH_ECHO),0);
phtl.Insert(X2CH_CHAT,jS(X2CH_CHAT),0);
phtl.Insert(CH2X_CHAT,jS(CH2X_CHAT),0);
phtl.Insert(X2CH_USER_LOGIN_CHANNEL,jS(X2CH_USER_LOGIN_CHANNEL),0);
phtl.Insert(CH2X_NEW_TOWN_OK,jS(CH2X_NEW_TOWN_OK),0);
phtl.Insert(X2CH_NEW_TOWN,jS(X2CH_NEW_TOWN),0);
phtl.Insert(CH2X_SELECT_CASTLE,jS(CH2X_SELECT_CASTLE),0);
phtl.Insert(X2CH_TOWN_SELECT,jS(X2CH_TOWN_SELECT),0);
phtl.Insert(X2CH_TOWN_DELETE,jS(X2CH_TOWN_DELETE),0);
phtl.Insert(CH2X_TOWN_DELETE_OK,jS(CH2X_TOWN_DELETE_OK),0);
phtl.Insert(CH2X_TOWN_SELECT_RESULT,jS(CH2X_TOWN_SELECT_RESULT),0);
phtl.Insert(CH2X_CREATE_NEW_TOWN,jS(CH2X_CREATE_NEW_TOWN),0);
phtl.Insert(X2CH_USER_EXIT,jS(X2CH_USER_EXIT),0);
phtl.Insert(CH2X_USER_EXIT,jS(CH2X_USER_EXIT),0);
phtl.Insert(X2CH_GOTO_CASTLE_MAP,jS(X2CH_GOTO_CASTLE_MAP),0);
phtl.Insert(CH2X_GOTO_CASTLE_MAP,jS(CH2X_GOTO_CASTLE_MAP),0);
phtl.Insert(X2CH_GOTO_WORLD_MAP,jS(X2CH_GOTO_WORLD_MAP),0);
phtl.Insert(CH2X_GOTO_WORLD_MAP,jS(CH2X_GOTO_WORLD_MAP),0);
phtl.Insert(CH2X_UPDATE_CASTLE_MAP,jS(CH2X_UPDATE_CASTLE_MAP),0);
phtl.Insert(CH2X_UDPATE_WORLD_MAP,jS(CH2X_UDPATE_WORLD_MAP),0);
phtl.Insert(X2CH_GOTO_TOWN_MAP,jS(X2CH_GOTO_TOWN_MAP),0);
phtl.Insert(CH2X_GOTO_TOWN_MAP,jS(CH2X_GOTO_TOWN_MAP),0);
phtl.Insert(X2CH_NEW_BUILD,jS(X2CH_NEW_BUILD),0);
phtl.Insert(X2CH_BUILD_UPGRADE,jS(X2CH_BUILD_UPGRADE),0);
phtl.Insert(CH2X_BUILD_UPGRADE_RESULT,jS(CH2X_BUILD_UPGRADE_RESULT),0);
phtl.Insert(X2CH_BUILD_UPGRADE_CANCLE,jS(X2CH_BUILD_UPGRADE_CANCLE),0);
phtl.Insert(X2CH_BUILD_UPGRADE_CANCLE_OK,jS(X2CH_BUILD_UPGRADE_CANCLE_OK),0);
phtl.Insert(X2CH_BUILD_UPGRADE_CHECK,jS(X2CH_BUILD_UPGRADE_CHECK),0);
phtl.Insert(X2CH_BUILD_UPGRADE_CHECK_RESULT,jS(X2CH_BUILD_UPGRADE_CHECK_RESULT),0);
phtl.Insert(CH_ERROR,jS(CH_ERROR),0);
phtl.Insert(CH_HELLO,jS(CH_HELLO),0);
phtl.Insert(T2X_NOTICE,jS(T2X_NOTICE),0);
phtl.Insert(X2L_NOTICE_TEST,jS(X2L_NOTICE_TEST),0);
phtl.Insert(CH2X_USER_LOGIN_CHANNEL_OK,jS(CH2X_USER_LOGIN_CHANNEL_OK),0);
phtl.Insert(CH2X_USER_LOGIN_CHANNEL_OK2,jS(CH2X_USER_LOGIN_CHANNEL_OK2),0);
phtl.Insert(CH2X_USER_LOGIN_CHANNEL_OK3,jS(CH2X_USER_LOGIN_CHANNEL_OK3),0);
g_pPlugInHelpTableList = &phtl;
nMech::jBase::RegistNamedPointer(_T("nNET"),_T("ChannelServer"),g_pPlugInHelpTableList);
jRAISE_PACKET(pk_CH_ECHO == CH_ECHO);
jRAISE_PACKET(pk_X2CH_CHAT == X2CH_CHAT);
jRAISE_PACKET(pk_CH2X_CHAT == CH2X_CHAT);
jRAISE_PACKET(pk_X2CH_USER_LOGIN_CHANNEL == X2CH_USER_LOGIN_CHANNEL);
jRAISE_PACKET(pk_CH2X_NEW_TOWN_OK == CH2X_NEW_TOWN_OK);
jRAISE_PACKET(pk_X2CH_NEW_TOWN == X2CH_NEW_TOWN);
jRAISE_PACKET(pk_CH2X_SELECT_CASTLE == CH2X_SELECT_CASTLE);
jRAISE_PACKET(pk_X2CH_TOWN_SELECT == X2CH_TOWN_SELECT);
jRAISE_PACKET(pk_X2CH_TOWN_DELETE == X2CH_TOWN_DELETE);
jRAISE_PACKET(pk_CH2X_TOWN_DELETE_OK == CH2X_TOWN_DELETE_OK);
jRAISE_PACKET(pk_CH2X_TOWN_SELECT_RESULT == CH2X_TOWN_SELECT_RESULT);
jRAISE_PACKET(pk_CH2X_CREATE_NEW_TOWN == CH2X_CREATE_NEW_TOWN);
jRAISE_PACKET(pk_X2CH_USER_EXIT == X2CH_USER_EXIT);
jRAISE_PACKET(pk_CH2X_USER_EXIT == CH2X_USER_EXIT);
jRAISE_PACKET(pk_X2CH_GOTO_CASTLE_MAP == X2CH_GOTO_CASTLE_MAP);
jRAISE_PACKET(pk_CH2X_GOTO_CASTLE_MAP == CH2X_GOTO_CASTLE_MAP);
jRAISE_PACKET(pk_X2CH_GOTO_WORLD_MAP == X2CH_GOTO_WORLD_MAP);
jRAISE_PACKET(pk_CH2X_GOTO_WORLD_MAP == CH2X_GOTO_WORLD_MAP);
jRAISE_PACKET(pk_CH2X_UPDATE_CASTLE_MAP == CH2X_UPDATE_CASTLE_MAP);
jRAISE_PACKET(pk_CH2X_UDPATE_WORLD_MAP == CH2X_UDPATE_WORLD_MAP);
jRAISE_PACKET(pk_X2CH_GOTO_TOWN_MAP == X2CH_GOTO_TOWN_MAP);
jRAISE_PACKET(pk_CH2X_GOTO_TOWN_MAP == CH2X_GOTO_TOWN_MAP);
jRAISE_PACKET(pk_X2CH_NEW_BUILD == X2CH_NEW_BUILD);
jRAISE_PACKET(pk_X2CH_BUILD_UPGRADE == X2CH_BUILD_UPGRADE);
jRAISE_PACKET(pk_CH2X_BUILD_UPGRADE_RESULT == CH2X_BUILD_UPGRADE_RESULT);
jRAISE_PACKET(pk_X2CH_BUILD_UPGRADE_CANCLE == X2CH_BUILD_UPGRADE_CANCLE);
jRAISE_PACKET(pk_X2CH_BUILD_UPGRADE_CANCLE_OK == X2CH_BUILD_UPGRADE_CANCLE_OK);
jRAISE_PACKET(pk_X2CH_BUILD_UPGRADE_CHECK == X2CH_BUILD_UPGRADE_CHECK);
jRAISE_PACKET(pk_X2CH_BUILD_UPGRADE_CHECK_RESULT == X2CH_BUILD_UPGRADE_CHECK_RESULT);
jRAISE_PACKET(pk_CH_ERROR == CH_ERROR);
jRAISE_PACKET(pk_CH_HELLO == CH_HELLO);
jRAISE_PACKET(pk_T2X_NOTICE == T2X_NOTICE);
jRAISE_PACKET(pk_X2L_NOTICE_TEST == X2L_NOTICE_TEST);
jRAISE_PACKET(pk_CH2X_USER_LOGIN_CHANNEL_OK == CH2X_USER_LOGIN_CHANNEL_OK);
jRAISE_PACKET(pk_CH2X_USER_LOGIN_CHANNEL_OK2 == CH2X_USER_LOGIN_CHANNEL_OK2);
jRAISE_PACKET(pk_CH2X_USER_LOGIN_CHANNEL_OK3 == CH2X_USER_LOGIN_CHANNEL_OK3);
#ifndef ChannelServer_jNOTUSE_SQ_CODE
jSQ_Class(S_CH_ECHO)
jSQ_gfn(S_CH_ECHO,get_msg, "","return net_string")
jSQ_fn(set_msg,"tcstr sz","")
jSQ_var(type,"uint8")
jSQ_gfn(S_CH_ECHO,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH_ECHO,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_CHAT)
jSQ_gfn(S_X2CH_CHAT,get_msg, "","return net_string")
jSQ_fn(set_msg,"tcstr sz","")
jSQ_var(type,"uint8")
jSQ_fn(get_id,"int i","return wstring*")
jSQ_fn(set_id,"int i,wstring* data","")
jSQ_fn(insert_id,"wstring* data","")
jSQ_fn(clear_id,"","")
jSQ_fn(size_id,"","return size_t")
jSQ_fn(get_pid,"int i","return player_id_t*")
jSQ_fn(set_pid,"int i,player_id_t* data","")
jSQ_fn(insert_pid,"player_id_t* data","")
jSQ_fn(clear_pid,"","")
jSQ_fn(size_pid,"","return size_t")
jSQ_gfn(S_X2CH_CHAT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_CHAT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_CHAT)
jSQ_gfn(S_CH2X_CHAT,get_msg, "","return net_string")
jSQ_fn(set_msg,"tcstr sz","")
jSQ_var(type,"uint8")
jSQ_gfn(S_CH2X_CHAT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_CHAT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_USER_LOGIN_CHANNEL)
jSQ_var(pid,"player_id_t")
jSQ_gfn(S_X2CH_USER_LOGIN_CHANNEL,get_id, "","return net_string")
jSQ_fn(set_id,"tcstr sz","")
jSQ_gfn(S_X2CH_USER_LOGIN_CHANNEL,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_USER_LOGIN_CHANNEL,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_NEW_TOWN_OK)
jSQ_var(index,"channelid_t")
jSQ_var(town,"Use_Town")
jSQ_gfn(S_CH2X_NEW_TOWN_OK,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_NEW_TOWN_OK,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_NEW_TOWN)
jSQ_var(csid,"Sys_Castle_id_t")
jSQ_var(tpsid,"Sys_TownPos_id_t")
jSQ_gfn(S_X2CH_NEW_TOWN,get_name, "","return net_string")
jSQ_fn(set_name,"tcstr sz","")
jSQ_gfn(S_X2CH_NEW_TOWN,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_NEW_TOWN,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_SELECT_CASTLE)
jSQ_gfn(S_CH2X_SELECT_CASTLE,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_SELECT_CASTLE,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_TOWN_SELECT)
jSQ_var(index,"channelid_t")
jSQ_gfn(S_X2CH_TOWN_SELECT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_TOWN_SELECT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_TOWN_DELETE)
jSQ_var(index,"channelid_t")
jSQ_gfn(S_X2CH_TOWN_DELETE,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_TOWN_DELETE,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_TOWN_DELETE_OK)
jSQ_var(index,"channelid_t")
jSQ_gfn(S_CH2X_TOWN_DELETE_OK,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_TOWN_DELETE_OK,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_TOWN_SELECT_RESULT)
jSQ_var(channelNo,"channelid_t")
jSQ_var(e,"jError")
jSQ_gfn(S_CH2X_TOWN_SELECT_RESULT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_TOWN_SELECT_RESULT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_CREATE_NEW_TOWN)
jSQ_gfn(S_CH2X_CREATE_NEW_TOWN,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_CREATE_NEW_TOWN,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_USER_EXIT)
jSQ_gfn(S_X2CH_USER_EXIT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_USER_EXIT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_USER_EXIT)
jSQ_gfn(S_CH2X_USER_EXIT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_USER_EXIT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_GOTO_CASTLE_MAP)
jSQ_var(channelNo,"uint8")
jSQ_gfn(S_X2CH_GOTO_CASTLE_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_GOTO_CASTLE_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_GOTO_CASTLE_MAP)
jSQ_var(channelNo,"uint8")
jSQ_var(castle_map_info,"jIE*")
jSQ_gfn(S_CH2X_GOTO_CASTLE_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_GOTO_CASTLE_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_GOTO_WORLD_MAP)
jSQ_var(channelNo,"uint8")
jSQ_gfn(S_X2CH_GOTO_WORLD_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_GOTO_WORLD_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_GOTO_WORLD_MAP)
jSQ_var(channelNo,"uint8")
jSQ_var(world_map_info,"jIE*")
jSQ_gfn(S_CH2X_GOTO_WORLD_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_GOTO_WORLD_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_UPDATE_CASTLE_MAP)
jSQ_var(castle_map_info,"jIE*")
jSQ_gfn(S_CH2X_UPDATE_CASTLE_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_UPDATE_CASTLE_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_UDPATE_WORLD_MAP)
jSQ_var(world_map_info,"jIE*")
jSQ_gfn(S_CH2X_UDPATE_WORLD_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_UDPATE_WORLD_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_GOTO_TOWN_MAP)
jSQ_var(channelNo,"uint8")
jSQ_gfn(S_X2CH_GOTO_TOWN_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_GOTO_TOWN_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_GOTO_TOWN_MAP)
jSQ_var(channelNo,"uint8")
jSQ_gfn(S_CH2X_GOTO_TOWN_MAP,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_GOTO_TOWN_MAP,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_NEW_BUILD)
jSQ_gfn(S_X2CH_NEW_BUILD,get_build_slot, "","return net_string")
jSQ_fn(set_build_slot,"tcstr sz","")
jSQ_var(_EBuildType,"uint8")
jSQ_var(hero_id,"uint8")
jSQ_gfn(S_X2CH_NEW_BUILD,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_NEW_BUILD,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_BUILD_UPGRADE)
jSQ_gfn(S_X2CH_BUILD_UPGRADE,get_build_slot, "","return net_string")
jSQ_fn(set_build_slot,"tcstr sz","")
jSQ_var(hero_id,"uint8")
jSQ_gfn(S_X2CH_BUILD_UPGRADE,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_BUILD_UPGRADE_RESULT)
jSQ_gfn(S_CH2X_BUILD_UPGRADE_RESULT,get_build_slot, "","return net_string")
jSQ_fn(set_build_slot,"tcstr sz","")
jSQ_var(_EBuildType,"uint8")
jSQ_var(level,"uint8")
jSQ_var(e,"jError")
jSQ_var(curr_server_time,"j_time_t")
jSQ_var(upgrade_sec,"int32")
jSQ_var(hero_id,"uint8")
jSQ_gfn(S_CH2X_BUILD_UPGRADE_RESULT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_BUILD_UPGRADE_RESULT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_BUILD_UPGRADE_CANCLE)
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CANCLE,get_build_slot, "","return net_string")
jSQ_fn(set_build_slot,"tcstr sz","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CANCLE,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CANCLE,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_BUILD_UPGRADE_CANCLE_OK)
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CANCLE_OK,get_build_slot, "","return net_string")
jSQ_fn(set_build_slot,"tcstr sz","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CANCLE_OK,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CANCLE_OK,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_BUILD_UPGRADE_CHECK)
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CHECK,get_build_slot, "","return net_string")
jSQ_fn(set_build_slot,"tcstr sz","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CHECK,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CHECK,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2CH_BUILD_UPGRADE_CHECK_RESULT)
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CHECK_RESULT,get_build_slot, "","return net_string")
jSQ_fn(set_build_slot,"tcstr sz","")
jSQ_var(e,"jError")
jSQ_var(left_sec,"int32")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CHECK_RESULT,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2CH_BUILD_UPGRADE_CHECK_RESULT,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH_ERROR)
jSQ_var(ei,"jErrorInfo")
jSQ_gfn(S_CH_ERROR,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH_ERROR,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH_HELLO)
jSQ_var(si,"jServerInfo")
jSQ_gfn(S_CH_HELLO,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH_HELLO,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_T2X_NOTICE)
jSQ_var(info,"jNoticeInfo")
jSQ_gfn(S_T2X_NOTICE,get_msg, "","return net_string")
jSQ_fn(set_msg,"tcstr sz","")
jSQ_gfn(S_T2X_NOTICE,get_date, "","return net_string")
jSQ_fn(set_date,"tcstr sz","")
jSQ_gfn(S_T2X_NOTICE,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_T2X_NOTICE,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_X2L_NOTICE_TEST)
jSQ_gfn(S_X2L_NOTICE_TEST,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_X2L_NOTICE_TEST,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_USER_LOGIN_CHANNEL_OK)
jSQ_var(user,"nAQ::Use_User")
jSQ_fn(get_town,"int i","return nAQ::Use_Town*")
jSQ_fn(set_town,"int i,nAQ::Use_Town* data","")
jSQ_fn(insert_town,"nAQ::Use_Town* data","")
jSQ_fn(clear_town,"","")
jSQ_fn(size_town,"","return size_t")
jSQ_gfn(S_CH2X_USER_LOGIN_CHANNEL_OK,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_USER_LOGIN_CHANNEL_OK,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_USER_LOGIN_CHANNEL_OK2)
jSQ_fn(get_hero,"int i","return nAQ::Use_Hero*")
jSQ_fn(set_hero,"int i,nAQ::Use_Hero* data","")
jSQ_fn(insert_hero,"nAQ::Use_Hero* data","")
jSQ_fn(clear_hero,"","")
jSQ_fn(size_hero,"","return size_t")
jSQ_fn(get_force,"int i","return nAQ::Use_Force*")
jSQ_fn(set_force,"int i,nAQ::Use_Force* data","")
jSQ_fn(insert_force,"nAQ::Use_Force* data","")
jSQ_fn(clear_force,"","")
jSQ_fn(size_force,"","return size_t")
jSQ_gfn(S_CH2X_USER_LOGIN_CHANNEL_OK2,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_USER_LOGIN_CHANNEL_OK2,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
jSQ_Class(S_CH2X_USER_LOGIN_CHANNEL_OK3)
jSQ_var(town_xml,"jIE*")
jSQ_var(server_time,"j_time_t")
jSQ_gfn(S_CH2X_USER_LOGIN_CHANNEL_OK3,WritePacket,"jIPacketSocket_IOCP* pS","")
jSQ_gfn(S_CH2X_USER_LOGIN_CHANNEL_OK3,WriteToPacket,"jIPacketSocket_IOCP* pS,jIP_Address *pIP","")
jSQ_fn(ReadPacket,"jIPacketSocket_IOCP* pS,jPacket_Base* pk","")
jSQ_fn(DebugPrint,"bool isPrintAll","")
jSQ_end();
#endif //ChannelServer_jNOTUSE_SQ_CODE
}
jONCE_RUN_DTOR(__ChannelServer__)
{
nMech::jBase::UnRegistNamedPointer(_T("nNET"),_T("ChannelServer"));
}
}/* nChannelServer */ }/*nNET*/ } //nMech
#ifndef ChannelServer_jNOT_USE_PACKET_PLUGIN_HELP
jxDEFINE_ChannelServer(ChannelServer);
jxDEFINE_ChannelServer(CH_ECHO);
jxDEFINE_ChannelServer(X2CH_CHAT);
jxDEFINE_ChannelServer(CH2X_CHAT);
jxDEFINE_ChannelServer(X2CH_USER_LOGIN_CHANNEL);
jxDEFINE_ChannelServer(CH2X_NEW_TOWN_OK);
jxDEFINE_ChannelServer(X2CH_NEW_TOWN);
jxDEFINE_ChannelServer(CH2X_SELECT_CASTLE);
jxDEFINE_ChannelServer(X2CH_TOWN_SELECT);
jxDEFINE_ChannelServer(X2CH_TOWN_DELETE);
jxDEFINE_ChannelServer(CH2X_TOWN_DELETE_OK);
jxDEFINE_ChannelServer(CH2X_TOWN_SELECT_RESULT);
jxDEFINE_ChannelServer(CH2X_CREATE_NEW_TOWN);
jxDEFINE_ChannelServer(X2CH_USER_EXIT);
jxDEFINE_ChannelServer(CH2X_USER_EXIT);
jxDEFINE_ChannelServer(X2CH_GOTO_CASTLE_MAP);
jxDEFINE_ChannelServer(CH2X_GOTO_CASTLE_MAP);
jxDEFINE_ChannelServer(X2CH_GOTO_WORLD_MAP);
jxDEFINE_ChannelServer(CH2X_GOTO_WORLD_MAP);
jxDEFINE_ChannelServer(CH2X_UPDATE_CASTLE_MAP);
jxDEFINE_ChannelServer(CH2X_UDPATE_WORLD_MAP);
jxDEFINE_ChannelServer(X2CH_GOTO_TOWN_MAP);
jxDEFINE_ChannelServer(CH2X_GOTO_TOWN_MAP);
jxDEFINE_ChannelServer(X2CH_NEW_BUILD);
jxDEFINE_ChannelServer(X2CH_BUILD_UPGRADE);
jxDEFINE_ChannelServer(CH2X_BUILD_UPGRADE_RESULT);
jxDEFINE_ChannelServer(X2CH_BUILD_UPGRADE_CANCLE);
jxDEFINE_ChannelServer(X2CH_BUILD_UPGRADE_CANCLE_OK);
jxDEFINE_ChannelServer(X2CH_BUILD_UPGRADE_CHECK);
jxDEFINE_ChannelServer(X2CH_BUILD_UPGRADE_CHECK_RESULT);
jxDEFINE_ChannelServer(CH_ERROR);
jxDEFINE_ChannelServer(CH_HELLO);
jxDEFINE_ChannelServer(T2X_NOTICE);
jxDEFINE_ChannelServer(X2L_NOTICE_TEST);
jxDEFINE_ChannelServer(CH2X_USER_LOGIN_CHANNEL_OK);
jxDEFINE_ChannelServer(CH2X_USER_LOGIN_CHANNEL_OK2);
jxDEFINE_ChannelServer(CH2X_USER_LOGIN_CHANNEL_OK3);
#endif // ChannelServer_jNOT_USE_PACKET_PLUGIN_HELP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.