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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5c40a3b6e312a49db5ad54fdc54c531465d67541 | 4ab030516baab368419e64c8a5452d02d72daeb8 | /example/calculator/main.cpp | 8af8feab9a88757aef07602029574a417847f794 | [] | no_license | Leopard-C/ExpressionEvaluator | 0e3cd78a570a624a47fb9b621ca34e6080b9ff41 | bef8e57d2588e04dff10d590a608234486c68711 | refs/heads/master | 2021-05-23T08:19:06.117190 | 2020-04-05T09:17:13 | 2020-04-05T09:17:13 | 253,194,541 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,345 | cpp | main.cpp | #include "../../ExpressionEvaluator.h"
#include <unistd.h>
#include <getopt.h>
#include <iostream>
#include <iomanip>
#include <cstring>
void run();
int main(int argc, char** argv) {
if (argc == 1) {
run();
return 0;
}
else if (argc == 2) {
ExpressionEvaluator expEv;
double result = expEv.eval(argv[1]);
if (expEv.getLastError() == EXPEV_NO_ERROR) {
std::cout << result << std::endl;
}
else {
std::cout << expEv.getErrorDesc() << std::endl;
return 1;
}
}
else {
std::cout << "Too many parameters" << std::endl;
return 1;
}
return 0;
}
void run() {
ExpressionEvaluator expEv;
std::cout << std::setprecision(13);
while (1) {
// Prompt
std::cout << ">>> ";
std::cout.flush();
// Get input
char str[512];
std::cin.getline(str, 512);
if (strcmp(str, "exit") == 0 || strcmp(str, "quit") == 0 ||
strcmp(str, "q") == 0) {
break;
}
// Calculate
double result = expEv.eval(str);
if (expEv.getLastError() == EXPEV_NO_ERROR) {
std::cout << result << std::endl;
}
else {
std::cout << expEv.getErrorDesc() << std::endl;
}
}
}
|
76200d71b702b28122e6184726f19de3458acdef | abced4f3967faf64cc21cf8f6d4392464e1be734 | /protobuf/protobuf_test.h | 44bd2a45099f7ba920aeaecbb99bf0ff6a1d2700 | [] | no_license | gmlyytt-YANG/cxx_grammar | ad9f5cd05ea7d775135a0b4f4be99bbb1f519ba6 | 9b18551b6a3650264b1431d19f13351579a9bb42 | refs/heads/master | 2020-06-19T18:07:18.236590 | 2019-11-17T12:32:16 | 2019-11-17T12:32:16 | 196,814,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | h | protobuf_test.h | /*************************************************************************
*
* Copyright (c) 2019 liyang. All Rights Reserved
*
************************************************************************/
/*
* @file protobuf_test.h
* @author gmlyytt@outlook.com
* @date 2019-07-21
* @brief
* */
#ifndef SELF_PROTOBUF_TEST_H
#define SELF_PROTOBUF_TEST_H
#include "../header.h"
#include "person.pb.h"
/**
* @brief proto的常规操作, 包括定义proto, set和get成员
* @param
* @return
*/
void test_protobuf() {
tutorial::AddressBook address_book;
tutorial::Person* bob = address_book.add_people();
bob->set_id(2);
std::cout << bob->id() << std::endl;
}
#endif //SELF_PROTOBUF_TEST_H
|
a2e45a248ab3c9fe9298a04b0eebae751d1f88f7 | 63fadaa93caca22ca6b6546584243daf24e0e3fd | /sangwon/ch29_BFS/29-5.cpp | 5576b5982f919e48b6c06bdbabbea2f2605b6de1 | [] | no_license | snulion-study/algorithm-int | 60e69f58d0a94560798881ef98bd7a434c472733 | 7ac1cefe7b1e77b5ade9a28f302b5db0bb67a427 | refs/heads/master | 2023-03-14T09:52:47.139136 | 2021-02-27T05:13:02 | 2021-02-27T05:13:02 | 293,447,189 | 0 | 5 | null | 2021-02-27T05:13:03 | 2020-09-07T06:57:35 | C++ | UTF-8 | C++ | false | false | 20 | cpp | 29-5.cpp | // 어린이날 pass |
68ed704534145e972c49cc5adab3bbd6a0fa05a0 | fce4a30a8b4a7967bc57d94e25258319c4a40121 | /Practica1 c++/PersonaMascota/Persona/Mascota.cpp | 02a90199e25750b5d2cc29da23d38db709716949 | [] | no_license | jcvincenti/Estructuras-de-datos | 8b4cae3cbb2e7e6b37b493a1f1233e44381b4571 | 8f03da4ff519d837b51fe95766a1f28d0b4f7ee0 | refs/heads/main | 2023-04-14T15:32:27.424124 | 2021-04-28T02:29:15 | 2021-04-28T02:29:15 | 362,313,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | Mascota.cpp | #include "Mascota.h"
struct MascotaSt {
string nombre;
string especie;
};
Mascota crearM(string nombre, string especie) {
MascotaSt* m = new MascotaSt;
m->nombre = nombre;
m->especie = especie;
return m;
}
string getNombre(Mascota m) {
return m->nombre;
}
void cambiarNombre(string nombre, Mascota& m) {
m->nombre = nombre;
}
void destruir(Mascota& m) {
delete m;
}
|
4313840af6bcf357bb1e6eeebd8172a74446c9ba | e62458a3b66b818511eecff600aec7e40bc9da6b | /GhostHouse/GhostHouse/SourceCode/Object/Gimmick/BookShelf/BookShelf.h | 3cac739e1c5986c97f1d1c8846b1861c6fc24c6d | [] | no_license | OTakotiri/GhostHouse | 273e55e138ff15b519f79600ebe41befcfe92f43 | b8c4dc358a40960c709f5f2b2830475644f521e6 | refs/heads/master | 2021-01-01T13:53:26.019850 | 2020-02-13T16:52:44 | 2020-02-13T16:52:44 | 239,307,602 | 0 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,176 | h | BookShelf.h | #ifndef BOOK_SHELF_H
#define BOOK_SHELF_H
#include "..\..\..\ObjectBase\GimmickBase\GimmickBase.h"
class CBookShelf : public CGimmickBase
{
const char* MAIN_MODEL_NAME = "BookShelf"; // 仕様モデル名.
const float MODEL_SCALE = 0.08f;
const float SPHERE_COLLISION_RADIUS = 1.0f; // 当たり判定用の半径の大きさ.
const float MOVE_POWER = 2.0f;
public:
CBookShelf(const stObjectInfo& objInfo);
~CBookShelf();
// 更新関数.
virtual void Update(shared_ptr<CObjectBase> pObj) override;
// 描画関数.
virtual void Render(D3DXMATRIX& mView, D3DXMATRIX& mProj,
Light& stLight, stCAMERA& stCamera) override;
// 当たり判定用関数.
virtual void Collision(shared_ptr<CObjectBase> pObj) override;
virtual void Load(ID3D11Device* pDevice11, ID3D11DeviceContext* pContext11) override;
virtual LPD3DXMESH GetMeshData() override;
private:
CBookShelf() {};
// 動作関数.
virtual void Action(shared_ptr<CObjectBase> pObj) override;
void AxisMove();
void FadeInOut();
private:
shared_ptr<CDX9Mesh> m_pStaticMesh;
float m_fCount;
bool m_bFadeInFlag;
bool m_isMoveing;
D3DXVECTOR3 m_PlayerPosition;
};
#endif // #ifndef BOOK_SHELF_H. |
3cfa8b288c851600a9dd7e94bd8d8d9c0390ab9f | 95450959948d7d2e301d960ea6bda47f31a16130 | /ctp2_code/robotcom/fuzzy/FliAction.cpp | 269daa79eabfc341db89054b22791d4d42e04239 | [] | no_license | ptitSeb/ctp2 | 88de6f9be54b97bf9cf4358dc1c14dc6f8d20eb2 | ac46e601b94fad8162677b964ff87a2e07923c9e | refs/heads/master | 2021-05-16T13:49:17.280404 | 2020-09-17T19:09:48 | 2020-09-17T19:09:48 | 105,444,215 | 31 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,756 | cpp | FliAction.cpp | #include "c3.h"
#include "fliif.h"
#include "globals.h"
#include "ic3player.h"
#include "FliAction.h"
#include "globals.h"
#include "aimain.h"
#include "FliEngine.h"
#include "pointerlist.h"
#include "FliSymbol.h"
#include "common.h"
#include "linked_list.h"
#include "semi_dynamic_array.h"
#include "sorted_array.h"
#include "planner.h"
#include "AIP_Manager.h"
extern AIP_Manager * g_AIP_manager;
FliAction::FliAction(const char *name, FliEngine *engine)
{
m_engine = engine;
if(!stricmp(name, "load")) {
m_action = FLI_ACTION_LOAD_AIP;
} else {
m_engine->ReportError("FliAction: %s is an unknown action", name);
}
m_arguments = new PointerList<char>;
}
FliAction::~FliAction()
{
#ifdef _DEBUG
sint32 finite_loop=0;
#endif
if(m_arguments) {
char *str;
while((str = m_arguments->RemoveHead()) != NULL) {
Assert(++finite_loop < 100000);
delete [] str;
str = NULL;
}
delete m_arguments;
m_arguments = NULL;
}
}
void FliAction::AddArgument(const char *str)
{
char *arg = new char[strlen(str) + 1];
strcpy(arg, str);
m_arguments->AddTail(arg);
}
void FliAction::SetBoolExp(FliSymbol *sym, BFLOP_TYPE op, double value)
{
m_symbol = sym;
m_op = op;
m_value = value;
}
void FliAction::Evaluate(AiMain *ai)
{
switch(m_op) {
case BFLOP_LT:
if(m_symbol->GetValue() < m_value)
Execute(ai);
break;
case BFLOP_GT:
if(m_symbol->GetValue() > m_value)
Execute(ai);
break;
case BFLOP_EQ:
if(m_symbol->GetValue() == m_value)
Execute(ai);
break;
}
}
void FliAction::Execute(AiMain *ai)
{
switch(m_action) {
case FLI_ACTION_LOAD_AIP:
g_AIP_manager->Update_AIP(ai, &(ai->m_planner->the_AIP), m_arguments->GetHead());
break;
default:
Assert(FALSE);
break;
}
}
|
b16cc88057dc2ec4a35c696e5b8604f0b50e0e9c | 216666b411f104e18602464e967a9b4f76890293 | /Array/Find_Duplicate-using_Hashing.cpp | a0990d2b94f6e108de34a9d8f27687417001e45c | [] | no_license | dhiman-007/DSA | b98f2f57c6b0ca9c6cd452ca96f6c84df5c97ba5 | 097b1ea3c7c1c2a82b32157e5699904c4a00158b | refs/heads/master | 2022-11-26T19:25:20.434817 | 2020-08-03T05:41:13 | 2020-08-03T05:41:13 | 283,533,711 | 1 | 0 | null | 2020-07-29T15:20:09 | 2020-07-29T15:20:08 | null | UTF-8 | C++ | false | false | 550 | cpp | Find_Duplicate-using_Hashing.cpp | #include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
int p;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
p = *max_element(a,a+n); // this is use to calculate maximum from an array i.e using STL
int H[p]; // size of array is the maximum element in array B
for(int i=0;i<n;i++)
{
H[i]=0; // the value of all index is 0
}
for(int i=0;i<n;i++)
{
H[a[i]]++; // use hashing
}
for(int i=0;i<=p;i++)
{
if(H[i]>1)
{
cout<<i<<" "<<H[i]<<"times"<<"\n";
}
}
}
|
6c9447a33b5cf100edbd36b4c84835f9107f7941 | dc5fa623bf004f37d759384921220eb9e2b3482b | /sketch_jun16a3/sketch_jun16a3.ino | f015f8e75e885a2ab086d9b24b4e99cd4d6dedf0 | [] | no_license | nakaimauricio/BrewControl | e892d69391a2a6f8daf2d1d50c751e5e8908957c | 6ce0a64653195ce1504510e79f34bb997347bc6c | refs/heads/master | 2022-12-02T12:57:49.410136 | 2020-08-20T14:02:53 | 2020-08-20T14:02:53 | 286,577,645 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,246 | ino | sketch_jun16a3.ino |
/*
* Projeto para Arduino UNO
* Controle de temperatura para fermentação da cerveja
* Criação: 23/07/2020
* Atualização: 23/07/2020
* Autor: Mauricio Eiji Nakai
*/
#include <LiquidCrystal.h>
#include <OneWire.h>
#include "sensor_temperatura.h"
#include "timer.h"
#define saida_aquecedor 12
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
#define btnRIGHT 0
#define btnUP 1
#define btnDOWN 2
#define btnLEFT 3
#define btnSELECT 4
#define btnNONE 5
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
#define ONE_WIRE_BUS 10
OneWire ds(ONE_WIRE_BUS);
void setup() {
pinMode(saida_aquecedor, OUTPUT);
pinMode(ONE_WIRE_BUS, INPUT_PULLUP);
lcd.begin(16,2);
lcd.noCursor();
lcd.noBlink();
lcd.display();
lcd.noAutoscroll();
lcd.leftToRight();
lcd.print("D.");
lcd.setCursor(0,2);
lcd.print("A.");
Serial.begin(9600);
timer_pool_init();
// put your setup code here, to run once:
}
//byte contador;
void loop() {
// Serial.print("Estado_sensor_temperatura ");
// Serial.println(contador++);
decrement_timers();
sensor_temperatura();
interface();
LCD_buttons();
}
|
6ba4625ad1d412f3fe2479bcadf1babe9ed68461 | 1cdf43d103a1c5664a9197fdc6002905f8fcf73a | /MOLab3/MOLab3/Non-linear.cpp | 22c6591ed5e2aa9b0dd6fe33cfec7fbb266b5feb | [] | no_license | RomanTymchyshyn/NumericalMethods | 8750ce23fa94dac72db27f1313c2e1d13bd6cac0 | 344333f5706f9209a37f81c53b90ac1c97d29aed | refs/heads/master | 2016-08-12T13:48:27.059598 | 2016-03-28T20:49:08 | 2016-03-28T20:49:08 | 54,922,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,413 | cpp | Non-linear.cpp | #include "Non-linear.h"
double f(const double & x, const double & y)
{
return (0.7*x - (1.0/3.0)*sin(y) - 2);
}
double g(const double & x, const double & y)
{
return (1.1*x + 2*y - sin(x/5.0) + 1);
}
double f1x(const double & x, const double & y)
{
return 0.7;
}
double f1y(const double & x, const double & y)
{
return (-1.0/3.0)*cos(y);
}
double g1x(const double & x, const double & y)
{
return (1.1 - (1.0/5.0)*cos(x/5.0));
}
double g1y(const double & x, const double & y)
{
return 2.0;
}
void Newton(const double & startX, const double & startY,double & x_sol, double & y_sol, const double & eps, ostream & o)
{
double oldX = 0.0;
double oldY = 0.0;
double newX = startX;
double newY = startY;
o<<"Start approximation: x0 = "<<startX<<"\ty0 = "<<startY<<endl;
int numOfIter = 0;
o.precision(10);
do
{
oldX = newX;
oldY = newY;
newX = oldX - det(f(oldX,oldY), f1y(oldX,oldY), g(oldX, oldY), g1y(oldX, oldY))/
det(f1x(oldX,oldY), f1y(oldX,oldY), g1x(oldX, oldY), g1y(oldX, oldY));
newY = oldY - det(f1x(oldX,oldY), f(oldX,oldY), g1x(oldX, oldY), g(oldX, oldY))/
det(f1x(oldX,oldY), f1y(oldX,oldY), g1x(oldX, oldY), g1y(oldX, oldY));
++numOfIter;
o<<"x"<<numOfIter<<" = "<<newX<<"\ty"<<numOfIter<<" = "<<newY<<endl;
}
while(max(fabs(newX - oldX), fabs(newY - oldY)) > eps);
x_sol = newX;
y_sol = newY;
o<<"Number of iteration: "<<numOfIter<<endl;
return;
} |
41a4bfb7bea14c43b46087bca752cee99c34800a | 4039fe60cb7e643d61049b99038a5b6d9ec30314 | /DateTime.cpp | 0c5653b72b6407b9c7e4f1a763b9cc3125d2b78e | [] | no_license | anthonyho007/Kattis | 2a93fb0d8b358a08861594c3cf0874e9f2b0689c | 1907888794b17d8226121438f557edf29c6cb94f | refs/heads/master | 2021-01-19T16:40:12.325606 | 2017-10-11T08:15:52 | 2017-10-11T08:24:39 | 88,276,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,488 | cpp | DateTime.cpp | // #include <stdlib.h>
// #include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main () {
char date[100];
char input_format[100];
char out_format[100];
char year[5];
char month[3];
char day[3];
int ctr = 0;
while (scanf("%s %s %s", date, input_format, out_format)==3) {
// search for year, month and day
int size = strlen(input_format);
int year_f = 0;
int month_f = 0;
int day_f = 0;
for ( int i = 0; i < size; i++)
{
if ( input_format[i] == 'y' && year_f == 0) {
for( int j = 0; j < 4; j++ ) {
year[j] = date[i+j];
// printf("%c", year[j]);
}
i += 4;
year_f = 1;
}
else if ( input_format[i] == 'm' && month_f == 0) {
for (int j = 0; j < 2; j++) {
month[j] = date[i+j];
// printf("%c", month[j]);
}
i+= 2;
month_f = 1;
} else if ( input_format[i] == 'd' && day_f == 0) {
for (int j = 0; j <2 ; j++ ) {
day[j] = date[i+j];
// printf("%c", day[j]);
}
i += 2;
day_f = 1;
}
}
// finished extraction, now to put them in place
int size2 = strlen(out_format);
int year_f2 = 0;
int month_f2 = 0;
int day_f2 = 0;
for ( int i = 0; i < size2; i++)
{
if ( out_format[i] == 'y' && year_f2 == 0) {
for( int j = 0; j < 4; j++ ) {
out_format[i+j] = year[j];
// printf("%c", year[j]);
}
i += 4;
year_f = 1;
}
else if ( out_format[i] == 'm' && month_f2 == 0) {
for (int j = 0; j < 2; j++) {
out_format[i+j] = month[j];
// month[j] = date[i+j];
}
i+= 2;
month_f = 1;
} else if ( out_format[i] == 'd' && day_f2 == 0) {
for (int j = 0; j <2 ; j++ ) {
out_format[i+j] = day[j];
// day[j] = date[i+j];
}
i += 2;
day_f = 1;
}
}
// print out_format out
printf("%s", out_format);
}
}
|
1713fbc062cdd01afe7d26ecc01ec68eb3b7e0db | 9937103d8a80958b97eab699ab0334d8f91c98ca | /Queue/DoubleListQueue.cpp | a89f79a37e68af053fdc0cfec66f0c4e723dd798 | [] | no_license | Lokol1337/DataStructures | 57726c73b2061bdfec832b38a538e8b0d9913107 | 4a3e984554b049f3774fdaf585462fb90bb9b523 | refs/heads/master | 2022-11-05T06:14:10.927549 | 2020-06-15T17:39:11 | 2020-06-15T17:39:11 | 258,742,358 | 0 | 0 | null | 2020-04-25T10:03:44 | 2020-04-25T10:03:43 | null | UTF-8 | C++ | false | false | 503 | cpp | DoubleListQueue.cpp | #pragma once
#include "DoubleListQueue.h"
#include <cstddef>
DoubleListQueue::DoubleListQueue() {}
void DoubleListQueue::enqueue(const ValueType& value) {
pushFront(value);
}
void DoubleListQueue::dequeue() {
this->removeBack();
}
const ValueType& DoubleListQueue::front() const {
return getNode(size()-1)->value;
}
bool DoubleListQueue::isEmpty() const {
if (LinkedList2::size() == 0)
return true;
return false;
}
size_t DoubleListQueue::size() const {
return this->LinkedList2::size();
} |
a19c83067673812bc9a20b222272f28656cbc21b | ef7d308ff157eb43d9056dae91ea24effd2f32b2 | /XorBoard.cpp | 491ab1a0b7427aef03aebca6ebe00fccd82e089e | [] | no_license | abhiranjankumar00/TopCoder-SRM-submissions | cd37f2f2638c2e40daa571d08e2b068382921f23 | d0d3ee3bde2be630f6126d53f4bb0ea008a03150 | refs/heads/master | 2021-01-18T01:42:20.313261 | 2018-04-09T19:04:42 | 2018-04-09T19:04:42 | 5,789,738 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 7,299 | cpp | XorBoard.cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <climits>
#include <cstring>
using namespace std;
typedef long long int64;
typedef vector<int> vi;
typedef string ST;
typedef stringstream SS;
typedef vector< vector <int> > vvi;
typedef pair<int,int> ii;
typedef vector <string> vs;
#define endl ("\n")
#define DEBUG(x) cout << #x << " = " << x << "\n"
#define Pf printf
#define Sf scanf
#define ep 1e-9
#define PI M_PI
#define E M_E
#define CL(a, b) memset(a, b, sizeof(a))
#define mp make_pair
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define tr(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define present(x, c) ((c).find(x) != (c).end()) //map & set//
#define cpresent(x, c) (find(all(c),x) != (c).end()) //vector & list//
#define forn(i, n) for(int i = 0, loop_ends_here = (int)n; i < loop_ends_here ; i++)
#define forab(i, a, b) for(int i = a, loop_ends_here = (int)b; i <= loop_ends_here; i++)
#define rep(i, a, b) for(int i = a, loop_ends_here = (int)b; i >= loop_ends_here; i--)
#define read(n) scanf("%d", &n)
#define write(n) printf("%d ", n)
#define writeln(n) printf("%d\n", n)
class XorBoard
{
public:
int count(int H, int W, int Rcount, int Ccount, int S);
};
const int64 mod = 555555555LL;
const int sz = (int)(2*1.6e3);
int Comb[sz+11][sz+11];
int XorBoard::count (int H, int W, int Rcount, int Ccount, int S)
{
forab(i, 0, sz) forab(j, 0, i)
Comb[i][j] = (j == 0 || i == j) ? 1 : (Comb[i-1][j] + Comb[i-1][j-1])%mod;
int64 ret = 0;
forab(r, 0, min(Rcount, H)) if(r % 2 == Rcount % 2)
forab(c, 0, min(Ccount, W)) if(c % 2 == Ccount % 2)
if(r*W + c*H - 2*r*c == S) {
int64 tmp;
int left = (Rcount - r)/2;
tmp = 1ll*Comb[H][r] * Comb[H + left - 1][left];
tmp %= mod;
left = (Ccount - c)/2;
tmp *= (1ll*Comb[W][c] * Comb[W+left-1][left])%mod;
tmp %= mod;
ret = (ret + tmp) % mod;
}
ret = (ret + mod) % mod;
return ret;
}
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.8 (beta) modified by pivanof
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, int p3, int p4, bool hasAnswer, int p5) {
cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2 << "," << p3 << "," << p4;
cout << "]" << endl;
XorBoard *obj;
int answer;
obj = new XorBoard();
clock_t startTime = clock();
answer = obj->count(p0, p1, p2, p3, p4);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p5 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p5;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
int p0;
int p1;
int p2;
int p3;
int p4;
int p5;
{
// ----- test 0 -----
p0 = 2;
p1 = 2;
p2 = 2;
p3 = 2;
p4 = 4;
p5 = 4;
all_right = KawigiEdit_RunTest(0, p0, p1, p2, p3, p4, true, p5) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = 2;
p1 = 2;
p2 = 0;
p3 = 0;
p4 = 1;
p5 = 0;
all_right = KawigiEdit_RunTest(1, p0, p1, p2, p3, p4, true, p5) && all_right;
// ------------------
}
{
// ----- test 2 -----
p0 = 10;
p1 = 20;
p2 = 50;
p3 = 40;
p4 = 200;
p5 = 333759825;
all_right = KawigiEdit_RunTest(2, p0, p1, p2, p3, p4, true, p5) && all_right;
// ------------------
}
{
// ----- test 3 -----
p0 = 1200;
p1 = 1000;
p2 = 800;
p3 = 600;
p4 = 4000;
p5 = 96859710;
all_right = KawigiEdit_RunTest(3, p0, p1, p2, p3, p4, true, p5) && all_right;
// ------------------
}
{
// ----- test 4 -----
p0 = 555;
p1 = 555;
p2 = 555;
p3 = 555;
p4 = 5550;
p5 = 549361755;
all_right = KawigiEdit_RunTest(4, p0, p1, p2, p3, p4, true, p5) && all_right;
// ------------------
}
{
// ----- test 5 -----
p0 = 1200;
p1 = 1000;
p2 = 800;
p3 = 600;
p4 = 4000;
all_right = KawigiEdit_RunTest(5, p0, p1, p2, p3, p4, false, p5) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// PROBLEM STATEMENT
// Fox Jiro has a rectangular grid with H rows and W columns (i.e., the grid has H*W cells in total). Initially, each cell in the grid contained the character '0'.
//
// A row flip is an operation in which Jiro picks a row of the grid, and in that row he changes all '0's to '1's and vice versa.
// Similarly, a column flip is an operation in which Jiro does the same to a column of the grid.
// Jiro took the grid that contained '0's everywhere.
// He performed a row flip Rcount times, and then a column flip Ccount times.
// (It is possible that Jiro flipped the same row or column multiple times.)
// At the end, Jiro noticed that there are exactly S '1's in the grid.
//
// You are given the ints H, W, Rcount, Ccount, and S.
// We are interested in the number of different ways in which Jiro could have flipped the rows and columns of the grid.
// Two ways of flipping are considered different if there is a row or a column that was flipped a different number of times.
// (That is, the order in which the rows and columns are flipped does not matter.)
// Return the number of different ways of flipping that match the given situation, modulo 555,555,555.
//
//
// DEFINITION
// Class:XorBoard
// Method:count
// Parameters:int, int, int, int, int
// Returns:int
// Method signature:int count(int H, int W, int Rcount, int Ccount, int S)
//
//
// CONSTRAINTS
// -H will be between 1 and 1,555, inclusive.
// -W will be between 1 and 1,555, inclusive.
// -Rcount will be between 0 and 1,555, inclusive.
// -Ccount will be between 0 and 1,555, inclusive.
// -S will be between 0 and H*W, inclusive.
//
//
// EXAMPLES
//
// 0)
// 2
// 2
// 2
// 2
// 4
//
// Returns: 4
//
// In two of the four ways, Jiro flips each row once, and then the same column twice.
// In the other two ways he first flips the same row twice, and then each column once.
//
// 1)
// 2
// 2
// 0
// 0
// 1
//
// Returns: 0
//
// Without any flips, all cells still contain '0's, so S=1 is impossible.
//
// 2)
// 10
// 20
// 50
// 40
// 200
//
// Returns: 333759825
//
// Rcount and Ccount may be greater than H and W.
//
// 3)
// 1200
// 1000
// 800
// 600
// 4000
//
// Returns: 96859710
//
//
//
// 4)
// 555
// 555
// 555
// 555
// 5550
//
// Returns: 549361755
//
//
//
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
|
94d38d1b869a42eeaa4dfce36ed5fb9ac272a8c8 | d2d4dadbbb4f4c4df145ac8cdfed585a9bc5e701 | /src/main/cpp/disenum/TransferType.cpp | cd34e1db2a89893ed7fc17419e67202d98c1a1ae | [
"BSD-2-Clause"
] | permissive | Updownquark/DISEnumerations | c5e0368d4780a7d1c0de24603f4ab2dbe8c312ae | 6b90dd4fb4323d3daf5e1d282078d9c0ffe0545c | refs/heads/master | 2021-03-04T22:33:52.529451 | 2020-03-09T15:26:36 | 2020-03-09T15:26:36 | 246,071,613 | 0 | 0 | NOASSERTION | 2020-03-09T15:25:08 | 2020-03-09T15:25:07 | null | UTF-8 | C++ | false | false | 2,552 | cpp | TransferType.cpp | #include <sstream>
#include <cstddef>
#include <disenum/TransferType.h>
namespace DIS {
hashMap<int,TransferType*> TransferType::enumerations;
TransferType TransferType::OTHER(0, "Other");
TransferType TransferType::CONTROLLING_APPLICATION_REQUESTS_TRANSFER_OF_AN_ENTITY(1, "Controlling application requests transfer of an entity");
TransferType TransferType::APPLICATION_DESIRING_CONTROL_REQUESTS_TRANSFER_OF_AN_ENTITY(2, "Application desiring control requests transfer of an entity");
TransferType TransferType::MUTUAL_EXCHANGE_SWAP_OF_AN_ENTITY(3, "Mutual exchange / swap of an entity");
TransferType TransferType::CONTROLLING_APPLICATION_REQUESTS_TRANSFER_OF_AN_ENVIRONMENTAL_PROCESS(4, "Controlling application requests transfer of an environmental process");
TransferType TransferType::APPLICATION_DESIRING_CONTROLS_REQUESTS_TRANSFER_OF_AN_ENVIRONMENTAL_PROCESS(5, "Application desiring controls requests transfer of an environmental process");
TransferType TransferType::MUTUAL_EXCHANGE_SWAP_OF_AN_ENVIRONMENTAL(6, "Mutual exchange / swap of an environmental");
TransferType TransferType::CANCEL_TRANSFER(7, "Cancel transfer");
TransferType::TransferType(int value, std::string description) :
Enumeration(value, description)
{
enumerations[value] = this;
};
TransferType* TransferType::findEnumeration(int aVal) {
TransferType* pEnum;
enumContainer::iterator enumIter = enumerations.find(aVal);
if (enumIter == enumerations.end()) pEnum = NULL;
else pEnum = (*enumIter).second;
return pEnum;
};
std::string TransferType::getDescriptionForValue(int aVal) {
TransferType* pEnum = findEnumeration(aVal);
if (pEnum) return pEnum->description;
else {
std::stringstream ss;
ss << "Invalid enumeration: " << aVal;
return (ss.str());
}
};
TransferType TransferType::getEnumerationForValue(int aVal) throw(EnumException) {
TransferType* pEnum = findEnumeration(aVal);
if (pEnum) return (*pEnum);
else {
std::stringstream ss;
ss << "No enumeration found for value " << aVal << " of enumeration TransferType";
throw EnumException("TransferType", aVal, ss.str());
}
};
bool TransferType::enumerationForValueExists(int aVal) {
TransferType* pEnum = findEnumeration(aVal);
if (pEnum) return (true);
else return (false);
};
TransferType::enumContainer TransferType::getEnumerations() {
return (enumerations);
};
TransferType& TransferType::operator=(const int& aVal) throw(EnumException)
{
(*this) = getEnumerationForValue(aVal);
return (*this);
};
} /* namespace DIS */
|
c56c32209083661b2845c1c3a3ed3a389fb81948 | 631f1edc4281df77469586e85cbc91e526287c2e | /GLSL-Particle-Systems-CLR/Engine/ParticleSystem/ParticleExportAndHeaders/ContainerXMLData.hpp | cb866e6ebceb340519e386791bced5a933d2993e | [] | no_license | CesarRocha/GLSL-Particle-Systems | dd9e647a830c1d6b81b84d23c1a04db7cda54624 | a93607fc34fa3cf58e6a2c32e22ffe8e3f373d8f | refs/heads/master | 2021-01-12T11:37:32.153909 | 2016-11-04T05:56:50 | 2016-11-04T05:56:50 | 72,234,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | hpp | ContainerXMLData.hpp | #pragma once
#ifndef _ContainerXMLData_
#define _ContainerXMLData_
#include "EmitterXMLData.hpp"
//===================================================================================================
// struct ContainerXMLData ==
//===================================================================================================
struct ContainerXMLData
{
public:
ContainerXMLData();
void PopulateXMLWithContainerData(XMLNode& xmlNode, std::string newContainerName);
std::string containerName;
std::string containerTexturePath;
Vector3 particlePosition;
int spriteCountTotal;
int spriteCountX;
int spriteCountY;
//EmitterData
std::vector<EmitterXMLData*> xmlEmitterData;
};
#endif // !_ConttainerXMLData_
|
f145158064f1fdf71be76ca978f258b5c7d96bcd | 5c1b2e754c434c1af197c7087ba5230ca8005bed | /src/zed_processor/src/capture.cc | 93b1915d0862745819ac649caa3c55907a586ae7 | [] | no_license | konstantin-azarov/robomagellan | 7748c874fa5610784bad7effb5c1c09c6791364d | 9151fe151dc9281df503e4891387d9b0d2f88021 | refs/heads/master | 2021-01-20T11:48:10.432035 | 2017-04-22T05:55:40 | 2017-04-22T05:55:40 | 45,894,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,854 | cc | capture.cc | #include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <pthread.h>
#include <string>
#include <iostream>
#include <iomanip>
#include "camera.hpp"
#include "utils.hpp"
#define BACKWARD_HAS_DW 1
#include "backward.hpp"
using namespace std;
using boost::format;
using boost::str;
namespace po = boost::program_options;
const int FRAME_WIDTH = 1280;
const int FRAME_HEIGHT = 720;
const int FRAME_SIZE = FRAME_WIDTH*FRAME_HEIGHT;
const int FPS = 60;
backward::SignalHandling sh;
void fail(const char* msg) {
cerr << msg << endl;
exit(1);
}
FILE* open_video_sink(string video_format, string output_file) {
FILE* video_sink = nullptr;
if (video_format == "x264") {
std::string cmd = string("ffmpeg ") +
"-f rawvideo " +
"-pix_fmt gray " +
"-s 1280x480 " +
"-r 30 " +
"-i - " +
"-r 30 " +
"-c:v libx264 " +
"-preset ultrafast " +
"-qp 0 " +
"-an " +
"-f avi " +
"-y " +
output_file;
cout << "Running ffmpeg: " << cmd << endl;
video_sink = popen(cmd.c_str(), "w");
if (video_sink == 0) {
fail("Failed to open ffmpeg");
}
} else if (video_format == "raw") {
video_sink = fopen(output_file.c_str(), "wb");
if (video_sink == 0) {
fail("Failed to open output file");
}
} else {
fail("Invalid video format");
}
return video_sink;
}
void close_video_sink(string video_format, FILE* video_sink) {
if (video_sink != nullptr) {
if (video_format == "x264"){
pclose(video_sink);
} else {
fclose(video_sink);
}
}
}
int main(int argc, char **argv) {
string snapshots_dir, output_file, video_format;
int video_duration = -1;
po::options_description desc("Command line options");
desc.add_options()
("output-dir",
po::value<string>(&snapshots_dir)->required(),
"where to store snapshots");
desc.add_options()
("output-file",
po::value<string>(&output_file),
"where to store outpit video file");
desc.add_options()
("duration",
po::value<int>(&video_duration),
"how long to record the video for");
desc.add_options()
("format",
po::value<string>(&video_format)->default_value("raw"),
"raw or x264");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
#ifdef NO_PREVIEW
if (output_file.empty()) {
fail("Output file is required");
}
if (video_duration == -1) {
fail("Video duration is required");
}
#endif
if (video_format != "raw" && video_format != "x264") {
fail("--video_format should be either 'raw' or 'x264'");
}
Camera camera;
if (!camera.init(FRAME_WIDTH*2, FRAME_HEIGHT, FPS)) {
fail("Failed to initialize camera");
}
FILE* video_sink = nullptr;
#ifndef NO_PREVIEW
cv::namedWindow("preview");
#else
if (!output_file.empty()) {
video_sink = open_video_sink(video_format, output_file);
}
#endif
int minExposure = 1, maxExposure = 30000, curExposure = 10000;
camera.setExposure(curExposure);
cout << "Ready" << endl;
uint8_t buffer[FRAME_SIZE*4];
cv::Mat raw(FRAME_HEIGHT, FRAME_WIDTH*2, CV_8UC2, buffer);
cv::Mat combined(FRAME_HEIGHT, FRAME_WIDTH*2, CV_8UC3);
cv::Mat preview;
int current_snapshot_index = 0;
bool done = false;
int frame_count = 0;
double last_timestamp = nanoTime();
double t0 = last_timestamp;
int fps_frame_count = 0;
while(!done) {
camera.nextFrame(buffer);
cv::cvtColor(raw, combined, CV_YUV2RGB_YVYU);
frame_count++;
#ifndef NO_PREVIEW
cv::resize(combined, preview, cv::Size(0, 0), 0.5, 0.5);
cv::imshow("preview", preview);
#endif
if (video_sink != nullptr) {
fwrite(buffer, 1, FRAME_SIZE*2, video_sink);
}
fps_frame_count++;
double t = nanoTime();
if (t - last_timestamp >= 2) {
cout << setprecision(3) << "t = " << t - t0
<< " FPS = " << (fps_frame_count / (t - last_timestamp))
<< endl;
last_timestamp = t;
fps_frame_count = 0;
// cout << "Exposure: " << camera.getExposure() << endl;
// cout << "Gain: " << camera.getGain() << endl;
}
if (video_duration != -1 && frame_count >= video_duration*FPS) {
done = true;
}
#ifndef NO_PREVIEW
int key = cv::waitKey(1);
if (key != -1) {
key &= 0xFF; // In ubuntu it returns some sort of a long key.
}
switch (key) {
case 27:
done = true;
break;
case 32:
printf("Snapshot %d!\n", ++current_snapshot_index);
cv::imwrite(
str(format("%s/snapshot_%d.bmp") %
snapshots_dir %
current_snapshot_index),
combined);
break;
case 'r':
if (video_sink == nullptr) {
cout << "Recording" << endl;
video_sink = open_video_sink(video_format, output_file);
} else {
cout << "Stopped recording" << endl;
close_video_sink(video_format, video_sink);
video_sink = nullptr;
}
break;
case '=':
case '+':
curExposure = min(maxExposure, curExposure + (key == '=' ? 50 : 1000));
cout << "Exposure: cur = " << curExposure << endl;
camera.setExposure(curExposure);
break;
case '-':
case '_':
curExposure = max(minExposure, curExposure - (key == '-' ? 50 : 1000));
cout << "Exposure: cur = " << curExposure << endl;
camera.setExposure(curExposure);
break;
case 226:
break; // shift
case -1:
break;
default:
printf("Unknown code %d\n", key);
break;
}
#endif
}
close_video_sink(video_format, video_sink);
camera.shutdown();
return 0;
}
|
18b632758f68138d2594e6d10e65d1abb696ee4f | b1ccd1f03f9c3d28bb4bba83c3001a988e7ba54d | /inc/flymove.h | 5e6b91485cd39c2b31cd0bc59f839f1ba44ff9c7 | [] | no_license | twixthehero/GameEngine | ebb0a9570738c7bbdd97c9f965d4edf89aa7438f | cf611ce9bc18d763dce79fab56b1481657492f27 | refs/heads/master | 2021-01-19T03:01:13.916975 | 2015-11-16T01:50:29 | 2015-11-16T01:50:29 | 44,633,788 | 0 | 0 | null | 2015-11-16T01:50:29 | 2015-10-20T20:42:51 | C++ | UTF-8 | C++ | false | false | 212 | h | flymove.h | #pragma once
#include "gamec.h"
class Transform;
class FlyMove : public GameComponent
{
public:
FlyMove();
virtual void init();
virtual void update();
double moveSpeed = 5.0f;
private:
Transform* trans;
}; |
52704c01d41f4f3a446fdb21fb5298ec9fb4f9ec | 141fc7929c4d8327bd5ae929230552f52ce0c1d6 | /filereader.h | afcadfb00cf9fe5bd2426c9caccdeeae1e987bf3 | [] | no_license | bradishungry/CS-sound-project | db0eeda33a1c70223917c132aae83183eba5de41 | fb0f5e2fd14ba2b5979bf22bef799b160052d6ca | refs/heads/master | 2022-07-22T12:57:46.322735 | 2022-06-13T15:43:24 | 2022-06-13T15:43:24 | 46,454,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | h | filereader.h | /*
* File: filereader.h
* Author: bboswell
*
* Created on November 11, 2015, 12:29 PM
*/
#ifndef FILEREADER_H
#define FILEREADER_H
#include <iostream>
#include <fstream>
#include "help.h"
using namespace std;
class filereader : public help {
public:
filereader();
filereader(string, int *, int *, int *, int *, int **);
virtual ~filereader();
void readFile(string);
virtual void fhelp() {
cout << "This program gives out file information for a .cs229 or .wav file" << endl;
cout << "enter a valid filename after the program name and it will return information from the file" << endl;
cout << "note that whitespace or # signs will be ignored." << endl;
}
private:
};
void sampleGetter(ifstream &, int *);
#endif /* FILEREADER_H */
|
92c3a481488bcfa25a86d55296b345feb1b5e7ce | a215932246c9fb7623f17b9ccc9ef04d3e4d85c3 | /cloudDiskServer/server.cpp | 17aeb23709c63f9d171dc7afe3c81813d0485874 | [] | no_license | JachinLin2022/cloudDisk | 80ba7774c285bfe23f9e3f868af62da602716e9c | 74b638aa09fa2a43d87d430dccd42b92b5ad194a | refs/heads/main | 2023-06-03T14:41:26.147287 | 2021-06-26T14:37:45 | 2021-06-26T14:37:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,251 | cpp | server.cpp | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<sys/ioctl.h>
#include<sys/fcntl.h>
#include<net/if.h>
#include<iostream>
#include <vector>
#include <mysql.h>
using namespace std;
MYSQL *mysql;
MYSQL_RES *result;
MYSQL_ROW row;
vector<string> args;
char buff[4096];
void connect_mysql()//数据库连接
{
mysql = mysql_init( NULL ); /* 连接初始化 */
if ( !mysql )
{
printf("mysql_init failed\n");
exit(0);
}
mysql = mysql_real_connect( mysql, "localhost", "root", "root123", "cloudDisk", 0, NULL, 0 ); /* 建立实际连接 */
/* 参数分别为:初始化的连接句柄指针,主机名(或者IP),用户名,密码,数据库名,0,NULL,0)后面三个参数在默认安装mysql>的情况下不用改 */
mysql_set_character_set(mysql, "gbk");
if ( mysql ){
printf( "MariaDB connect success\n" );
}
else{
printf( "MariaDB connect failed\n" );
exit(0);
}
}
//注册账户,数据库中插入账户密码,若成功返回1
bool reg()
{
char sqlcmd[100];
sprintf(sqlcmd, "insert into user values(\"%s\",\"%s\")", args[1].c_str(),args[2].c_str());
cout<<sqlcmd<<endl;
if (mysql_query(mysql, sqlcmd)) {
cout << "mysql_query failed(" << mysql_error(mysql) << ")" << endl;
return 0;
}
return 1;
}
//登录账户,校验密码,密码符合返回1
bool login()
{
char sqlcmd[100];
sprintf(sqlcmd, "select * from user where username=\'%s\'", args[1].c_str());
cout<<sqlcmd<<endl;
if (mysql_query(mysql, sqlcmd)) {
cout << "mysql_query failed(" << mysql_error(mysql) << ")" << endl;
return 0;
}
if ((result = mysql_store_result(mysql))==NULL) {
cout << "mysql_store_result failed" << endl;
return 0;
}
row=mysql_fetch_row(result);
if(row==NULL)
return 0;
if(row[1]!=args[2])
return 0;
return 1;
}
//字符串split
void SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c)//字符串分割函数
{
std::string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while(std::string::npos != pos2)
{
v.push_back(s.substr(pos1, pos2-pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if(pos1 != s.length())
v.push_back(s.substr(pos1));
}
//处理参数
void cmdArgs(const string& cmd) {
args.clear();
string str;
unsigned int p, q;
for (p = 0, q = 0; q < cmd.length(); p = q + 1) {
q = cmd.find_first_of(" \n", p);
str = cmd.substr(p, q - p);
if (!str.empty()) {
args.push_back(str);
}
if (q == string::npos)
return;
}
}
bool md5_exist(string md5)
{
char sqlcmd[100];
sprintf(sqlcmd, "select * from file where md5=\'%s\'",md5.c_str());
if (mysql_query(mysql, sqlcmd)) {
cout << "mysql_query failed(" << mysql_error(mysql) << ")" << endl;
return -1;
}
if ((result = mysql_store_result(mysql))==NULL) {
cout << "mysql_store_result failed" << endl;
return -1;
}
if((int)mysql_num_rows(result)==0)//该文件不存在
return 0;
return 1;//文件存在
}
bool insert_file(string md5,string filename,string cite,string md5dir ,string md5name)
{
char sqlcmd[200];
sprintf(sqlcmd, "insert into file values(\"%s\",\"%s\",%s,\"%s\",\"%s\")",md5.c_str(),filename.c_str(),cite.c_str(),md5dir.c_str(),md5name.c_str());
// cout<<sqlcmd<<endl;
if (mysql_query(mysql, sqlcmd)) {
// cout << "mysql_query failed(" << mysql_error(mysql) << ")" << endl;
return 0;
}
return 1;
}
bool insert_path(string md5,string type,string username,string clientpath)
{
char sqlcmd[200];
string path=username+"\\\\"+args[2]+"\\\\"+clientpath.substr(args[1].length()+1);
// cout<<clientpath<<endl;
sprintf(sqlcmd, "insert into path values(\"%s\",%s,\"%s\",\"%s\")",path.c_str(),type.c_str(),md5.c_str(),clientpath.c_str());
// cout<<sqlcmd<<endl;
if (mysql_query(mysql, sqlcmd)) {
// cout << "mysql_query failed(" << mysql_error(mysql) << ")" << endl;
return 0;
}
return 1;
}
void client_to_server(int connfd)
{
while(1)
{
string fileheader;
vector<string> fileinfo;
int filesize;
memset(buff,0,sizeof(buff));
int n=read(connfd,buff,200);//接收文件头信息
fileheader=buff;
if(fileheader=="end")//如果接收到end,则说明所有文件已经同步完毕
break;
SplitString(fileheader,fileinfo,"\n");//0为文件名,1为文件大小,2为MD5码,3为用户名,4为客户端上目录
insert_path(fileinfo[2],"0",fileinfo[3],fileinfo[4]);//插入路径表
if(insert_file(fileinfo[2],fileinfo[0],"0",fileinfo[2].substr(0,4),fileinfo[2].substr(4,28))==0)
{
write(connfd,"0",1);//回复客户端,该文件已经存在,传下一个
continue;
}
write(connfd,"1",1);//回复客户端,该文件不存在,准备接收
filesize=atoi(fileinfo[1].c_str());
char* filedata=(char*)malloc(sizeof(char) * filesize);
int leftsize=filesize;
int readsize=0;
while(1)
{
n=read(connfd,filedata+readsize,leftsize);//接收文件
readsize+=n;
leftsize-=n;
if(leftsize==0)
break;
}
string dir="mkdir -p data/"+fileinfo[2].substr(0,4);
system(dir.c_str());
string clouDir="data/"+fileinfo[2].substr(0,4)+"/"+fileinfo[2].substr(5,28);
FILE* fp = fopen(clouDir.c_str(),"wb");
fwrite(filedata,1,filesize,fp);
fclose(fp);
free(filedata);
write(connfd,"1",1);//回复客户端,准备好接收下个文件
}
}
int main(int argc, char** argv){
int sockfd,connfd;
sockaddr_in servaddr;
int port=-1;
if(argc!=3)
{
printf("param not right!!\n");
return 0;
}
for(int i=1;i<argc;i=i+2)
{
if(strcmp(argv[i],"--port")==0)
port=atoi(argv[i+1]);
}
if(port<0||port>65535)
{
printf("port is not in [0~65535]\n");
return 0;
}
// printf("port is %d\n",port);
connect_mysql();
if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){
printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);
return 0;
}
int on = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
if( bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){
printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);
return 0;
}
if( listen(sockfd, 10) == -1){
printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);
return 0;
}
printf("======waiting for client's request======\n");
if( (connfd = accept(sockfd, (struct sockaddr*)NULL, NULL)) == -1){
printf("accept socket error: %s(errno: %d)\n",strerror(errno),errno);
}
printf("======connect success======\n");
//监听客户端的动作
while(1)
{
memset(buff,0,sizeof(buff));
int n=read(connfd,buff,100);
if(n<=0)
break;
cmdArgs(buff);
//注册
if(args[0]=="register")
{
if(reg())
{
write(connfd,"1",1);
}
else
write(connfd,"0",1);
}
//登录
else if(args[0]=="login")
{
if(login())
{
write(connfd,"1",1);
}
else
write(connfd,"0",1);
}
//bind初始化
else if(args[0]=="bind")
{
//客户端同步到服务端
client_to_server(connfd);
//服务端同步到客户端
}
}
return 0;
} |
2129e372bf06ea8a661aba95c7c35431b07697db | 68a34bffe4cdfab1e968c05b0e0def8ec972c348 | /Source/PlayerSystem.h | 778b66d72be77e18f9e9a0b621b85b0329a58fc6 | [] | no_license | pkuzmickas/HomecomingDEMO | 2b890012bbbf53cadad48fc8f4f4c879e6428240 | acdeb5cde5b2365782e4bbd12745feb7741e32f6 | refs/heads/master | 2023-03-12T08:08:10.285979 | 2021-02-28T18:36:39 | 2021-02-28T18:36:39 | 126,629,237 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | h | PlayerSystem.h | #pragma once
#include "Movement.h"
#include "PlayerStats.h"
#include "PlayerInput.h"
#include "PlayerMovement.h"
#include "PlayerAnimator.h"
#include "DialogueSystem.h"
#include "PlayerAbilities.h"
class PlayerSystem {
public:
static Entity* createPlayer(int globalPosX, int globalPosY, SDL_Texture* texture, SDL_Renderer* renderer, Graphics* graphics, PlayerAnimator::LookDirection lookDirection = PlayerAnimator::LookDirection::RIGHT);
static void disableMovement();
static void enableMovement();
static Entity* getPlayer();
static void resetPlayer();
private:
PlayerSystem();
static Entity* player;
}; |
0b43efdbb89c8123562ae124ee071499d0d96ac0 | b7f1b4df5d350e0edf55521172091c81f02f639e | /ui/ozone/platform/drm/gpu/overlay_plane.h | 4bfb9b4738c959671df557043efb9218148f979c | [
"BSD-3-Clause"
] | permissive | blusno1/chromium-1 | f13b84547474da4d2702341228167328d8cd3083 | 9dd22fe142b48f14765a36f69344ed4dbc289eb3 | refs/heads/master | 2023-05-17T23:50:16.605396 | 2018-01-12T19:39:49 | 2018-01-12T19:39:49 | 117,339,342 | 4 | 2 | NOASSERTION | 2020-07-17T07:35:37 | 2018-01-13T11:48:57 | null | UTF-8 | C++ | false | false | 1,498 | h | overlay_plane.h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_OZONE_PLATFORM_DRM_GPU_OVERLAY_PLANE_H_
#define UI_OZONE_PLATFORM_DRM_GPU_OVERLAY_PLANE_H_
#include <vector>
#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/overlay_transform.h"
namespace ui {
class ScanoutBuffer;
struct OverlayPlane;
typedef std::vector<OverlayPlane> OverlayPlaneList;
struct OverlayPlane {
// Simpler constructor for the primary plane.
explicit OverlayPlane(const scoped_refptr<ScanoutBuffer>& buffer,
int fence_fd);
OverlayPlane(const scoped_refptr<ScanoutBuffer>& buffer,
int z_order,
gfx::OverlayTransform plane_transform,
const gfx::Rect& display_bounds,
const gfx::RectF& crop_rect,
int fence_fd);
OverlayPlane(const OverlayPlane& other);
bool operator<(const OverlayPlane& plane) const;
~OverlayPlane();
// Returns the primary plane in |overlays|.
static const OverlayPlane* GetPrimaryPlane(const OverlayPlaneList& overlays);
scoped_refptr<ScanoutBuffer> buffer;
int z_order = 0;
gfx::OverlayTransform plane_transform;
gfx::Rect display_bounds;
gfx::RectF crop_rect;
int fence_fd;
};
} // namespace ui
#endif // UI_OZONE_PLATFORM_DRM_GPU_OVERLAY_PLANE_H_
|
e13d819cf943bd5164caf00a9eafefe52c739f22 | bd138afefd41e09026e564e26f78d40f60ee834b | /c-cpp/closure_lambda/closure.cpp | 0a8dca312d8991e7338018f01f3b14e62e65b5c5 | [] | no_license | GCZhang/Tests | 698bc44fc7261102b7a8de37091f449f06763651 | 33798024b759a741b3a1d30eb03570402dffa524 | refs/heads/master | 2022-12-01T07:09:40.070014 | 2022-11-20T03:09:29 | 2022-11-20T03:09:29 | 72,281,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | cpp | closure.cpp | #include <iostream>
#include <functional>
std::function<void(void)> closureWrapper1()
{
int x = 10;
// if we write "x += 1; ..." here, then the compiler would complain "error: assignment of read-only variable 'x'"
return [x]()
{ std::cout << "Value in the closure: " << x << std::endl; };
}
std::function<void(void)> closureWrapper2()
{
int x = 10;
return [&x]()
{ x += 1; std::cout << "Value in the closure: " << x << std::endl; };
}
int main(int args, char *argv[])
{
int x = 10;
auto func0 = [&x]()
{ x += 1; std::cout << "Value in the closure: " << x << std::endl; };
std::function<void(void)> func1 = closureWrapper1();
std::function<void(void)> func2 = closureWrapper2();
func0();
func0();
func0();
std::cout << "-------------------------" << std::endl;
func1();
func1();
func1();
std::cout << "-------------------------" << std::endl;
func2();
func2();
func2();
std::cout << "-------------------------" << std::endl;
return 0;
}
|
b8fe009149b4d56f7c98fa292596fd08f434f84e | 3d35cfdcff63dee9851d600e0ea88a5b2702edc0 | /src/cyrt/graph/node.hpp | f997f0ed7a12fa22aec206b8eaee6239fea5ab32 | [] | no_license | andyjost/Sprite | 20cfef31ad91f7b1625aecbce9c28b8cca47128d | c28c09ca100ac102fcaa8559ad2e12eb0d12d7d5 | refs/heads/master | 2023-05-01T06:17:05.173021 | 2023-04-24T19:59:29 | 2023-04-24T19:59:29 | 614,023,214 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | hpp | node.hpp | #pragma once
#include <iosfwd>
#include "cyrt/fwd.hpp"
#include "cyrt/graph/cursor.hpp"
#include <string>
namespace cyrt
{
struct Node
{
InfoTable const * info;
// Create a complete node.
static Node * create(InfoTable const *, Arg const * = nullptr);
template<typename ... Args> static Node * create(InfoTable const *, Arg, Args && ...);
// Create a partial application.
static Node * create_partial(InfoTable const *, Arg const *, size_t numargs);
template<typename ... Args>
static Node * create_partial(InfoTable const *, Args && ...);
// Materialize a completed partial application.
static Node * from_partial(PartApplicNode const *, Node * finalarg = nullptr);
// Create a flat expression (each successor is a fresh variable).
static Node * create_flat(InfoTable const *, RuntimeState *);
void forward_to(Node *);
void forward_to(Variable const &);
template<typename ... Args> void forward_to(InfoTable const *, Args && ...);
tag_type make_failure();
tag_type make_nil();
tag_type make_unit();
// Copy.
Node * copy();
Node * deepcopy();
// Show.
std::string repr();
void repr(std::ostream &);
std::string str();
std::string str(SubstFreevars, ShowMonitor * = nullptr);
void str(std::ostream &, SubstFreevars=SUBST_FREEVARS, ShowMonitor * = nullptr);
// Equality.
std::size_t hash() const;
bool operator==(Node &);
bool operator!=(Node &);
// Indexing.
Cursor const successor(index_type);
Arg * successors();
Cursor operator[](index_type);
index_type size() const;
Arg * begin();
Arg * end();
};
}
#include "cyrt/graph/node.hxx"
|
4ca2bb165ac2e09e66150d503af1d289238c877c | a5b566fe7906ec05fa0e638eab99d623eac8564e | /sources/Permutation.hpp | 24f453757bd6621becf32fbb20ed3b55138abd74 | [] | no_license | bayesiancook/bayescode | 6d44f97ee617164538ac977cb5219ae670135674 | 855ac3b331267b9626d2ac25952d36a6a9374bdd | refs/heads/master | 2023-08-29T03:37:01.202960 | 2022-10-05T16:06:57 | 2022-10-05T16:06:57 | 92,596,965 | 4 | 4 | null | 2022-04-14T08:36:06 | 2017-05-27T12:20:15 | C++ | UTF-8 | C++ | false | false | 923 | hpp | Permutation.hpp | #ifndef PERM_H
#define PERM_H
#include "Array.hpp"
/**
* \brief A permutation of 1..N
*/
class Permutation : public SimpleArray<int> {
public:
//! constructor (parameterized by N)
Permutation(int size) : SimpleArray<int>(size) { Reset(); }
~Permutation() {}
//! set equal to identity permuation
void Reset() {
for (int i = 0; i < GetSize(); i++) {
(*this)[i] = i;
}
}
//! return size when put into an MPI buffer
unsigned int GetMPISize() const { return GetSize(); }
//! put current value of count and beta into an MPI buffer
void MPIPut(MPIBuffer &buffer) const {
for (int i = 0; i < GetSize(); i++) {
buffer << GetVal(i);
}
}
//! get value from MPI buffer
void MPIGet(const MPIBuffer &buffer) {
for (int i = 0; i < GetSize(); i++) {
buffer >> (*this)[i];
}
}
};
#endif
|
7af585a1636e0a3159462d8d3d24b5ef3ce918cf | 95f8ed7c4ad87975c4caf2dedb906bde1f2fdb3c | /examples/Due_Energyboard_Test/Due_Energyboard_Test.ino | 86614d698b1be43b374ee412178bd1e9a31db174 | [] | no_license | fhackenberger/SBS_CAN | 91e96ead4c3a5bb050d03a4453f0dcee736626c6 | 9912491fe01256d94078091940f3b19bfcea7ea4 | refs/heads/master | 2020-03-30T13:07:47.409259 | 2019-08-06T16:16:27 | 2019-08-06T16:16:27 | 151,257,667 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,347 | ino | Due_Energyboard_Test.ino | // This was tested with:
// Arduino Due on pins CANRX/TX connected to the CAN transceiver
// CJMCU-1051 based on NXP TJA1051 CAN Transceiver
// Wiring as documented in "2018-07-20 Report Leader 50V Battery CAN Readings": https://docs.google.com/document/d/1OmkW_UTGWCwyDriThNI7dI2qDYE3IVobrKOOHKtsnHs/edit#
// SbsCAN.h and its dependencies are from https://github.com/fhackenberger/SBS_CAN @ 7de365e
#include <SbsCAN.h>
byte canPort = 0; // Port 0 is on CANRX/TX, Port 1 is on DAC0 (CANRX1) und Pin 53 (CANTX1) of the Arduino Due
int outLioIonBtnPin = 24; // The Arduino pin which is connected to the Bat-enable pin of the battery. Pull to GND (LOW) to simulate pressing on the button, set to INPUT to release the button
unsigned long battEnPushedMs = 0L;
unsigned long lastKeepAliveMs;
unsigned long lastValidMsgMs = 0L;
unsigned long highPowerOnSinceMs;
unsigned long battOnSinceMs = 0L;
long id = 0;
byte dta[8];
unsigned int canStateOut = BMS_CTRL_STATE_INACTIVE;
unsigned long idOut = 0;
byte dtaOut[8] = {0};
BMSState bmsState;
void setup() {
// Set the serial interface baud rate
Serial.begin(115200);
// Initialize the CAN controller
if(canInit(canPort, CAN_BPS_500K) == CAN_OK) {
Serial.print("CAN"); Serial.print(canPort); Serial.print(": Initialized Successfully.\n\r");
}else {
Serial.print("CAN"); Serial.print(canPort); Serial.print(": Initialization Failed.\n\r");
}
lastKeepAliveMs = millis();
lastValidMsgMs = 0;
pinMode(outLioIonBtnPin, INPUT); // Don't press the button (setting the output to HIGH does not work as expected after it was LOW)
digitalWrite(30, LOW);
pinMode(30, OUTPUT);
digitalWrite(30, LOW);
digitalWrite(28, LOW);
pinMode(28, OUTPUT);
digitalWrite(28, LOW);
// XXX Enabling the following two lines breaks the example, we seem to have some kind of interference issues
pinMode(22, OUTPUT);
pinMode(29, OUTPUT);
// XXX force sending the 48V enable msg for testing
bmsState.bmsState = BMS_STATE_IDLE;
}
void loop() {
// canStateOut = BMS_CTRL_STATE_DISCHARGE;
// bmsState.encodeSetStateMsg(canStateOut, idOut, dtaOut);
// if(canTx(canPort, idOut, false, dtaOut, 8) != CAN_OK)
// Serial.println("Sending ctrl message failed");
// Serial.print("Sent ctrl message to battery for state "); Serial.println(canStateOut);
// delay(50);
// return;
byte cDataLen;
unsigned long now = millis();
if((lastValidMsgMs == 0L || (now - lastValidMsgMs) > 10000) && // No CAN msg or dead for more than 10 seconds
now > 2500 && // Wait for a CAN msg 2.5s after booting
(battEnPushedMs == 0L || (now - battEnPushedMs) > 5000)) { // Retry 5s after the last try, if still no CAN msg
// 2.5 seconds running and still no CAN msg, battery is probably in deep sleep
Serial.println("Waking up the battery using battery enable line");
pinMode(outLioIonBtnPin, OUTPUT);
digitalWrite(outLioIonBtnPin, LOW);
delay(300);
pinMode(outLioIonBtnPin, INPUT);
battEnPushedMs = now;
}
// Check for received message
if(canRx(canPort, &id, false, &dta[0], &cDataLen) == CAN_OK) {
int msgRcv = bmsState.decodeMsg(id, dta, 8);
if(msgRcv > 0)
lastValidMsgMs = now;
if(msgRcv == 2) {
Serial.print("Info02: State "); Serial.print(bmsState.getBmsStateStr()); Serial.print(" SoC: "); Serial.print(bmsState.stateOfCharge); Serial.print("% SoH: "); Serial.print(bmsState.stateOfHealth); Serial.print("% curr: "); Serial.print(bmsState.packCurrent); Serial.print("A remCapa: "); Serial.print(bmsState.remainingCapacity_mAh); Serial.print("mAh lastFullCapa "); Serial.print(bmsState.lastFullCapacity_mAh); Serial.println("mAh");
}
}
if(battOnSinceMs == 0L && lastValidMsgMs != 0L)
battOnSinceMs = now;
// Cycle the battery between high power on for 4 seconds and off for 2 seconds for 20 seconds
if(bmsState.bmsState == BMS_STATE_DISCHARGE && highPowerOnSinceMs == 0L)
highPowerOnSinceMs = now;
else if(bmsState.bmsState != BMS_STATE_DISCHARGE)
highPowerOnSinceMs = 0L;
if((millis() - lastKeepAliveMs) > 2000) {
String dbgMsg = "";
boolean sendCtrlMsg = false;
Serial.print("checking for CAN data... Last valid msg "); Serial.print(millis() - lastValidMsgMs); Serial.print("ms ago. Err present: "); Serial.println(bmsState.isErrActive() ? "true" : "false");
lastKeepAliveMs = millis();
if(battOnSinceMs != 0L && (now - battOnSinceMs) >= (20 * 1000)) { // If battery was on for more than 60 seconds
canStateOut = BMS_CTRL_STATE_DEEP_SLEEP;
dbgMsg = "put battery to sleep";
sendCtrlMsg = true;
}else if(highPowerOnSinceMs == 0L && bmsState.bmsState == BMS_STATE_IDLE) {
canStateOut = BMS_CTRL_STATE_DISCHARGE;
dbgMsg = "enable High Voltage output";
sendCtrlMsg = true;
}else if((now - highPowerOnSinceMs) > (4 * 1000)) { // If high power was on for more than 10 seconds
canStateOut = BMS_CTRL_STATE_INACTIVE;
dbgMsg = "disable High Voltage output";
sendCtrlMsg = true;
}
if(sendCtrlMsg) {// && (now - lastValidMsgMs) < 5000) {
bmsState.encodeSetStateMsg(canStateOut, idOut, dtaOut);
if(canTx(canPort, idOut, false, dtaOut, 8) != CAN_OK)
Serial.println("Sending ctrl message failed");
Serial.print("Sent ctrl message to battery for state "); Serial.println(canStateOut);
}
}
}
|
e44065881161d77018f7531a87ca415458f7a015 | af23d6a348ae0e9a97bfcd6d2c40d3393b8ae55c | /src/rendering/CursesInstance.cpp | f1a891832166bf31d37f0920c414a1570a0643d1 | [
"MIT"
] | permissive | evan1026/ncurses-maze | ae5bbcfa0954b39f4636daa42f04892cd6d3fa22 | ab41d7f4ab8099440b813ca01e3f6bf7461beea6 | refs/heads/master | 2021-01-15T15:32:02.344269 | 2016-07-17T16:41:00 | 2016-07-17T16:41:00 | 43,563,130 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,052 | cpp | CursesInstance.cpp | #include <ncurses.h>
#include "CursesInstance.h"
int CursesInstance::instCount = 0;
bool CursesInstance::isColor = false;
CursesInstance::CursesInstance() {
if (instCount == 0) {
//Init ncurses
initscr(); //Basic init
cbreak(); //Don't wait for \n to put chars in buffer
noecho(); //Don't print typed characters to the screen
keypad(stdscr, true); //Enables reading special characters like F1, F2, ..., arrow keys, etc.
nodelay(stdscr, true); //Makes getch non-blocking
curs_set(0); //Makes cursor invisible
if (has_colors()) {
isColor = true;
start_color();
}
}
instCount++;
}
CursesInstance::CursesInstance(const CursesInstance& c) {
instCount++;
}
CursesInstance::CursesInstance(CursesInstance&& c) {
instCount++; //Destructor of other still called, so we need this
}
CursesInstance::~CursesInstance() {
instCount--;
if (instCount == 0) {
endwin();
}
}
CursesInstance& CursesInstance::operator=(const CursesInstance& c) {
//This one was counted in instCount and still is, so we don't
//do anything
return *this;
}
CursesInstance& CursesInstance::operator=(CursesInstance&& c) {
//Once again, this one has already been counted, so we
//don't need to count it again
return *this;
}
bool CursesInstance::hasColor() {
return isColor;
}
void CursesInstance::initColorPair(int pairNum, int foreground, int background) {
init_pair(pairNum, foreground, background);
}
chtype CursesInstance::getColorPair(int pairNum) {
return COLOR_PAIR(pairNum);
}
chtype CursesInstance::applyColorPair(int pairNum, chtype c) {
return c | getColorPair(pairNum);
}
void CursesInstance::handleResize() {
clear(); //rest is already handled by ncurses
}
int CursesInstance::getWidth() {
return getmaxx(stdscr);
}
int CursesInstance::getHeight() {
return getmaxy(stdscr);
}
int CursesInstance::getChar() {
return getch();
}
|
4a520a0e228e5f5c181d47ff800584f6ca7d98fa | 8162087251f674ed90c5d3ae89713f4e09e24c7e | /pbfs/pennant.h | 5652ba651d395907f7bcf9bbf4e7979fdd4d6497 | [] | no_license | puhach/pbfs | 1455599ae0c6d8d1122fd212c3f03542699e0096 | 45e4bd69490f48debe18ab52499e443f992beebc | refs/heads/master | 2023-05-23T07:16:41.113204 | 2021-06-01T13:08:53 | 2021-06-01T13:08:53 | 304,072,456 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | h | pennant.h | #ifndef PENNANT_H
#define PENNANT_H
#include <cstddef>
#include <memory>
#include <cassert>
class Pennant
{
public:
constexpr Pennant(int vertex) noexcept
: vertex(vertex), size(1) {}
Pennant(const Pennant& other);
Pennant(Pennant&& other) = default;
Pennant& operator = (const Pennant& other);
Pennant& operator = (Pennant&& other) = default;
constexpr int getVertex() const noexcept { assert(size > 0); return vertex; }
constexpr std::size_t getSize() const noexcept { return size; }
std::unique_ptr<Pennant> split() noexcept;
void merge(std::unique_ptr<Pennant> other);
// TODO: perhaps implement an overloaded version of merge:
// Pennant & merge(Pennant &&other);
private:
int vertex;
std::size_t size;
std::unique_ptr<Pennant> left, right;
}; // Pennant
#endif // PENNANT_H |
f263a48650ffe7cb50246cd67a6346f9134c9eec | d35486bdd83fc83c71a115eaf5b304270b795587 | /ApertusVR/plugins/ogre21Render/ApeOgre21RenderPlugin.cpp | 7e2f0a3b6d115d82749925bb90b768878fbcd7d1 | [] | no_license | MTASZTAKI/Experimental | e6c952df1af31cd1d3b11272ebb8d26133dd82d0 | d759890152b5ded54db7ecb689a282250cd03b3b | refs/heads/master | 2021-11-29T01:11:42.333398 | 2021-11-25T12:41:20 | 2021-11-25T12:41:20 | 211,269,901 | 1 | 2 | null | null | null | null | ISO-8859-2 | C++ | false | false | 115,954 | cpp | ApeOgre21RenderPlugin.cpp | /*MIT License
Copyright (c) 2016 MTA SZTAKI
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 "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filewritestream.h"
#include "ApeOgre21RenderPlugin.h"
//#include "apeOgreUtilities.h"
ape::Ogre21RenderPlugin::Ogre21RenderPlugin() //constructor
{
APE_LOG_FUNC_ENTER();
mpSceneManager = ape::ISceneManager::getSingletonPtr();
mpCoreConfig = ape::ICoreConfig::getSingletonPtr();
//mpMainWindow = ape::IMainWindow::getSingletonPtr(); -> itt is mást kell
mEventDoubleQueue = ape::DoubleQueue<Event>();
mpEventManager = ape::IEventManager::getSingletonPtr();
mpEventManager->connectEvent(ape::Event::Group::NODE, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::LIGHT, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::CAMERA, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_FILE, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_TEXT, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_PLANE, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_BOX, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_CYLINDER, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_CONE, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_TUBE, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_SPHERE, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_TORUS, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_INDEXEDFACESET, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_INDEXEDLINESET, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::MATERIAL_FILE, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::MATERIAL_MANUAL, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::MATERIAL_PBS, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::PASS_MANUAL, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::TEXTURE_MANUAL, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::TEXTURE_UNIT, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::GEOMETRY_RAY, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::SKY, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::WATER, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpEventManager->connectEvent(ape::Event::Group::POINT_CLOUD, std::bind(&Ogre21RenderPlugin::eventCallBack, this, std::placeholders::_1));
mpRoot = nullptr;
mpSceneMgr = nullptr;
mRenderWindows = std::map<std::string, Ogre::RenderWindow*>();
mpHlmsPbsManager = nullptr;
mOgreRenderPluginConfig = ape::Ogre21RenderPluginConfig();
mOgreCameras = std::vector<Ogre::Camera*>();
mCameraCountFromConfig = 0;
mpActualRenderwindow = nullptr;
mSkyBoxMaterial = Ogre::MaterialPtr();
APE_LOG_FUNC_LEAVE();
}
ape::Ogre21RenderPlugin::~Ogre21RenderPlugin() //destructor
{
std::cout << "OgreRenderPlugin dtor" << std::endl;
Ogre::CompositorManager2* compositorManager = mpRoot->getCompositorManager2();
compositorManager->removeAllWorkspaces();
delete mpRoot;
}
void ape::Ogre21RenderPlugin::eventCallBack(const ape::Event& event)
{
mEventDoubleQueue.push(event);
}
void ape::Ogre21RenderPlugin::processEventDoubleQueue()
{
mEventDoubleQueue.swap();
while (!mEventDoubleQueue.emptyPop())
{
ape::Event event = mEventDoubleQueue.front();
if (event.group == ape::Event::Group::NODE)
{
if (auto node = mpSceneManager->getNode(event.subjectName).lock())
{
std::string nodeName = node->getName();
if (event.type == ape::Event::Type::NODE_CREATE)
{
auto ogreNode = mpSceneMgr->getRootSceneNode()->createChildSceneNode();
ogreNode->setName(nodeName);
}
else
{
Ogre::SceneNode* ogreNode = nullptr;
auto ogreNodeList = mpSceneMgr->findSceneNodes(nodeName);
if (!ogreNodeList.empty())
{
ogreNode = mpSceneMgr->getSceneNode(ogreNodeList[0]->getId());
}
if (ogreNode)
{
switch (event.type)
{
case ape::Event::Type::NODE_PARENTNODE:
{
if (auto parentNode = node->getParentNode().lock())
{
auto ogreOldParentNode = ogreNode->getParentSceneNode();
if (ogreOldParentNode)
{
ogreOldParentNode->removeChild(ogreNode);
}
auto ogreNodeList = mpSceneMgr->findSceneNodes(parentNode->getName());
if (ogreNodeList[0] != nullptr)
{
auto ogreNewParentNode = mpSceneMgr->getSceneNode(ogreNodeList[0]->getId());
ogreNewParentNode->addChild(ogreNode);
}
}
}
break;
case ape::Event::Type::NODE_DELETE:
;
break;
case ape::Event::Type::NODE_POSITION:
ogreNode->setPosition(ape::ConversionToOgre21(node->getPosition()));
break;
case ape::Event::Type::NODE_ORIENTATION:
ogreNode->setOrientation(ape::ConversionToOgre21(node->getOrientation()));
break;
case ape::Event::Type::NODE_SCALE:
ogreNode->setScale(ape::ConversionToOgre21(node->getScale()));
break;
case ape::Event::Type::NODE_CHILDVISIBILITY:
ogreNode->setVisible(node->getChildrenVisibility());
break;
case ape::Event::Type::NODE_FIXEDYAW:
ogreNode->setFixedYawAxis(node->isInheritOrientation());
break;
case ape::Event::Type::NODE_INITIALSTATE:
;//ilyen nincs az ogre2.1ben
break;
case ape::Event::Type::NODE_SHOWBOUNDINGBOX:
;
//ogreNode->showBoundingBox(true); ilyensincs
break;
case ape::Event::Type::NODE_HIDEBOUNDINGBOX:
;
//ogreNode->showBoundingBox(false); ilyen sincs
break;
}
}
}
}
}
else if (event.group == ape::Event::Group::MATERIAL_FILE)
{
if (auto materialFile = std::static_pointer_cast<ape::IFileMaterial>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string materialName = materialFile->getName();
Ogre::MaterialPtr ogreMaterial;
if (Ogre::MaterialManager::getSingleton().resourceExists(materialName))
{
ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(materialName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
switch (event.type)
{
case ape::Event::Type::MATERIAL_FILE_CREATE:
;
break;
case ape::Event::Type::MATERIAL_FILE_DELETE:
;
break;
case ape::Event::Type::MATERIAL_FILE_FILENAME:
;
break;
case ape::Event::Type::MATERIAL_FILE_SETASSKYBOX:
{
if (mSkyBoxMaterial.isNull())
{
mSkyBoxMaterial = Ogre::MaterialManager::getSingletonPtr()->getByName(materialName);
}
/*if (mpActualWorkSpace->isValid())
{
//Ogre::Material* material = materialPtr.getPointer();
Ogre::TextureUnitState* tex = material->getTechnique(0)->getPass(0)->getTextureUnitState(0);
tex->setCubicTextureName(materialName+".dds", true);
tex->setGamma(2.0);
material->compile();
mpActualWorkSpace->setEnabled(true);
}*/
}
break;
case ape::Event::Type::MATERIAL_FILE_TEXTURE:
{
if (auto texture = materialFile->getPassTexture().lock())
{
auto ogreTexture = Ogre::TextureManager::getSingleton().getByName(texture->getName());
if (!ogreTexture.isNull() && !ogreMaterial.isNull())
ogreMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTexture(ogreTexture);
}
}
break;
case ape::Event::Type::MATERIAL_FILE_GPUPARAMETERS:
{
if (!ogreMaterial.isNull())
{
Ogre::GpuProgramParametersSharedPtr ogreGpuParameters = ogreMaterial->getTechnique(0)->getPass(0)->getVertexProgramParameters();
if (!ogreGpuParameters.isNull())
{
for (auto passGpuParameter : materialFile->getPassGpuParameters())
ogreGpuParameters->setNamedConstant(passGpuParameter.name, ConversionToOgre21(passGpuParameter.value));
}
}
}
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_FILE)
{
if (auto geometryFile = std::static_pointer_cast<ape::IFileGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = geometryFile->getName();
std::string fileName = geometryFile->getFileName();
std::string parentNodeName = "";
if (auto parentNode = geometryFile->getParentNode().lock())
{
parentNodeName = parentNode->getName();
}
switch (event.type)
{
case ape::Event::Type::GEOMETRY_FILE_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_FILE_PARENTNODE:
{
if (mItemList[geometryName] != nullptr)
{
auto ogreEntity = mItemList[geometryName];
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
{
ogreParentNode->attachObject(ogreEntity);
}
}
}
case ape::Event::Type::GEOMETRY_FILE_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_FILE_FILENAME:
{
if (fileName.find_first_of(".") != std::string::npos)
{
std::string fileExtension = fileName.substr(fileName.find_last_of("."));
if (fileExtension == ".mesh")
{
//---------------------
Ogre::MeshPtr v2Mesh;
v2Mesh = Ogre::MeshManager::getSingleton().load(
fileName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::Item *item = mpSceneMgr->createItem(fileName,
Ogre::ResourceGroupManager::
AUTODETECT_RESOURCE_GROUP_NAME,
Ogre::SCENE_DYNAMIC);
//---------------------
//Ogre::Item* Item = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME, Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = item;
}
}
else if(mManualObjectList[fileName])
{
auto ogreManual = mManualObjectList[fileName];
std::stringstream meshName;
meshName << fileName << ".mesh";
if (Ogre::MeshManager::getSingleton().getByName(meshName.str()).isNull())
{
//ogreManual->convertToMesh(meshName.str());
Ogre::MeshPtr v2Mesh;
v2Mesh = Ogre::MeshManager::getSingleton().createManual(fileName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
if (!mItemList[geometryName])
{
auto item = mpSceneMgr->createItem(geometryName);
mItemList[geometryName] = item;
}
}
}
break;
case ape::Event::Type::GEOMETRY_FILE_MERGESUBMESHES:
{
//Ogre 2.1 not support
}
break;
case ape::Event::Type::GEOMETRY_FILE_EXPORT:
{
if (geometryFile->isExportMesh())
{
Ogre::MeshSerializer mMeshSerializer(0);
if (fileName.find_first_of(".") != std::string::npos)
{
std::string fileExtension = fileName.substr(fileName.find_last_of("."));
if (fileExtension == ".mesh")
{
auto mesh = Ogre::MeshManager::getSingleton().getByName(fileName);
if (!mesh.isNull())
{
mMeshSerializer.exportMesh(mesh.getPointer(), fileName);
}
}
}
else if (mManualObjectList[geometryName])
{
auto ogreManual = mManualObjectList[geometryName];
std::stringstream meshName;
meshName << geometryName << ".mesh";
if (Ogre::MeshManager::getSingleton().getByName(meshName.str()).isNull())
{
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createManual(meshName.str(),Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
if (!mesh.isNull())
{
mMeshSerializer.exportMesh(mesh.getPointer(), meshName.str());
//Ogre::Mesh::SubMeshIterator subMeshIterator = mesh->getSubMeshIterator();
Ogre::SubMesh* subMesh = nullptr;
int i = 0;
auto subMeshNum = mesh->getNumSubMeshes();
auto subMeshVec = mesh->getSubMeshes();
while (i<subMeshNum)
{
subMesh = subMeshVec[i];
std::string materialName = subMesh->getMaterialName();
auto ogreMaterial = Ogre::MaterialManager::getSingletonPtr()->getByName(materialName);
if (!ogreMaterial.isNull())
{
std::string filePath = ogreManual->getName();
std::size_t found = filePath.find_last_of("/\\");
filePath = filePath.substr(0, found + 1);
std::string materialFileName = materialName;
//TODO_apeOgreRenderPlugin automatic filesystem check for filenames and coding conversion
materialFileName.erase(std::remove(materialFileName.begin(), materialFileName.end(), '<'), materialFileName.end());
materialFileName.erase(std::remove(materialFileName.begin(), materialFileName.end(), '>'), materialFileName.end());
materialFileName.erase(std::remove(materialFileName.begin(), materialFileName.end(), '/'), materialFileName.end());
materialFileName.erase(std::remove(materialFileName.begin(), materialFileName.end(), '/\\'), materialFileName.end());
materialFileName.erase(std::remove(materialFileName.begin(), materialFileName.end(), ':'), materialFileName.end());
materialFileName.erase(std::remove(materialFileName.begin(), materialFileName.end(), ','), materialFileName.end());
/*std::wstring wMaterialFileName = utf8_decode(materialFileName.c_str());
std::wcout << wMaterialFileName << std::endl;*/
std::size_t materialFileNameHash = std::hash<std::string>{}(materialFileName);
std::stringstream materialFilePath;
materialFilePath << filePath << materialFileNameHash << ".material";
std::ifstream materialFile(materialFilePath.str());
if (!materialFile)
mMaterialSerializer.exportMaterial(ogreMaterial, materialFilePath.str());
}
}
mpSceneMgr->destroyManualObject(ogreManual);
auto ogreItem = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
mItemList[geometryName] = ogreItem;
}
}
}
}
}
break;
case ape::Event::Type::GEOMETRY_FILE_MATERIAL:
{
if (mItemList[geometryName])
{
auto ogreItem = mItemList[geometryName];
if (auto material = geometryFile->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
if (!ogreMaterial.isNull())
ogreItem->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_FILE_VISIBILITY:
{
if (mItemList[geometryName])
{
auto ogreItem = mItemList[geometryName];
ogreItem->setVisibilityFlags(geometryFile->getVisibilityFlag());
}
}
break;
}
}
}
else if (event.group == ape::Event::Group::LIGHT)
{
if (auto light = std::static_pointer_cast<ape::ILight>(mpSceneManager->getEntity(event.subjectName).lock()))
{
Ogre::Light* ogreLight = nullptr;
if (mLightList[light->getName()] != nullptr)
ogreLight = mLightList[light->getName()];
switch (event.type)
{
case ape::Event::Type::LIGHT_CREATE:
{
ogreLight = mpSceneMgr->createLight();
ogreLight->setName(light->getName());
mLightList[light->getName()] = ogreLight;
Ogre::SceneNode* lightNode = mpSceneMgr->getRootSceneNode(Ogre::SCENE_DYNAMIC)->createChildSceneNode(Ogre::SCENE_DYNAMIC);
lightNode->attachObject(ogreLight);
}
break;
case ape::Event::Type::LIGHT_ATTENUATION:
ogreLight->setAttenuation(light->getLightAttenuation().range, light->getLightAttenuation().constant, light->getLightAttenuation().linear, light->getLightAttenuation().quadratic);
break;
case ape::Event::Type::LIGHT_DIFFUSE:
ogreLight->setDiffuseColour(ape::ConversionToOgre21(light->getDiffuseColor()));
break;
case ape::Event::Type::LIGHT_DIRECTION:
ogreLight->setDirection(ape::ConversionToOgre21(light->getLightDirection()));
;
break;
case ape::Event::Type::LIGHT_SPECULAR:
ogreLight->setSpecularColour(ape::ConversionToOgre21(light->getSpecularColor()));
break;
case ape::Event::Type::LIGHT_SPOTRANGE:
ogreLight->setSpotlightRange(Ogre::Radian(light->getLightSpotRange().innerAngle.toRadian()), Ogre::Radian(light->getLightSpotRange().outerAngle.toRadian()), light->getLightSpotRange().falloff);
break;
case ape::Event::Type::LIGHT_TYPE:
ogreLight->setType(ape::ConversionToOgre21(light->getLightType()));
break;
case ape::Event::Type::LIGHT_PARENTNODE:
{
if (auto parentNode = light->getParentNode().lock())
{
auto parentList = mpSceneMgr->findSceneNodes(parentNode->getName());
if (auto ogreParentNode = mpSceneMgr->getSceneNode(parentList[0]->getId()))
{
ogreLight->detachFromParent();
ogreParentNode->attachObject(ogreLight);
}
}
ogreLight->setDirection(ape::ConversionToOgre21(light->getLightDirection()));
}
break;
case ape::Event::Type::LIGHT_DELETE:
;
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_PLANE)
{
if (auto primitive = std::static_pointer_cast<ape::IPlaneGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = primitive->getName();
std::string parentNodeName = "";
if (auto parentNode = primitive->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_PLANE_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_PLANE_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = mpSceneMgr->getSceneNode(parentList[0]->getId()))
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_PLANE_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_PLANE_MATERIAL:
{
if (Ogre::Item* ogreItem = mItemList[geometryName])
{
if (auto material = primitive->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
ogreItem->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_PLANE_PARAMETERS:
{
std::stringstream meshFileName;
meshFileName << geometryName << ".mesh";
if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, meshFileName.str()))
{
ape::GeometryPlaneParameters parameters = primitive->getParameters();
// procedural not yet implemented
//Procedural::PlaneGenerator().setNumSegX(parameters.numSeg.x).setNumSegY(parameters.numSeg.y).setSizeX(parameters.size.x).setSizeY(parameters.size.y)
//.setUTile(parameters.tile.x).setVTile(parameters.tile.y).realizeMesh(meshFileName.str());
}
Ogre::Item* planeItem = mpSceneMgr->createItem(geometryName,Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = planeItem;
}
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_BOX)
{
if (auto primitive = std::static_pointer_cast<ape::IBoxGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = primitive->getName();
std::string parentNodeName = "";
if (auto parentNode = primitive->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_BOX_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_BOX_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto ParentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = ParentList[0])
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_BOX_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_BOX_MATERIAL:
{
if (auto ogreItem = mItemList[geometryName])
{
if (auto material = primitive->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
ogreItem->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_BOX_PARAMETERS:
{
std::stringstream meshFileName;
meshFileName << geometryName << ".mesh";
if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, meshFileName.str()))
{
ape::GeometryBoxParameters parameters = primitive->getParameters();
// procedural not yet implemented
//Procedural::BoxGenerator().setSizeX(parameters.dimensions.x).setSizeY(parameters.dimensions.x).setSizeZ(parameters.dimensions.x)
// .realizeMesh(meshFileName.str());
}
Ogre::Item* boxItem = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = boxItem;
}
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_SPHERE)
{
if (auto primitive = std::static_pointer_cast<ape::ISphereGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = primitive->getName();
std::string parentNodeName = "";
if (auto parentNode = primitive->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_SPHERE_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_SPHERE_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_SPHERE_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_SPHERE_MATERIAL:
{
if (auto ogreItem = mItemList[geometryName])
{
if (auto material = primitive->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
ogreItem->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_SPHERE_PARAMETERS:
{
std::stringstream meshFileName;
meshFileName << geometryName << ".mesh";
if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, meshFileName.str()))
{
ape::GeometrySphereParameters parameters = primitive->getParameters();
// procedural not yet implemented
//Procedural::SphereGenerator().setRadius(parameters.radius)
// .setUTile(parameters.tile.x).setVTile(parameters.tile.y)
// .realizeMesh(meshFileName.str());
}
Ogre::Item* sphereItem = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = sphereItem;
}
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_CYLINDER)
{
if (auto primitive = std::static_pointer_cast<ape::ICylinderGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = primitive->getName();
std::string parentNodeName = "";
if (auto parentNode = primitive->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_CYLINDER_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_CYLINDER_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_CYLINDER_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_CYLINDER_MATERIAL:
{
if (auto ogreItem = mItemList[geometryName])
{
if (auto material = primitive->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
ogreItem->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_CYLINDER_PARAMETERS:
{
std::stringstream meshFileName;
meshFileName << geometryName << ".mesh";
if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, meshFileName.str()))
{
ape::GeometryCylinderParameters parameters = primitive->getParameters();
//not implemented
//Procedural::CylinderGenerator().setHeight(parameters.height)
// .setRadius(parameters.radius)
// .setUTile(parameters.tile)
// .realizeMesh(meshFileName.str());
}
Ogre::Item* cylinderItem = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = cylinderItem;
}
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_TORUS)
{
if (auto primitive = std::static_pointer_cast<ape::ITorusGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = primitive->getName();
std::string parentNodeName = "";
if (auto parentNode = primitive->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_TORUS_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_TORUS_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_TORUS_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_TORUS_MATERIAL:
{
if (auto ogreEntity = mItemList[geometryName])
{
if (auto material = primitive->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
ogreEntity->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_TORUS_PARAMETERS:
{
std::stringstream meshFileName;
meshFileName << geometryName << ".mesh";
if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, meshFileName.str()))
{
ape::GeometryTorusParameters parameters = primitive->getParameters();
//not implemted
//Procedural::TorusGenerator().setRadius(parameters.radius)
// .setSectionRadius(parameters.sectionRadius)
// .setUTile(parameters.tile.x).setVTile(parameters.tile.y)
// .realizeMesh(meshFileName.str());
}
Ogre::Item* torusItem = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = torusItem;
}
break;
}
}
}
/*else if (event.group == ape::Event::Group::GEOMETRY_CONE)
{
if (auto primitive = std::static_pointer_cast<ape::IConeGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = primitive->getName();
std::string parentNodeName = "";
if (auto parentNode = primitive->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_CONE_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_CONE_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_CONE_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_CONE_MATERIAL:
{
if (auto ogreEntity = mItemList[geometryName])
{
if (auto material = primitive->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
ogreEntity->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_CONE_PARAMETERS:
{
std::stringstream meshFileName;
meshFileName << geometryName << ".mesh";
if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, meshFileName.str()))
{
ape::GeometryConeParameters parameters = primitive->getParameters();
//not implemented
//Procedural::ConeGenerator().setRadius(parameters.radius)
// .setHeight(parameters.height)
// //.setNumSegBase(parameters.numSeg.x).setNumSegHeight(parameters.numSeg.y)
// //.setUTile(parameters.tile)
// .realizeMesh(meshFileName.str());
}
Ogre::Item* coneItem = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = coneItem;
}
break;
}
}
}*/
else if (event.group == ape::Event::Group::GEOMETRY_TUBE)
{
if (auto primitive = std::static_pointer_cast<ape::ITubeGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = primitive->getName();
std::string parentNodeName = "";
if (auto parentNode = primitive->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_TUBE_CREATE:
;
break;
case ape::Event::Type::GEOMETRY_TUBE_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_TUBE_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_TUBE_MATERIAL:
{
if (auto ogreEntity = mItemList[geometryName])
{
if (auto material = primitive->getMaterial().lock())
{
auto ogreMaterial = Ogre::MaterialManager::getSingleton().getByName(material->getName());
ogreEntity->setMaterial(ogreMaterial);
}
}
}
break;
case ape::Event::Type::GEOMETRY_TUBE_PARAMETERS:
{
std::stringstream meshFileName;
meshFileName << geometryName << ".mesh";
if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, meshFileName.str()))
{
ape::GeometryTubeParameters parameters = primitive->getParameters();
//not implemented
//Procedural::TubeGenerator().setHeight(parameters.height)
// .setUTile(parameters.tile)
// .realizeMesh(meshFileName.str());
}
Ogre::Item* tubeItem = mpSceneMgr->createItem(meshFileName.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::SCENE_DYNAMIC);
mItemList[geometryName] = tubeItem;
}
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_INDEXEDFACESET)
{
if (auto manual = std::static_pointer_cast<ape::IIndexedFaceSetGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
ape::GeometryIndexedFaceSetParameters parameters = manual->getParameters();
std::string geometryName = manual->getName();
if (parameters.groupName.size())
geometryName = parameters.groupName;
std::string parentNodeName = "";
if (auto parentNode = manual->getParentNode().lock())
parentNodeName = parentNode->getName();
Ogre::MeshPtr pmeshv2;
if (mMeshPtrList[geometryName])
{
pmeshv2 = mMeshPtrList[geometryName];
}else
{
pmeshv2 = Ogre::MeshManager::getSingleton().createManual(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
mMeshPtrList[geometryName] = pmeshv2;
}
switch (event.type)
{
case ape::Event::Type::GEOMETRY_INDEXEDFACESET_CREATE:
{
}
break;
case ape::Event::Type::GEOMETRY_INDEXEDFACESET_PARENTNODE:
{
if (mManualObjectList[geometryName])
{
if (auto ogreManual = mManualObjectList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
{
ogreParentNode->attachObject(ogreManual);
}
}
}
else if (mItemList[geometryName])
{
if (auto ogreItem = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
ogreParentNode->attachObject(ogreItem);
}
}
else if (mMeshPtrList[geometryName])
{
auto item = mpSceneMgr->createItem(pmeshv2);
mItemList[geometryName] = item;
auto parentList = mpSceneMgr->findSceneNodes(parentNodeName);
if (auto ogreParentNode = parentList[0])
ogreParentNode->attachObject(item);
}
}
break;
case ape::Event::Type::GEOMETRY_INDEXEDFACESET_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_INDEXEDFACESET_MATERIAL:
{
if (!mItemList[geometryName])
{
auto item = mpSceneMgr->createItem(pmeshv2);
mItemList[geometryName] = item;
}
if (auto ogreItem = mItemList[geometryName])
{
if (auto material = manual->getMaterial().lock())
{
//Ogre::HlmsPbsDatablock ogreMaterial = mpRoot->getHlmsManager()->getDatablock(material->getName());
Ogre::HlmsPbsDatablock* ogreMaterial = mPbsDataBlockList[material->getName()];
//ogreItem->setDatablock(ogreMaterial);
auto till = ogreItem->getNumSubItems();
for (size_t i = 0; i < till; i++)
{
ogreItem->getSubItem(i)->setDatablock(ogreMaterial);
/*mItemList["Cube_d.mesh"]->setDatablock("Rocks");
mItemList["Sphere1000.mesh"]->setDatablock("Rocks");*/
}
}
}
}
break;
case ape::Event::Type::GEOMETRY_INDEXEDFACESET_PARAMETERS:
{
Ogre::VaoManager *vaoManager = Ogre::Root::getSingleton().getRenderSystem()->getVaoManager();
// create vertex buffer
unsigned short numreal = 3;
Ogre::VertexElement2Vec velements;
velements.push_back(Ogre::VertexElement2(Ogre::VET_FLOAT3, Ogre::VES_POSITION));
if (manual->getHasNormals())
{
numreal += 3;
velements.push_back(Ogre::VertexElement2(Ogre::VET_FLOAT3, Ogre::VES_NORMAL));
}if (manual->getHasTangents())
{
numreal += 3;
velements.push_back(Ogre::VertexElement2(Ogre::VET_FLOAT3, Ogre::VES_TANGENT));
}
if (manual->getHasTextureCoords())
{
numreal += 3;
velements.push_back(Ogre::VertexElement2(Ogre::VET_FLOAT3, Ogre::VES_TEXTURE_COORDINATES));
}
if (manual->getHasVertexColors())
{
numreal += 3;
velements.push_back(Ogre::VertexElement2(Ogre::VET_FLOAT3, Ogre::VES_DIFFUSE));
}
//parameters.faces.faceVectors.size();
Ogre::Real *vertexdata = reinterpret_cast<Ogre::Real *> (OGRE_MALLOC_SIMD(
sizeof(Ogre::Real) * numreal * parameters.faces.faceVectors.size(), Ogre::MEMCATEGORY_GEOMETRY));
Ogre::FreeOnDestructor vdataPtr(vertexdata);
// fill vertexdata manually
// prime pointers to vertex related data
std::vector<ape::Vector3> uvvec = manual->getUvs();
//ape::Vector3 *uv = uvvec[0];
ape::Vector4 *col = manual->getCols();
ape::Vector3 vect3 = parameters.faces.faceVectors[0];
Ogre::Aabb subAABB(Ogre::Vector3(vect3.x, vect3.y, vect3.z), Ogre::Vector3::ZERO);
int normalhelper = 0;
int tangenthelper = 0;
int cordHelp = 0;
for (unsigned int i = 0, offset = 0; i < parameters.faces.faceVectors.size(); ++i)
{
// position
vect3 = parameters.faces.faceVectors[i];
vertexdata[offset + 0] = vect3.x;
vertexdata[offset + 1] = vect3.y;
vertexdata[offset + 2] = vect3.z;
//vertexdata[offset + 0] = parameters.coordinates[cordHelp + 0];
//vertexdata[offset + 1] = parameters.coordinates[cordHelp + 1];
//vertexdata[offset + 2] = parameters.coordinates[cordHelp + 2];
offset += 3;
subAABB.merge(Ogre::Vector3(vect3.x, vect3.y, vect3.z));
//subAABB.merge(Ogre::Vector3(parameters.coordinates[cordHelp + 0], parameters.coordinates[cordHelp + 1], parameters.coordinates[cordHelp + 2]));
cordHelp += 3;
// normal
if (manual->getHasNormals())
{
vertexdata[offset + 0] = parameters.normals[normalhelper + 0];
vertexdata[offset + 1] = parameters.normals[normalhelper + 1];
vertexdata[offset + 2] = parameters.normals[normalhelper + 2];
offset += 3;
normalhelper += 3;
}
//tangent
if (manual->getHasTangents())
{
vertexdata[offset + 0] = parameters.tangents[tangenthelper + 0];
vertexdata[offset + 1] = parameters.tangents[tangenthelper + 1];
vertexdata[offset + 2] = parameters.tangents[tangenthelper + 2];
offset += 3;
tangenthelper += 3;
}
// uv
if (manual->getHasTextureCoords())
{
vertexdata[offset + 0] = uvvec[i].x;
vertexdata[offset + 1] = uvvec[i].y;
vertexdata[offset + 2] = uvvec[i].z;
offset += 3;
}
// color
if (manual->getHasVertexColors())
{
vertexdata[offset + 0] = col[i].x;//r
vertexdata[offset + 1] = col[i].y;//g
vertexdata[offset + 2] = col[i].z;//b
offset += 3;
}
}
Ogre::VertexBufferPacked *vertexBuffer = 0;
try
{
//Create the actual vertex buffer.
vertexBuffer = vaoManager->createVertexBuffer(velements, parameters.faces.faceVectors.size(),
Ogre::BT_IMMUTABLE,
vertexdata, false);
}
catch (Ogre::Exception &e)
{
// When keepAsShadow = true, the memory will be freed when the index buffer is destroyed.
// However if for some weird reason there is an exception raised, the memory will
// not be freed, so it is up to us to do so.
// The reasons for exceptions are very rare. But we're doing this for correctness.
OGRE_FREE_SIMD(vertexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
vertexBuffer = 0;
throw e;
}
//We'll just use one vertex buffer source (multi-source not working yet)
Ogre::VertexBufferPackedVec vertexBuffers;
vertexBuffers.push_back(vertexBuffer);
// currently consider 16-bit indices array only
Ogre::uint16 * indexdata = reinterpret_cast<Ogre::uint16 *>(OGRE_MALLOC_SIMD(
sizeof(Ogre::uint16) * 3 * parameters.faces.face.size(), Ogre::MEMCATEGORY_GEOMETRY));
Ogre::FreeOnDestructor iddataPtr(indexdata);
for (unsigned int i = 0, offset = 0; i < parameters.indices.size()/3; ++i)
{
indexdata[offset + 0] = (Ogre::uint16)parameters.indices[offset + 0];
indexdata[offset + 1] = (Ogre::uint16)parameters.indices[offset + 1];
indexdata[offset + 2] = (Ogre::uint16)parameters.indices[offset + 2];
offset += 3;
}
Ogre::IndexBufferPacked *indexBuffer = 0;
try
{
indexBuffer = vaoManager->createIndexBuffer(Ogre::IndexBufferPacked::IT_16BIT,
3 * parameters.indices.size()/3, // number of indices
Ogre::BT_IMMUTABLE,
indexdata, false);
}
catch (Ogre::Exception &e)
{
// When keepAsShadow = true, the memory will be freed when the index buffer is destroyed.
// However if for some weird reason there is an exception raised, the memory will
// not be freed, so it is up to us to do so.
// The reasons for exceptions are very rare. But we're doing this for correctness.
OGRE_FREE_SIMD(indexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
indexBuffer = 0;
throw e;
}
Ogre::SubMesh * submesh = pmeshv2->createSubMesh(manual->getIndex());
Ogre::VertexArrayObject *vao = vaoManager->createVertexArrayObject(
vertexBuffers, indexBuffer, Ogre::OT_TRIANGLE_LIST);
//Each Vao pushed to the vector refers to an LOD level.
//Must be in sync with mesh->mLodValues & mesh->mNumLods if you use more than one level
submesh->mVao[Ogre::VpNormal].push_back(vao);
//Use the same geometry for shadow casting.
submesh->mVao[Ogre::VpShadow].push_back(vao);
// AABB
if (pmeshv2->getNumSubMeshes() > 0) // not first
{
subAABB.merge(pmeshv2->getAabb());
}
pmeshv2->_setBounds(subAABB, false); // merging AABB from all sub-meshes, pad need to be FALSE
pmeshv2->_setBoundingSphereRadius(subAABB.getRadius());
}
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_INDEXEDLINESET)
{
if (auto manual = std::static_pointer_cast<ape::IIndexedLineSetGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = manual->getName();
std::string parentNodeName = "";
if (auto parentNode = manual->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_INDEXEDLINESET_CREATE:
{
Ogre::ManualObject* manObj = mpSceneMgr->createManualObject();
manObj->setName(geometryName);
mManualObjectList[geometryName] = manObj;
}
break;
case ape::Event::Type::GEOMETRY_INDEXEDLINESET_PARENTNODE:
{
if (auto ogreGeometry = mItemList[geometryName])
{
auto parentList = mpSceneMgr->findSceneNodes(geometryName);
if (auto ogreParentNode =parentList[0])
ogreParentNode->attachObject(ogreGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_INDEXEDLINESET_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_INDEXEDLINESET_PARAMETERS:
{
ape::GeometryIndexedLineSetParameters parameters = manual->getParameters();
if (auto ogreManual = mManualObjectList[geometryName])
{
// Ogre v1
ogreManual->begin("FlatVertexColorNoLighting");
for (int coordinateIndex = 0; coordinateIndex < parameters.coordinates.size(); coordinateIndex = coordinateIndex + 3)
{
ogreManual->position(parameters.coordinates[coordinateIndex], parameters.coordinates[coordinateIndex + 1], parameters.coordinates[coordinateIndex + 2]);
ogreManual->colour(ape::ConversionToOgre21(parameters.color));
}
int indexIndex = 0;
while (indexIndex < parameters.indices.size())
{
while (indexIndex < parameters.indices.size() && parameters.indices[indexIndex] != -1)
{
ogreManual->index(parameters.indices[indexIndex]);
indexIndex++;
}
indexIndex++;
}
ogreManual->end();
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createManual(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
auto item = mpSceneMgr->createItem(geometryName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
mpSceneMgr->destroyManualObject(mManualObjectList[geometryName]);
mManualObjectList.erase(geometryName);
mItemList[geometryName] = item;
}
}
break;
}
}
}
/*else if (event.group == ape::Event::Group::GEOMETRY_TEXT)
{
if (auto geometryText = std::static_pointer_cast<ape::ITextGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string geometryName = geometryText->getName();
std::string parentNodeName = "";
if (auto parentNode = geometryText->getParentNode().lock())
parentNodeName = parentNode->getName();
switch (event.type)
{
case ape::Event::Type::GEOMETRY_TEXT_CREATE:
{
if (auto ogreText = (ape::OgreMovableText*)mpOgreSceneManager->createMovableObject(geometryName, "MovableText"))
{
ogreText->setTextAlignment(ape::OgreMovableText::H_CENTER, ape::OgreMovableText::V_ABOVE);
ogreText->showOnTop(false);
}
}
break;
case ape::Event::Type::GEOMETRY_TEXT_SHOWONTOP:
{
if (auto ogreText = (ape::OgreMovableText*)mpOgreSceneManager->getMovableObject(geometryName, "MovableText"))
{
if (auto textGeometry = std::static_pointer_cast<ape::ITextGeometry>(mpSceneManager->getEntity(geometryName).lock()))
ogreText->showOnTop(textGeometry->isShownOnTop());
}
}
break;
case ape::Event::Type::GEOMETRY_TEXT_PARENTNODE:
{
if (auto ogreTextGeometry = (ape::OgreMovableText*)mpOgreSceneManager->getMovableObject(geometryName, "MovableText"))
{
if (auto ogreParentNode = mpOgreSceneManager->getSceneNode(parentNodeName))
ogreParentNode->attachObject(ogreTextGeometry);
}
}
break;
case ape::Event::Type::GEOMETRY_TEXT_DELETE:
;
break;
case ape::Event::Type::GEOMETRY_TEXT_CAPTION:
{
if (auto ogreText = (ape::OgreMovableText*)mpOgreSceneManager->getMovableObject(geometryName, "MovableText"))
{
if (auto textGeometry = std::static_pointer_cast<ape::ITextGeometry>(mpSceneManager->getEntity(geometryName).lock()))
ogreText->setCaption(textGeometry->getCaption());
}
}
break;
}
}
}*/
else if (event.group == ape::Event::Group::MATERIAL_PBS)
{
if (auto materialPbs = std::static_pointer_cast<ape::IPbsMaterial>(mpSceneManager->getEntity(event.subjectName).lock()))
{
//--
//**********
/*Ogre::String basename;
basename = materialPbs->getName();
Ogre::MaterialManager* omatMgr = Ogre::MaterialManager::getSingletonPtr();
Ogre::ResourceManager::ResourceCreateOrRetrieveResult status = omatMgr->createOrRetrieve(basename, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::MaterialPtr omat = status.first.staticCast<Ogre::Material>();
mMatList[basename] = omat;*/
//omat->setAmbient(clr.r, clr.g, clr.b);
//**********
std::string materialName = materialPbs->getName();
auto HlmsPbs = static_cast<Ogre::HlmsPbs*>(Ogre::Root::getSingleton().getHlmsManager()->getHlms(Ogre::HlmsTypes::HLMS_PBS));
Ogre::HlmsPbsDatablock* datablock;
if (mPbsDataBlockList[materialName] == nullptr)
{
datablock = static_cast<Ogre::HlmsPbsDatablock*>(HlmsPbs->createDatablock(Ogre::IdString(materialName),
materialName,
Ogre::HlmsMacroblock(),
Ogre::HlmsBlendblock(),
Ogre::HlmsParamVec()));
datablock->setWorkflow(Ogre::HlmsPbsDatablock::Workflows::MetallicWorkflow);
mPbsDataBlockList[materialName] = datablock;
}
else
{
datablock = static_cast<Ogre::HlmsPbsDatablock*>(HlmsPbs->getDatablock(Ogre::IdString(materialName)));
}
//datablock
//---
switch (event.type)
{
case ape::Event::Type::MATERIAL_PBS_CREATE:
;
break;
case ape::Event::Type::MATERIAL_PBS_DELETE:
;
break;
case ape::Event::Type::MATERIAL_PBS_DIFFUSE: //base color + alfa
{
datablock->setDiffuse(ConversionToOgre21_Alfaless(materialPbs->getDiffuseColor()));
float alpha = (ConversionToOgre21_Alfa(materialPbs->getDiffuseColor()));
auto transparentMode = (alpha == 1) ? Ogre::HlmsPbsDatablock::None : Ogre::HlmsPbsDatablock::Transparent;
datablock->setTransparency(alpha, transparentMode);
/*ape::Color clr = materialPbs->getDiffuseColor();
omat->setDiffuse(clr.r, clr.g, clr.b,clr.a);*/
}
break;
case ape::Event::Type::MATERIAL_PBS_SPECULAR:
{
/*ape::Color clr = materialPbs->getSpecularColor();
omat->setSpecular(clr.r, clr.g, clr.b, clr.a);*/
datablock->setSpecular(ConversionToOgre21_SCPECULAR(materialPbs->getSpecularColor()));
}
break;
case ape::Event::Type::MATERIAL_PBS_AMBIENT:
{
/*ape::Color clr = materialPbs->getAmbientColor();
omat->setAmbient(clr.r, clr.g, clr.b);*/
}
break;
case ape::Event::Type::MATERIAL_PBS_SHADINGMODE:
{
/*if (materialPbs->getShadingMode() == "SO_GOURAUD")
{
omat->setShadingMode(Ogre::SO_GOURAUD);
}
else if (materialPbs->getShadingMode() == "SO_FLAT")
{
omat->setShadingMode(Ogre::SO_FLAT);
}*/
}
break;
case ape::Event::Type::MATERIAL_PBS_SHININESS:
{
//omat->setShininess(Ogre::Real(materialPbs->getShininess()));
}
case ape::Event::Type::MATERIAL_PBS_EMISSIVE:
{
/*ape::Color clr = materialPbs->getEmissiveColor();
omat->setSelfIllumination(clr.r, clr.g, clr.b);*/
datablock->setEmissive(ConversionToOgre21_Alfaless(materialPbs->getEmissiveColor()));
}
break;
case ape::Event::Type::MATERIAL_PBS_ALPHAMODE:
{
if (materialPbs->getAlphaMode() == "BLEND")
{
auto blendBlock = *datablock->getBlendblock();
blendBlock.setBlendType(Ogre::SBT_TRANSPARENT_ALPHA);
datablock->setBlendblock(blendBlock);
}
else if (materialPbs->getAlphaMode() == "MASK")
{
datablock->setAlphaTest(Ogre::CMPF_GREATER_EQUAL);
}
}
break;
case ape::Event::Type::MATERIAL_PBS_BASECOLOR_TEXTURE:
{
/*auto texture = materialPbs->getBaseColorTexture();
Ogre::TexturePtr texptr = mpRoot->getTextureManager()->getByName(texture);
datablock->setTexture(Ogre::PbsTextureTypes::PBSM_DIFFUSE, 0, texptr);*/
/*static Ogre::uint8 s_RGB[] = { 128, 0, 255, 128, 0, 255, 128, 0, 255, 128, 0, 255 };
// attempt to load the image
Ogre::Image image;
std::string path = materialPbs->getBaseColorTexture();
// possibly if we fail to actually find it, pop up a box?
Ogre::String pathname(materialPbs->getBaseColorTexture());
std::ifstream imgstream;
imgstream.open(path.data(), std::ios::binary);
if (!imgstream.is_open())
imgstream.open(Ogre::String(path + Ogre::String("\\") + Ogre::String(path.data())).c_str(), std::ios::binary);
if (imgstream.is_open())
{
// Wrap as a stream
Ogre::DataStreamPtr strm(OGRE_NEW Ogre::FileStreamDataStream(path.data(), &imgstream, false));
if (!strm->size() || strm->size() == 0xffffffff)
{
// fall back to our very simple and very hardcoded hot-pink version
Ogre::DataStreamPtr altStrm(OGRE_NEW Ogre::MemoryDataStream(s_RGB, sizeof(s_RGB)));
image.loadRawData(altStrm, 2, 2, 1, Ogre::PF_R8G8B8);
}
else
{
// extract extension from filename
size_t pos = pathname.find_last_of('.');
Ogre::String ext = pathname.substr(pos + 1);
image.load(strm, ext);
imgstream.close();
}
}
else {
// fall back to our very simple and very hardcoded hot-pink version
Ogre::DataStreamPtr altStrm(OGRE_NEW Ogre::MemoryDataStream(s_RGB, sizeof(s_RGB)));
image.loadRawData(altStrm, 2, 2, 1, Ogre::PF_R8G8B8);
}
// Ogre::TextureManager::getSingleton().loadImage(Ogre::String(szPath.data), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, image);
//TODO: save this to materials/textures ?
//Ogre::TextureUnitState* texUnitState = omat->getTechnique(0)->getPass(0)->createTextureUnitState(basename);
const auto renderSystem = Ogre::Root::getSingleton().getRenderSystem();
const auto renderSystemGammaConversionConfigOption = renderSystem->getConfigOptions().at("sRGB Gamma Conversion");
bool isHardwareGammaEnabled;
if (renderSystemGammaConversionConfigOption.currentValue != "Yes")
{
isHardwareGammaEnabled = true;
}
else
{
isHardwareGammaEnabled = false;
}
const auto pixelFormat = [&] {
if (!(image.getHasAlpha())) return Ogre::PF_BYTE_RGB;
if (image.getHasAlpha()) return Ogre::PF_BYTE_RGBA;
}();
Ogre::TexturePtr BaseTex = mpRoot->getTextureManager()->createManual(materialPbs->getMetallicRoughnessTexture(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TextureType::TEX_TYPE_2D_ARRAY, image.getWidth(),
image.getHeight(),
1,
1,
pixelFormat,
Ogre::TU_DEFAULT,
nullptr,
isHardwareGammaEnabled);*/
Ogre::Image img = Ogre::Image();
img.load(materialPbs->getBaseColorTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//Ogre::TexturePtr metalTex = mpRoot->getTextureManager()->loadImage(materialPbs->getMetallicRoughnessTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, img);
const auto pixelFormat = [&] {
if (!(img.getHasAlpha())) return Ogre::PF_BYTE_RGB;
if (img.getHasAlpha()) return Ogre::PF_BYTE_RGBA;
}();
const auto renderSystem = Ogre::Root::getSingleton().getRenderSystem();
bool isHardwareGammaEnabled;
const auto renderSystemGammaConversionConfigOption = renderSystem->getConfigOptions().at("sRGB Gamma Conversion");
if (renderSystemGammaConversionConfigOption.currentValue != "Yes")
{
isHardwareGammaEnabled = true;
}
else
{
isHardwareGammaEnabled = false;
}
Ogre::TexturePtr BaseTex = mpRoot->getTextureManager()->createManual(materialPbs->getMetallicRoughnessTexture(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TextureType::TEX_TYPE_2D_ARRAY, img.getWidth(),
img.getHeight(),
1,
1,
pixelFormat,
Ogre::TU_DEFAULT,
nullptr,
isHardwareGammaEnabled);
BaseTex->loadImage(img);
datablock->setTexture(Ogre::PbsTextureTypes::PBSM_DIFFUSE, 0, BaseTex);
}
break;
case ape::Event::Type::MATERIAL_PBS_METALLICROUGHNESS_TEXTURE:
{
Ogre::Image img = Ogre::Image();
img.load(materialPbs->getMetallicRoughnessTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//Ogre::TexturePtr metalTex = mpRoot->getTextureManager()->loadImage(materialPbs->getMetallicRoughnessTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, img);
const auto pixelFormat = [&] {
if (!(img.getHasAlpha())) return Ogre::PF_BYTE_RGB;
if (img.getHasAlpha()) return Ogre::PF_BYTE_RGBA;
}();
const auto renderSystem = Ogre::Root::getSingleton().getRenderSystem();
bool isHardwareGammaEnabled;
const auto renderSystemGammaConversionConfigOption = renderSystem->getConfigOptions().at("sRGB Gamma Conversion");
if (renderSystemGammaConversionConfigOption.currentValue != "Yes")
{
isHardwareGammaEnabled = true;
}
else
{
isHardwareGammaEnabled = false;
}
Ogre::TexturePtr metalTex = mpRoot->getTextureManager()->createManual(materialPbs->getMetallicRoughnessTexture(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TextureType::TEX_TYPE_2D_ARRAY, img.getWidth(),
img.getHeight(),
1,
1,
pixelFormat,
Ogre::TU_DEFAULT,
nullptr,
isHardwareGammaEnabled);
metalTex->loadImage(img);
if (metalTex)
{
//OgreLog("metalness greyscale texture extracted by textureImporter : " + metalTexure->getName());
datablock->setTexture(Ogre::PbsTextureTypes::PBSM_METALLIC, 0, metalTex);
}
}
break;
case ape::Event::Type::MATERIAL_PBS_BASECOLOR:
{
//datablock->setFresnel(ConversionToOgre21_Alfaless(materialPbs->getF0()),false);
}
break;
case ape::Event::Type::MATERIAL_PBS_METALNESS:
{
datablock->setMetalness(materialPbs->getMetalness());
}
break;
case ape::Event::Type::MATERIAL_PBS_ROUGHNESS:
{
datablock->setRoughness(materialPbs->getRoughness());
}
break;
case ape::Event::Type::MATERIAL_PBS_NORMAL_TEXTURE:
{
Ogre::Image img = Ogre::Image();
img.load(materialPbs->getNormalTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//Ogre::TexturePtr metalTex = mpRoot->getTextureManager()->loadImage(materialPbs->getMetallicRoughnessTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, img);
const auto pixelFormat = [&] {
if (!(img.getHasAlpha())) return Ogre::PF_BYTE_RGB;
if (img.getHasAlpha()) return Ogre::PF_BYTE_RGBA;
}();
const auto renderSystem = Ogre::Root::getSingleton().getRenderSystem();
bool isHardwareGammaEnabled;
const auto renderSystemGammaConversionConfigOption = renderSystem->getConfigOptions().at("sRGB Gamma Conversion");
if (renderSystemGammaConversionConfigOption.currentValue != "Yes")
{
isHardwareGammaEnabled = true;
}
else
{
isHardwareGammaEnabled = false;
}
//auto BaseTex = mpRoot->getTextureManager()->create(materialPbs->getMetallicRoughnessTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TextureType::TEX_TYPE_2D_ARRAY);
Ogre::TexturePtr BaseTex = mpRoot->getTextureManager()->createManual(materialPbs->getMetallicRoughnessTexture(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TextureType::TEX_TYPE_2D_ARRAY, img.getWidth(),
img.getHeight(),
1,
1,
pixelFormat,
Ogre::TU_DEFAULT,
nullptr,
isHardwareGammaEnabled);
////--
// Ogre::HlmsTextureManager::TextureLocation texLocation =
// mpRoot->getHlmsManager()->getTextureManager()->createOrRetrieveTexture(materialPbs->getBaseColorTexture(), materialPbs->getBaseColorTexture(), Ogre::HlmsTextureManager::TEXTURE_TYPE_DIFFUSE);
//
// texLocation.texture = BaseTex;
//
//
////--
BaseTex->loadImage(img);
BaseTex->load();
datablock->setTexture(Ogre::PbsTextureTypes::PBSM_DIFFUSE,0 , BaseTex);
}
break;
case ape::Event::Type::MATERIAL_PBS_EMISSIVE_TEXTURE:
{
Ogre::Image img = Ogre::Image();
img.load(materialPbs->getEmissiveTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//Ogre::TexturePtr metalTex = mpRoot->getTextureManager()->loadImage(materialPbs->getMetallicRoughnessTexture(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, img);
const auto pixelFormat = [&] {
if (!(img.getHasAlpha())) return Ogre::PF_BYTE_RGB;
if (img.getHasAlpha()) return Ogre::PF_BYTE_RGBA;
}();
const auto renderSystem = Ogre::Root::getSingleton().getRenderSystem();
bool isHardwareGammaEnabled;
const auto renderSystemGammaConversionConfigOption = renderSystem->getConfigOptions().at("sRGB Gamma Conversion");
if (renderSystemGammaConversionConfigOption.currentValue != "Yes")
{
isHardwareGammaEnabled = true;
}
else
{
isHardwareGammaEnabled = false;
}
Ogre::TexturePtr EmissiveTex = mpRoot->getTextureManager()->createManual(materialPbs->getMetallicRoughnessTexture(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TextureType::TEX_TYPE_2D_ARRAY, img.getWidth(),
img.getHeight(),
1,
1,
pixelFormat,
Ogre::TU_DEFAULT,
nullptr,
isHardwareGammaEnabled);
EmissiveTex->loadImage(img);
datablock->setTexture(Ogre::PbsTextureTypes::PBSM_EMISSIVE, 0, EmissiveTex);
}
break;
/*case ape::Event::Type::MATERIAL_PBS_TEXTURE:
{
}
break;
case ape::Event::Type::MATERIAL_PBS_CULLINGMODE:
{
}
break;
case ape::Event::Type::MATERIAL_PBS_DEPTHBIAS:
{
}
break;
case ape::Event::Type::MATERIAL_PBS_LIGHTING:
{
}
break;
case ape::Event::Type::MATERIAL_PBS_SCENEBLENDING:
{
}
break;
case ape::Event::Type::MATERIAL_PBS_OVERLAY:
{
}
break;*/
}
}
// Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(true);
}
else if (event.group == ape::Event::Group::MATERIAL_MANUAL)
{
if (auto materialManual = std::static_pointer_cast<ape::IManualMaterial>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string materialName = materialManual->getName();
auto result = Ogre::MaterialManager::getSingleton().createOrRetrieve(materialName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//--
//---
Ogre::MaterialPtr ogreMaterial = result.first.staticCast<Ogre::Material>();
switch (event.type)
{
case ape::Event::Type::MATERIAL_MANUAL_CREATE:
;
break;
case ape::Event::Type::MATERIAL_MANUAL_DELETE:
;
break;
case ape::Event::Type::MATERIAL_MANUAL_DIFFUSE:
ogreMaterial->setDiffuse(ConversionToOgre21(materialManual->getDiffuseColor()));
//datablock->setDiffuse;
break;
case ape::Event::Type::MATERIAL_MANUAL_SPECULAR:
ogreMaterial->setSpecular(ConversionToOgre21(materialManual->getSpecularColor()));
break;
case ape::Event::Type::MATERIAL_MANUAL_AMBIENT:
ogreMaterial->setAmbient(ConversionToOgre21(materialManual->getAmbientColor()));
break;
case ape::Event::Type::MATERIAL_MANUAL_EMISSIVE:
ogreMaterial->setSelfIllumination(ConversionToOgre21(materialManual->getEmissiveColor()));
break;
case ape::Event::Type::MATERIAL_MANUAL_PASS:
{
if (auto pass = materialManual->getPass().lock())
{
Ogre::MaterialManager::getSingleton().remove(materialName);
auto ogrePassMaterial = Ogre::MaterialManager::getSingleton().getByName(pass->getName());
if (!ogrePassMaterial.isNull())
ogrePassMaterial->clone(materialName);
}
}
break;
case ape::Event::Type::MATERIAL_MANUAL_TEXTURE:
{
if (auto texture = materialManual->getPassTexture().lock())
{
Ogre::TexturePtr ogreTexture = Ogre::TextureManager::getSingleton().getByName(texture->getName(), Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);
Ogre::HlmsTextureManager* texmgr = mpRoot->getHlmsManager()->getTextureManager();
//texmgr->createOrRetrieveTexture(texture->getName(),)
if (!ogreTexture.isNull() && !ogreMaterial.isNull())
{
if (!ogreMaterial->getTechnique(0)->getPass(0)->getNumTextureUnitStates())
ogreMaterial->getTechnique(0)->getPass(0)->createTextureUnitState();
ogreMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTexture(ogreTexture);
}
}
}
break;
case ape::Event::Type::MATERIAL_MANUAL_CULLINGMODE:
{
// Ogre v1
//ogreMaterial->setCullingMode(ape::ConversionToOgre21(materialManual->getCullingMode()));
}
break;
case ape::Event::Type::MATERIAL_MANUAL_DEPTHBIAS:
{
// Ogre v1
//ogreMaterial->setDepthBias(materialManual->getDepthBias().x, materialManual->getDepthBias().x);
}
break;
case ape::Event::Type::MATERIAL_MANUAL_LIGHTING:
{
//ogre v1
/*ogreMaterial->setLightingEnabled(materialManual->getLightingEnabled());
if (mpShaderGenerator)
mpShaderGenerator->removeAllShaderBasedTechniques(ogreMaterial->getName());
mpShaderGeneratorResolver->appendIgnoreList(ogreMaterial->getName());*/
}
break;
case ape::Event::Type::MATERIAL_MANUAL_SCENEBLENDING:
{
//ogre v1
/*ogreMaterial->setCullingMode(ape::ConversionToOgre(materialManual->getCullingMode()));
ogreMaterial->setSceneBlending(ape::ConversionToOgre(materialManual->getSceneBlendingType()));
if (materialManual->getSceneBlendingType() == ape::Pass::SceneBlendingType::TRANSPARENT_ALPHA)
ogreMaterial->setDepthWriteEnabled(false);*/
}
break;
case ape::Event::Type::MATERIAL_MANUAL_OVERLAY:
{
//Ogre v1
/*auto overlay = Ogre::OverlayManager::getSingleton().getByName(materialName);
if (materialManual->isShowOnOverlay())
{
if (!overlay)
{
auto overlayPanelElement = static_cast<Ogre::PanelOverlayElement*>(Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", materialName));
overlayPanelElement->setMetricsMode(Ogre::GMM_RELATIVE);
overlayPanelElement->setMaterialName(materialName);
overlayPanelElement->setDimensions(1, 1);
overlayPanelElement->setPosition(0, 0);
overlay = Ogre::OverlayManager::getSingleton().create(materialName);
overlay->add2D(overlayPanelElement);
overlay->setZOrder(materialManual->getZOrder());
}
overlay->show();
}
else if (overlay)
overlay->hide();*/
}
break;
}
}
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(true);
}
/*else if (event.group == ape::Event::Group::PASS_PBS)
{
if (auto passPbs = std::static_pointer_cast<ape::IPbsPass>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string passPbsName = passPbs->getName();
auto result = Ogre::MaterialManager::getSingleton().createOrRetrieve(passPbsName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::MaterialPtr ogrePbsPassMaterial = result.first.staticCast<Ogre::Material>();
if (!ogrePbsPassMaterial.isNull())
{
switch (event.type)
{
case ape::Event::Type::MATERIAL_PBS_CREATE:
{
ogrePbsPassMaterial->createTechnique()->createPass();
Ogre::PbsMaterial* ogrePbsMaterial = new Ogre::PbsMaterial();
mPbsMaterials[passPbsName] = ogrePbsMaterial;
}
break;
case ape::Event::Type::MATERIAL_PBS_AMBIENT:
ogrePbsPassMaterial->setAmbient(ConversionToOgre21(passPbs->getAmbientColor()));
break;
case ape::Event::Type::MATERIAL_PBS_DIFFUSE:
ogrePbsPassMaterial->setDiffuse(ConversionToOgre21(passPbs->getDiffuseColor()));
break;
case ape::Event::Type::MATERIAL_PBS_EMISSIVE:
ogrePbsPassMaterial->setSelfIllumination(ConversionToOgre21(passPbs->getEmissiveColor()));
break;
case ape::Event::Type::MATERIAL_PBS_SPECULAR:
ogrePbsPassMaterial->setSpecular(ConversionToOgre21(passPbs->getSpecularColor()));
break;
case ape::Event::Type::MATERIAL_PBS_SHININESS:
ogrePbsPassMaterial->setShininess(passPbs->getShininess());
break;
case ape::Event::Type::MATERIAL_PBS_ALBEDO:
mPbsMaterials[passPbsName]->setAlbedo(ConversionToOgre21(passPbs->getAlbedo()));
break;
case ape::Event::Type::MATERIAL_PBS_F0:
mPbsMaterials[passPbsName]->setF0(ConversionToOgre21(passPbs->getF0()));
break;
case ape::Event::Type::MATERIAL_PBS_ROUGHNESS:
mPbsMaterials[passPbsName]->setRoughness(passPbs->getRoughness());
break;
case ape::Event::Type::MATERIAL_PBS_LIGHTROUGHNESSOFFSET:
mPbsMaterials[passPbsName]->setLightRoughnessOffset(passPbs->getLightRoughnessOffset());
break;
case ape::Event::Type::MATERIAL_PBS_DELETE:
;
break;
}
}
}
}*/
else if (event.group == ape::Event::Group::PASS_MANUAL)
{
if (auto passManual = std::static_pointer_cast<ape::IManualPass>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string passManualName = passManual->getName();
auto result = Ogre::MaterialManager::getSingleton().createOrRetrieve(passManualName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::MaterialPtr ogreManualPassMaterial = result.first.staticCast<Ogre::Material>();
if (!ogreManualPassMaterial.isNull())
{
switch (event.type)
{
case ape::Event::Type::PASS_MANUAL_CREATE:
ogreManualPassMaterial->createTechnique()->createPass();
break;
case ape::Event::Type::PASS_MANUAL_AMBIENT:
ogreManualPassMaterial->setAmbient(ConversionToOgre21(passManual->getAmbientColor()));
break;
case ape::Event::Type::PASS_MANUAL_DIFFUSE:
ogreManualPassMaterial->setDiffuse(ConversionToOgre21(passManual->getDiffuseColor()));
break;
case ape::Event::Type::PASS_MANUAL_EMISSIVE:
ogreManualPassMaterial->setSelfIllumination(ConversionToOgre21(passManual->getEmissiveColor()));
break;
case ape::Event::Type::PASS_MANUAL_SPECULAR:
ogreManualPassMaterial->setSpecular(ConversionToOgre21(passManual->getSpecularColor()));
break;
case ape::Event::Type::PASS_MANUAL_SHININESS:
ogreManualPassMaterial->setShininess(passManual->getShininess());
break;
case ape::Event::Type::PASS_MANUAL_SCENEBLENDING:
{
//ogre v1
/*ogreManualPassMaterial->setSceneBlending(ConversionToOgre21(passManual->getSceneBlendingType()));
if (passManual->getSceneBlendingType() == ape::Pass::SceneBlendingType::TRANSPARENT_ALPHA)
ogreManualPassMaterial->setDepthWriteEnabled(false);*/
}
break;
case ape::Event::Type::PASS_MANUAL_TEXTURE:
{
if (auto texture = passManual->getTexture().lock())
{
auto ogreTexture = Ogre::TextureManager::getSingleton().getByName(texture->getName());
if (!ogreTexture.isNull())
{
if (!ogreManualPassMaterial->getTechnique(0)->getPass(0)->getNumTextureUnitStates())
ogreManualPassMaterial->getTechnique(0)->getPass(0)->createTextureUnitState();
ogreManualPassMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTexture(ogreTexture);
}
}
}
break;
case ape::Event::Type::PASS_MANUAL_GPUPARAMETERS:
{
Ogre::GpuProgramParametersSharedPtr ogreGpuParameters = ogreManualPassMaterial->getTechnique(0)->getPass(0)->getVertexProgramParameters();
if (!ogreGpuParameters.isNull())
{
for (auto passGpuParameter : passManual->getPassGpuParameters())
ogreGpuParameters->setNamedConstant(passGpuParameter.name, ConversionToOgre21(passGpuParameter.value));
}
}
break;
case ape::Event::Type::PASS_MANUAL_DELETE:
;
break;
}
}
}
}
else if (event.group == ape::Event::Group::TEXTURE_FILE)
{
if (auto textureManual = std::static_pointer_cast<ape::IManualTexture>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string textureManualName = textureManual->getName();
switch (event.type)
{
case ape::Event::Type::TEXTURE_FILE_CREATE:
break;
case ape::Event::Type::TEXTURE_FILE_FILENAME:
{
auto ogreTexture = Ogre::TextureManager::getSingleton().createOrRetrieve(textureManualName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
break;
case ape::Event::Type::TEXTURE_FILE_DELETE:
;
break;
}
}
}
else if (event.group == ape::Event::Group::TEXTURE_MANUAL)
{
if (auto textureManual = std::static_pointer_cast<ape::IManualTexture>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string textureManualName = textureManual->getName();
switch (event.type)
{
case ape::Event::Type::TEXTURE_MANUAL_CREATE:
break;
case ape::Event::Type::TEXTURE_MANUAL_PARAMETERS:
{
ape::ManualTextureParameters parameters = textureManual->getParameters();
auto ogreTexture = Ogre::TextureManager::getSingleton().createManual(textureManualName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, Ogre::uint(parameters.width), Ogre::uint(parameters.height), 0, ape::ConversionToOgre21(parameters.pixelFormat),
ape::ConversionToOgre21(parameters.usage), nullptr, true, mOgreRenderPluginConfig.ogreRenderWindowConfigList[0].fsaa, mOgreRenderPluginConfig.ogreRenderWindowConfigList[0].fsaaHint);
if (mOgreRenderPluginConfig.renderSystem == "OGL")
{
/*GLuint glid;
ogreTexture->getCustomAttribute("GLID", &glid);
textureManual->setGraphicsApiID((void*)glid);*/
bool outIsFsaa;
textureManual->setGraphicsApiID((void*)static_cast<Ogre::GL3PlusTexture*>(Ogre::TextureManager::getSingleton().getByName(textureManualName).getPointer())->getGLID(outIsFsaa));
}
if (mOgreRenderPluginConfig.renderSystem == "DX11")
{
textureManual->setGraphicsApiID((void*)static_cast<Ogre::D3D11Texture*>(Ogre::TextureManager::getSingleton().getByName(textureManualName).getPointer())->GetTex2D());
}
}
break;
case ape::Event::Type::TEXTURE_MANUAL_BUFFER:
{
auto ogreTexture = Ogre::TextureManager::getSingleton().getByName(textureManualName);
if (!ogreTexture.isNull())
{
// Ogre v1
////APE_LOG_DEBUG("TEXTURE_MANUAL_BUFFER write begin");
//Ogre::HardwarePixelBufferSharedPtr texBuf = ogreTexture->getBuffer();
//texBuf->lock(Ogre::HardwareBuffer::HBL_DISCARD);
//memcpy(texBuf->getCurrentLock().data, textureManual->getBuffer(), textureManual->getParameters().width * textureManual->getParameters().height * 4);
//texBuf->unlock();
///*static int s = 1;
//std::wostringstream oss;
//oss << std::setw(4) << std::setfill(L'0') << s++ << L".bmp";
//ape::SaveVoidBufferToImage(oss.str(), textureManual->getBuffer(), textureManual->getParameters().width, textureManual->getParameters().height);*/
////APE_LOG_DEBUG("TEXTURE_MANUAL_BUFFER write end");
}
}
break;
case ape::Event::Type::TEXTURE_MANUAL_SOURCECAMERA:
{
auto ogreTexture = Ogre::TextureManager::getSingleton().getByName(textureManualName);
if (!ogreTexture.isNull())
{
if (auto camera = textureManual->getSourceCamera().lock())
{
if (auto ogreCamera = mpSceneMgr->findCamera(camera->getName()))
{
if (auto ogreRenderTexture = ogreTexture->getBuffer()->getRenderTarget())
{
//ogreRenderTexture->setAutoUpdated(true);
if (auto ogreViewport = ogreRenderTexture->addViewport())
{
//ogreViewport->setClearEveryFrame(true);
//ogreViewport->setAutoUpdated(true);
if (mOgreRenderPluginConfig.shading == "perPixel" || mOgreRenderPluginConfig.shading == "")
{
// Ogre v1
//ogreViewport->setMaterialScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
}
mRttList.push_back(textureManual);
}
}
}
}
}
}
break;
case ape::Event::Type::TEXTURE_MANUAL_DELETE:
;
break;
}
}
}
else if (event.group == ape::Event::Group::TEXTURE_UNIT)
{
if (auto textureUnit = std::static_pointer_cast<ape::IUnitTexture>(mpSceneManager->getEntity(event.subjectName).lock()))
{
std::string textureUnitName = textureUnit->getName();
ape::IUnitTexture::Parameters parameters = textureUnit->getParameters();
Ogre::MaterialPtr ogreMaterial;
if (auto material = parameters.material.lock())
ogreMaterial = Ogre::MaterialManager::getSingletonPtr()->getByName(material->getName());
switch (event.type)
{
case ape::Event::Type::TEXTURE_UNIT_CREATE:
break;
case ape::Event::Type::TEXTURE_UNIT_PARAMETERS:
{
if (!ogreMaterial.isNull())
ogreMaterial->getTechnique(0)->getPass(0)->createTextureUnitState(parameters.fileName);
}
break;
case ape::Event::Type::TEXTURE_UNIT_SCROLL:
{
if (!ogreMaterial.isNull())
{
auto ogreTextureUnit = ogreMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0);
if (ogreTextureUnit)
ogreTextureUnit->setTextureScroll(textureUnit->getTextureScroll().x, textureUnit->getTextureScroll().y);
}
}
break;
case ape::Event::Type::TEXTURE_UNIT_ADDRESSING:
{
//Ogre v1
/*if (!ogreMaterial.isNull())
{
auto ogreTextureUnit = ogreMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0);
if (ogreTextureUnit)
ogreTextureUnit->setTextureAddressingMode(ape::ConversionToOgre21(textureUnit->getTextureAddressingMode()));
}*/
}
break;
case ape::Event::Type::TEXTURE_UNIT_FILTERING:
{
//Ogre v1
/*if (!ogreMaterial.isNull())
{
auto ogreTextureUnit = ogreMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0);
if (ogreTextureUnit)
ogreTextureUnit->setTextureFiltering(ape::ConversionToOgre21(textureUnit->getTextureFiltering().minFilter), ape::ConversionToOgre21(textureUnit->getTextureFiltering().magFilter), ape::ConversionToOgre21(textureUnit->getTextureFiltering().mipFilter));
}
*/
}
break;
case ape::Event::Type::TEXTURE_MANUAL_DELETE:
;
break;
}
}
}
else if (event.group == ape::Event::Group::GEOMETRY_RAY)
{
if (auto geometryRay = std::static_pointer_cast<ape::IRayGeometry>(mpSceneManager->getEntity(event.subjectName).lock()))
{
switch (event.type)
{
case ape::Event::Type::GEOMETRY_RAY_CREATE:
break;
case ape::Event::Type::GEOMETRY_RAY_INTERSECTIONQUERY:
{
if (auto rayOverlayNode = geometryRay->getParentNode().lock())
{
if (auto raySpaceNode = rayOverlayNode->getParentNode().lock())
{
Ogre::Ray ray = mOgreCameras[0]->getCameraToViewportRay(rayOverlayNode->getPosition().x / mOgreRenderPluginConfig.ogreRenderWindowConfigList[0].width,
rayOverlayNode->getPosition().y / mOgreRenderPluginConfig.ogreRenderWindowConfigList[0].height); //TODO_apeOgreRenderPlugin check enabled window in ogreRenderWindowConfigList
Ogre::RaySceneQuery *raySceneQuery = mpSceneMgr->createRayQuery(ray);
if (raySceneQuery != NULL)
{
raySceneQuery->setSortByDistance(true);
raySceneQuery->execute();
Ogre::RaySceneQueryResult query_result = raySceneQuery->getLastResults();
std::vector<ape::EntityWeakPtr> intersections;
for (size_t i = 0, size = query_result.size(); i < size; ++i)
{
if (auto entiy = mpSceneManager->getEntity(query_result[i].movable->getName()).lock())
{
intersections.push_back(entiy);
}
}
geometryRay->setIntersections(intersections);
}
}
}
}
break;
case ape::Event::Type::GEOMETRY_RAY_DELETE:
;
break;
}
}
}
else if (event.group == ape::Event::Group::CAMERA)
{
if (auto camera = std::static_pointer_cast<ape::ICamera>(mpSceneManager->getEntity(event.subjectName).lock()))
{
switch (event.type)
{
case ape::Event::Type::CAMERA_CREATE:
{
mOgreCameras.push_back(mpSceneMgr->createCamera(event.subjectName));
for (int i = 0; i < mOgreRenderPluginConfig.ogreRenderWindowConfigList.size(); i++)
{
for (int j = 0; j < mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].viewportList.size(); j++)
{
for (int k = 0; k < mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].viewportList[j].cameras.size(); k++)
{
auto cameraSetting = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].viewportList[j].cameras[k];
if (cameraSetting.name == camera->getName())
{
camera->setWindow(mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].name);
camera->setFocalLength(1.0f);
camera->setNearClipDistance(cameraSetting.nearClip);
camera->setFarClipDistance(cameraSetting.farClip);
camera->setFOVy(cameraSetting.fovY.toRadian());
}
}
}
}
}
break;
case ape::Event::Type::CAMERA_WINDOW:
{
if (mpSceneMgr->findCamera(event.subjectName))
{
Ogre::Camera* ogreCamera = mpSceneMgr->findCamera(event.subjectName);
if (ogreCamera != nullptr)
{
for (int i = 0; i < mOgreRenderPluginConfig.ogreRenderWindowConfigList.size(); i++)
{
for (int j = 0; j < mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].viewportList.size(); j++)
{
auto renderWindowSetting = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i];
auto viewportSetting = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].viewportList[j];
for (int k = 0; k < mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].viewportList[j].cameras.size(); k++)
{
auto cameraSetting = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].viewportList[j].cameras[k];
if (cameraSetting.name == camera->getName())
{
int zorder = viewportSetting.zOrder;
float width = (float)viewportSetting.width / (float)renderWindowSetting.width;
float height = (float)viewportSetting.height / (float)renderWindowSetting.height;
float left = (float)viewportSetting.left / (float)renderWindowSetting.width;
float top = (float)viewportSetting.top / (float)renderWindowSetting.height;
if (auto ogreViewPort = mRenderWindows[camera->getWindow()]->addViewport(left,top,width,height))
{
APE_LOG_DEBUG("ogreViewport: " << "zorder: " << zorder << " left: " << left << " top: " << top << " width: " << width << " height: " << height);
ogreCamera->setAspectRatio(Ogre::Real(ogreViewPort->getActualWidth()) / Ogre::Real(ogreViewPort->getActualHeight()));
/*if (mOgreRenderPluginConfig.shading == "perPixel" || mOgreRenderPluginConfig.shading == "")
{
ogreViewPort->setMaterialScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
}*///nincs
//------------------
mpActualRenderwindow = mRenderWindows[camera->getWindow()];
if (!mSkyBoxMaterial.isNull())
{
Ogre::CompositorManager2* compositorManager = mpRoot->getCompositorManager2();
//Ogre::IdString workspaceName("MyOwnWorkspace");
//if (!compositorManager->hasWorkspaceDefinition(workspaceName))
// compositorManager->createBasicWorkspaceDef("MyOwnWorkspace", Ogre::ColourValue(0.6f, 0.0f, 0.6f));
//compositorManager->addWorkspace(mpSceneMgr, mRenderWindows[camera->getWindow()], ogreCamera,
// "MyOwnWorkspace", true);
//compositorManager->addWorkspaceDefinition("WorkSpace01");
mpActualWorkSpace = compositorManager->addWorkspace(mpSceneMgr, mRenderWindows[camera->getWindow()], ogreCamera,
"SkyPostprocessWorkspace", true);
mpActualWorkSpace->setEnabled(true);
}
//--------
//--------
//change sky
/*Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingletonPtr()->getByName("SkyPostprocess");
if (materialPtr.isNull())
return;
Ogre::Material* material = materialPtr.getPointer();
Ogre::TextureUnitState* tex = material->getTechnique(0)->getPass(0)->getTextureUnitState(0);
tex->setCubicTextureName("SkyBoxNone.dds", true);
tex->setGamma(2.0);
material->compile();
*/
//--------
}
}
}
}
}
}
//ogreCamera->lookAt(Ogre::Vector3(0, 0, 0));
}
}
break;
case ape::Event::Type::CAMERA_PARENTNODE:
{
if (auto ogreCamera = mpSceneMgr->findCamera(camera->getName()))
{
if (auto parentNode = camera->getParentNode().lock())
{
auto hasSceneNodeList = mpSceneMgr->findSceneNodes(parentNode->getName());
if (!hasSceneNodeList.empty())
{
if (auto ogreParentNode = mpSceneMgr->getSceneNode(hasSceneNodeList[0]->getId()))
{
if (ogreCamera->getParentNode())
ogreCamera->detachFromParent();
ogreParentNode->attachObject(ogreCamera);
}
}
}
}
}
break;
case ape::Event::Type::CAMERA_DELETE:
;
break;
case ape::Event::Type::CAMERA_FOCALLENGTH:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setFocalLength(camera->getFocalLength());
}
break;
case ape::Event::Type::CAMERA_ASPECTRATIO:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setAspectRatio(camera->getAspectRatio());
}
break;
case ape::Event::Type::CAMERA_AUTOASPECTRATIO:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setAutoAspectRatio(camera->isAutoAspectRatio());
}
break;
case ape::Event::Type::CAMERA_FOVY:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setFOVy(ConversionToOgre21(camera->getFOVy()));
}
break;
case ape::Event::Type::CAMERA_FRUSTUMOFFSET:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setFrustumOffset(ape::ConversionToOgre21(camera->getFrustumOffset()));
}
break;
case ape::Event::Type::CAMERA_FARCLIP:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setFarClipDistance(camera->getFarClipDistance());
}
break;
case ape::Event::Type::CAMERA_NEARCLIP:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setNearClipDistance(camera->getNearClipDistance());
}
break;
case ape::Event::Type::CAMERA_PROJECTION:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setCustomProjectionMatrix(true, ape::ConversionToOgre21(camera->getProjection()));
}
break;
case ape::Event::Type::CAMERA_PROJECTIONTYPE:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setProjectionType(ConversionToOgre21(camera->getProjectionType()));
}
break;
case ape::Event::Type::CAMERA_ORTHOWINDOWSIZE:
{
if (mpSceneMgr->findCamera(event.subjectName))
mpSceneMgr->findCamera(event.subjectName)->setOrthoWindow(camera->getOrthoWindowSize().x, camera->getOrthoWindowSize().y);
}
break;
case ape::Event::Type::CAMERA_VISIBILITY:
{
if (mpSceneMgr->findCamera(event.subjectName))
{
Ogre::Viewport* ogreViewport = mpSceneMgr->findCamera(event.subjectName)->getLastViewport();
//ogrev1
//if (ogreViewport)
//ogreViewport->setVisibilityMask(camera->getVisibilityMask());
}
}
break;
}
}
}
mEventDoubleQueue.pop();
}
}
bool ape::Ogre21RenderPlugin::frameStarted(const Ogre::FrameEvent& evt)
{
return Ogre::FrameListener::frameStarted(evt);
}
bool ape::Ogre21RenderPlugin::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
processEventDoubleQueue();
return Ogre::FrameListener::frameRenderingQueued(evt);
}
bool ape::Ogre21RenderPlugin::frameEnded(const Ogre::FrameEvent& evt)
{
return Ogre::FrameListener::frameEnded(evt);
}
void ape::Ogre21RenderPlugin::Stop()
{
}
void ape::Ogre21RenderPlugin::Suspend()
{
}
void ape::Ogre21RenderPlugin::Restart()
{
}
void ape::Ogre21RenderPlugin::Run()
{
APE_LOG_FUNC_ENTER();
try
{
//mpRoot->renderOneFrame();
mpRoot->startRendering();
}
catch (const Ogre::RenderingAPIException& ex)
{
std::cout << ex.getFullDescription() << std::endl;
APE_LOG_ERROR(ex.getFullDescription());
}
catch (const Ogre::Exception& ex)
{
std::cout << ex.getFullDescription() << std::endl;
APE_LOG_ERROR(ex.getFullDescription());
}
APE_LOG_FUNC_LEAVE();
}
void ape::Ogre21RenderPlugin::Step()
{
try
{
mpRoot->renderOneFrame();
#ifndef __APPLE__
Ogre::WindowEventUtilities::messagePump();
#endif
}
catch (const Ogre::RenderingAPIException& ex)
{
std::cout << ex.getFullDescription() << std::endl;
APE_LOG_ERROR(ex.getFullDescription());
}
catch (const Ogre::Exception& ex)
{
std::cout << ex.getFullDescription() << std::endl;
APE_LOG_ERROR(ex.getFullDescription());
}
}
void ape::Ogre21RenderPlugin::Init()
{
APE_LOG_FUNC_ENTER();
/*mpUserInputMacro = ape::UserInputMacro::getSingletonPtr();
mUserInputMacroPose = ape::UserInputMacro::ViewPose();*/
std::stringstream fileFullPath;
fileFullPath << mpCoreConfig->getConfigFolderPath() << "\\apeOgre21RenderPlugin.json";
FILE* apeOgreRenderPluginConfigFile = std::fopen(fileFullPath.str().c_str(), "r");
char readBuffer[65536];
if (apeOgreRenderPluginConfigFile)
{
rapidjson::FileReadStream jsonFileReaderStream(apeOgreRenderPluginConfigFile, readBuffer, sizeof(readBuffer));
rapidjson::Document jsonDocument;
jsonDocument.ParseStream(jsonFileReaderStream);
if (jsonDocument.IsObject())
{
rapidjson::Value& renderSystem = jsonDocument["renderSystem"];
mOgreRenderPluginConfig.renderSystem = renderSystem.GetString();
rapidjson::Value& lodLevels = jsonDocument["lodLevels"];
for (rapidjson::Value::MemberIterator lodLevelsMemberIterator =
lodLevels.MemberBegin(); lodLevelsMemberIterator != lodLevels.MemberEnd(); ++lodLevelsMemberIterator)
{
if (lodLevelsMemberIterator->name == "autoGenerateAndSave")
mOgreRenderPluginConfig.ogreLodLevelsConfig.autoGenerateAndSave = lodLevelsMemberIterator->value.GetBool();
else if (lodLevelsMemberIterator->name == "bias")
mOgreRenderPluginConfig.ogreLodLevelsConfig.bias = lodLevelsMemberIterator->value.GetFloat();
}
if (jsonDocument.HasMember("shading"))
{
rapidjson::Value& shading = jsonDocument["shading"];
mOgreRenderPluginConfig.shading = shading.GetString();
}
rapidjson::Value& renderWindows = jsonDocument["renderWindows"];
for (auto& renderWindow : renderWindows.GetArray())
{
ape::OgreRenderWindowConfig ogreRenderWindowConfig;
for (rapidjson::Value::MemberIterator renderWindowMemberIterator =
renderWindow.MemberBegin(); renderWindowMemberIterator != renderWindow.MemberEnd(); ++renderWindowMemberIterator)
{
if (renderWindowMemberIterator->name == "enable")
ogreRenderWindowConfig.enable = renderWindowMemberIterator->value.GetBool();
else if (renderWindowMemberIterator->name == "name")
ogreRenderWindowConfig.name = renderWindowMemberIterator->value.GetString();
else if (renderWindowMemberIterator->name == "monitorIndex")
ogreRenderWindowConfig.monitorIndex = renderWindowMemberIterator->value.GetInt();
else if (renderWindowMemberIterator->name == "resolution")
{
for (rapidjson::Value::MemberIterator resolutionMemberIterator =
renderWindow[renderWindowMemberIterator->name].MemberBegin();
resolutionMemberIterator != renderWindow[renderWindowMemberIterator->name].MemberEnd(); ++resolutionMemberIterator)
{
if (resolutionMemberIterator->name == "width")
ogreRenderWindowConfig.width = resolutionMemberIterator->value.GetInt();
else if (resolutionMemberIterator->name == "height")
ogreRenderWindowConfig.height = resolutionMemberIterator->value.GetInt();
else if (resolutionMemberIterator->name == "fullScreen")
ogreRenderWindowConfig.fullScreen = resolutionMemberIterator->value.GetBool();
}
}
else if (renderWindowMemberIterator->name == "miscParams")
{
for (rapidjson::Value::MemberIterator miscParamsMemberIterator =
renderWindow[renderWindowMemberIterator->name].MemberBegin();
miscParamsMemberIterator != renderWindow[renderWindowMemberIterator->name].MemberEnd(); ++miscParamsMemberIterator)
{
if (miscParamsMemberIterator->name == "vSync")
ogreRenderWindowConfig.vSync = miscParamsMemberIterator->value.GetBool();
else if (miscParamsMemberIterator->name == "vSyncInterval")
ogreRenderWindowConfig.vSyncInterval = miscParamsMemberIterator->value.GetInt();
else if (miscParamsMemberIterator->name == "colorDepth")
ogreRenderWindowConfig.colorDepth = miscParamsMemberIterator->value.GetInt();
else if (miscParamsMemberIterator->name == "FSAA")
ogreRenderWindowConfig.fsaa = miscParamsMemberIterator->value.GetInt();
else if (miscParamsMemberIterator->name == "FSAAHint")
ogreRenderWindowConfig.fsaaHint = miscParamsMemberIterator->value.GetString();
}
}
else if (renderWindowMemberIterator->name == "viewports")
{
rapidjson::Value& viewports = renderWindow[renderWindowMemberIterator->name];
for (auto& viewport : viewports.GetArray())
{
ape::OgreViewPortConfig ogreViewPortConfig;
for (rapidjson::Value::MemberIterator viewportMemberIterator =
viewport.MemberBegin();
viewportMemberIterator != viewport.MemberEnd(); ++viewportMemberIterator)
{
if (viewportMemberIterator->name == "zOrder")
ogreViewPortConfig.zOrder = viewportMemberIterator->value.GetInt();
else if (viewportMemberIterator->name == "left")
ogreViewPortConfig.left = viewportMemberIterator->value.GetInt();
else if (viewportMemberIterator->name == "top")
ogreViewPortConfig.top = viewportMemberIterator->value.GetInt();
else if (viewportMemberIterator->name == "width")
ogreViewPortConfig.width = viewportMemberIterator->value.GetInt();
else if (viewportMemberIterator->name == "height")
ogreViewPortConfig.height = viewportMemberIterator->value.GetInt();
else if (viewportMemberIterator->name == "cameras")
{
rapidjson::Value& cameras = viewport[viewportMemberIterator->name];
for (auto& camera : cameras.GetArray())
{
ape::OgreCameraConfig ogreCameraConfig;
for (rapidjson::Value::MemberIterator cameraMemberIterator =
camera.MemberBegin();
cameraMemberIterator != camera.MemberEnd(); ++cameraMemberIterator)
{
if (cameraMemberIterator->name == "name")
ogreCameraConfig.name = cameraMemberIterator->value.GetString();
else if (cameraMemberIterator->name == "nearClip")
ogreCameraConfig.nearClip = cameraMemberIterator->value.GetFloat();
else if (cameraMemberIterator->name == "farClip")
ogreCameraConfig.farClip = cameraMemberIterator->value.GetFloat();
else if (cameraMemberIterator->name == "fovY")
ogreCameraConfig.fovY = cameraMemberIterator->value.GetFloat();
else if (cameraMemberIterator->name == "positionOffset")
{
for (rapidjson::Value::MemberIterator elementMemberIterator =
viewport[viewportMemberIterator->name][cameraMemberIterator->name].MemberBegin();
elementMemberIterator != viewport[viewportMemberIterator->name][cameraMemberIterator->name].MemberEnd(); ++elementMemberIterator)
{
if (elementMemberIterator->name == "x")
ogreCameraConfig.positionOffset.x = elementMemberIterator->value.GetFloat();
else if (elementMemberIterator->name == "y")
ogreCameraConfig.positionOffset.y = elementMemberIterator->value.GetFloat();
else if (elementMemberIterator->name == "z")
ogreCameraConfig.positionOffset.z = elementMemberIterator->value.GetFloat();
}
}
else if (cameraMemberIterator->name == "orientationOffset")
{
Ogre::Quaternion orientationOffset;
Ogre::Degree angle;
Ogre::Vector3 axis;
for (rapidjson::Value::MemberIterator elementMemberIterator =
viewport[viewportMemberIterator->name][cameraMemberIterator->name].MemberBegin();
elementMemberIterator != viewport[viewportMemberIterator->name][cameraMemberIterator->name].MemberEnd(); ++elementMemberIterator)
{
if (elementMemberIterator->name == "angle")
angle = elementMemberIterator->value.GetFloat();
else if (elementMemberIterator->name == "x")
axis.x = elementMemberIterator->value.GetFloat();
else if (elementMemberIterator->name == "y")
axis.y = elementMemberIterator->value.GetFloat();
else if (elementMemberIterator->name == "z")
axis.z = elementMemberIterator->value.GetFloat();
}
orientationOffset.FromAngleAxis(angle, axis);
ogreCameraConfig.orientationOffset = ape::ConversionFromOgre21(orientationOffset);
}
else if (cameraMemberIterator->name == "parentNodeName")
{
ogreCameraConfig.parentNodeName = cameraMemberIterator->value.GetString();
}
}
ogreViewPortConfig.cameras.push_back(ogreCameraConfig);
}
}
}
ogreRenderWindowConfig.viewportList.push_back(ogreViewPortConfig);
}
}
}
mOgreRenderPluginConfig.ogreRenderWindowConfigList.push_back(ogreRenderWindowConfig);
}
}
fclose(apeOgreRenderPluginConfigFile);
}
mpRoot = OGRE_NEW Ogre::Root("", "", "apeOgre21RenderPlugin.log");
Ogre::LogManager::getSingleton().createLog("apeOgre21RenderPlugin.log", true, false, false);
//mpOverlaySys = OGRE_NEW Ogre::v1::OverlaySystem();
#if defined (_DEBUG)
Ogre::LogManager::getSingleton().setLogDetail(Ogre::LL_BOREME);
if (mOgreRenderPluginConfig.renderSystem == "DX11")
mpRoot->loadPlugin("RenderSystem_Direct3D11_d");
else
mpRoot->loadPlugin("RenderSystem_GL3Plus_d");
#else
Ogre::LogManager::getSingleton().setLogDetail(Ogre::LL_NORMAL);
if (mOgreRenderPluginConfig.renderSystem == "DX11")
mpRoot->loadPlugin("RenderSystem_Direct3D11");
else
mpRoot->loadPlugin("RenderSystem_GL3Plus");
#endif
Ogre::RenderSystem* renderSystem = nullptr;
if (mOgreRenderPluginConfig.renderSystem == "DX11")
renderSystem = mpRoot->getRenderSystemByName("Direct3D11 Rendering Subsystem");
else
renderSystem = mpRoot->getRenderSystemByName("Open_GL3Plus Rendering Subsystem");
std::stringstream mediaFolder;
mediaFolder << APE_SOURCE_DIR << "/plugins/ogre21Render/media";
mpRoot->setRenderSystem(renderSystem);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/Hlms", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/models", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/modelsV2", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, false);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/scripts", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/PbsMaterials", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/textures", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, false);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/textures/Cubemaps", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, false);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
/*Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/DebugPack.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/cubemap.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/cubemapsJS.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/dragon.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/fresneldemo.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/OgreCore.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/ogredance.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/profiler.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/SdkTrays.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/Sinbad.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/packs/skybox.zip", "Zip", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);*/
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/scripts/Compositors", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, false);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/scripts/materials/TutorialSky_Postprocess", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, false);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mediaFolder.str() + "/apeSky", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, false);
for (auto resourceLocation : mpCoreConfig->getNetworkConfig().resourceLocations)
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(resourceLocation, "FileSystem");
mpRoot->getRenderSystem()->setConfigOption("sRGB Gamma Conversion", "Yes");
mpRoot->initialise(false, "ape");
Ogre::InstancingThreadedCullingMethod instancingThreadedCullingMethod = Ogre::INSTANCING_CULLING_SINGLETHREAD; //-> új miatt
#if OGRE_DEBUG_MODE
const size_t numThreads = 1;
#else
const size_t numThreads = std::max<size_t>(1, Ogre::PlatformInformation::getNumLogicalCores());
if (numThreads > 1)
instancingThreadedCullingMethod = Ogre::INSTANCING_CULLING_THREADED;
#endif
mpRoot->addFrameListener(this);
Ogre::RenderWindowList renderWindowList;
Ogre::RenderWindowDescriptionList winDescList;
void* mainWindowHnd = 0;
for (int i = 0; i < mOgreRenderPluginConfig.ogreRenderWindowConfigList.size(); i++)
{
if (mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].enable)
{
Ogre::RenderWindowDescription winDesc;
std::stringstream ss;
ss << mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].name;
winDesc.name = ss.str();
winDesc.height = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].height;
winDesc.width = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].width;
winDesc.useFullScreen = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].fullScreen;
std::stringstream colourDepthSS;
colourDepthSS << mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].colorDepth;
winDesc.miscParams["colourDepth"] = colourDepthSS.str().c_str();
winDesc.miscParams["vsync"] = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].vSync ? "Yes" : "No";
std::stringstream vsyncIntervalSS;
vsyncIntervalSS << mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].vSyncInterval;
winDesc.miscParams["vsyncInterval"] = vsyncIntervalSS.str().c_str();
std::stringstream fsaaSS;
fsaaSS << mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].fsaa;
winDesc.miscParams["FSAA"] = fsaaSS.str().c_str();
winDesc.miscParams["FSAAHint"] = mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].fsaaHint;
std::stringstream monitorIndexSS;
monitorIndexSS << mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].monitorIndex;
winDesc.miscParams["monitorIndex"] = monitorIndexSS.str().c_str();
//--
winDesc.miscParams["gamma"] = "true";
//--
winDescList.push_back(winDesc);
APE_LOG_DEBUG("winDesc:" << " name=" << winDesc.name << " width=" << winDesc.width << " height=" << winDesc.height << " fullScreen=" << winDesc.useFullScreen);
mRenderWindows[winDesc.name] = mpRoot->createRenderWindow(winDesc.name, winDesc.width, winDesc.height, winDesc.useFullScreen, &winDesc.miscParams);
mRenderWindows[winDesc.name]->setDeactivateOnFocusChange(false);
mRenderWindows[winDesc.name]->setHidden(mOgreRenderPluginConfig.ogreRenderWindowConfigList[i].hidden);
mpSceneMgr = mpRoot->createSceneManager(Ogre::ST_GENERIC, numThreads, instancingThreadedCullingMethod);// ->új miatt
}
}
int mainWindowID = 0; //first window will be the main window
Ogre::RenderWindowDescription mainWindowDesc = winDescList[mainWindowID];
mRenderWindows[mainWindowDesc.name]->getCustomAttribute("WINDOW", &mainWindowHnd);
std::ostringstream windowHndStr;
windowHndStr << mainWindowHnd;
mOgreRenderPluginConfig.ogreRenderWindowConfigList[mainWindowID].windowHandler = windowHndStr.str();
ape::WindowConfig windowConfig(mainWindowDesc.name, mOgreRenderPluginConfig.renderSystem, mainWindowHnd, mOgreRenderPluginConfig.ogreRenderWindowConfigList[mainWindowID].width,
mOgreRenderPluginConfig.ogreRenderWindowConfigList[mainWindowID].height);
mpCoreConfig->setWindowConfig(windowConfig);
//Must be after creating Rendering Window
registerHlms();
// Initialise, parse scripts etc
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(true);
//------makessome ground
/*
Ogre::v1::MeshPtr planeMeshV1 = Ogre::v1::MeshManager::getSingleton().createPlane("Plane v1",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::Plane(Ogre::Vector3::UNIT_Y, 10.0f), 500.0f, 500.0f,
1, 1, true, 1, 4.0f, 4.0f, Ogre::Vector3::UNIT_Z,
Ogre::v1::HardwareBuffer::HBU_STATIC,
Ogre::v1::HardwareBuffer::HBU_STATIC);
Ogre::MeshPtr planeMesh = Ogre::MeshManager::getSingleton().createManual(
"Plane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
planeMesh->importV1(planeMeshV1.get(), true, true, true);
{
Ogre::Item *item = mpSceneMgr->createItem(planeMesh, Ogre::SCENE_DYNAMIC);
item->setDatablock("Marble");
Ogre::SceneNode *sceneNode = mpSceneMgr->getRootSceneNode(Ogre::SCENE_DYNAMIC)->
createChildSceneNode(Ogre::SCENE_DYNAMIC);
sceneNode->setPosition(0, -25, 0);
sceneNode->attachObject(item);
//Change the addressing mode of the roughness map to wrap via code.
//Detail maps default to wrap, but the rest to clamp.
assert(dynamic_cast<Ogre::HlmsPbsDatablock*>(item->getSubItem(0)->getDatablock()));
Ogre::HlmsPbsDatablock *datablock = static_cast<Ogre::HlmsPbsDatablock*>(
item->getSubItem(0)->getDatablock());
//Make a hard copy of the sampler block
Ogre::HlmsSamplerblock samplerblock(*datablock->getSamplerblock(Ogre::PBSM_ROUGHNESS));
samplerblock.mU = Ogre::TAM_WRAP;
samplerblock.mV = Ogre::TAM_WRAP;
samplerblock.mW = Ogre::TAM_WRAP;
//Set the new samplerblock. The Hlms system will
//automatically create the API block if necessary
datablock->setSamplerblock(Ogre::PBSM_ROUGHNESS, samplerblock);
}
//-------------
//***
Ogre::String meshName;
meshName = "Cube_d.mesh";
Ogre::MeshPtr v2Mesh;
v2Mesh = Ogre::MeshManager::getSingleton().load(
meshName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::Item *item = mpSceneMgr->createItem(meshName,
Ogre::ResourceGroupManager::
AUTODETECT_RESOURCE_GROUP_NAME,
Ogre::SCENE_DYNAMIC);
item->setDatablock("Rocks");
//item->setDatablock("Rocks");
//item->setVisibilityFlags(0x000000001);
mItemList[meshName] = item;
auto mSceneNode = mpSceneMgr->getRootSceneNode(Ogre::SCENE_DYNAMIC)->
createChildSceneNode(Ogre::SCENE_DYNAMIC);
mSceneNode->setPosition(50.0,10.0,10.0);
mSceneNode->setScale(10.65f, 10.65f, 10.65f);
//mSceneNode->roll(Ogre::Radian((Ogre::Real)idx));
mSceneNode->attachObject(item);
meshName = "Sphere1000.mesh";
Ogre::MeshPtr v2Mesh2;
v2Mesh2 = Ogre::MeshManager::getSingleton().load(
meshName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::Item *item2 = mpSceneMgr->createItem(meshName,
Ogre::ResourceGroupManager::
AUTODETECT_RESOURCE_GROUP_NAME,
Ogre::SCENE_DYNAMIC);
mItemList[meshName] = item2;
auto mSceneNode2 = mpSceneMgr->getRootSceneNode(Ogre::SCENE_DYNAMIC)->
createChildSceneNode(Ogre::SCENE_DYNAMIC);
mSceneNode2->setPosition(100.0, 100.0, 10.0);
mSceneNode2->setScale(100.65f, 100.65f, 100.65f);
//mSceneNode->roll(Ogre::Radian((Ogre::Real)idx));
mSceneNode2->attachObject(item2);
*/
//***
APE_LOG_FUNC_LEAVE();
}
void ape::Ogre21RenderPlugin::registerHlms()
{
static const Ogre::String OGRE_RENDERSYSTEM_DIRECTX11 = "Direct3D11 Rendering Subsystem";
static const Ogre::String OGRE_RENDERSYSTEM_OPENGL3PLUS = "OpenGL 3+ Rendering Subsystem";
static const Ogre::String OGRE_RENDERSYSTEM_METAL = "Metal Rendering Subsystem";
std::stringstream mediaFolder;
mediaFolder << APE_SOURCE_DIR << "/plugins/ogre21Render/media";
Ogre::String dataFolder = mediaFolder.str() + "/";
Ogre::RenderSystem* renderSystem = mpRoot->getRenderSystem();
Ogre::String shaderSyntax = "GLSL";
if (renderSystem->getName() == OGRE_RENDERSYSTEM_DIRECTX11)
shaderSyntax = "HLSL";
else if (renderSystem->getName() == OGRE_RENDERSYSTEM_METAL)
shaderSyntax = "Metal";
Ogre::Archive* archiveLibrary = Ogre::ArchiveManager::getSingletonPtr()->load(
dataFolder + "Hlms/Common/" + shaderSyntax,
"FileSystem", true);
Ogre::Archive* archiveLibraryAny = Ogre::ArchiveManager::getSingletonPtr()->load(
dataFolder + "Hlms/Common/Any",
"FileSystem", true);
Ogre::Archive* archivePbsLibraryAny = Ogre::ArchiveManager::getSingletonPtr()->load(
dataFolder + "Hlms/Pbs/Any",
"FileSystem", true);
Ogre::Archive* archiveUnlitLibraryAny = Ogre::ArchiveManager::getSingletonPtr()->load(
dataFolder + "Hlms/Unlit/Any",
"FileSystem", true);
Ogre::ArchiveVec library;
library.push_back(archiveLibrary);
library.push_back(archiveLibraryAny);
Ogre::Archive* archiveUnlit = Ogre::ArchiveManager::getSingletonPtr()->load(
dataFolder + "Hlms/Unlit/" + shaderSyntax,
"FileSystem", true);
library.push_back(archiveUnlitLibraryAny);
Ogre::HlmsUnlit* hlmsUnlit = OGRE_NEW Ogre::HlmsUnlit(archiveUnlit, &library);
mpRoot->getHlmsManager()->registerHlms(hlmsUnlit);
library.pop_back();
Ogre::Archive* archivePbs = Ogre::ArchiveManager::getSingletonPtr()->load(
dataFolder + "Hlms/Pbs/" + shaderSyntax,
"FileSystem", true);
library.push_back(archivePbsLibraryAny);
Ogre::HlmsPbs* hlmsPbs = OGRE_NEW Ogre::HlmsPbs(archivePbs, &library);
mpRoot->getHlmsManager()->registerHlms(hlmsPbs);
library.pop_back();
if (renderSystem->getName() == "Direct3D11 Rendering Subsystem")
{
//Set lower limits 512kb instead of the default 4MB per Hlms in D3D 11.0
//and below to avoid saturating AMD's discard limit (8MB) or
//saturate the PCIE bus in some low end machines.
bool supportsNoOverwriteOnTextureBuffers;
renderSystem->getCustomAttribute("MapNoOverwriteOnDynamicBufferSRV",
&supportsNoOverwriteOnTextureBuffers);
if (!supportsNoOverwriteOnTextureBuffers)
{
hlmsPbs->setTextureBufferDefaultSize(512 * 1024);
hlmsUnlit->setTextureBufferDefaultSize(512 * 1024);
}
}
}
template <class id_t>
Ogre::IndexBufferPacked* ape::Ogre21RenderPlugin::inflateIndexBufferPacked(ape::GeometryIndexedFaceSetParameters parameters, Ogre::VaoManager* vaomgr,
Ogre::IndexBufferPacked::IndexType typenum, id_t* buffer)
{
unsigned int idnum = 3 * parameters.faces.face.size();
buffer = reinterpret_cast<id_t*>(OGRE_MALLOC_SIMD(
sizeof(id_t) * idnum, Ogre::MEMCATEGORY_GEOMETRY));
Ogre::FreeOnDestructor idDtor(buffer);
for (unsigned int i = 0, offset = 0; i < parameters.faces.face.size(); ++i, offset += 3)
{
if (parameters.faces.face[i].size() == 4)
{
buffer[offset + 0] = parameters.faces.face[i][0];
buffer[offset + 1] = parameters.faces.face[i][1];
buffer[offset + 2] = parameters.faces.face[i][2];
buffer[offset + 3] = parameters.faces.face[i][3];
}
else
{
buffer[offset + 0] = parameters.faces.face[i][0];
buffer[offset + 1] = parameters.faces.face[i][1];
buffer[offset + 2] = parameters.faces.face[i][2];
}
}
Ogre::IndexBufferPacked *indexBuffer = 0;
try
{
indexBuffer = vaomgr->createIndexBuffer(typenum,
idnum, // number of indices
Ogre::BT_IMMUTABLE,
buffer, false);
}
catch (Ogre::Exception &e)
{
// When keepAsShadow = true, the memory will be freed when the index buffer is destroyed.
// However if for some weird reason there is an exception raised, the memory will
// not be freed, so it is up to us to do so.
// The reasons for exceptions are very rare. But we're doing this for correctness.
OGRE_FREE_SIMD(indexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
indexBuffer = 0;
throw e;
}
return indexBuffer;
} |
2b2dc0e8a065ad7dd988de7392d98dd4730d4cd0 | 81ace47dd4f4ea67330a12c31bee887d3ff38885 | /graph/graph.cpp | ea4ccc10e9bd8ca9d1be34dc54c8a1493791f8b6 | [] | no_license | macabdul9/ds-algo | df86a58198235b89c0b99133903bb1b8c4154313 | 2b7a3f21049118eaa78254e2da0c2eba5efd8159 | refs/heads/master | 2020-03-25T15:54:38.592779 | 2019-09-24T19:20:23 | 2019-09-24T19:20:23 | 143,906,641 | 0 | 0 | null | 2019-04-21T21:50:20 | 2018-08-07T17:33:35 | C++ | UTF-8 | C++ | false | false | 2,787 | cpp | graph.cpp | /*
* @author : macab (macab@debian)
* @file : graph
* @created : Friday Apr 19, 2019 04:28:50 IST
*/
#include<bits/stdc++.h>
#define endl "\n"
#define merge(a, b) a##b
#define loop(i,a,b) for(int i=(int)a;i<(int)b;++i)
#define rloop(i,a,b) for(int i=(int)a;i<=(int)b;++i)
#define loopl(i,a,b) for(ll i=(ll)a;i<(ll)b;++i)
#define loopr(i,a,b) for(int i=(int)a;i>=(int)b;--i)
#define MOD 1000000007
#define MAX 1e9
#define MIN -1e9
#define pll pair<ll,ll>
#define pii pair<int,int>
#define psi pair<string, int>
#define pci pair<char, int>
#define all(p) p.begin(),p.end()
#define max(x,y) (x>y)?x:y
#define min(x,y) (x<y)?x:y
#define vi vector<int>
#define vll vector<long long int>
#define vs vector<string>
#define si set<int>
#define ss set<string>
#define sll set<long long int>
#define mii map<int, int>
#define mll map<long long int, long long int>
#define msi map<string, int>
#define umii unordered_map<int, int>
#define umsi unordered_map<string, int>
typedef long long int ll;
typedef unsigned int uint;
typedef unsigned long long int ull;
using namespace std;
/*
* adjaceny list implementation of graph
*/
class Graph{
// array of list of represent the arraylist represent of a graph !
int v;
list<int> *adjList;
public:
// constructor to initialize the graph having V vertices !
Graph(int vertex){
this->v = vertex;
adjList = new list<int>[v];
}
// this function will add a bidirectional edge from vertex u to v
void addEdge(int u, int v, bool isBidirectional = true){
adjList[u].push_back(v);
// if edge is bidirectional (in case of undirected graph)
if(isBidirectional)
adjList[v].push_back(u);
}
// function to print graph !
void printGraph(){
for(int i = 0; i < v; i++){
cout << i << "->";
for(int each : adjList[i])
cout << each << ", ";
cout << endl;
}
}
};
int main(){
ios::sync_with_stdio(0);
// time to create the object of the graph class !
Graph g(5);
g.addEdge(0, 1);
g.addEdge(0, 3);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 2);
g.addEdge(2, 4);
g.addEdge(3, 4);
g.printGraph();
return 0;
}
|
0948adc87c9d3441efa59cce17251c8f098bcf4e | d678392676b34b0822da7832ae9db330662a9f20 | /AquaLand/DecorCastle.h | bd5e321b171edc5292464d7c7c50ccfe26d7d46a | [] | no_license | shreyjindal81/CSE335-Aqualand | cbf53f22a20d1eff24d27ceb1e44060017e97161 | 0ba489440cf811ca02dc9293b58beb8e44a8496c | refs/heads/master | 2023-04-18T23:37:05.592520 | 2021-04-14T11:37:16 | 2021-04-14T11:37:16 | 357,883,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 618 | h | DecorCastle.h | /**
*
*\file DecorCastle.h
*
* \ by Shrey Jindal
* THis is one of the items floating in the aquarium.
*/
#pragma once
#include <string>
#include <memory>
#include "Item.h"
using namespace std;
/**
* Implements a Castle
*/
class CDecorCastle : public CItem
{
public:
/// constructor for CDecorCastle
CDecorCastle(CAquarium* aquarium);
virtual std::shared_ptr<xmlnode::CXmlNode> XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node) override;
/// Default constructor (disabled)
CDecorCastle() = delete;
/// Copy constructor (disabled)
CDecorCastle(const CDecorCastle&) = delete;
};
|
aff1e2d3eb69e19bccfc991367f690945faff524 | 7f8ebd131b35df3adcb7a4ae5414ef9acb6a64b9 | /include/config/device/DeviceConfig.hpp | bfdc37019425a55503b7574513e447deb1955ab7 | [
"MIT"
] | permissive | alemoke/RoomHub | 19f0a8a339d9de326e7d8e355e7ecbda03efc779 | 9661c5a04a572ae99a812492db7091da07cf5789 | refs/heads/master | 2023-02-15T22:14:08.232081 | 2021-01-16T23:13:20 | 2021-01-16T23:13:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,097 | hpp | DeviceConfig.hpp | #pragma once
#include <stdint.h>
enum class DeviceType {
DIGITAL_INPUT = 1,
DIGITAL_OUTPUT = 2,
ANALOG_INPUT = 3,
DHT22 = 4,
BME280 = 5,
SCT013 = 6,
EMULATED_SWITCH = 7
};
enum class WireColor {
ORANGE_WHITE = 1,
ORANGE = 2,
GREEN_WHITE = 3,
BLUE = 4,
BLUE_WHITE = 5,
GREEN = 6,
BROWN_WHITE = 7,
BROWN = 8
};
class DeviceConfig {
public:
DeviceConfig(uint8_t _id, const char* _name, DeviceType _type, uint8_t _portNumber, WireColor _wire, uint16_t _debounceMs, uint8_t _pjonId = 0);
~DeviceConfig();
const uint8_t getId();
const char* getName();
const DeviceType getDeviceType();
const uint8_t getPortNumber();
const WireColor getWireColor();
const uint16_t getDebounceMs();
const uint8_t getPjonId();
bool isPjonDevice();
static const char* deviceTypeToString(DeviceType deviceType);
private:
const uint8_t id;
const char* name;
const DeviceType type;
const uint8_t portNumber;
const WireColor wire;
const uint16_t debounceMs;
const uint8_t pjonId;
}; |
06fce96589ec71282727d9ccbd12bf6e70e7907a | f7d1eb441baf395e884fb47937d2944a753bca1f | /plexus_test.cpp | 7c0ea55d5d2c4ac1b97f9c0dcc7da3d340a5965a | [] | no_license | tamwaiban/boba | 0a2a55973bd07de7d8fe319a664c2f9d8bae160f | e420d60f7d8416c1e34eebe05fa746f8547d6bde | refs/heads/master | 2020-12-28T15:26:29.382030 | 2014-09-30T13:27:32 | 2014-09-30T13:27:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,905 | cpp | plexus_test.cpp | #include "plexus_test.hpp"
#include "graphics.hpp"
#include "deferred_context.hpp"
#include "app.hpp"
#include "demo_engine.hpp"
#include "proto_helpers.hpp"
#include "resource_manager.hpp"
#include "init_sequence.hpp"
#include "boba_loader.hpp"
#include "protocol/effect_settings_generator_bindings.hpp"
#include "scene.hpp"
#include "dynamic_mesh.hpp"
#include "animation.hpp"
#pragma warning(push)
#pragma warning(disable: 4244 4267)
#include "protocol/effect_settings_plexus.pb.h"
#pragma warning(pop)
#include "protocol/effect_plexus_proto.hpp"
using namespace boba;
using namespace bristol;
static DynamicMesh g_mesh;
namespace boba
{
struct PathGenerator
{
virtual ~PathGenerator() {}
virtual void GeneratePoints(const UpdateState& state, vector<Vector3>* vertices, vector<u32>* indices) = 0;
virtual void ApplyConfig(const effect::plexus::TextPathConfig& config) {}
};
struct TextPathGenerator : public PathGenerator
{
TextPathGenerator()
: _stride(3)
{
Init("meshes/text1.boba");
WriteText("NEUROTICA EFS");
}
void ApplyConfig(const effect::plexus::TextPathConfig& config)
{
_config = config;
}
bool Init(const char* filename)
{
// Extract all the letters from the given file
if (!_loader.Load(filename))
{
return false;
}
u32 numLetters = 'Z' - 'A' + 1;
_letters.resize(numLetters);
Letter* curLetter = nullptr;
for (u32 i = 0; i < _loader.meshes.size(); ++i)
{
// Letter mesh names are ['A'..'Z']
BobaLoader::MeshElement* e = _loader.meshes[i];
int t = (int)e->name[0] - 'A';
if (strlen(e->name) == 1 && t >= 0 && t < (int)numLetters)
{
curLetter = &_letters[t];
curLetter->outline = e;
}
else if (strcmp(e->name, "Cap 1") == 0)
{
if (curLetter)
curLetter->cap1 = e;
else
LOG_WARN("Cap found without matching letter!");
}
else if (strcmp(e->name, "Cap 2") == 0)
{
if (curLetter)
curLetter->cap2 = e;
else
LOG_WARN("Cap found without matching letter!");
}
}
return true;
}
void AddVerts(
const BobaLoader::MeshElement* e,
float xOfs, float yOfs, float zOfs,
vector<float>* verts,
vector<u32>* indices,
float* minX,
float* maxX)
{
u32 numVerts = (u32)verts->size();
u32 numIndices = (u32)indices->size();
u32 v = e->numVerts / 3;
u32 stride = _stride;
verts->resize(verts->size() + v * stride);
indices->resize(indices->size() + e->numIndices);
*minX = *maxX = e->verts[0];
for (u32 i = 0; i < e->numVerts/3; ++i) {
float x = e->verts[i*3+0];
float y = e->verts[i*3+1];
float z = e->verts[i*3+2];
(*verts)[numVerts+i*stride+0] = x + xOfs;
(*verts)[numVerts+i*stride+1] = y + yOfs;
(*verts)[numVerts+i*stride+2] = z + zOfs;
*minX = min(*minX, x);
*maxX = max(*maxX, x);
}
// update indices to point to the correct spot in the combined VB
u32 ofs = numVerts / stride;
for (u32 i = 0; i < e->numIndices; ++i)
{
(*indices)[numIndices+i] = e->indices[i] + ofs;
}
}
void WriteText(const char* text)
{
_verts.clear();
_indices.clear();
u32 len = (u32)strlen(text);
float xOfs = -1000;
float yOfs = -80;
float zOfs = 1000;
for (u32 i = 0; i < len; ++i)
{
if (text[i] == ' ')
{
xOfs += 50;
continue;
}
int t = toupper(text[i]) - 'A';
Letter* letter = &_letters[t];
BobaLoader::MeshElement* e = letter->outline;
float minX, maxX;
AddVerts(e, xOfs, yOfs, zOfs, &_verts, &_indices, &minX, &maxX);
AddVerts(letter->cap1, xOfs, yOfs, zOfs, &_verts, &_indices, &minX, &maxX);
xOfs += 1.05f * (maxX - minX);
}
_numVerts = (u32)_verts.size() / _stride;
_numIndices = (u32)_indices.size();
}
void GeneratePoints(const UpdateState& state, vector<Vector3>* verts, vector<u32>* indices)
{
verts->resize(_numVerts * 4);
indices->resize(_numVerts * 6);
// 1 2
// 0 3
float s = 10;
Vector3 ofs0(-s, -s, 0);
Vector3 ofs1(-s, +s, 0);
Vector3 ofs2(+s, +s, 0);
Vector3 ofs3(+s, -s, 0);
Vector3* vertOut = verts->data();
u32* idxOut = indices->data();
for (u32 i = 0; i < _numVerts; ++i)
{
Vector3 b = Vector3(_verts[i*3+0], _verts[i*3+1], _verts[i*3+2]);
*vertOut++ = b + ofs0;
*vertOut++ = b + ofs1;
*vertOut++ = b + ofs2;
*vertOut++ = b + ofs3;
*idxOut++ = i*4 + 0;
*idxOut++ = i*4 + 1;
*idxOut++ = i*4 + 2;
*idxOut++ = i*4 + 0;
*idxOut++ = i*4 + 2;
*idxOut++ = i*4 + 3;
}
}
struct Letter
{
Letter() { memset(this, 0, sizeof(Letter)); }
BobaLoader::MeshElement* outline;
BobaLoader::MeshElement* cap1;
BobaLoader::MeshElement* cap2;
};
u32 _stride;
u32 _numVerts;
u32 _numIndices;
vector<float> _verts;
vector<u32> _indices;
vector<Letter> _letters;
BobaLoader _loader;
effect::plexus::TextPathConfig _config;
};
struct Renderer
{
Renderer(DeferredContext* ctx) : _ctx(ctx) {}
virtual bool Init() { return true; }
virtual void Render(const Matrix& viewProj, const vector<Vector3>& verts, const vector<u32>& indices) = 0;
DeferredContext* _ctx;
};
struct PointRenderer : public Renderer
{
PointRenderer(DeferredContext* ctx) : Renderer(ctx) {}
bool Init()
{
BEGIN_INIT_SEQUENCE();
CD3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC(CD3D11_DEFAULT());
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE;
CD3D11_DEPTH_STENCIL_DESC depthDesc = CD3D11_DEPTH_STENCIL_DESC(CD3D11_DEFAULT());
depthDesc.DepthEnable = FALSE;
INIT(_gpuState.Create(depthDesc, blendDesc, CD3D11_RASTERIZER_DESC(CD3D11_DEFAULT())));
INIT(_gpuObjects.CreateDynamic(1024 * 1024, DXGI_FORMAT_R32_UINT, nullptr, 1024 * 1024, sizeof(Vector3), nullptr));
INIT(_cb.Create());
INIT_ASSIGN(_particleTexture, GRAPHICS.LoadTexture("gfx/particle1.png"));
INIT(_gpuObjects.LoadShadersFromFile("shaders/particle", "VsMain", "PsMain", VF_POS));
END_INIT_SEQUENCE();
}
void Render(const Matrix& viewProj, const vector<Vector3>& verts, const vector<u32>& indices)
{
GPU_BeginEvent(0xffffffff, L"PointRenderer");
float black[] ={ 0, 0, 0, 0 };
_ctx->SetSwapChain(GRAPHICS.DefaultSwapChain(), black);
_ctx->BeginFrame();
_ctx->CopyToBuffer(_gpuObjects._vb, verts.data(), (u32)verts.size() * sizeof(Vector3));
_ctx->CopyToBuffer(_gpuObjects._ib, indices.data(), (u32)indices.size() * sizeof(u32));
_cb.data.viewProj = viewProj.Transpose();
_ctx->SetCBuffer(_cb, ShaderType::VertexShader, 0);
_ctx->SetGpuState(_gpuState);
_ctx->SetGpuStateSamplers(_gpuState, ShaderType::PixelShader);
_ctx->SetGpuObjects(_gpuObjects);
_ctx->SetCBuffer(_cb, ShaderType::VertexShader, 0);
_ctx->SetShaderResource(_particleTexture, ShaderType::PixelShader);
_ctx->DrawIndexed((u32)indices.size(), 0, 0);
_ctx->EndFrame();
_ctx->UnsetSRVs(0, 1, ShaderType::PixelShader);
GPU_EndEvent();
}
struct CBufferPerFrame
{
Matrix viewProj;
};
ConstantBuffer<CBufferPerFrame> _cb;
GpuObjects _gpuObjects;
GpuState _gpuState;
ObjectHandle _particleTexture;
};
struct LineRenderer : public Renderer
{
};
struct PolygonRenderer : public Renderer
{
};
struct Effector
{
virtual void Apply(const UpdateState& state, vector<Vector3>* verts) = 0;
virtual void ApplyConfig(const effect::plexus::NoiseEffectorConfig& config) {}
};
struct NoiseEffector : public Effector
{
virtual void ApplyConfig(const effect::plexus::NoiseEffectorConfig& config)
{
_config = config;
_displacementX = ANIMATION.AddAnimation(config.displacement.x, _displacementX);
_displacementY = ANIMATION.AddAnimation(config.displacement.y, _displacementY);
_displacementZ = ANIMATION.AddAnimation(config.displacement.z, _displacementZ);
}
void Apply(const UpdateState& state, vector<Vector3>* verts)
{
if (_offsets.size() != verts->size())
{
// we want each of the 4 verts in the particle to be affected by the same amount
// to avoid tearing and weird artifacts
_offsets.resize(verts->size() / 4);
for (size_t i = 0, e = verts->size() / 4; i < e; ++i)
{
_offsets[i] = Vector3(randf(-1.f, 1.f), randf(-1.f, 1.f), randf(-1.f, 1.f));
}
}
s64 ms = state.globalTime.TotalMilliseconds();
float x = ANIMATION.Interpolate(_displacementX, (u32)ms);
float y = ANIMATION.Interpolate(_displacementY, (u32)ms);
float z = ANIMATION.Interpolate(_displacementZ, (u32)ms);
for (size_t i = 0, e = verts->size(); i < e; ++i)
{
Vector3& v = (*verts)[i];
v.x += x * _offsets[i/4].x;
v.y += y * _offsets[i/4].y;
v.z += z * _offsets[i/4].z;
}
}
vector<Vector3> _offsets;
ObjectHandle _displacementX;
ObjectHandle _displacementY;
ObjectHandle _displacementZ;
effect::plexus::NoiseEffectorConfig _config;
};
//------------------------------------------------------------------------------
struct Plexus
{
Plexus(DeferredContext* ctx);
~Plexus();
bool Init();
void Update(const UpdateState& state);
void Render(const Matrix& viewProj);
void ApplyConfig(const effect::plexus::PlexusConfig& config);
vector<Vector3> _verts;
vector<u32> _indices;
vector<PathGenerator*> _paths;
vector<Effector*> _effectors;
vector<Renderer*> _renderers;
effect::plexus::PlexusConfig _config;
};
//------------------------------------------------------------------------------
Plexus::Plexus(DeferredContext* ctx)
{
_paths.push_back(new TextPathGenerator());
_effectors.push_back(new NoiseEffector());
_renderers.push_back(new PointRenderer(ctx));
}
//------------------------------------------------------------------------------
Plexus::~Plexus()
{
SeqDelete(&_paths);
SeqDelete(&_effectors);
SeqDelete(&_renderers);
}
//------------------------------------------------------------------------------
bool Plexus::Init()
{
BEGIN_INIT_SEQUENCE();
for (Renderer* r : _renderers)
{
INIT(r->Init());
}
END_INIT_SEQUENCE();
}
//------------------------------------------------------------------------------
void Plexus::ApplyConfig(const effect::plexus::PlexusConfig& config)
{
_config = config;
for (size_t i = 0; i < config.textPaths.size(); ++i)
{
_paths[i]->ApplyConfig(config.textPaths[i]);
}
for (size_t i = 0; i < config.noiseEffectors.size(); ++i)
{
_effectors[i]->ApplyConfig(config.noiseEffectors[i]);
}
}
//------------------------------------------------------------------------------
void Plexus::Update(const UpdateState& state)
{
_verts.clear();
for (PathGenerator* path : _paths)
{
path->GeneratePoints(state, &_verts, &_indices);
}
for (Effector* e : _effectors)
{
e->Apply(state, &_verts);
}
}
void Plexus::Render(const Matrix& viewProj)
{
for (Renderer* r : _renderers)
{
r->Render(viewProj, _verts, _indices);
}
}
}
struct TextWriter
{
bool Init(const char* filename)
{
if (!_loader.Load(filename))
{
return false;
}
u32 numLetters = 'Z' - 'A' + 1;
_letters.resize(numLetters);
Letter* curLetter = nullptr;
for (u32 i = 0; i < _loader.meshes.size(); ++i)
{
// Letter mesh names are ['A'..'Z']
BobaLoader::MeshElement* e = _loader.meshes[i];
int t = (int)e->name[0] - 'A';
if (strlen(e->name) == 1 && t >= 0 && t < (int)numLetters)
{
curLetter = &_letters[t];
curLetter->outline = e;
}
else if (strcmp(e->name, "Cap 1") == 0)
{
if (curLetter)
curLetter->cap1 = e;
else
LOG_WARN("Cap found without matching letter!");
}
else if (strcmp(e->name, "Cap 2") == 0)
{
if (curLetter)
curLetter->cap2 = e;
else
LOG_WARN("Cap found without matching letter!");
}
}
GRAPHICS.LoadShadersFromFile("shaders/text_shader",
&_meshObjects._vs, &_meshObjects._ps, &_meshObjects._layout, VF_POS | VF_NORMAL | VF_COLOR);
return true;
}
void AppendMeshToBuffer(
const BobaLoader::MeshElement* e,
float xOfs, float yOfs, float zOfs,
const Color& color,
vector<float>* verts,
vector<u32>* indices,
float* minX,
float* maxX)
{
u32 numVerts = (u32)verts->size();
u32 numIndices = (u32)indices->size();
u32 v = e->numVerts / 3;
u32 stride = 10;
verts->resize(verts->size() + v * stride);
indices->resize(indices->size() + e->numIndices);
*minX = *maxX = e->verts[0];
for (u32 i = 0; i < e->numVerts/3; ++i) {
float x = e->verts[i*3+0];
float y = e->verts[i*3+1];
float z = e->verts[i*3+2];
(*verts)[numVerts+i*stride+0] = x + xOfs;
(*verts)[numVerts+i*stride+1] = y + yOfs;
(*verts)[numVerts+i*stride+2] = z + zOfs;
(*verts)[numVerts+i*stride+3] = e->normals[i*3+0];
(*verts)[numVerts+i*stride+4] = e->normals[i*3+1];
(*verts)[numVerts+i*stride+5] = e->normals[i*3+2];
(*verts)[numVerts+i*stride+6] = color.x;
(*verts)[numVerts+i*stride+7] = color.y;
(*verts)[numVerts+i*stride+8] = color.z;
(*verts)[numVerts+i*stride+9] = color.w;
*minX = min(*minX, x);
*maxX = max(*maxX, x);
}
// update indices to point to the correct spot in the combined VB
u32 ofs = numVerts / 10;
for (u32 i = 0; i < e->numIndices; ++i)
{
(*indices)[numIndices+i] = e->indices[i] + ofs;
}
}
void WriteText(const char* text)
{
u32 len = (u32)strlen(text);
vector<float> verts;
vector<u32> indices;
float xOfs = -1000;
float yOfs = -80;
float zOfs = 1000;
for (u32 i = 0; i < len; ++i)
{
if (text[i] == ' ')
{
xOfs += 50;
continue;
}
int t = toupper(text[i]) - 'A';
Letter* letter = &_letters[t];
BobaLoader::MeshElement* e = letter->outline;
float minX, maxX;
AppendMeshToBuffer(e, xOfs, yOfs, zOfs, Color(1,0,0,0), &verts, &indices, &minX, &maxX);
AppendMeshToBuffer(letter->cap1, xOfs, yOfs, zOfs, Color(0,1,0,0), &verts, &indices, &minX, &maxX);
//AppendMeshToBuffer(letter->cap2, xOfs, yOfs, zOfs, &verts, &indices, &minX, &maxX);
xOfs += 1.05f * (maxX - minX);
}
_numVerts = (u32)verts.size() / 10;
_numIndices = (u32)indices.size();
_meshObjects.CreateDynamic(
_numIndices * sizeof(u32), DXGI_FORMAT_R32_UINT, indices.data(),
_numVerts * sizeof(PosNormalColor), sizeof(PosNormalColor), verts.data());
}
GpuObjects _meshObjects;
u32 _numVerts;
u32 _numIndices;
struct Letter
{
Letter() { memset(this, 0, sizeof(Letter)); }
BobaLoader::MeshElement* outline;
BobaLoader::MeshElement* cap1;
BobaLoader::MeshElement* cap2;
};
vector<Letter> _letters;
BobaLoader _loader;
};
TextWriter g_textWriter;
//------------------------------------------------------------------------------
PlexusTest::PlexusTest(const string& name, u32 id)
: Effect(name, id)
, _rotatingObject(false)
, _dirtyFlag(true)
, _lua(nullptr)
, _numIndices(0)
, _cameraDir(0,0,1)
, _curAdaption(0)
, _postProcess(nullptr)
, _plexus(nullptr)
{
_renderFlags.Set(PlexusTest::RenderFlags::Luminance);
}
//------------------------------------------------------------------------------
PlexusTest::~PlexusTest()
{
SAFE_DELETE(_plexus);
SAFE_DELETE(_postProcess);
}
//------------------------------------------------------------------------------
bool PlexusTest::Init(const protocol::effect::EffectSetting& config)
{
BEGIN_INIT_SEQUENCE();
//_configName = config;
_planeConfig = config.generator_plane_config();
if (_planeConfig.has_camera_pos()) _cameraPos = ::boba::common::FromProtocol(_planeConfig.camera_pos());
if (_planeConfig.has_camera_dir()) _cameraDir = ::boba::common::FromProtocol(_planeConfig.camera_dir());
//BindSpiky(&_spikyConfig, &_dirtyFlag);
static bool tmp;
BindPlaneConfig(&_planeConfig, &tmp);
INIT(_meshObjects.CreateDynamic(64 * 1024, DXGI_FORMAT_R32_UINT, 64 * 1024, sizeof(PosNormal)));
INIT(_cb.Create());
INIT(_cbToneMapping.Create());
INIT_ASSIGN(_luminanceAdaption[0], GRAPHICS.CreateRenderTarget(1, 1, DXGI_FORMAT_R16_FLOAT, BufferFlags(BufferFlag::CreateSrv)));
INIT_ASSIGN(_luminanceAdaption[1], GRAPHICS.CreateRenderTarget(1, 1, DXGI_FORMAT_R16_FLOAT, BufferFlags(BufferFlag::CreateSrv)));
INIT(_meshObjects.LoadShadersFromFile("shaders/generator", "VsMain", "PsMain", VF_POS | VF_NORMAL));
_postProcess = new PostProcess(_ctx);
INIT(_postProcess->Init());
int w, h;
GRAPHICS.GetBackBufferSize(&w, &h);
INIT_ASSIGN(_renderTarget,
GRAPHICS.CreateRenderTarget(w, h, DXGI_FORMAT_R16G16B16A16_FLOAT, BufferFlags(BufferFlag::CreateDepthBuffer) | BufferFlag::CreateSrv));
INIT(GRAPHICS.LoadShadersFromFile("shaders/copy", nullptr, &_psCopy, nullptr, 0));
INIT(GRAPHICS.LoadShadersFromFile("shaders/tonemap", nullptr, &_psLuminance, nullptr, 0, nullptr, "LuminanceMap"));
INIT(GRAPHICS.LoadShadersFromFile("shaders/tonemap", nullptr, &_psComposite, nullptr, 0, nullptr, "Composite"));
INIT(GRAPHICS.LoadShadersFromFile("shaders/tonemap", nullptr, &_psAdaption, nullptr, 0, nullptr, "AdaptLuminance"));
INIT(GRAPHICS.LoadShadersFromFile("shaders/tonemap", nullptr, &_psThreshold, nullptr, 0, nullptr, "BloomThreshold"));
INIT(GRAPHICS.LoadComputeShadersFromFile("shaders/blur", &_csBlurX, "BoxBlurX"));
INIT(GRAPHICS.LoadComputeShadersFromFile("shaders/blur", &_csBlurY, "BoxBlurY"));
INIT(GRAPHICS.LoadComputeShadersFromFile("shaders/blur", &_csCopyTranspose, "CopyTranspose"));
INIT(GRAPHICS.LoadComputeShadersFromFile("shaders/blur", &_csBlurTranspose, "BlurTranspose"));
INIT(GRAPHICS.LoadShadersFromFile("shaders/text_shader", nullptr, &_psEdgeDetect, nullptr, 0, nullptr, "EdgeDetect"));
INIT(_cbBlur.Create());
INIT(_cbBloom.Create());
INIT(_cbComposite.Create());
INIT(_gpuState.Create());
INIT(g_textWriter.Init("meshes/text1.boba"));
_plexus = new Plexus(_ctx);
_plexusConfig.textPaths.push_back({"NEUROTICA EFS"});
_plexusConfig.noiseEffectors.push_back(effect::plexus::NoiseEffectorConfig());
INIT(_plexus->Init());
g_textWriter.WriteText(_plexusConfig.textPaths.front().text.c_str());
END_INIT_SEQUENCE();
}
//------------------------------------------------------------------------------
bool PlexusTest::Update(const UpdateState& state)
{
_plexus->Update(state);
_updateState = state;
return true;
}
//------------------------------------------------------------------------------
void PlexusTest::RenderText()
{
Color black(0.1f, 0.1f, 0.1f, 0);
_ctx->SetGpuState(_gpuState);
int w, h;
GRAPHICS.GetBackBufferSize(&w, &h);
auto f = BufferFlags(BufferFlag::CreateSrv) | BufferFlags(BufferFlag::CreateDepthBuffer);
ScopedRenderTarget scratch(w, h, DXGI_FORMAT_R8G8B8A8_UNORM, f);
_ctx->SetRenderTarget(scratch.h, &black);
_ctx->BeginFrame();
_proj = Matrix::CreatePerspectiveFieldOfView(45.0f / 180 * 3.1415f, 16.0f / 10, 1, 10000);
_view = Matrix::CreateLookAt(_cameraPos, _cameraPos + 100 * _cameraDir, Vector3(0, 1, 0));
_invView = _view.Invert();
Matrix world = Matrix::Identity();
world = g_mesh.rotation;
_cb.data.world = world.Transpose();
_cb.data.viewProj = (_view * _proj).Transpose();
GPU_BeginEvent(0xffffffff, L"DrawObj");
_ctx->SetCBuffer(_cb, ShaderType::VertexShader, 0);
_ctx->SetGpuObjects(g_textWriter._meshObjects);
_ctx->DrawIndexed(g_textWriter._numIndices, 0, 0);
GPU_EndEvent();
_ctx->SetVB(nullptr, 24);
_ctx->SetIB(nullptr, DXGI_FORMAT_R32_UINT);
_ctx->UnsetSRVs(0, 1, ShaderType::PixelShader);
ObjectHandle rtDest = GRAPHICS.RenderTargetForSwapChain(GRAPHICS.DefaultSwapChain());
_postProcess->Setup();
_postProcess->Execute({ scratch.h }, rtDest, _psEdgeDetect, &black, L"EdgeDetect");
_ctx->EndFrame();
_ctx->SetSwapChain(GRAPHICS.DefaultSwapChain(), false);
}
//------------------------------------------------------------------------------
bool PlexusTest::Render()
{
_proj = Matrix::CreatePerspectiveFieldOfView(45.0f / 180 * 3.1415f, 16.0f / 10, 1, 10000);
_view = Matrix::CreateLookAt(_cameraPos, _cameraPos + 100 * _cameraDir, Vector3(0, 1, 0));
_plexus->Render(_view * _proj);
//RenderText();
return true;
}
//------------------------------------------------------------------------------
bool PlexusTest::Close()
{
return true;
}
//------------------------------------------------------------------------------
bool PlexusTest::SaveSettings()
{
if (FILE* f = fopen(_configName.c_str() ,"wt"))
{
::boba::common::ToProtocol(_cameraPos, _planeConfig.mutable_camera_pos());
::boba::common::ToProtocol(_cameraDir, _planeConfig.mutable_camera_dir());
::boba::common::ToProtocol(g_mesh.translation, _planeConfig.mutable_obj_t());
::boba::common::ToProtocol(g_mesh.rotation, _planeConfig.mutable_obj_r());
fprintf(f, "%s", _planeConfig.DebugString().c_str());
fclose(f);
}
return true;
}
//------------------------------------------------------------------------------
Effect* PlexusTest::Create(const char* name, u32 id)
{
return new PlexusTest(name, id);
}
//------------------------------------------------------------------------------
const char* PlexusTest::Name()
{
return "plexus_test";
}
//------------------------------------------------------------------------------
void PlexusTest::ToProtocol(protocol::effect::EffectSetting* settings) const
{
settings->set_type(protocol::effect::EffectSetting_Type_Plexus);
protocol::effect::plexus::PlexusConfig plexusConfig;
boba::effect::plexus::ToProtocol(_plexusConfig, &plexusConfig);
// TODO:
//settings->set_config_msg(plexusConfig.SerializeAsString());
}
//------------------------------------------------------------------------------
void PlexusTest::FromProtocol(const std::string& str)
{
protocol::effect::plexus::PlexusConfig p;
p.ParseFromString(str);
_plexusConfig = boba::effect::plexus::FromProtocol(p);
_plexus->ApplyConfig(_plexusConfig);
}
//------------------------------------------------------------------------------
void PlexusTest::WndProc(UINT message, WPARAM wParam, LPARAM lParam)
{
float speed = 10;
switch (message)
{
case WM_KEYDOWN:
switch (wParam)
{
case '1':
_renderFlags.Toggle(RenderFlags::Wireframe);
break;
case '2':
_renderFlags.Toggle(RenderFlags::Luminance);
break;
case 'A':
{
_cameraPos += -speed * _invView.Right();
break;
}
case 'D':
{
_cameraPos += speed * _invView.Right();
break;
}
case 'W':
{
_cameraPos += speed * _invView.Up();
break;
}
case 'S':
{
_cameraPos += -speed * _invView.Up();
break;
}
}
break;
case WM_LBUTTONDOWN:
{
// start of rotation
u32 xs = LOWORD(lParam);
u32 ys = HIWORD(lParam);
Vector3 org_vs = Vector3(0, 0, 0);
Vector3 dir_vs = ScreenToViewSpace(_proj, xs, ys);
Matrix worldToObj = g_mesh.World().Invert();
Matrix viewToObj = _invView * worldToObj;
Vector3 org_os = Vector4::Transform(Vector4(_invView._41, _invView._42, _invView._43, 1), worldToObj);
Vector3 dir_os = Vector4::Transform(Vector4(dir_vs.x, dir_vs.y, dir_vs.z, 0), viewToObj);
dir_os.Normalize();
float t = Raycast(Vector3(0, 0, 0), g_mesh.radius, org_os, dir_os);
_rotatingObject = t > 0;
_rotatingObject = true;
if (_rotatingObject)
{
Vector3 d = Vector4::Transform(Vector4(dir_vs.x, dir_vs.y, dir_vs.z, 0), _invView);
d.Normalize();
_v0 = d;
}
break;
}
case WM_LBUTTONUP:
_prevRot = g_mesh.rotation;
_rotatingObject = false;
break;
case WM_MOUSEMOVE:
{
if (_rotatingObject)
{
u32 xs = LOWORD(lParam);
u32 ys = HIWORD(lParam);
// Find the click point in world space
Vector3 pos = ScreenToViewSpace(_proj, xs, ys);
// Vector from eye pos (0,0,0) to click point in world space
Vector3 v1 = Vector4::Transform(Vector4(pos.x, pos.y, pos.z, 0), _invView);
v1.Normalize();
// angle between the two vectors
float speed = 2;
float angle = acos(_v0.Dot(v1));
Vector3 axis = _v0.Cross(v1);
if (axis.Length() > 0)
g_mesh.rotation = _prevRot * Matrix::CreateFromAxisAngle(axis, speed * angle);
}
break;
}
case WM_MOUSEWHEEL:
{
s16 delta = HIWORD(wParam);
float fDelta = delta / 120.0f;
_cameraPos += 10 * fDelta * _invView.Forward();
break;
}
}
}
|
465eed3d736c659f3328c16a7fc490422aea7d4c | 20ffe3ddc443ec996c08a2271542c224c464f4d4 | /NUAASwimmingAssociationVersion/NUAASwimmingAssociationVersion/ControlWindow.cpp | 86e5ddd140999321bf46c15221db2bcbe140ce1a | [] | no_license | fuookami/SCSGS | 0209052f31de4d6c8a765f1f0b4fd4383ca388c6 | 4b5331887e49e4944556bf56996c0ac84ee926b2 | refs/heads/master | 2021-01-18T15:45:49.994450 | 2017-05-31T16:07:03 | 2017-05-31T16:07:03 | 86,682,203 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 17,465 | cpp | ControlWindow.cpp | #include "ControlWindow.h"
#include <ctime>
ControlWindow::ControlWindow(QMainWindow *parent /* = NULL */) :QMainWindow(parent)
{
thisCom = new Competion();
screenWin = new ScreenWindow(Screen, thisCom->getTeamNames());
screenWin->show();
monitor = new ScreenWindow(Monitor, thisCom->getTeamNames());
monitor->show();
gameNames = thisCom->getGameNames();
teamNames = thisCom->getTeamNames();
ui = new Ui::ControlWindow();
ui->setupUi(this);
ui->RegistrationCompetitionName->setText(QString::fromLocal8Bit(QByteArray("比赛还未正式开始")));
mediaPlayer = new QMediaPlayer();
mediaPlayer->setMedia(QUrl(QString::fromLocal8Bit("Whistle.wav")));
connect(ui->StartBtn, SIGNAL(clicked()), this, SLOT(startComp()));
ui->StopBtn->setEnabled(false);
ui->ContinueBtn->setEnabled(false);
ui->Refresh->setEnabled(false);
ui->Next->setEnabled(false);
ui->LastLoad->setEnabled(false);
ui->NextLoad->setEnabled(false);
teamScore demo = { 0, 0 };
for (int i(0), j(thisCom->getTeamNames().size() - 1); i < j; ++i)
{
demo.team = i;
scores.push_back(demo);
}
currGameOr = 0;
setMap();
}
ControlWindow::~ControlWindow(void)
{
}
void ControlWindow::startComp(void)
{
thisGame = thisCom->getGameByOrder(currGameOr);
thisGame.currentGroup = -1;
currLoadGameOr = 0;
ui->RegistrationCompetitionName->setText(QString::fromLocal8Bit((thisGame.gameName + std::string("预决赛")).c_str()));
screenWin->setLoad(gameNames[0] + std::string("预决赛"));
monitor->setLoad(gameNames[0] + std::string("预决赛"));
disconnect(ui->StartBtn, SIGNAL(clicked()));
ui->StartBtn->setEnabled(false);
ui->Next->setEnabled(true);
ui->Whistle->setEnabled(true);
ui->NextLoad->setEnabled(true);
connect(ui->Whistle, SIGNAL(clicked()), this, SLOT(playWhistle()));
connect(ui->Next, SIGNAL(clicked()), this, SLOT(nextGroup()));
connect(ui->StopBtn, SIGNAL(clicked()), this, SLOT(stopComp()));
connect(ui->ContinueBtn, SIGNAL(clicked()), this, SLOT(continueComp()));
connect(ui->Refresh, SIGNAL(clicked()), this, SLOT(refresh()));
connect(ui->LastLoad, SIGNAL(clicked()), this, SLOT(lastLoad()));
connect(ui->NextLoad, SIGNAL(clicked()), this, SLOT(nextLoad()));
}
void ControlWindow::playWhistle(void)
{
mediaPlayer->play();
}
void ControlWindow::stopComp(void)
{
ui->StopBtn->setEnabled(false);
ui->ContinueBtn->setEnabled(true);
screenWin->setStop();
screenWin->setStop();
}
void ControlWindow::continueComp(void)
{
ui->StopBtn->setEnabled(true);
ui->ContinueBtn->setEnabled(false);
monitor->refresh(thisGame.groups[thisGame.currentGroup]);
monitor->setGame(thisGame.gameName + std::string("预决赛") + Setting::groupNames[thisGame.currentGroup]);
screenWin->refresh(thisGame.groups[thisGame.currentGroup]);
screenWin->setGame(thisGame.gameName + std::string("预决赛") + Setting::groupNames[thisGame.currentGroup]);
}
void ControlWindow::nextGroup(void)
{
ui->StopBtn->setEnabled(true);
if (thisGame.currentGroup != -1) {
for (int i(0); i < Setting::LineNums; ++i)
{
getGrade(i);
}
}
if (++thisGame.currentGroup == thisGame.groups.size())
{
if (++currGameOr == thisCom->getGameNum())
{
screenWin->setEnd();
monitor->setEnd();
clearWin();
ui->CompetitionName->setText(QString::fromLocal8Bit("已完赛"));
deal();
outPutTeamScore();
return;
}
deal();
thisGame = thisCom->getGameByOrder(currGameOr);
thisGame.currentGroup = 0;
}
refreshWin();
}
void ControlWindow::refreshWin(void)
{
clearWin();
monitor->refresh(thisGame.groups[thisGame.currentGroup]);
monitor->setGame(thisGame.gameName + std::string("预决赛") + Setting::groupNames[thisGame.currentGroup]);
screenWin->refresh(thisGame.groups[thisGame.currentGroup]);
screenWin->setGame(thisGame.gameName + std::string("预决赛") + Setting::groupNames[thisGame.currentGroup]);
ui->CompetitionName->setText(QString::fromLocal8Bit((thisGame.gameName + Setting::groupNames[thisGame.currentGroup]).c_str()));
for (int i(0); i < Setting::LineNums; ++i)
{
setLine(i);
}
ui->Next->setEnabled(false);
ui->Refresh->setEnabled(true);
}
void ControlWindow::refresh(void)
{
for (int i(0); i < Setting::LineNums; ++i)
{
getGrade(i);
}
std::array<athlete, Setting::LineNums> temp(thisGame.groups[thisGame.currentGroup]);
std::sort(temp.begin(), temp.end());
for (int i(0), j(1); i < Setting::LineNums; ++i)
{
if (temp[i].name.empty())
{
continue;
}
if (i != 0)
{
j = (temp[i].grade == temp[i - 1].grade) ? j : i + 1;
}
std::array<athlete, Setting::LineNums>::iterator thisRank
(std::find(thisGame.groups[thisGame.currentGroup].begin(), thisGame.groups[thisGame.currentGroup].end(), temp[i]));
thisRank->thisRank = (thisRank->grade < 10000.0) ? j : -1;
}
screenWin->refresh(thisGame.groups[thisGame.currentGroup]);
screenWin->setGame(thisGame.gameName + std::string("预决赛") + Setting::groupNames[thisGame.currentGroup]);
monitor->refresh(thisGame.groups[thisGame.currentGroup]);
monitor->setGame(thisGame.gameName + std::string("预决赛") + Setting::groupNames[thisGame.currentGroup]);
ui->CompetitionName->setText(QString::fromLocal8Bit((thisGame.gameName + Setting::groupNames[thisGame.currentGroup]).c_str()));
ui->Next->setEnabled(true);
}
void ControlWindow::lastLoad(void)
{
if (--currLoadGameOr == 0)
{
ui->LastLoad->setEnabled(false);
}
ui->NextLoad->setEnabled(true);
ui->RegistrationCompetitionName->setText
(QString::fromLocal8Bit(gameNames[currLoadGameOr].c_str()));
screenWin->setLoad(gameNames[currLoadGameOr] + std::string("预决赛"));
monitor->setLoad(gameNames[currLoadGameOr] + std::string("预决赛"));
}
void ControlWindow::nextLoad(void)
{
if (++currLoadGameOr == gameNames.size() - 1)
{
ui->NextLoad->setEnabled(false);
}
ui->LastLoad->setEnabled(true);
ui->RegistrationCompetitionName->setText
(QString::fromLocal8Bit(gameNames[currLoadGameOr].c_str()) + QString::fromLocal8Bit("预决赛"));
screenWin->setLoad(gameNames[currLoadGameOr] + std::string("预决赛"));
monitor->setLoad(gameNames[currLoadGameOr] + std::string("预决赛"));
}
void ControlWindow::setLine(int line)
{
athlete &thisAth(thisGame.groups[thisGame.currentGroup][line]);
if (thisAth.name.empty())
{
return;
}
names[line]->setText(QString::fromLocal8Bit(thisAth.name.c_str()));
teams[line]->setText(QString::fromLocal8Bit(teamNames[thisAth.team].c_str()));
}
void ControlWindow::setMap(void)
{
names[0] = ui->Line0Name;
names[1] = ui->Line1Name;
names[2] = ui->Line2Name;
names[3] = ui->Line3Name;
names[4] = ui->Line4Name;
names[5] = ui->Line5Name;
names[6] = ui->Line6Name;
names[7] = ui->Line7Name;
names[8] = ui->Line8Name;
names[9] = ui->Line9Name;
teams[0] = ui->Line0Team;
teams[1] = ui->Line1Team;
teams[2] = ui->Line2Team;
teams[3] = ui->Line3Team;
teams[4] = ui->Line4Team;
teams[5] = ui->Line5Team;
teams[6] = ui->Line6Team;
teams[7] = ui->Line7Team;
teams[8] = ui->Line8Team;
teams[9] = ui->Line9Team;
qs[0] = ui->Line0Q;
qs[1] = ui->Line1Q;
qs[2] = ui->Line2Q;
qs[3] = ui->Line3Q;
qs[4] = ui->Line4Q;
qs[5] = ui->Line5Q;
qs[6] = ui->Line6Q;
qs[7] = ui->Line7Q;
qs[8] = ui->Line8Q;
qs[9] = ui->Line9Q;
dqs[0] = ui->Line0DQ;
dqs[1] = ui->Line1DQ;
dqs[2] = ui->Line2DQ;
dqs[3] = ui->Line3DQ;
dqs[4] = ui->Line4DQ;
dqs[5] = ui->Line5DQ;
dqs[6] = ui->Line6DQ;
dqs[7] = ui->Line7DQ;
dqs[8] = ui->Line8DQ;
dqs[9] = ui->Line9DQ;
mins[0] = ui->Line0Min;
mins[1] = ui->Line1Min;
mins[2] = ui->Line2Min;
mins[3] = ui->Line3Min;
mins[4] = ui->Line4Min;
mins[5] = ui->Line5Min;
mins[6] = ui->Line6Min;
mins[7] = ui->Line7Min;
mins[8] = ui->Line8Min;
mins[9] = ui->Line9Min;
secs[0] = ui->Line0Sec;
secs[1] = ui->Line1Sec;
secs[2] = ui->Line2Sec;
secs[3] = ui->Line3Sec;
secs[4] = ui->Line4Sec;
secs[5] = ui->Line5Sec;
secs[6] = ui->Line6Sec;
secs[7] = ui->Line7Sec;
secs[8] = ui->Line8Sec;
secs[9] = ui->Line9Sec;
hun_msecs[0] = ui->Line0HunMSec;
hun_msecs[1] = ui->Line1HunMSec;
hun_msecs[2] = ui->Line2HunMSec;
hun_msecs[3] = ui->Line3HunMSec;
hun_msecs[4] = ui->Line4HunMSec;
hun_msecs[5] = ui->Line5HunMSec;
hun_msecs[6] = ui->Line6HunMSec;
hun_msecs[7] = ui->Line7HunMSec;
hun_msecs[8] = ui->Line8HunMSec;
hun_msecs[9] = ui->Line9HunMSec;
}
void ControlWindow::getGrade(int line)
{
athlete &thisAth(thisGame.groups[thisGame.currentGroup][line]);
if (thisAth.name.empty())
{
return;
}
thisAth.hasGrade = true;
if (qs[line]->isChecked())
{
thisAth.gradeStr = std::string("DSQ");
thisAth.grade = 10000.0;
}
else if (dqs[line]->isChecked())
{
thisAth.gradeStr = std::string("DNS");
thisAth.grade = 100000.0;
}
else
{
std::string temp(hun_msecs[line]->toPlainText().toLocal8Bit());
if (temp.size() == 1 || temp.size() == 0)
{
temp.append(2 - temp.size(), '0');
}
else if (temp.size() > 2)
{
temp.erase(temp.begin() + 2, temp.end());
}
thisAth.grade = mins[line]->toPlainText().toDouble() * 60
+ secs[line]->toPlainText().toDouble()
+ std::stod(temp) / 100;
thisAth.gradeStr.clear();
if (mins[line]->toPlainText().toDouble() > 0.0)
{
thisAth.gradeStr = std::string(mins[line]->toPlainText().toLocal8Bit()) + std::string(":");
}
thisAth.gradeStr.append(std::string(secs[line]->toPlainText().toLocal8Bit()) + std::string(".")
+ temp);
}
}
void ControlWindow::clearWin(void)
{
for (int i(0); i < Setting::LineNums; ++i)
{
qs[i]->setChecked(false);
dqs[i]->setChecked(false);
mins[i]->clear();
secs[i]->clear();
hun_msecs[i]->clear();
names[i]->clear();
teams[i]->clear();
}
}
void ControlWindow::deal(void)
{
time_t tt = time(NULL);
tm* t = localtime(&tt);
std::ostringstream timeStr;
timeStr << t->tm_year + 1900 << '/' << t->tm_mon + 1 << '/' << t->tm_mday << ' ' << t->tm_hour << ':' << t->tm_min << ':' << t->tm_sec;
std::ofstream fout(std::string("Result/") + thisCom->getCompName() + thisGame.gameName + std::string("决赛") + std::string("成绩公告.html"));
fout << this->thisCom->getHead();
fout << "<td colspan=2 class=xl75 align=right width=550 style='width:413pt'>" << timeStr.str() << "</td></tr>";
bool isRelay = false;
std::array<std::vector<athlete>, 3> athletes;
for (int i(0), j(thisGame.groups.size()); i < j; ++i)
{
for (int p(0); p < Setting::LineNums; ++p)
{
if (!thisGame.groups[i][p].name.empty())
{
if (thisGame.groups[i][p].cla == 3)
{
isRelay = true;
goto outOfCirculation;
}
athletes[thisGame.groups[i][p].cla].push_back(thisGame.groups[i][p]);
}
}
}
outOfCirculation:
if (isRelay)
{
fout << "<tr height=19 valign=middle style='height:14.25pt'>" <<
"<td colspan = 3 height = 19 class = xl74 style = 'height:14.25pt'>" << thisGame.gameName << "</td>" <<
"<td></td>" <<
"<td class = xl65>决赛成绩公告</td>" <<
"<td></td>" <<
"</tr>" <<
"<tr height = 19 valign = middle style = 'height:14.25pt'>" <<
"<td height = 19 class = xl68 align = center style = 'height:14.25pt'>名次</td>" <<
"<td class = xl68 align = center>道</td>" <<
"<td class = xl68 align = center>姓名</td>" <<
"<td class = xl68 align = center>单位</td>" <<
"<td class = xl70>成绩</td>" <<
"<td class = xl68 align = center>备注</td>" <<
"</tr>";
std::vector<athlete> temp;
for (int i(0), j(thisGame.groups.size()); i < j; ++i)
{
for (int p(0); p < Setting::LineNums; ++p)
{
if (!thisGame.groups[i][p].name.empty())
{
temp.push_back(thisGame.groups[i][p]);
}
}
}
std::sort(temp.begin(), temp.end());
int j = 1;
for (int p(0), q(temp.size()); p < q; ++p)
{
if (p != 0)
{
j = (temp[p].grade == temp[p - 1].grade) ? j : p + 1;
}
if (temp[p].grade < 10000.0)
{
fout << "<tr height = 19 valign = middle style = 'height:14.25pt'>" <<
"<td height = 19 class = xl67 align = center style = 'height:14.25pt'><font" <<
"color = '#000000'>" << j << "</font></td>" <<
"<td class = xl67 align = center><font color = '#000000'>" << temp[p].line << "</font></td>" <<
"<td class = xl67 align = center>" << temp[p].name << "</td>" <<
"<td class = xl67 align = center>" << teamNames[temp[p].team] << "</td>" <<
"<td class = xl69>" << temp[p].gradeStr << "</td>"
"<td class = xl67 align = center></td>" <<
"</tr>";
if (j <= 8)
{
scores[temp[p].team].score += Setting::rankScores[j - 1] * thisGame.weight;
}
}
else
{
fout << "<tr height = 19 valign = middle style = 'height:14.25pt'>" <<
"<td height = 19 class = xl67 align = center style = 'height:14.25pt'><font" <<
"color = '#000000'></font ></td>" <<
"<td class = xl67 align = center><font color = '#000000'>" << temp[p].line << "</font></td>" <<
"<td class = xl67 align = center>" << temp[p].name << "</td>" <<
"<td class = xl67 align = center>" << teamNames[temp[p].team] << "</td>" <<
"<td class = xl69>" << temp[p].gradeStr << "</td>"
"<td class = xl67 align = center></td>" <<
"</tr>";
}
}
fout << "<tr height=19 valign=middle style='height:14.25pt'>" <<
"<td height = 19 class = btd style = 'height:14.25pt'></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"</tr>";
}
else
{
std::sort(athletes[0].begin(), athletes[0].end());
std::sort(athletes[1].begin(), athletes[1].end());
std::sort(athletes[2].begin(), athletes[2].end());
for (int i(0); i < 3; ++i)
{
fout << "<tr height=19 valign=middle style='height:14.25pt'>" <<
"<td colspan = 3 height = 19 class = xl74 style = 'height:14.25pt'>" << thisGame.gameName
<< Setting::classDisplay[i] << "组" << "</td>" <<
"<td></td>" <<
"<td class = xl65>决赛成绩公告</td>" <<
"<td></td>" <<
"</tr>" <<
"<tr height = 19 valign = middle style = 'height:14.25pt'>" <<
"<td height = 19 class = xl68 align = center style = 'height:14.25pt'>名次</td>" <<
"<td class = xl68 align = center>道</td>" <<
"<td class = xl68 align = center>姓名</td>" <<
"<td class = xl68 align = center>单位</td>" <<
"<td class = xl70>成绩</td>" <<
"<td class = xl68 align = center>备注</td>" <<
"</tr>";
std::vector<athlete> &thisClass = athletes[i];
int j = 1;
for (int p(0), q(thisClass.size()); p < q; ++p)
{
if (p != 0)
{
j = (thisClass[p].grade == thisClass[p - 1].grade) ? j : p + 1;
}
if (thisClass[p].grade < 10000.0)
{
fout << "<tr height = 19 valign = middle style = 'height:14.25pt'>" <<
"<td height = 19 class = xl67 align = center style = 'height:14.25pt'><font" <<
"color = '#000000'>" << j << "</font></td>" <<
"<td class = xl67 align = center><font color = '#000000'>" << thisClass[p].line << "</font></td>" <<
"<td class = xl67 align = center>" << thisClass[p].name << "</td>" <<
"<td class = xl67 align = center>" << teamNames[thisClass[p].team] << "</td>" <<
"<td class = xl69>" << thisClass[p].gradeStr << "</td>"
"<td class = xl67 align = center></td>" <<
"</tr>";
if (j <= 8)
{
scores[thisClass[p].team].score += Setting::rankScores[j - 1] * thisGame.weight;
}
}
else
{
fout << "<tr height = 19 valign = middle style = 'height:14.25pt'>" <<
"<td height = 19 class = xl67 align = center style = 'height:14.25pt'><font" <<
"color = '#000000'></font></td>" <<
"<td class = xl67 align = center><font color = '#000000'>" << thisClass[p].line << "</font></td>" <<
"<td class = xl67 align = center>" << thisClass[p].name << "</td>" <<
"<td class = xl67 align = center>" << teamNames[thisClass[p].team] << "</td>" <<
"<td class = xl69>" << thisClass[p].gradeStr << "</td>"
"<td class = xl67 align = center></td>" <<
"</tr>";
}
}
fout << "<tr height=19 valign=middle style='height:14.25pt'>" <<
"<td height = 19 class = btd style = 'height:14.25pt'></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"<td class = btd></td>" <<
"</tr>";
}
}
fout << "<tr height=19 valign=middle style='height:14.25pt'>" <<
"<td height = 19 style = 'height:14.25pt'></td>" <<
"<td class=xl66 colspan=4 style='mso-ignore:colspan'>备注:<span" <<
"style = 'mso-spacerun:yes'></span> DSQ:犯规<span style = 'mso-spacerun:yes'>" <<
"</span> DNS:弃权</td><td></td><td></td></tr>";
fout << "<tr height = 19 valign = middle style = 'height:14.25pt'>" <<
"<td height = 19 style = 'height:14.25pt'></td>" <<
"<td class = xl71 colspan = 4 style = 'mso-ignore:colspan'>" <<
"室温 : " << thisCom->getTempeture() << "℃<span style = 'mso-spacerun:yes'></span> 水温 : " << thisCom->getWaterTempeture() << "℃</td>" <<
"<td></td></tr>";
fout << thisCom->getTail();
fout.close();
}
void ControlWindow::outPutTeamScore(void)
{
std::ofstream fout(std::string("Result/") + thisCom->getCompName() + std::string("总积分.txt"));
std::sort(scores.begin(), scores.end());
std::reverse(scores.begin(), scores.end());
int thisScore(0), thisRank(1);
for (int i(0), j(scores.size()); i < j; ++i)
{
if (i != 0)
{
thisRank = (scores[i].score == scores[i - 1].score) ? thisRank : i + 1;
}
fout << thisRank << '\t' << teamNames[scores[i].team] << '\t' << scores[i].score << std::endl;
}
fout.close();
} |
b93a9971172e2cc040d0a765180835cc45b918ff | 254f91a2567d485954ea9089cd0e915a9f71edda | /Stack/Overlapping Intervals.cpp | fabd93a0d5a0c17de2c44658fcb3de61cef9f706 | [] | no_license | Aleena-Mishra-10/Data-Structure | dfd1b5058f8db6b7675d6593072fd4de5f980371 | 58a5c84186011c6487768f4f38e1cf4e688875f1 | refs/heads/master | 2023-04-25T16:59:10.252996 | 2021-05-24T18:04:11 | 2021-05-24T18:04:11 | 280,817,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | cpp | Overlapping Intervals.cpp | bool compare(pair<int,int>a,pair<int,int>b){
return a.first<b.first;
}
vector<pair<int,int>> overlappedInterval(vector<pair<int,int>> v, int n) {
int i;
sort(v.begin(),v.end(),compare);
for(i=1;i<v.size();i++){
if(v[i].first<=v[i-1].second&&v[i-1].first!=-1){
v[i].first=v[i-1].first;
v[i].second=max(v[i].second,v[i-1].second);
v[i-1].first=-1;
i--;
}
}
vector<pair<int,int>> res;
for(i=0;i<v.size();i++){
if(v[i].first!=-1){
//res[i]=make_pair(v[i].first,v[i].second);
res.push_back(v[i]);
}
}
return res;
}
|
6ff9852f501ac841f9bfaa16476257743530636b | 09824dbcc644fb45b1e6de06f3c75d3e95bfad91 | /Chapter06/main_book.cpp | a7600495eb4bc63bb148a20e5972796425a2a827 | [] | no_license | ScienceBoy/Guide-to-scientific-computing-C- | 8de0dd4b0ff78444fb5d4cb3ca0c63c8e2f4e9f6 | 390fe22c4489d32426d44457cedb1ce629e27118 | refs/heads/main | 2023-05-12T06:02:33.075702 | 2021-06-08T12:52:03 | 2021-06-08T12:52:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | main_book.cpp | #include <iostream>
#include "Book.hpp"
int main(int argc, char* argv[])
{
Book my_favourite_book;
my_favourite_book.author = "Lewis Carroll";
my_favourite_book.title =
"Alice's adventures in Wonderland";
my_favourite_book.publisher = "Macmillan";
my_favourite_book.price = 199;
my_favourite_book.format = "hardback";
my_favourite_book.yearOfPublication = 1865;
std::cout << "Year of publication of "
<< my_favourite_book.title << " is "
<< my_favourite_book.yearOfPublication << "\n";
}
//Code from Chapter06.tex line 151 save as main_book.cpp
|
82bcfc3229b0d8df48258d549550bb03125bc42b | a8dead89e139e09733d559175293a5d3b2aef56c | /src/addons/K2/Fx/SineForceController.cpp | afa50713e1ba075df56370dda92b2059937e8304 | [
"MIT"
] | permissive | riyanhax/Demi3D | 4f3a48e6d76462a998b1b08935b37d8019815474 | 73e684168bd39b894f448779d41fab600ba9b150 | refs/heads/master | 2021-12-04T06:24:26.642316 | 2015-01-29T22:06:00 | 2015-01-29T22:06:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,067 | cpp | SineForceController.cpp |
/**********************************************************************
This source file is a part of Demi3D
__ ___ __ __ __
| \|_ |\/|| _)| \
|__/|__| || __)|__/
Copyright (c) 2013-2014 Demi team
https://github.com/wangyanxing/Demi3D
Released under the MIT License
https://github.com/wangyanxing/Demi3D/blob/master/License.txt
***********************************************************************/
/****************************************************
This module was originally from Particle Universe
Repo: https://github.com/scrawl/particleuniverse
License: MIT
****************************************************/
#include "K2Pch.h"
#include "SineForceController.h"
#include "ParticleElement.h"
namespace Demi
{
const float DiSineForceController::DEFAULT_FREQ_MIN = 1.0f;
const float DiSineForceController::DEFAULT_FREQ_MAX = 1.0f;
DiSineForceController::DiSineForceController(void) :
DiBaseForceController(),
mAngle(361),
mFrequencyMin(DEFAULT_FREQ_MIN),
mFrequencyMax(DEFAULT_FREQ_MAX),
mFrequency(1.0f)
{
}
void DiSineForceController::CopyTo (DiParticleController* affector)
{
DiBaseForceController::CopyTo(affector);
DiSineForceController* sineForceAffector = static_cast<DiSineForceController*>(affector);
sineForceAffector->mFrequencyMin = mFrequencyMin;
sineForceAffector->mFrequencyMax = mFrequencyMax;
sineForceAffector->mFrequency = mFrequency;
sineForceAffector->mAngle = mAngle;
}
void DiSineForceController::PreProcessParticles(DiParticleElement* particleTechnique, float timeElapsed)
{
mAngle += mFrequency * timeElapsed;
float sineValue = DiMath::Sin(DiRadian(mAngle));
mScaledVector = mForceVector * timeElapsed * sineValue;
if (mAngle > DiMath::TWO_PI)
{
mAngle = 0.0f;
if (mFrequencyMin != mFrequencyMax)
{
mFrequency = DiMath::RangeRandom(mFrequencyMin, mFrequencyMax);
}
}
}
float DiSineForceController::GetFrequencyMin(void) const
{
return mFrequencyMin;
}
void DiSineForceController::SetFrequencyMin(const float frequencyMin)
{
mFrequencyMin = frequencyMin;
if (frequencyMin > mFrequencyMax)
{
mFrequency = frequencyMin;
}
}
float DiSineForceController::GetFrequencyMax(void) const
{
return mFrequencyMax;
}
void DiSineForceController::SetFrequencyMax(const float frequencyMax)
{
mFrequencyMax = frequencyMax;
mFrequency = frequencyMax;
}
void DiSineForceController::Control(DiParticleElement* particleTechnique, DiParticle* particle, float timeElapsed)
{
if (mForceApplication == FA_ADD)
{
particle->direction += mScaledVector;
}
else
{
particle->direction = (particle->direction + mForceVector) / 2;
}
}
}
|
9c9831de231855d6f1b29cccff9355dfa116cb1c | 53487542f1d068b817b877d6b8f672c82e2bab96 | /network_helper/http_helper.h | ca5ebebd69dcdc4134cae3fca74857396fd069f3 | [] | no_license | z-h-s/NetworkThirdParty | e071c6b8e1fd6a9df9ffc403e77d11798ca38aaf | 0169cb63756801d84c07ee91dd3614ef01700d88 | refs/heads/master | 2023-03-19T18:13:51.584510 | 2021-03-11T09:00:24 | 2021-03-11T09:00:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,420 | h | http_helper.h | #ifndef HTTP_HELPER_H
#define HTTP_HELPER_H
#include <string>
#include"timer_queue.h"
#include "c_log.h"
#include <map>
namespace micagent {
using namespace std;
enum HTTP_PACKET_TYPE{
HTTP_POST_REQUEST,//for post request
HTTP_GET_REQUEST,//for get request
HTTP_RESPONSE,//for response
HTTP_UNKNOWN,//default status,you can't call build_packet
};
class http_helper;
using HTTP_PACKET_RECV_CALLBACK=function<void (pair<shared_ptr<uint8_t>,uint32_t>)>;
class http_helper{
friend class http_client;
static constexpr uint32_t HTTP_INVALID_BODY_LEN=0xffffffff;
static constexpr uint32_t HTTP_MAX_HEADR_LEN=1024*32;//32k
static constexpr const char *const HTTP_POST_STRING="POST";
static constexpr const char *const HTTP_GET_STRING="GET";
static constexpr const char *const HTTP_VERSION="HTTP/1.1";
static constexpr const char *const CONTENT_KEY="Content-Type";
static constexpr const char *const DEFAULT_CONTENT_TYPE="application/json";
static constexpr const char *const UNKNOWN_CONTENT_TYPE="application/octet-stream";
static const char *const CONTENT_LENGTH_KEY;
static constexpr const char *const HEAD_END="\r\n\r\n";
static constexpr const int HEAD_END_LEN=4;
static constexpr const char * const LINE_END="\r\n";
static constexpr const int LINE_END_LEN=2;
static constexpr const int KEY_MAX_LEN=128;
static constexpr const int VALUE_MAX_LEN=1024;
public:
http_helper();
/**
* @brief http_helper build a class from the existing class
* @param instance
*/
http_helper(const http_helper &instance);
/**
* @brief update update the http cache with a data stream
* @param buf
* @param buf_len
* @return last incomplete packet's missing len
*/
uint32_t update(const void *buf,uint32_t buf_len);
/**
* @brief set_head set the http_header's key:value
* @param key
* @param value
*/
void set_head(const string &key,const string &value);
/**
* @brief set_api config the api
* @param api
*/
void set_api(const string&api);
/**
* @brief set_packet_type set the work mode
* @param type
*/
void set_packet_type(HTTP_PACKET_TYPE type);
/**
* @brief set_get_param set the GET request's param
* @param param
*/
void set_get_param(const string ¶m);
/**
* @brief set_response_status set the http response's status
* @param status_code http status
* @param status_string http status string
*/
void set_response_status(const string &status_code,const string &status_string);
/**
* @brief set_body set the payload when it works as a http response or a post request
* @param buf
* @param buf_len
* @param content_type the standard http content type string
*/
void set_body(const void *buf,uint32_t buf_len,const string&content_type=DEFAULT_CONTENT_TYPE);
/**
* @brief get_head_info get the specific key's value string
* @param key
* @return if key is not existed,it will return an empty string
*/
string get_head_info(const string &key)const;
/**
* @brief get_api get the api of http connection
* @return
*/
string get_api()const;
/**
* @brief get_packet_type get the work mode
* @return
*/
HTTP_PACKET_TYPE get_packet_type()const;
/**
* @brief get_get_param get the get request's param
* @return
*/
string get_get_param()const;
/**
* @brief get_response_status get http response's status
* @return
*/
pair<string,string>get_response_status()const;
/**
* @brief get_body get the http payload
* @param wait_time_ms set it to nozero and block to get the payload
* @return
*/
pair<shared_ptr<uint8_t>,uint32_t> get_body(int64_t wait_time_ms=0)const;
/**
* @brief build_packet build a http packet with the content tha contains
* @param reset if it's true,the function will reset all header info
* @return
*/
string build_packet(bool reset=true);
~http_helper();
/**
* @brief get_next_line get a new line start pos
* @param input
* @return
*/
static const char * get_next_line(const char *input);
/**
* @brief get_next_line get a new line start pos
* @param input
* @return
*/
static const uint8_t * get_next_line(const uint8_t *input);
/**
* @brief util_test test the member function
*/
static void util_test();
/**
* @brief set_packet_finished_callback set the callback which will be call when you update the class status with the "update" function's calling and a finished http packet occurs
* @param callback
*/
void set_packet_finished_callback(const HTTP_PACKET_RECV_CALLBACK &callback){
lock_guard<mutex>locker(m_mutex);
m_http_packet_recv_callback=callback;
}
protected:
/**
* @brief load_default_set derived classes can do a default action'config in this function
*/
virtual void load_default_set();
private:
/**
* @brief reset_header_info reset the header part to default status
*/
void reset_header_info();
/**
* @brief parse_first_len parse http packet's first line
*/
void parse_first_len();
/**
* @brief build_http_response build a http response packet
* @return
*/
string build_http_response();
/**
* @brief build_http_get_request build a http get requset packet
* @return
*/
string build_http_get_request();
/**
* @brief build_http_post_request build a http post requset packet
* @return
*/
string build_http_post_request();
private:
mutable mutex m_mutex;
/**
* @brief m_con sync the body's blocking acquirement
*/
mutable condition_variable m_con;
/**
* @brief m_head_map a map that saves all key:value pair
*/
map<string,string>m_head_map;
/**
* @brief m_packet_type workr mode
*/
HTTP_PACKET_TYPE m_packet_type;
/**
* @brief m_status_code http response status code
*/
string m_status_code;
/**
* @brief m_status_string http response status string
*/
string m_status_string;
/**
* @brief m_http_version http protocal's version
*/
string m_http_version;
/**
* @brief m_request_method "GET" , "PORT",etc.
*/
string m_request_method;
/**
* @brief m_get_param GET request's param
*/
string m_get_param;
/**
* @brief m_api the remote resource url you want to access
*/
string m_api;
/**
* @brief m_body_len http body's len
*/
uint32_t m_body_len;
/**
* @brief m_body_filled_len when it work as a http packet receiver,this object may be not equal with m_body_len
*/
uint32_t m_body_filled_len;
/**
* @brief m_body save the http body
*/
shared_ptr<uint8_t>m_body;
/**
* @brief m_buf_cache_len m_buf_cache's length
*/
uint32_t m_buf_cache_len;
/**
* @brief m_buf_cache a cache which cache the outstanding data
*/
shared_ptr<uint8_t>m_buf_cache;
/**
* @brief m_http_packet_recv_callback when a http packet is finished,this function will be called
*/
HTTP_PACKET_RECV_CALLBACK m_http_packet_recv_callback;
};
}
#endif // HTTP_HELPER_H
|
615d570eeba86c0e20c9f6ed0fadfe9cfa1d2aa4 | 9d23a4abfad737b1194bc80328653ecae9cbd847 | /Motor2D/JungleCampManager.cpp | dd547b2c80e5da8fe55bf11d6ba83c421ee7272a | [] | no_license | bubleegames/Project2_Zelda | 8cb900144ce22e3e58c3269fe31ec62f1a3ed468 | 0ea5121e0a123db710fb2d7605c3c38ab592ca73 | refs/heads/master | 2020-04-29T12:01:10.692097 | 2017-06-12T09:18:23 | 2017-06-12T09:18:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,622 | cpp | JungleCampManager.cpp | #include "JungleCampManager.h"
#include "j1App.h"
#include "j1Map.h"
#include "j1Entity.h"
#include "j1Timer.h"
#include "Snakes.h"
#include "Skeleton.h"
#include "MageSkeleton.h"
#include "Guards.h"
#include "p2Log.h"
#include "j1Audio.h"
#define SNAKE_RESPAWN_TIME 60
#define SKELETON_RESPAWN_TIME 100
#define MAGESKELETON_RESPAWN_TIME 60
#define GUARD_RESPAWN_TIME 80
#define HALFMAP 81*32
JungleCampManager::JungleCampManager()
{
}
JungleCampManager::~JungleCampManager()
{
}
bool JungleCampManager::Start()
{
bool ret = true;
// Stopping timers
snakes_timer_camp1 = App->AddGameplayTimer(); snakes_timer_camp1->Stop();
snakes_timer_camp2 = App->AddGameplayTimer(); snakes_timer_camp2->Stop();
skeleton_timer_camp1 = App->AddGameplayTimer(); skeleton_timer_camp1->Stop();
skeleton_timer_camp2 = App->AddGameplayTimer(); skeleton_timer_camp2->Stop();
mageskeleton_timer_camp1 = App->AddGameplayTimer(); mageskeleton_timer_camp1->Stop();
mageskeleton_timer_camp2 = App->AddGameplayTimer(); mageskeleton_timer_camp2->Stop();
guards_timer_camp1.Stop();
guards_timer_camp2.Stop();
// Spawning jungle camps
SpawnSkeleton(0);
SpawnSnake(0);
SpawnMageSkeleton(0);
SpawnGuard(0);
death_sound_effect = App->audio->LoadFx("Audio/FX/Entities/Enemies/LTTP_Enemy_Kill.wav");
return ret;
}
bool JungleCampManager::Update(float dt)
{
bool ret = true;
if (snakes_camp1.empty() && !snakes_timer_camp1->IsActive())
{
snakes_timer_camp1->Start();
}
if (snakes_camp2.empty() && !snakes_timer_camp2->IsActive())
{
snakes_timer_camp2->Start();
}
if (snakes_timer_camp1->ReadSec() > SNAKE_RESPAWN_TIME)
{
SpawnSnake(1);
snakes_timer_camp1->Stop();
}
if (snakes_timer_camp2->ReadSec() > SNAKE_RESPAWN_TIME)
{
SpawnSnake(2);
snakes_timer_camp2->Stop();
}
if (skeleton_camp1 == nullptr && !skeleton_timer_camp1->IsActive())
{
skeleton_timer_camp1->Start();
}
if (skeleton_camp2 == nullptr && !skeleton_timer_camp2->IsActive())
{
skeleton_timer_camp2->Start();
}
if (skeleton_timer_camp1->ReadSec() > SKELETON_RESPAWN_TIME)
{
SpawnSkeleton(1);
skeleton_timer_camp1->Stop();
}
if (skeleton_timer_camp2->ReadSec() > SKELETON_RESPAWN_TIME)
{
SpawnSkeleton(2);
skeleton_timer_camp2->Stop();
}
if (mageskeleton_camp1.empty() && !mageskeleton_timer_camp1->IsActive())
{
mageskeleton_timer_camp1->Start();
}
if (mageskeleton_camp2.empty() && !mageskeleton_timer_camp2->IsActive())
{
mageskeleton_timer_camp2->Start();
}
if (mageskeleton_timer_camp1->ReadSec() > MAGESKELETON_RESPAWN_TIME)
{
SpawnMageSkeleton(1);
mageskeleton_timer_camp1->Stop();
}
if (mageskeleton_timer_camp2->ReadSec() > MAGESKELETON_RESPAWN_TIME)
{
SpawnMageSkeleton(2);
mageskeleton_timer_camp2->Stop();
}
if (guards_camp1.empty() && !guards_timer_camp1.IsActive())
{
guards_timer_camp1.Start();
}
if (guards_camp2.empty() && !guards_timer_camp2.IsActive())
{
guards_timer_camp2.Start();
}
if (guards_timer_camp1.ReadSec() > GUARD_RESPAWN_TIME)
{
SpawnGuard(1);
guards_timer_camp1.Stop();
}
if (guards_timer_camp2.ReadSec() > GUARD_RESPAWN_TIME)
{
SpawnGuard(2);
guards_timer_camp2.Stop();
}
return ret;
}
bool JungleCampManager::CleanUp()
{
LOG("Unloading JungleCampManager");
// Cleaning snakes
for (int i = 0; i < snakes_camp1.size(); i++)
{
App->entity->DeleteEntity(snakes_camp1[i]);
}
snakes_camp1.clear();
for (int i = 0; i < snakes_camp2.size(); i++)
{
App->entity->DeleteEntity(snakes_camp2[i]);
}
snakes_camp2.clear();
// ------
// Cleaning skeletons
if(skeleton_camp1 != nullptr)
{
App->entity->DeleteEntity(skeleton_camp1);
}
if(skeleton_camp2 != nullptr)
{
App->entity->DeleteEntity(skeleton_camp2);
}
// ------
// Cleaning megaeskeletons
for (int i = 0; i < mageskeleton_camp1.size(); i++)
{
App->entity->DeleteEntity(mageskeleton_camp1[i]);
}
mageskeleton_camp1.clear();
for (int i = 0; i<mageskeleton_camp2.size(); i++)
{
App->entity->DeleteEntity(mageskeleton_camp2[i]);
}
mageskeleton_camp2.clear();
// ------
//Cleaning guards
for (int i = 0; i < guards_camp1.size(); i++)
{
App->entity->DeleteEntity(guards_camp1[i]);
}
guards_camp1.clear();
for (int i = 0; i < guards_camp2.size(); i++)
{
App->entity->DeleteEntity(guards_camp2[i]);
}
guards_camp2.clear();
// ------
// Clean timers
App->DeleteGameplayTimer(snakes_timer_camp1);
App->DeleteGameplayTimer(snakes_timer_camp2);
App->DeleteGameplayTimer(skeleton_timer_camp1);
App->DeleteGameplayTimer(skeleton_timer_camp2);
App->DeleteGameplayTimer(mageskeleton_timer_camp1);
App->DeleteGameplayTimer(mageskeleton_timer_camp2);
return true;
}
void JungleCampManager::SpawnSnake(uint camp)
{
switch (camp)
{
case 0:
{
std::vector<iPoint> snake_positions = App->map->GetSnakesSpawns();
Snakes* s1 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[0]);
Snakes* s2 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[1]);
snakes_camp1.push_back(s1);
snakes_camp1.push_back(s2);
Snakes* s3 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[2]);
Snakes* s4 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[3]);
snakes_camp2.push_back(s3);
snakes_camp2.push_back(s4);
break;
}
case 1:
{
std::vector<iPoint> snake_positions = App->map->GetSnakesSpawns();
Snakes* s1 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[0]);
Snakes* s2 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[1]);
snakes_camp1.push_back(s1);
snakes_camp1.push_back(s2);
break;
}
case 2:
{
std::vector<iPoint> snake_positions = App->map->GetSnakesSpawns();
Snakes* s3 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[2]);
Snakes* s4 = (Snakes*)App->entity->CreateEntity(snake, snake_positions[3]);
snakes_camp2.push_back(s3);
snakes_camp2.push_back(s4);
break;
}
default:
break;
}
}
void JungleCampManager::SpawnMageSkeleton(uint camp)
{
switch (camp)
{
case 0:
{
std::vector<iPoint> mskeleton_positions = App->map->GetMageSkeletonSpawns();
MageSkeleton* s1 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[0]);
MageSkeleton* s2 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[1]);
MageSkeleton* s3 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[2]);
MageSkeleton* s4 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[3]);
mageskeleton_camp1.push_back(s1);
mageskeleton_camp1.push_back(s2);
mageskeleton_camp1.push_back(s3);
mageskeleton_camp1.push_back(s4);
MageSkeleton* s5 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[4]);
MageSkeleton* s6 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[5]);
MageSkeleton* s7 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[6]);
MageSkeleton* s8 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[7]);
mageskeleton_camp2.push_back(s5);
mageskeleton_camp2.push_back(s6);
mageskeleton_camp2.push_back(s7);
mageskeleton_camp2.push_back(s8);
break;
}
case 1:
{
std::vector<iPoint> mskeleton_positions = App->map->GetMageSkeletonSpawns();
MageSkeleton* s1 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[0]);
MageSkeleton* s2 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[1]);
MageSkeleton* s3 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[2]);
MageSkeleton* s4 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[3]);
mageskeleton_camp1.push_back(s1);
mageskeleton_camp1.push_back(s2);
mageskeleton_camp1.push_back(s3);
mageskeleton_camp1.push_back(s4);
break;
}
break;
case 2:
{
std::vector<iPoint> mskeleton_positions = App->map->GetMageSkeletonSpawns();
MageSkeleton* s5 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[4]);
MageSkeleton* s6 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[5]);
MageSkeleton* s7 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[6]);
MageSkeleton* s8 = (MageSkeleton*)App->entity->CreateEntity(mskeleton, mskeleton_positions[7]);
mageskeleton_camp2.push_back(s5);
mageskeleton_camp2.push_back(s6);
mageskeleton_camp2.push_back(s7);
mageskeleton_camp2.push_back(s8);
break;
}
default:
break;
}
}
void JungleCampManager::SpawnGuard(uint camp)
{
switch (camp)
{
case 0:
{
std::vector<iPoint> guard_positions = App->map->GetGuardsSpawns();
Guards* g1 = (Guards*)App->entity->CreateEntity(guards, guard_positions[0]);
Guards* g2 = (Guards*)App->entity->CreateEntity(guards, guard_positions[1]);
Guards* g3 = (Guards*)App->entity->CreateEntity(guards, guard_positions[2]);
guards_camp1.push_back(g1);
guards_camp1.push_back(g2);
guards_camp1.push_back(g3);
Guards* g4 = (Guards*)App->entity->CreateEntity(guards, guard_positions[3]);
Guards* g5 = (Guards*)App->entity->CreateEntity(guards, guard_positions[4]);
Guards* g6 = (Guards*)App->entity->CreateEntity(guards, guard_positions[5]);
guards_camp2.push_back(g4);
guards_camp2.push_back(g5);
guards_camp2.push_back(g6);
break;
}
case 1:
{
std::vector<iPoint> guard_positions = App->map->GetGuardsSpawns();
Guards* g1 = (Guards*)App->entity->CreateEntity(guards, guard_positions[0]);
Guards* g2 = (Guards*)App->entity->CreateEntity(guards, guard_positions[1]);
Guards* g3 = (Guards*)App->entity->CreateEntity(guards, guard_positions[2]);
guards_camp1.push_back(g1);
guards_camp1.push_back(g2);
guards_camp1.push_back(g3);
break;
}
case 2:
{
std::vector<iPoint> guard_positions = App->map->GetGuardsSpawns();
Guards* g4 = (Guards*)App->entity->CreateEntity(guards, guard_positions[3]);
Guards* g5 = (Guards*)App->entity->CreateEntity(guards, guard_positions[4]);
Guards* g6 = (Guards*)App->entity->CreateEntity(guards, guard_positions[5]);
guards_camp2.push_back(g4);
guards_camp2.push_back(g5);
guards_camp2.push_back(g6);
break;
}
default:
break;
}
}
void JungleCampManager::SpawnSkeleton(uint camp)
{
switch (camp)
{
case 0:
{
std::vector<iPoint> skeleton_positions = App->map->GetSkeletonSpawns();
skeleton_camp1 = (Skeleton*)App->entity->CreateEntity(skeleton, skeleton_positions[0]);
skeleton_camp2 = (Skeleton*)App->entity->CreateEntity(skeleton, skeleton_positions[1]);
break;
}
case 1:
{
std::vector<iPoint> skeleton_positions = App->map->GetSkeletonSpawns();
skeleton_camp1 = (Skeleton*)App->entity->CreateEntity(skeleton, skeleton_positions[0]);
break;
}
case 2:
{
std::vector<iPoint> skeleton_positions = App->map->GetSkeletonSpawns();
skeleton_camp2 = (Skeleton*)App->entity->CreateEntity(skeleton, skeleton_positions[1]);
break;
}
default:
break;
}
}
void JungleCampManager::KillJungleCamp(Entity * camp)
{
switch (camp->type)
{
case snake:
{
if (camp->GetPos().x > HALFMAP)
{
for (std::vector<Entity*>::iterator it = snakes_camp1.begin(); it != snakes_camp1.end(); it++)
{
if (camp == *it)
{
snakes_camp1.erase(it);
break;
}
}
}
else
{
for (std::vector<Entity*>::iterator it = snakes_camp2.begin(); it != snakes_camp2.end(); it++)
{
if (camp == *it)
{
snakes_camp2.erase(it);
break;
}
}
}
break;
}
case skeleton:
{
if (camp->GetPos().x < HALFMAP)
{
skeleton_camp1 = nullptr;
}
else
{
skeleton_camp2 = nullptr;
}
break;
}
case mskeleton:
{
if (camp->GetPos().x < HALFMAP)
{
for (std::vector<Entity*>::iterator it = mageskeleton_camp1.begin(); it != mageskeleton_camp1.end(); it++)
{
if (camp == *it)
{
mageskeleton_camp1.erase(it);
break;
}
}
}
else
{
for (std::vector<Entity*>::iterator it = mageskeleton_camp2.begin(); it != mageskeleton_camp2.end(); it++)
{
if (camp == *it) {
mageskeleton_camp2.erase(it);
break;
}
}
}
break;
}
case guards:
{
if (camp->GetPos().x > HALFMAP)
{
for (std::vector<Entity*>::iterator it = guards_camp1.begin(); it != guards_camp1.end(); it++)
{
if (camp == *it)
{
guards_camp1.erase(it);
break;
}
}
}
else
{
for (std::vector<Entity*>::iterator it = guards_camp2.begin(); it != guards_camp2.end(); it++)
{
if (camp == *it)
{
guards_camp2.erase(it);
break;
}
}
}
break;
}
}
App->entity->DeleteEntity(camp);
//App->audio->PlayFx(death_sound_effect, 0);
}
|
04af7e01666dc27c8dc6dd6dff694264a5b25a37 | 5c2addf99fb73b7a95897eb0486e28e9929fdd08 | /이분매칭/상어의저녁식사 1671.cpp | 0afb16695c3b72895fd713a393b242e01ccff326 | [] | no_license | UmJaeJeong/Algorithm-DataStruct | 902bc7b86dc4b74b8334984a78c0159bd2bc3e5d | 51cdd53a7cf815eb20801215d8147fb537d67e59 | refs/heads/master | 2020-04-03T15:28:36.084262 | 2019-02-15T01:14:08 | 2019-02-15T01:14:08 | 155,363,765 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,084 | cpp | 상어의저녁식사 1671.cpp | #include<iostream>
#include<vector>
using namespace std;
//최대2마리
#define MAX 51
vector<int> a[MAX];
int d[MAX];
bool c[MAX];
int n;
int s[MAX], v[MAX], k[MAX];//지능, 속도, 크기를 비교
bool dfs(int x) {
for (int i= 0; i < a[x].size(); i++) {
int y = a[x][i];
if (c[y])continue;
c[y] = true;
if (d[y] == 0 || dfs(d[y])) {
d[y] = x;
return true;
}
}
return false;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> s[i] >> v[i] >> k[i];
}
//조건을 비롯한 간선 연결
for (int i = 1; i <= n-1; i++) {
for (int j = i+1; j <= n; j++) {
if (s[i] == s[j] && v[i] == v[j] && k[i] == k[j]) {
a[i].push_back(j);
}else
if (s[i] >= s[j] && v[i] >= v[j] && k[i] >= k[j]) {
a[i].push_back(j);
}
else if (s[i] <= s[j] && v[i] <= v[j] && k[i] <= k[j]) {
a[j].push_back(i);
}
}
}
//최대 2마리를 먹을 수있음
int cnt = 0;
for (int k = 1; k <= 2; k++) {
for (int i = 1; i <= n; i++) {
fill(c, c + MAX, false);
if (dfs(i)) cnt++;
}
}
cout << n-cnt << endl;
return 0;
} |
768c759245ed9c1790a4b217590d90bc8f73c4b7 | f26ef5026614c9a1a53c1ddc09794ba1b1971947 | /XML-Parse-Library/XML_CDATA.hpp | b97ce383474fdd517b16634b1bcb24bfe8e1465a | [
"Apache-2.0"
] | permissive | PiotrGardocki/XML-Parse-Library | 651d77c52383714f9bd196c71b9c9796c847a04c | 2ae94ba3275b30bc1c8909c7013c568655215cfc | refs/heads/master | 2020-03-31T02:38:03.289550 | 2019-01-16T18:33:54 | 2019-01-16T18:33:54 | 151,833,326 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | hpp | XML_CDATA.hpp | #ifndef XML_CDATA_HPP_
#define XML_CDATA_HPP_
#include <string>
#include "XML_BaseElement.hpp"
class XML_CDATA : public XML_BaseElement
{
public:
XML_CDATA() = default;
explicit XML_CDATA(const std::string & value);
virtual XML_ElementType getElementType() const override;
virtual void setValue(const std::string & value) override;
virtual std::string getValueInOneLine() const override;
virtual std::list<std::string> getValueInLines() const override;
virtual std::string getElementWithValueInOneLine() const override;
virtual std::list<std::string> getElementWithValueInLines() const override;
protected:
virtual std::string getClassName() const override;
virtual std::unique_ptr<XML_BaseElement> makeCopy() const override;
virtual std::unique_ptr<XML_BaseElement> makeMovedCopy() override;
private:
std::string mValue;
};
#endif // XML_CDATA_HPP_ |
aaab06940095f804c3e03211cf9029e65cdd1b48 | 76748c80f9fe11ac9dc7e0b287c4ea28c98c7e55 | /inputs02.h | 72a7ea73b3c49b9f8c0239ce5ffa4bb59328db85 | [
"Apache-2.0"
] | permissive | andrewPetti/AdventOfCode-2019 | 3ac157fd761cf8a4f348b22f02e0e035ee060d36 | 6726be899ed9535e6345b7a762fd25c7b595af85 | refs/heads/master | 2020-09-22T08:38:25.218000 | 2019-12-19T00:05:17 | 2019-12-19T00:05:17 | 225,123,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | h | inputs02.h | #pragma once
#include <vector>
namespace inputs
{
std::vector<int> GetInputs02()
{
std::vector<int> input{
1, 0, 0, 3, 1, 1, 2, 3, 1, 3, 4, 3, 1, 5, 0, 3, 2, 13, 1, 19, 1, 19, 9, 23, 1, 5, 23, 27, 1, 27, 9, 31, 1, 6, 31, 35, 2, 35, 9, 39, 1, 39, 6, 43, 2, 9, 43, 47, 1, 47, 6, 51, 2, 51, 9, 55, 1, 5, 55, 59, 2, 59, 6, 63, 1, 9, 63, 67, 1, 67, 10, 71, 1, 71, 13, 75, 2, 13, 75, 79, 1, 6, 79, 83, 2, 9, 83, 87, 1, 87, 6, 91, 2, 10, 91, 95, 2, 13, 95, 99, 1, 9, 99, 103, 1, 5, 103, 107, 2, 9, 107, 111, 1, 111, 5, 115, 1, 115, 5, 119, 1, 10, 119, 123, 1, 13, 123, 127, 1, 2, 127, 131, 1, 131, 13, 0, 99, 2, 14, 0, 0};
return input;
}
} // namespace inputs |
6cc2e4bc18794806bb47070b1cd91870b35e2e2a | f4b1d1c3707e008254101c80f5b43ff61f6810b6 | /1_CppGrundlagen/own/Chars.cpp | 946d2cd010562f3ffb50de796986c8f270a859a8 | [
"MIT"
] | permissive | stefan-ewald/e_fork_UdemyCpp | 94e0841c4d8a64f973e63113220bef9fb5e2a78f | f880b566774882a1722e2c76c5ce3bdbd33b35d0 | refs/heads/master | 2023-07-24T09:39:57.463769 | 2021-08-28T15:02:29 | 2021-08-28T15:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | cpp | Chars.cpp | #include <iostream>
int main()
{
char myCharacter = 'A';
char offset = 2;
std::cout << myCharacter + offset << std::endl;
return 0;
}
|
b2e4a46898eb29bcc5a8d8f429f6b93a2e090874 | 06c58b02c8411a416a881759ee4ba6de67299241 | /SNNS/start.cpp | 19673739cb86b4892686803921f7881ed233515f | [] | no_license | siarheikapkovich/SNNS | e3f798a2e726020d28df817e59633a6e213a8acd | eca40965e931c353c279231dc0de0c24ffb13aea | refs/heads/master | 2022-04-18T00:45:22.659399 | 2020-04-19T14:56:35 | 2020-04-19T14:56:35 | 257,025,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,099 | cpp | start.cpp | #include "global.h"
LRESULT CALLBACK WndFunction(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
INT RetVal = 0;
static INT DragNum = -1;
static INT CyrObj = -1;
static INT DesObj = -1;
POINT pt;
NEURON_VIEW nv;
switch(message)
{
case WM_COMMAND:
switch(wParam)
{
case IDM_NEW:
RetVal = (INT)DialogBox(g_hInst, MAKEINTRESOURCE(IDD_CREATE_NEW), g_hWnd, NewDlgFunction);
if(RetVal)
{
PrepContext();
}
break;
case IDM_EXIT:
DestroyWindow(hwnd);
break;
case IDM_ADD_NEURON:
RetVal = (INT)DialogBox(g_hInst, MAKEINTRESOURCE(IDD_ADD_NEURON), g_hWnd, DlgAddNeuron);
if(RetVal == 1)
{
g_NCount++;
nv.m_Number = g_NCount;
nv.m_Type = NEURON;
nv.m_Pos.x = 10 + MAP_STEP;
nv.m_Pos.y = 10 + MAP_STEP;
if(NeuView.size() != 0)
{
vector<NEURON_VIEW>::iterator p = NeuView.begin();
while(p->m_Type != NEURON && p->m_Number != g_NCount - 1)
{
if(p == NeuView.end())
break;
p++;
}
p++;
if(p <= NeuView.end())
{
NeuView.insert(p, nv);
}
else
NeuView.push_back(nv);
}
else
NeuView.push_back(nv);
}
SendMessage(g_hWnd, WM_PAINT, 0, 0);
break;
case IDM_ADD_INPUT:
g_ICount++;
nv.m_Number = g_ICount;
nv.m_Type = INPUT;
nv.m_Pos.x = 10 + MAP_STEP;
nv.m_Pos.y = 10 + MAP_STEP;
if(NeuView.size() != 0)
{
vector<NEURON_VIEW>::iterator p = NeuView.begin();
while(p->m_Type != INPUT && p->m_Number != g_ICount - 1)
{
if(p == NeuView.end())
break;
p++;
}
p++;
if(p <= NeuView.end())
{
NeuView.insert(p, nv);
}
else
NeuView.push_back(nv);
}
else
NeuView.push_back(nv);
SendMessage(g_hWnd, WM_PAINT, 0, 0);
break;
case IDM_ADD_OUTPUT:
g_OCount++;
nv.m_Number = g_OCount;
nv.m_Type = OUTPUT;
nv.m_Pos.x = 10 + MAP_STEP;
nv.m_Pos.y = 10 + MAP_STEP;
NeuView.push_back(nv);
SendMessage(g_hWnd, WM_PAINT, 0, 0);
break;
case IDM_ADD_SYNAPS:
RetVal = (INT)DialogBox(g_hInst, MAKEINTRESOURCE(IDD_ADD_SYNAPSE), g_hWnd, DlgAddSynapse);
if(RetVal == 1)
{
MessageBox(g_hWnd, "Ура!!!", "Дебил", MB_OK);
}
break;
case IDM_ADD_COLS:
g_MapWidtch += MAP_STEP;
PrepContext();
SendMessage(g_hWnd, WM_PAINT, 0, 0);
break;
case IDM_ADD_ROWS:
g_MapHeight += MAP_STEP;
PrepContext();
SendMessage(g_hWnd, WM_PAINT, 0, 0);
break;
case P_ADD_NEURON:
SendMessage(g_hWnd, WM_COMMAND, IDM_ADD_NEURON, 0);
break;
case P_ADD_IN:
SendMessage(g_hWnd, WM_COMMAND, IDM_ADD_INPUT, 0);
break;
case P_ADD_OUT:
SendMessage(g_hWnd, WM_COMMAND, IDM_ADD_OUTPUT, 0);
break;
case P_ADD_SYNAPSE:
if(DesObj != -1)
{
//
DesObj = -1;
}
break;
case P_INFO:
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_INFO), g_hWnd, DlgInfo);
if(DesObj != -1)
{
DesObj = -1;
}
break;
}
break;
case WM_PAINT:
HDC hd;
PAINTSTRUCT ps;
RECT Rect;
hd = BeginPaint(hwnd, &ps);
GetClientRect(g_hWnd, &Rect);
PatBlt(hd, 0, 0, Rect.right, Rect.bottom, WHITENESS);
PatBlt(g_hCDC, 0, 0, g_MapWidtch, g_MapHeight, WHITENESS);
DrawBackGround();
if(NeuView.size() > 0)
{
for(UINT i = 0; i < NeuView.size(); i++)
{
switch(NeuView[i].m_Type)
{
case INPUT:
{
DrawInput(NeuView[i].m_Pos, NS_NULL);
if(CyrObj == i)
DrawSelInORect(NeuView[i].m_Pos);
}
break;
case NEURON:
{
DrawNeuron(NeuView[i].m_Pos, NS_NULL);
if(CyrObj == i)
DrawSelNeuRect(NeuView[i].m_Pos);
}
break;
case OUTPUT:
{
DrawOutput(NeuView[i].m_Pos, NS_NULL);
if(CyrObj == i)
DrawSelInORect(NeuView[i].m_Pos);
}
break;
default: break;
}
}
}
BitBlt(g_hDC, 0, 0,g_MapWidtch,g_MapHeight,g_hCDC,g_Rect.left,g_Rect.top,SRCCOPY);
EndPaint(hwnd, &ps);
break;
case WM_CREATE:
break;
case WM_RBUTTONUP:
HMENU hmenu; // menu template
HMENU hmenuTrackPopup; // shortcut menu
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
DesObj = -1;
// Загрузка меню
hmenu = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_MENU1));
hmenuTrackPopup = GetSubMenu(hmenu, 0);
if(NeuView.size() != 0)
{
UINT d2 = 1000;
INT step = -1;
while(d2 > 100)
{
step++;
d2 = (pt.x - NeuView[step].m_Pos.x)*(pt.x - NeuView[step].m_Pos.x) + (pt.y - NeuView[step].m_Pos.y)*(pt.y - NeuView[step].m_Pos.y);
if(step >= (INT)NeuView.size())
{
step = -1;
break;
}
}
if(step != -1)
DesObj = step;
if(NeuView.size() < 2 || DesObj == -1 || CyrObj == -1)
EnableMenuItem(hmenuTrackPopup, P_ADD_SYNAPSE, MF_GRAYED);
}
else
EnableMenuItem(hmenuTrackPopup, P_ADD_SYNAPSE, MF_GRAYED);
if(DesObj != -1)
{
// Запрещаем операции не выполняемые над объектами
EnableMenuItem(hmenuTrackPopup, P_ADD_NEURON, MF_GRAYED);
EnableMenuItem(hmenuTrackPopup, P_ADD_IN, MF_GRAYED);
EnableMenuItem(hmenuTrackPopup, P_ADD_OUT, MF_GRAYED);
}
// Отображаем меню
ClientToScreen(hwnd, (LPPOINT) &pt);
TrackPopupMenu(hmenuTrackPopup, TPM_LEFTALIGN | TPM_LEFTBUTTON, pt.x, pt.y, 0, g_hWnd, NULL);
DestroyMenu(hmenu);
break;
case WM_LBUTTONDOWN:
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
// Проверяем попадание в обьект
if(NeuView.size() != 0)
{
UINT d2;
for(UINT i = 0; i < NeuView.size(); i++)
{
d2 = (pt.x - NeuView[i].m_Pos.x)*(pt.x - NeuView[i].m_Pos.x) + (pt.y - NeuView[i].m_Pos.y)*(pt.y - NeuView[i].m_Pos.y);
if(d2 < 100)
{
// Захват объекта для перетаскивания
DragNum = i;
// Выделение объекта как текущего
CyrObj = i;
}
}
}
break;
case WM_LBUTTONUP:
DragNum = -1;
DesObj = -1;
SendMessage(g_hWnd, WM_PAINT, 0, 0);
break;
case WM_MOUSEMOVE:
// Перетаскивание
if(DragNum != -1)
{
UINT sx, sy;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
sx = (pt.x - 10) % MAP_STEP;
if(sx >= 20)
pt.x += MAP_STEP - sx;
else
pt.x -= sx;
sy = (pt.y - 10) % MAP_STEP;
if(sy >= 20)
pt.y += MAP_STEP - sy;
else
pt.y -= sy;
// Контроль выхода за границы карты
if((UINT)pt.x > g_MapWidtch - 30)
pt.x = g_MapWidtch - 30;
if(pt.x < 30)
pt.x = 30;
if((UINT)pt.y > g_MapHeight - 30)
pt.y = g_MapHeight - 30;
if(pt.y < 30)
pt.y = 30;
NeuView[DragNum].m_Pos.x = pt.x ;
NeuView[DragNum].m_Pos.y = pt.y;
}
break;
case WM_SIZE:
PrepContext();
break;
case WM_DESTROY:
SelectObject(g_hCDC, g_hComBitmap);
DeleteObject(g_hComBitmap);
ReleaseDC(hwnd, g_hCDC);
ReleaseDC(hwnd, g_hDC);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
//RECT Rect;
WNDCLASS wClass;
MSG msg;
g_hInst = hInstance;
wClass.style = CS_HREDRAW|CS_VREDRAW;
wClass.cbClsExtra = NULL;
wClass.cbWndExtra = NULL;
wClass.hInstance = hInstance;
wClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wClass.lpszClassName = "WindowClass";
wClass.lpszMenuName = MAKEINTRESOURCE(IDR_MAIN_MENU);
wClass.lpfnWndProc = WndFunction;
RegisterClass(&wClass);
g_hWnd = CreateWindow("WindowClass", "Нейросимулятор", WS_OVERLAPPEDWINDOW, 0, 0, 200, 200, NULL, LoadMenu(hInstance,MAKEINTRESOURCE(IDR_MAIN_MENU)), hInstance, NULL);
if(!g_hWnd) return 0;
ShowWindow(g_hWnd, SW_MAXIMIZE);
UpdateWindow(g_hWnd);
InitCommonControls();
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
ReleaseDC(g_hWnd, g_hDC);
return (int)msg.lParam;
} |
8cc064244626d266de2c05b3faf9ae8163e67c77 | 72a86345ceb63b187a52632e828c81210919fa78 | /35.search-insert-position.cpp | 1895d28a159c60248242441c1cc994ccde6d67f9 | [] | no_license | stomachacheGE/leetcode | 535a6af727faa7c85ba2453b93fadf34876b75b7 | 579f903d4656e3877a7c75efe0ac9626a7efc44f | refs/heads/master | 2021-03-12T10:00:18.227887 | 2020-03-11T15:39:59 | 2020-03-11T15:39:59 | 246,610,086 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,074 | cpp | 35.search-insert-position.cpp | /*
* @lc app=leetcode id=35 lang=cpp
*
* [35] Search Insert Position
*
* https://leetcode.com/problems/search-insert-position/description/
*
* algorithms
* Easy (40.80%)
* Total Accepted: 396.6K
* Total Submissions: 972.1K
* Testcase Example: '[1,3,5,6]\n5'
*
* Given a sorted array and a target value, return the index if the target is
* found. If not, return the index where it would be if it were inserted in
* order.
*
* You may assume no duplicates in the array.
*
* Example 1:
*
*
* Input: [1,3,5,6], 5
* Output: 2
*
*
* Example 2:
*
*
* Input: [1,3,5,6], 2
* Output: 1
*
*
* Example 3:
*
*
* Input: [1,3,5,6], 7
* Output: 4
*
*
* Example 4:
*
*
* Input: [1,3,5,6], 0
* Output: 0
*
*
*/
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
////////// Solution One/Two //////////
// Binary search
int size = nums.size();
if (size == 0) return 0;
return searchInsert(nums, target, 0, size-1);
////////// Solution Three //////////
// ref.:https://leetcode.com/problems/search-insert-position/discuss/15101/C%2B%2B-O(logn)-Binary-Search-that-handles-duplicate
int low = 0, high = nums.size()-1;
// Invariant: the desired index is between [low, high+1]
while (low <= high) {
int mid = low + (high-low)/2;
if (nums[mid] < target) low = mid+1;
else high = mid-1;
}
// (1) At this point, low > high. That is, low >= high+1
// (2) From the invariant, we know that the index is between [low, high+1], so low <= high+1. Follwing from (1), now we know low == high+1.
// (3) Following from (2), the index is between [low, high+1] = [low, low], which means that low is the desired index
// Therefore, we return low as the answer. You can also return high+1 as the result, since low == high+1
return low;
}
private:
int searchInsert(vector<int>& nums, int target, int left, int right) {
////////// Solution One //////////
// The boudary check is over-complicated, and special attention
// has to be paied to "return searchInsert(nums, target, left, middle)"
// (not middle-1)!!!
// if (left == right) {
// if (nums[left] == target) return left;
// else if (nums[left] > target) return left;
// else return left+1;
// }
// int middle = (left + right) / 2;
// if (nums[middle] == target) return middle;
// else if (nums[middle] > target) return searchInsert(nums, target, left, middle);
// else return searchInsert(nums, target, middle+1, right);
////////// Solution Two //////////
if (left > right) return left;
int middle = (left + right) / 2;
if (nums[middle] == target) return middle;
else if (nums[middle] > target) return searchInsert(nums, target, left, middle-1);
else return searchInsert(nums, target, middle+1, right);
}
};
|
4e995e6f7d2c015f02163e065831c1aadbf8d249 | 116bf4d86f67aa5c18037b18bc1589e38400fa0c | /SDK/ZC_PlayerPawnCharacter_parameters.hpp | 26370833f9375f8d08d47392c7f790af1a6d193e | [] | no_license | hinnie123/ZeroCaliber_SDK | 67de4b0469acf273ca8b52450aa4036256ecdaef | 20786d77bb83366d8faa152aad117e8f90872c43 | refs/heads/master | 2020-04-03T03:41:38.590945 | 2018-11-10T14:32:07 | 2018-11-10T14:32:07 | 154,992,910 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 100,015 | hpp | ZC_PlayerPawnCharacter_parameters.hpp | #pragma once
// ZeroCaliber (0.6.0 EA) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetKills
struct APlayerPawnCharacter_C_GetKills_Params
{
int Kills; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetProjectilesHitHead
struct APlayerPawnCharacter_C_GetProjectilesHitHead_Params
{
int ProjectilesHitHead; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetProjectilesHit
struct APlayerPawnCharacter_C_GetProjectilesHit_Params
{
int ProjectilesHit; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetProjectilesFired
struct APlayerPawnCharacter_C_GetProjectilesFired_Params
{
int ProjectilesFired; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetAllyTeams
struct APlayerPawnCharacter_C_GetAllyTeams_Params
{
TArray<TEnumAsByte<ETeams>> AllyTeams; // (Parm, OutParm, ZeroConstructor)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetTeam
struct APlayerPawnCharacter_C_GetTeam_Params
{
TEnumAsByte<ETeams> Team; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.IsAlive
struct APlayerPawnCharacter_C_IsAlive_Params
{
bool Alive; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetTargetData
struct APlayerPawnCharacter_C_GetTargetData_Params
{
TArray<struct FTargetData> NewParam; // (Parm, OutParm, ZeroConstructor)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetTargetLocation
struct APlayerPawnCharacter_C_GetTargetLocation_Params
{
struct FVector TargetLocation; // (Parm, OutParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ResetVelocityScaler
struct APlayerPawnCharacter_C_ResetVelocityScaler_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ForcePullEndCheck
struct APlayerPawnCharacter_C_ForcePullEndCheck_Params
{
class AActor* Actor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AGrippableStaticMeshActorBase_C* ForcePullActor; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData)
class USphereComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* NearestObjectToHand; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData)
class UGripMotionControllerComponent* CallingMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetHandsEnabled
struct APlayerPawnCharacter_C_SetHandsEnabled_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnRep_PlayerHeight
struct APlayerPawnCharacter_C_OnRep_PlayerHeight_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetInputTurn_X
struct APlayerPawnCharacter_C_GetInputTurn_X_Params
{
float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnRep_HPCurrent
struct APlayerPawnCharacter_C_OnRep_HPCurrent_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OptionsIsRightHandedChanged
struct APlayerPawnCharacter_C_OptionsIsRightHandedChanged_Params
{
bool IsRightHanded; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateMCTriggerValues
struct APlayerPawnCharacter_C_UpdateMCTriggerValues_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReleaseMagazine
struct APlayerPawnCharacter_C_ReleaseMagazine_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OptionIsHeadOrientedLocomotionChanged
struct APlayerPawnCharacter_C_OptionIsHeadOrientedLocomotionChanged_Params
{
bool IsHeadOrientedLocomotion; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryToSecondaryGripObject
struct APlayerPawnCharacter_C_TryToSecondaryGripObject_Params
{
class UGripMotionControllerComponent** Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent** OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject** ObjectToTryToGrab; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FGameplayTag* GripSecondaryTag; // (BlueprintVisible, BlueprintReadOnly, Parm)
bool* ObjectImplementsInterface; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FTransform* RelativeSecondaryTransform; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
bool* bHadSlot; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool SecondaryGripped; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateSmoothTurning
struct APlayerPawnCharacter_C_UpdateSmoothTurning_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateSnapTurning
struct APlayerPawnCharacter_C_UpdateSnapTurning_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SliderOutOfBoundsClick
struct APlayerPawnCharacter_C_SliderOutOfBoundsClick_Params
{
class UGripMotionControllerComponent* CallingHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool IsGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnRep_PlayerRank
struct APlayerPawnCharacter_C_OnRep_PlayerRank_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InitializeRank
struct APlayerPawnCharacter_C_InitializeRank_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckWeaponSlotCorrectAttach
struct APlayerPawnCharacter_C_CheckWeaponSlotCorrectAttach_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnRep_GrenadeSlot2Attached
struct APlayerPawnCharacter_C_OnRep_GrenadeSlot2Attached_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnRep_GrenadeSlotAttached
struct APlayerPawnCharacter_C_OnRep_GrenadeSlotAttached_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnRep_PrimarySlotAttached
struct APlayerPawnCharacter_C_OnRep_PrimarySlotAttached_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnRep_SecondarySlotAttached
struct APlayerPawnCharacter_C_OnRep_SecondarySlotAttached_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReloadWeaponScale
struct APlayerPawnCharacter_C_ReloadWeaponScale_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SaveWeaponScale
struct APlayerPawnCharacter_C_SaveWeaponScale_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SwitchOutline
struct APlayerPawnCharacter_C_SwitchOutline_Params
{
bool TurnOn; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryToGrabObjectAfter
struct APlayerPawnCharacter_C_TryToGrabObjectAfter_Params
{
class UObject* ObjectToTryToGrab; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool IsSlotGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CycleHandPoses
struct APlayerPawnCharacter_C_CycleHandPoses_Params
{
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AttachmentReleasedButtonStatusChangeDuringHover
struct APlayerPawnCharacter_C_AttachmentReleasedButtonStatusChangeDuringHover_Params
{
bool Changed; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InitializeName
struct APlayerPawnCharacter_C_InitializeName_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Initialize
struct APlayerPawnCharacter_C_Initialize_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckSlotAttach
struct APlayerPawnCharacter_C_CheckSlotAttach_Params
{
class AActor* ItemToSlot; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ShowSlots
struct APlayerPawnCharacter_C_ShowSlots_Params
{
class UObject* GripedItem; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.EnableForcePull
struct APlayerPawnCharacter_C_EnableForcePull_Params
{
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool Enable; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ShouldOutline
struct APlayerPawnCharacter_C_ShouldOutline_Params
{
class AActor* Actor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool ShouldOutline; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ActivatePPDeath
struct APlayerPawnCharacter_C_ActivatePPDeath_Params
{
float BlendWeight; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HideSlots
struct APlayerPawnCharacter_C_HideSlots_Params
{
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ShowWeaponSlots
struct APlayerPawnCharacter_C_ShowWeaponSlots_Params
{
TEnumAsByte<EWeaponCategories> WeaponCategory; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ShowGrenadeSlots
struct APlayerPawnCharacter_C_ShowGrenadeSlots_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BeginPlayParent
struct APlayerPawnCharacter_C_BeginPlayParent_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckNewMagazineShouldSpawn
struct APlayerPawnCharacter_C_CheckNewMagazineShouldSpawn_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool ShouldSpawn; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateInteractibleObject
struct APlayerPawnCharacter_C_UpdateInteractibleObject_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetNearestActorToLine
struct APlayerPawnCharacter_C_GetNearestActorToLine_Params
{
TArray<class AActor*> Actors; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm)
struct FVector LineOrigin; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FVector LineDirection; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
class AActor* NearestActor; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckGrippedItemDistanceWithController
struct APlayerPawnCharacter_C_CheckGrippedItemDistanceWithController_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetGrippedItemWithController
struct APlayerPawnCharacter_C_GetGrippedItemWithController_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* GrippedItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckGrippedItemDistance
struct APlayerPawnCharacter_C_CheckGrippedItemDistance_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateHitIndicator
struct APlayerPawnCharacter_C_UpdateHitIndicator_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckClimb
struct APlayerPawnCharacter_C_CheckClimb_Params
{
bool RightHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool CanClimb; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HoverObject
struct APlayerPawnCharacter_C_HoverObject_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* NewObject; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetNearestObject
struct APlayerPawnCharacter_C_GetNearestObject_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class USphereComponent* Overlap_Component; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* NearestObject; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetValidForcePullableActors
struct APlayerPawnCharacter_C_GetValidForcePullableActors_Params
{
TArray<class AGrippableStaticMeshActorBase_C*> Actors; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm)
TArray<class AGrippableStaticMeshActorBase_C*> ValidActors; // (Parm, OutParm, ZeroConstructor)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GripDropOrUseObjectClean
struct APlayerPawnCharacter_C_GripDropOrUseObjectClean_Params
{
class UGripMotionControllerComponent** CallingMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent** OtherController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool* CanCheckClimb; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent** GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FGameplayTagContainer* RelevantGameplayTags; // (BlueprintVisible, BlueprintReadOnly, Parm)
bool PerformedAction; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.IsAttachmentReleaseButtonPressed
struct APlayerPawnCharacter_C_IsAttachmentReleaseButtonPressed_Params
{
bool Pressed; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.DropOrUseSecondaryAttachment
struct APlayerPawnCharacter_C_DropOrUseSecondaryAttachment_Params
{
class UGripMotionControllerComponent** Calling_Motion_Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent** Other_Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FGameplayTagContainer* GameplayTags; // (BlueprintVisible, BlueprintReadOnly, Parm)
bool DroppedOrUsedSecondary; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
bool HadSecondary; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateIKParams
struct APlayerPawnCharacter_C_UpdateIKParams_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OptionsChanged
struct APlayerPawnCharacter_C_OptionsChanged_Params
{
struct FOptionsStruct2 Options; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HitParticles
struct APlayerPawnCharacter_C_HitParticles_Params
{
float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FVector HitNormal; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FName HitBoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AttachGrenadeToSlotLocal
struct APlayerPawnCharacter_C_AttachGrenadeToSlotLocal_Params
{
class AGrenadeBase_C* Grenade; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* Slot; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CanObjectBeClimbed
struct APlayerPawnCharacter_C_CanObjectBeClimbed_Params
{
class UPrimitiveComponent** ObjectToCheck; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool CanClimb; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetOtherGrip
struct APlayerPawnCharacter_C_GetOtherGrip_Params
{
class UGripMotionControllerComponent* Grip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherGrip; // (Parm, OutParm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetStepSound
struct APlayerPawnCharacter_C_GetStepSound_Params
{
TEnumAsByte<EStepType> StepType; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
TEnumAsByte<EPhysicalSurface> SurfaceType; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class USoundBase* StepSound; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
float Intensity; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.PlayGearMovementSound
struct APlayerPawnCharacter_C_PlayGearMovementSound_Params
{
TEnumAsByte<EStepType> StepType; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.PlayStepSound
struct APlayerPawnCharacter_C_PlayStepSound_Params
{
TEnumAsByte<EStepType> StepType; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AnimStep
struct APlayerPawnCharacter_C_AnimStep_Params
{
TEnumAsByte<EStepType> Step; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AddMessage
struct APlayerPawnCharacter_C_AddMessage_Params
{
struct FMessageStruct Message; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetGrippedWeaponWithController
struct APlayerPawnCharacter_C_GetGrippedWeaponWithController_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AWeaponBase_C* GrippedWeapon; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.DieLocal
struct APlayerPawnCharacter_C_DieLocal_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandleDamage
struct APlayerPawnCharacter_C_HandleDamage_Params
{
float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AController* InstigatedBy; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FVector DamageCauserOriginalVelocity; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.IKFootTrace
struct APlayerPawnCharacter_C_IKFootTrace_Params
{
float TraceDistance; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FName Socket; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
float IKoffset; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AttachWeaponToSlotLocal
struct APlayerPawnCharacter_C_AttachWeaponToSlotLocal_Params
{
class AWeaponBase_C* Weapon; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* Slot; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReattachMotionController
struct APlayerPawnCharacter_C_ReattachMotionController_Params
{
class UGripMotionControllerComponent* GripMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryRemoveSecondaryAttachment
struct APlayerPawnCharacter_C_TryRemoveSecondaryAttachment_Params
{
class UGripMotionControllerComponent** Calling_Motion_Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent** Other_Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FGameplayTagContainer* GameplayTags; // (BlueprintVisible, BlueprintReadOnly, Parm)
bool DroppedSecondary; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
bool HadSecondary; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryToGrabObject
struct APlayerPawnCharacter_C_TryToGrabObject_Params
{
class UObject** ObjectToTryToGrab; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FTransform* WorldTransform; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
class UGripMotionControllerComponent** Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent** OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool* IsSlotGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FGameplayTag* GripSecondaryTag; // (BlueprintVisible, BlueprintReadOnly, Parm)
struct FName* GripBoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool* IsSecondaryGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool Gripped; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetGrippedWeapon
struct APlayerPawnCharacter_C_GetGrippedWeapon_Params
{
class AWeaponBase_C* GrippedWeapon; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TeleportRightPressed
struct APlayerPawnCharacter_C_TeleportRightPressed_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SpawnMagazineToHandLocal
struct APlayerPawnCharacter_C_SpawnMagazineToHandLocal_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AMagazineBase_C* Magazine; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetNearestOverlappingObject
struct APlayerPawnCharacter_C_GetNearestOverlappingObject_Params
{
class UPrimitiveComponent** OverlapComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent** Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* NearestObject; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
bool ImplementsInterface; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
struct FTransform ObjectTransform; // (Parm, OutParm, IsPlainOldData)
bool CanBeClimbed; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
struct FName BoneName; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
struct FVector ImpactLoc; // (Parm, OutParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UserConstructionScript
struct APlayerPawnCharacter_C_UserConstructionScript_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandGlowRight__FinishedFunc
struct APlayerPawnCharacter_C_HandGlowRight__FinishedFunc_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandGlowRight__UpdateFunc
struct APlayerPawnCharacter_C_HandGlowRight__UpdateFunc_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandGlowLeft__FinishedFunc
struct APlayerPawnCharacter_C_HandGlowLeft__FinishedFunc_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandGlowLeft__UpdateFunc
struct APlayerPawnCharacter_C_HandGlowLeft__UpdateFunc_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_MenuLeft_K2Node_InputActionEvent_15
struct APlayerPawnCharacter_C_InpActEvt_MenuLeft_K2Node_InputActionEvent_15_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_MenuRight_K2Node_InputActionEvent_14
struct APlayerPawnCharacter_C_InpActEvt_MenuRight_K2Node_InputActionEvent_14_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_GripLeft_K2Node_InputActionEvent_13
struct APlayerPawnCharacter_C_InpActEvt_GripLeft_K2Node_InputActionEvent_13_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_GripLeft_K2Node_InputActionEvent_12
struct APlayerPawnCharacter_C_InpActEvt_GripLeft_K2Node_InputActionEvent_12_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_GripRight_K2Node_InputActionEvent_11
struct APlayerPawnCharacter_C_InpActEvt_GripRight_K2Node_InputActionEvent_11_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_GripRight_K2Node_InputActionEvent_10
struct APlayerPawnCharacter_C_InpActEvt_GripRight_K2Node_InputActionEvent_10_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_TriggerLeft_K2Node_InputActionEvent_9
struct APlayerPawnCharacter_C_InpActEvt_TriggerLeft_K2Node_InputActionEvent_9_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_TriggerLeft_K2Node_InputActionEvent_8
struct APlayerPawnCharacter_C_InpActEvt_TriggerLeft_K2Node_InputActionEvent_8_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_TriggerRight_K2Node_InputActionEvent_7
struct APlayerPawnCharacter_C_InpActEvt_TriggerRight_K2Node_InputActionEvent_7_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_TriggerRight_K2Node_InputActionEvent_6
struct APlayerPawnCharacter_C_InpActEvt_TriggerRight_K2Node_InputActionEvent_6_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_Skill_AttachmentRelease_K2Node_InputActionEvent_5
struct APlayerPawnCharacter_C_InpActEvt_Skill_AttachmentRelease_K2Node_InputActionEvent_5_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_Skill_AttachmentRelease_K2Node_InputActionEvent_4
struct APlayerPawnCharacter_C_InpActEvt_Skill_AttachmentRelease_K2Node_InputActionEvent_4_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_Skill_FireModeChange_K2Node_InputActionEvent_3
struct APlayerPawnCharacter_C_InpActEvt_Skill_FireModeChange_K2Node_InputActionEvent_3_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_Skill_ReleaseMagazine_K2Node_InputActionEvent_2
struct APlayerPawnCharacter_C_InpActEvt_Skill_ReleaseMagazine_K2Node_InputActionEvent_2_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.InpActEvt_Skill_ReleaseSlider_K2Node_InputActionEvent_1
struct APlayerPawnCharacter_C_InpActEvt_Skill_ReleaseSlider_K2Node_InputActionEvent_1_Params
{
struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReceiveBeginPlay
struct APlayerPawnCharacter_C_ReceiveBeginPlay_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.RumbleController
struct APlayerPawnCharacter_C_RumbleController_Params
{
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
float Intensity; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
float Duration; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.RumbleControllerBoth
struct APlayerPawnCharacter_C_RumbleControllerBoth_Params
{
float Intensity; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
float Duration; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__GrabSphereLeft_K2Node_ComponentBoundEvent_1_ComponentBeginOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__GrabSphereLeft_K2Node_ComponentBoundEvent_1_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__GrabSphereRight_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__GrabSphereRight_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryDropSingle
struct APlayerPawnCharacter_C_TryDropSingle_Params
{
class UGripMotionControllerComponent** Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FVector_NetQuantize100* AngleVel; // (BlueprintVisible, BlueprintReadOnly, Parm)
struct FVector_NetQuantize100* LinearVel; // (BlueprintVisible, BlueprintReadOnly, Parm)
unsigned char* GripHash; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.On Possessed
struct APlayerPawnCharacter_C_On_Possessed_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckAndHandleGripAnimations
struct APlayerPawnCharacter_C_CheckAndHandleGripAnimations_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReceiveTick
struct APlayerPawnCharacter_C_ReceiveTick_Params
{
float* DeltaSeconds; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ApplyDamageCustom
struct APlayerPawnCharacter_C_ApplyDamageCustom_Params
{
float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UClass* DamageType; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AController* IntigatedBy; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AActor* DamageCauser; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FName HitBoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* HitComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FVector HitNormal; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FVector DamageCauserOriginalVelocity; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.PrimaryWeaponSlotPicked
struct APlayerPawnCharacter_C_PrimaryWeaponSlotPicked_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SecondaryWeaponSlotPicked
struct APlayerPawnCharacter_C_SecondaryWeaponSlotPicked_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckWeaponSlotPrimaryAttach
struct APlayerPawnCharacter_C_CheckWeaponSlotPrimaryAttach_Params
{
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckWeaponSlotSecondaryAttach
struct APlayerPawnCharacter_C_CheckWeaponSlotSecondaryAttach_Params
{
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryDropSingle_Client
struct APlayerPawnCharacter_C_TryDropSingle_Client_Params
{
class UGripMotionControllerComponent** Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FBPActorGripInformation* GripToDrop; // (BlueprintVisible, BlueprintReadOnly, Parm)
struct FVector* Angle_Vel; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FVector* Linear_Vel; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryDropSingleAfter
struct APlayerPawnCharacter_C_TryDropSingleAfter_Params
{
class UGripMotionControllerComponent* Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* ObjectToDrop; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReceiveRadialDamage
struct APlayerPawnCharacter_C_ReceiveRadialDamage_Params
{
float* DamageReceived; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UDamageType** DamageType; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FVector* Origin; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FHitResult* HitInfo; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
class AController** InstigatedBy; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AActor** DamageCauser; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AutiHealWait
struct APlayerPawnCharacter_C_AutiHealWait_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AutoHeal
struct APlayerPawnCharacter_C_AutoHeal_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckGrenadeSlotAttach
struct APlayerPawnCharacter_C_CheckGrenadeSlotAttach_Params
{
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GrenadeSlotPicked
struct APlayerPawnCharacter_C_GrenadeSlotPicked_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckGrenadeSlot2Attach
struct APlayerPawnCharacter_C_CheckGrenadeSlot2Attach_Params
{
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GrenadeSlot2Picked
struct APlayerPawnCharacter_C_GrenadeSlot2Picked_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Voice
struct APlayerPawnCharacter_C_Voice_Params
{
class USoundBase* Sound; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HitSounds
struct APlayerPawnCharacter_C_HitSounds_Params
{
struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryDropSingleAfterServer
struct APlayerPawnCharacter_C_TryDropSingleAfterServer_Params
{
class UGripMotionControllerComponent* Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* ObjectToDrop; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryDropSingleAfterMulti
struct APlayerPawnCharacter_C_TryDropSingleAfterMulti_Params
{
class UGripMotionControllerComponent* Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* ObjectToDrop; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Revive
struct APlayerPawnCharacter_C_Revive_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReviveServer
struct APlayerPawnCharacter_C_ReviveServer_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReviveMulti
struct APlayerPawnCharacter_C_ReviveMulti_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ShowRevivePOI
struct APlayerPawnCharacter_C_ShowRevivePOI_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReviveCheck
struct APlayerPawnCharacter_C_ReviveCheck_Params
{
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SpawnMagazineToHand
struct APlayerPawnCharacter_C_SpawnMagazineToHand_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SpawnMagazineToHandServer
struct APlayerPawnCharacter_C_SpawnMagazineToHandServer_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SpawnMagazineToHandMulti
struct APlayerPawnCharacter_C_SpawnMagazineToHandMulti_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GrabSpawnedMagazineMulti
struct APlayerPawnCharacter_C_GrabSpawnedMagazineMulti_Params
{
class AMagazineBase_C* Magazine; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UGripMotionControllerComponent* Calling_Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GrabSpawnedMagazineLocal
struct APlayerPawnCharacter_C_GrabSpawnedMagazineLocal_Params
{
class AMagazineBase_C* Magaizne; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UGripMotionControllerComponent* Calling_Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckAllyNames
struct APlayerPawnCharacter_C_CheckAllyNames_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateAllyName
struct APlayerPawnCharacter_C_UpdateAllyName_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckAndShowHideAllyName
struct APlayerPawnCharacter_C_CheckAndShowHideAllyName_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__Capsule_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__Capsule_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__ForcePullCapsuleRight_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__ForcePullCapsuleRight_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ForcePullStart
struct APlayerPawnCharacter_C_ForcePullStart_Params
{
class AGrippableStaticMeshActorBase_C* ForcePullActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool RightHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateForcePull
struct APlayerPawnCharacter_C_UpdateForcePull_Params
{
float DeltaSeconds; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__ForcePullCapsuleLeft_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__ForcePullCapsuleLeft_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__ForcePullCapsuleLeft_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__ForcePullCapsuleLeft_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__OutlineSphere_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__OutlineSphere_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__OutlineSphere_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__OutlineSphere_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetHandState
struct APlayerPawnCharacter_C_SetHandState_Params
{
TEnumAsByte<EGripEnum> HandState; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool RightHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ProjectileFired
struct APlayerPawnCharacter_C_ProjectileFired_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ProjectileHit
struct APlayerPawnCharacter_C_ProjectileHit_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ProjectileHitHead
struct APlayerPawnCharacter_C_ProjectileHitHead_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Kill
struct APlayerPawnCharacter_C_Kill_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Hover
struct APlayerPawnCharacter_C_Hover_Params
{
TEnumAsByte<EHoverEnum> InteractType; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class USceneComponent* Component; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Unhover
struct APlayerPawnCharacter_C_Unhover_Params
{
class UPrimitiveComponent* Component; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandleDamageMulti
struct APlayerPawnCharacter_C_HandleDamageMulti_Params
{
float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AActor* DamageInstigator; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FVector DamageCauserOriginalVelocity; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandleDamageLocal
struct APlayerPawnCharacter_C_HandleDamageLocal_Params
{
float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AActor* DamageInstigator; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FVector DamageCauserOriginalVelocity; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateRevivePoi
struct APlayerPawnCharacter_C_UpdateRevivePoi_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GrabWeaponRight
struct APlayerPawnCharacter_C_GrabWeaponRight_Params
{
class AActor* WeaponActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.StopHeartbeatSFX
struct APlayerPawnCharacter_C_StopHeartbeatSFX_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateHeartbeatSFX
struct APlayerPawnCharacter_C_UpdateHeartbeatSFX_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckOutline
struct APlayerPawnCharacter_C_CheckOutline_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CheckAndOutlineOverlappingActor
struct APlayerPawnCharacter_C_CheckAndOutlineOverlappingActor_Params
{
class AActor* Actor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnGrabItem
struct APlayerPawnCharacter_C_OnGrabItem_Params
{
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UObject* GripedItem; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GetEquipmentServer
struct APlayerPawnCharacter_C_GetEquipmentServer_Params
{
struct FPlayerEquipmentStruct PlayerEquipmentStruct; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetHandPoseServer
struct APlayerPawnCharacter_C_SetHandPoseServer_Params
{
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
TEnumAsByte<EHandPose> Pose; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetHandPoseMulti
struct APlayerPawnCharacter_C_SetHandPoseMulti_Params
{
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
TEnumAsByte<EHandPose> Pose; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetHandPose
struct APlayerPawnCharacter_C_SetHandPose_Params
{
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
TEnumAsByte<EHandPose> Pose; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryGrabMulti
struct APlayerPawnCharacter_C_TryGrabMulti_Params
{
class UObject* ObjectToGrab; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool IsSlotGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FTransform_NetQuantize GripTransform; // (BlueprintVisible, BlueprintReadOnly, Parm)
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FGameplayTag GripSecondaryTag; // (BlueprintVisible, BlueprintReadOnly, Parm)
struct FName GripBoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TryToGrabObjectAfterMulti
struct APlayerPawnCharacter_C_TryToGrabObjectAfterMulti_Params
{
class UObject* ObjectToTryToGrab; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UGripMotionControllerComponent* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool IsSlotGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.DropOrUseSecondaryAttachmentAfterMulti
struct APlayerPawnCharacter_C_DropOrUseSecondaryAttachmentAfterMulti_Params
{
class UGripMotionControllerComponent* GripMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.DropOrUseSecondaryAttachmentAfterServer
struct APlayerPawnCharacter_C_DropOrUseSecondaryAttachmentAfterServer_Params
{
class UGripMotionControllerComponent* GripMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.AttachWeaponToSlot
struct APlayerPawnCharacter_C_AttachWeaponToSlot_Params
{
class AWeaponBase_C* Weapon; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* Slot; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetSecodarySlotAttachedServer
struct APlayerPawnCharacter_C_SetSecodarySlotAttachedServer_Params
{
class AWeaponBase_C* SecondarySlotAttached; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetPrimarySlotAttachedServer
struct APlayerPawnCharacter_C_SetPrimarySlotAttachedServer_Params
{
class AWeaponBase_C* PrimarySlotAttached; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetGrenadeSlotAttachedServer
struct APlayerPawnCharacter_C_SetGrenadeSlotAttachedServer_Params
{
class AGrenadeBase_C* GrenadeSlotAttached; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetGreandeSlot2AttachedServer
struct APlayerPawnCharacter_C_SetGreandeSlot2AttachedServer_Params
{
class AGrenadeBase_C* GrenadeSlotAttached; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OnMenuClose
struct APlayerPawnCharacter_C_OnMenuClose_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.DropLeft
struct APlayerPawnCharacter_C_DropLeft_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.DropRight
struct APlayerPawnCharacter_C_DropRight_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.DropWeapon
struct APlayerPawnCharacter_C_DropWeapon_Params
{
EControllerHand Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetupOnPossession
struct APlayerPawnCharacter_C_SetupOnPossession_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Trigger Grip Or Drop
struct APlayerPawnCharacter_C_Trigger_Grip_Or_Drop_Params
{
class UGripMotionControllerComponent** Calling_Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent** OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool* IsGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent** GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandleGripPress_Oculus
struct APlayerPawnCharacter_C_HandleGripPress_Oculus_Params
{
class UGripMotionControllerComponent* CallingMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandleGripRelease_Oculus
struct APlayerPawnCharacter_C_HandleGripRelease_Oculus_Params
{
class UGripMotionControllerComponent* CallingMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandleTriggerPress_Oculus
struct APlayerPawnCharacter_C_HandleTriggerPress_Oculus_Params
{
class UGripMotionControllerComponent* CallingMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HandleTriggerRelease_Oculus
struct APlayerPawnCharacter_C_HandleTriggerRelease_Oculus_Params
{
class UGripMotionControllerComponent* CallingMotionController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CallCorrectDropSingleEvent
struct APlayerPawnCharacter_C_CallCorrectDropSingleEvent_Params
{
class UGripMotionControllerComponent** Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FBPActorGripInformation* Grip; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.CallCorrectGrabEvent
struct APlayerPawnCharacter_C_CallCorrectGrabEvent_Params
{
class UObject** ObjectToGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
EControllerHand* Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool* IsSlotGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FTransform* GripTransform; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FGameplayTag* GripSecondaryTag; // (BlueprintVisible, BlueprintReadOnly, Parm)
struct FName* OptionalBoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool* IsSecondaryGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetAttachmentReleaseButtonPressedServer
struct APlayerPawnCharacter_C_SetAttachmentReleaseButtonPressedServer_Params
{
bool AttachmentReleaseButtonPressed; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.UpdateMCTriggerValuesServer
struct APlayerPawnCharacter_C_UpdateMCTriggerValuesServer_Params
{
float MC_L_TriggerValue; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
float MC_R_TriggerValue; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetPlayerRankServer
struct APlayerPawnCharacter_C_SetPlayerRankServer_Params
{
int PlayerRank; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.StopLowHealthSoundEffect
struct APlayerPawnCharacter_C_StopLowHealthSoundEffect_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ReceiveEndPlay
struct APlayerPawnCharacter_C_ReceiveEndPlay_Params
{
TEnumAsByte<EEndPlayReason>* EndPlayReason; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OpenClosePauseMenu
struct APlayerPawnCharacter_C_OpenClosePauseMenu_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.OpenCloseMultiplayerMenu
struct APlayerPawnCharacter_C_OpenCloseMultiplayerMenu_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.HMDRecenter
struct APlayerPawnCharacter_C_HMDRecenter_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetPlayerHeightServer
struct APlayerPawnCharacter_C_SetPlayerHeightServer_Params
{
float PlayerHeight; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.GripOrDropAllTags
struct APlayerPawnCharacter_C_GripOrDropAllTags_Params
{
class UGripMotionControllerComponent* Calling_Hand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class UGripMotionControllerComponent* OtherHand; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
bool IsGrip; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* GrabSphere; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.SetSecondaryGripAsPrimaryServer
struct APlayerPawnCharacter_C_SetSecondaryGripAsPrimaryServer_Params
{
class AWeaponBase_C* Target; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.LevelDataInitialized
struct APlayerPawnCharacter_C_LevelDataInitialized_Params
{
class ALevelData_C* LevelData; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__EarLeftCollision_K2Node_ComponentBoundEvent_2_ComponentBeginOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__EarLeftCollision_K2Node_ComponentBoundEvent_2_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__EarRightCollision_K2Node_ComponentBoundEvent_5_ComponentBeginOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__EarRightCollision_K2Node_ComponentBoundEvent_5_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.StartVoiceChat
struct APlayerPawnCharacter_C_StartVoiceChat_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.StopVoiceChat
struct APlayerPawnCharacter_C_StopVoiceChat_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__EarLeftCollision_K2Node_ComponentBoundEvent_3_ComponentEndOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__EarLeftCollision_K2Node_ComponentBoundEvent_3_ComponentEndOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.BndEvt__EarRightCollision_K2Node_ComponentBoundEvent_6_ComponentEndOverlapSignature__DelegateSignature
struct APlayerPawnCharacter_C_BndEvt__EarRightCollision_K2Node_ComponentBoundEvent_6_ComponentEndOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TriggerRightVoiceChatEvent
struct APlayerPawnCharacter_C_TriggerRightVoiceChatEvent_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.TriggerLeftVoiceChatEvent
struct APlayerPawnCharacter_C_TriggerLeftVoiceChatEvent_Params
{
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.ExecuteUbergraph_PlayerPawnCharacter
struct APlayerPawnCharacter_C_ExecuteUbergraph_PlayerPawnCharacter_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.PlayerDamaged__DelegateSignature
struct APlayerPawnCharacter_C_PlayerDamaged__DelegateSignature_Params
{
float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class AActor* DamageInstigator; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FVector DamageCauserOriginalVelocity; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
};
// Function PlayerPawnCharacter.PlayerPawnCharacter_C.Died__DelegateSignature
struct APlayerPawnCharacter_C_Died__DelegateSignature_Params
{
class APlayerPawnCharacter_C* PlayerPawnCharacter; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
910bedc4919fec35c0b37af305842717b91718e5 | 0cbf8b4b0f823ba851342173d40c58c71d82b51f | /src/Physics/NuclearState/SRCNuclearRecoil.h | 426ac1e8c8bdb94db91dcdf3e6eea4da09e90474 | [] | no_license | GENIE-MC/Generator | 0a62ba4ee7b1ff88c625156554759bdfc4f3fab5 | eda8a5a7a5dae1e10a902b25a45fa83c4bf4b90e | refs/heads/master | 2023-08-30T23:45:31.474160 | 2023-08-08T09:59:14 | 2023-08-08T09:59:14 | 150,272,240 | 48 | 91 | null | 2023-09-13T09:37:46 | 2018-09-25T13:46:01 | C++ | UTF-8 | C++ | false | false | 1,742 | h | SRCNuclearRecoil.h | //____________________________________________________________________________
/*!
\class genie::SRCNuclearRecoil
\brief Created this new module that controls the addition of the recoil nucleon in the event record
and extracts its kinematics
\author Afroditi Papadopoulou <apapadop \at mit.edu>
Massachusetts Institute of Technology - October 04, 2019
\created October 04, 2019
\cpright Copyright (c) 2003-2023, The GENIE Collaboration
For the full text of the license visit http://copyright.genie-mc.org
or see $GENIE/LICENSE
*/
//____________________________________________________________________________
#ifndef _SRC_NUCLEAR_RECOIL_H_
#define _SRC_NUCLEAR_RECOIL_H_
#include "Framework/EventGen/EventRecordVisitorI.h"
#include "Framework/GHEP/GHepParticle.h"
#include "Physics/NuclearState/FermiMomentumTable.h"
#include "Framework/Interaction/Target.h"
#include "Physics/NuclearState/SecondNucleonEmissionI.h"
namespace genie {
class SRCNuclearRecoil : public SecondNucleonEmissionI {
public :
SRCNuclearRecoil();
SRCNuclearRecoil(string config);
~SRCNuclearRecoil();
//-- implement the EventRecordVisitorI interface
void ProcessEventRecord(GHepRecord * event_rec) const;
//-- overload the Algorithm::Configure() methods to load private data
// members from configuration options
void Configure(const Registry & config);
void Configure(string config);
protected:
void LoadConfig (void);
int SRCRecoilPDG( const GHepParticle & nucleon, const Target & tgt) const; // determine the PDG code of the SRC pair
private:
double fPPPairPercentage;
double fPNPairPercentage;
};
} // genie namespace
#endif // _SRC_NUCLEAR_RECOIL_H_
|
fea3eccdea378a3bdbd4f5ba3a4231ae795f2d7a | 2da298b950c8d3303235b33f870320f2733c516c | /LED_Strip_Functions/LN_strip_control.cpp | 9dcea7ec83e8ab5ab40e582f19bacf86bce8764e | [] | no_license | shibbs/Light_node | 421ba964710f9235ed3d18be14b2d996c9bf79a3 | 0156f0760526c2867e0fbcae887c68fd8649bf24 | refs/heads/master | 2021-09-06T07:22:23.420747 | 2018-02-03T18:31:41 | 2018-02-03T18:31:41 | 109,891,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | LN_strip_control.cpp | #include "LN_strip_control.h"
#define LEDS_PIN 4
int NUM_PIXELS = 0;
uint32_t * curr_pixels;
Adafruit_NeoPixel strip ;//=Adafruit_NeoPixel(10, LEDS_PIN, NEO_GRB + NEO_KHZ800);;
void InitializeStrip(int num_LEDs){
strip = Adafruit_NeoPixel(num_LEDs, LEDS_PIN, NEO_GRB + NEO_KHZ800);
NUM_PIXELS = num_LEDs;
curr_pixels = new uint32_t[NUM_PIXELS];
strip.begin();
}
void lightUpStrip(uint32_t * send_arr){
//loop over all pixels in array
// Serial.println("Setting Strip");
for (int i = 0; i < NUM_PIXELS; i++){
// //if pixel changed, then update it and update our static array
//For some reason the below chunk of code is inserting random colors into the output. Can't figure out hy
// if(curr_pixels[i] != send_arr[i]){
// curr_pixels[i] = send_arr[i];
// Serial.println(send_arr[i]);
// strip.setPixelColor(i, send_arr[i]);
// }
strip.setPixelColor(i, send_arr[i]);
}
strip.show(); // Refresh strip
}
|
eacde6ce998e47ff0d009a3eb410246e23ce7458 | 1c8a39b0d79d784228fdc1d9c1e034316cec87fe | /SparseWeightedGraph.hpp | 572cf63a18a2ff8f4179c6d0698dfa6bc43949ac | [] | no_license | rodrigueztonyk/SparseWeightedGraph | a6af760f3047023e2bc1839a8de3b6d2e8862b0b | bf7fec66b49f76c540a350b2d75ce46c0c0d0d80 | refs/heads/master | 2021-01-19T05:49:33.570115 | 2016-08-18T15:22:08 | 2016-08-18T15:22:08 | 64,867,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,447 | hpp | SparseWeightedGraph.hpp | // SparseWeightedGraph.hpp C++ interface for manipulating weighted graphs stored in a sparse format
// It is assumed vertices are labeled 0,1,...,(n-1)
// This utilizes nauty, so nauty must be installed
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <assert.h>
#include "nausparse.h"
#include "naututil.h"
#include <time.h>
#include <cmath>
class SparseWeightedGraph
{
private:
bool directed; // if graph is directed or undirected
int nv; // number of vertices
int nde; // number of edges
double grpsize; // size of automorphism group
std::vector<int> d; // array of degrees. d[i] stores degree of vertex i
std::vector<int> e; // list of directed edges
std::vector<int> w; // list of weights of edges
std::vector<int> v; //v[i] is where vertex i's list of adjacencies start in e
std::vector<int> lab; // nauty lab for initial coloring
std::vector<int> ptn; // nauty ptn for initial coloring
int nauty_nv; // number of vertices in nauty graph
int nauty_nde; // number of edges in nauty graph
std::vector<int> nauty_d; // array of degrees in nauty graph
std::vector<int> nauty_e; // array of directed edges in nauty graph
std::vector<size_t> nauty_v; // ith element stores where vertex i's list of adjacencies start in nauty_e
bool addArc(int i, int j, int m); // mutator for adding arc (i,j) of weight m
bool delArc(int i, int j); // mutator for deleting arc (i,j)
bool changeArcWeight(int i, int j, int m); // mutator for changing weight of arc (i,j) to m
bool updateW(); // builds weighted nauty graph
bool updateUW(); //builds unweighted nauty graph
public:
// constructor that takes number of vertices _nv and whether or not the graph is directed
// _directed should be true if directed, false if undirected. default value is true
SparseWeightedGraph(int _nv, bool _directed=true);
SparseWeightedGraph(const SparseWeightedGraph &); // copy constructor
SparseWeightedGraph(FILE * fp); // constructs graph from file. Must be in modified DIMACS format
virtual ~SparseWeightedGraph(); // destructor. virtual in case needed as base class
SparseWeightedGraph & operator=(const SparseWeightedGraph &); // copy assignment operator
bool callNauty(bool _print = false, bool _trivial = false); // used to call nauty.
// callNauty has two inputs, _print and _trivial. _print = true will print nauty output to stdout. _trivial = true will print trivial orbits
double groupSize() const {return grpsize;} // accessor for size of group
bool callNautyForNumber(FILE * _fp); // used to call nauty to print nauty output to file _fp
std::vector<int> orbits; // nauty orbits
bool print(); // outputs all variables to stdout
bool printOrbits(bool _print = false); // prints orbits from nauty to stdout. if _print is true will print all orbits (including trivial), otherwise just prints nontrivial orbits
int numVertices() const {return nv;} // accessor for nv
int numEdges(); // accessor for nde
int deg(int i) const {return d[i];} // accessor for d[i]
bool isEdge(int i, int j); // is (i.j) an edge
int getWeight(int i, int j); // gets weight of edge (i,j)
bool addEdge(int i, int j, int m = 1); // mutator for adding edge (i,j) of weight m. returns true if edge successfully added
bool delEdge(int i, int j); // mutator for deleting edge (i,j). returns true if successful
bool isDirected() const {return directed;} // accessor for directed
bool changeWeight(int i, int j, int m); // mutator for changing weight of edge (i,j) to m. returns true if successful
int whereInV(int i) const {return v[i];} // accessor for v[i]
// access to the beginning of the list of neighbors of i
std::vector<int>::const_iterator beginNeighbors(int i) const {return (e.begin() + v[i]);}
// access to an iterator at the end of the list of neighbors of i
std::vector<int>::const_iterator endNeighbors(int i) const {return (e.begin() + v[i] + d[i]);}
// access to an iterator of the list of weights of edges from i
std::vector<int>::const_iterator beginNeighborWeights(int i) const {return (w.begin() + v[i]);}
//access to an iterator the end of the list of weights of edges from i
std::vector<int>::const_iterator endNeighborWeights(int i) const {return (w.begin() + v[i] + d[i]);}
// write graph to stream
friend std::ostream & operator<<(std::ostream &, const SparseWeightedGraph &);
};
|
01770a34ac04d71a732373723347b9ca672f7f2d | 332c6e2de1d9729e337411adb23d2fdbef70da66 | /src/postgresql.cpp | 0f2946e8c8d7883856ff17152622fb48d46dd361 | [] | no_license | blake-sheridan/py-postgresql | 87b747ceef1d33b4e29f6c58299defdffc12bfe4 | 4d4b0fb4ecfde3289ed6bc83483e0f86309e65d2 | refs/heads/master | 2021-01-02T23:13:34.961018 | 2014-03-31T15:53:18 | 2014-03-31T15:53:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,001 | cpp | postgresql.cpp | #include "Python.h"
#include "libpq-fe.h"
#include "b/Identifier.hpp"
#include "b/python.h"
#include "b/type.hpp"
#include "postgresql/parameters.hpp"
#include "postgresql/type.hpp"
typedef struct {
PyObject_HEAD
PGconn *pg_conn;
// Properties, cached upon first access
PyObject *host;
PyUnicodeObject *name;
PyUnicodeObject *user;
} Database;
typedef struct {
PyBaseExceptionObject base;
PGconn *pg_conn;
} ConnectionError;
typedef struct {
PyBaseExceptionObject base;
PGresult *pg_result;
} ExecutionError;
typedef struct {
PyObject_HEAD
PGresult *pg_result;
int row_count; // Cached from PQntuples
int column_count; // Cached from PQnfields
} Result;
typedef struct {
PyObject_HEAD
Result *result;
int index;
} ResultIterator;
typedef struct Row {
PyObject_HEAD
Result *result;
int index;
} Row;
typedef struct {
PyObject_HEAD
Row *row;
int index;
} RowIterator;
typedef struct {
PyObject_HEAD
Database *database;
} Schema;
typedef struct {
PyObject_HEAD
Database *database;
} Transaction;
/* Forward */
static inline Row *Result_row(Result *, int);
static inline bool Row_check(PyObject *);
/* ConnectionError */
PyDoc_STRVAR(
ConnectionError___doc__,
"Exception raised when failing to establish a connection.");
static void
ConnectionError___del__(ConnectionError *self)
{
PQfinish(self->pg_conn);
((PyTypeObject *)PyExc_Exception)->tp_dealloc((PyObject *)self);
}
static PyObject *
ConnectionError___str__(ConnectionError *self)
{
return PyUnicode_FromString(PQerrorMessage(self->pg_conn));
}
static PyTypeObject
ConnectionError_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.ConnectionError",
/* tp_basicsize */ sizeof(ConnectionError),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)ConnectionError___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ (reprfunc)ConnectionError___str__,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ ConnectionError___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ 0,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ (PyTypeObject *)PyExc_Exception,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
static void
ConnectionError_set(PGconn *pg_conn)
{
if (!b::type::ensure_ready(&ConnectionError_type)) {
PyErr_SetString(PyExc_SystemError, "Failed to ready ConnectionError");
return;
}
ConnectionError *self = (ConnectionError *)ConnectionError_type.tp_alloc(&ConnectionError_type, 0);
if (self == NULL) {
PyErr_SetObject((PyObject *)&ConnectionError_type, NULL);
return;
}
self->pg_conn = pg_conn;
PyErr_SetObject((PyObject *)&ConnectionError_type, (PyObject *)self);
}
/* ExecutionError */
PyDoc_STRVAR(
ExecutionError___doc__,
"Exception raised when failing to establish a connection.");
static void
ExecutionError___del__(ExecutionError *self)
{
PQclear(self->pg_result);
((PyTypeObject *)PyExc_Exception)->tp_dealloc((PyObject *)self);
}
static PyObject *
ExecutionError___str__(ExecutionError *self)
{
const char * const SEP = "\n * ";
char *primary = PQresultErrorField(self->pg_result, PG_DIAG_MESSAGE_PRIMARY);
char *detail = PQresultErrorField(self->pg_result, PG_DIAG_MESSAGE_DETAIL);
char *hint = PQresultErrorField(self->pg_result, PG_DIAG_MESSAGE_HINT);
assert(primary != NULL);
if (detail == NULL)
return PyUnicode_FromString(primary);
if (hint == NULL)
return PyUnicode_FromFormat("%s%sDETAIL: %s", primary, SEP, detail);
else
return PyUnicode_FromFormat("%s%sDETAIL: %s%SHINT: %s", primary, SEP, detail, SEP, hint);
}
static PyTypeObject
ExecutionError_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.ExecutionError",
/* tp_basicsize */ sizeof(ExecutionError),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)ExecutionError___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ (reprfunc)ExecutionError___str__,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ ExecutionError___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ 0,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ (PyTypeObject *)PyExc_Exception,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
static void
ExecutionError_set(PGresult *pg_result)
{
if (!b::type::ensure_ready(&ExecutionError_type)) {
PyErr_SetString(PyExc_SystemError, "Failed to ready ExecutionError");
return;
}
ExecutionError *self = (ExecutionError *)ExecutionError_type.tp_alloc(&ExecutionError_type, 0);
if (self == NULL) {
PyErr_SetObject((PyObject *)&ExecutionError_type, NULL);
return;
}
self->pg_result = pg_result;
PyErr_SetObject((PyObject *)&ExecutionError_type, (PyObject *)self);
}
/* RowIterator */
PyDoc_STRVAR(
RowIterator___doc__,
"Iterator over a Row's columns");
static void
RowIterator___del__(RowIterator *self)
{
Py_DECREF(self->row);
return Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyLongObject *
RowIterator___length_hint__(RowIterator *self)
{
TODO();
return NULL;
}
static Row *
RowIterator___next__(RowIterator *self)
{
TODO();
return NULL;
}
static PyMethodDef
RowIterator_methods[] = {
{"__length_hint__", (PyCFunction)RowIterator___length_hint__, METH_NOARGS, NULL},
{NULL}
};
static PyTypeObject
RowIterator_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.RowIterator",
/* tp_basicsize */ sizeof(RowIterator),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)RowIterator___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ RowIterator___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ PyObject_SelfIter,
/* tp_iternext */ (iternextfunc)RowIterator___next__,
/* tp_methods */ RowIterator_methods,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
/* Row */
PyDoc_STRVAR(
Row___doc__,
"Object representing a PostgreSQL command result row.");
static void
Row___del__(Row *self)
{
Py_DECREF(self->result);
return Py_TYPE(self)->tp_free((PyObject *)self);
}
/* Row_as_sequence */
static Py_ssize_t
Row___len__(Row *self)
{
return self->result->column_count;
}
static PyObject *
Row___getitem__(Row *self, Py_ssize_t index)
{
return postgresql::decode(self->result->pg_result, self->index, index);
}
static PyObject *
Row_richcompare(Row *self, PyObject *other, int op)
{
if (!Row_check(other))
Py_RETURN_NOTIMPLEMENTED;
bool invert;
if (op == Py_EQ) {
invert = false;
} else if (op == Py_NE) {
invert = true;
} else {
Py_RETURN_NOTIMPLEMENTED;
}
TODO();
return NULL;
if (invert) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
static Py_hash_t
Row___hash__(Row *self)
{
TODO();
return -1;
}
static RowIterator *
Row___iter__(Row *self)
{
if (!b::type::ensure_ready(&RowIterator_type))
return NULL;
RowIterator *iterator = (RowIterator *)RowIterator_type.tp_alloc(&RowIterator_type, 0);
if (iterator == NULL)
return NULL;
Py_INCREF(self);
iterator->row = self;
iterator->index = 0;
return iterator;
}
static PyUnicodeObject *
Row___repr__(Row *self)
{
TODO();
return NULL;
}
static PySequenceMethods
Row_as_sequence = {
/* sq_length */ (lenfunc)Row___len__,
/* sq_concat */ 0,
/* sq_repeat */ 0,
/* sq_item */ (ssizeargfunc)Row___getitem__,
/* sq_ass_item */ 0,
/* sq_contains */ 0,
/* sq_inplace_concat */ 0,
/* sq_inplace_repeat */ 0,
};
static PyTypeObject
Row_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.Row",
/* tp_basicsize */ sizeof(Row),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)Row___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ (reprfunc)Row___repr__,
/* tp_as_number */ 0,
/* tp_as_sequence */ &Row_as_sequence,
/* tp_as_mapping */ 0,
/* tp_hash */ (hashfunc)Row___hash__,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ Row___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ (richcmpfunc)Row_richcompare,
/* tp_weaklist_offset */ 0,
/* tp_iter */ (getiterfunc)Row___iter__,
/* tp_iternext */ 0,
/* tp_methods */ 0,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
static inline bool
Row_check(PyObject *x)
{
return Py_TYPE(x) == &Row_type;
}
/* ResultIterator */
PyDoc_STRVAR(
ResultIterator___doc__,
"Iterator over the Rows of a Result");
static void
ResultIterator___del__(ResultIterator *self)
{
Py_XDECREF(self->result);
return Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyLongObject *
ResultIterator___length_hint__(ResultIterator *self)
{
size_t length;
Result *result = self->result;
if (result == NULL) {
length = 0;
} else {
length = result->row_count - self->index;
}
return (PyLongObject *)PyLong_FromSize_t(length);
}
static Row *
ResultIterator___next__(ResultIterator *self)
{
Result *result = self->result;
if (result == NULL)
return NULL;
int index = self->index;
int length = result->row_count;
if (index == length) {
Py_DECREF(result);
self->result = NULL;
return NULL;
}
Row *row = Result_row(result, index);
self->index = index + 1;
return row;
}
static PyMethodDef
ResultIterator_methods[] = {
{"__length_hint__", (PyCFunction)ResultIterator___length_hint__, METH_NOARGS, NULL},
{NULL}
};
static PyTypeObject
ResultIterator_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.ResultIterator",
/* tp_basicsize */ sizeof(ResultIterator),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)ResultIterator___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ ResultIterator___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ PyObject_SelfIter,
/* tp_iternext */ (iternextfunc)ResultIterator___next__,
/* tp_methods */ ResultIterator_methods,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
/* Result */
PyDoc_STRVAR(
Result___doc__,
"Object representing a PostgreSQL command result.");
static void
Result___del__(Result *self)
{
PQclear(self->pg_result);
return Py_TYPE(self)->tp_free((PyObject *)self);
}
static inline Row *
Result_row(Result *self, int i)
{
assert(i < self->row_count);
if (!b::type::ensure_ready(&Row_type))
return NULL;
Row *row = (Row *)Row_type.tp_alloc(&Row_type, 0);
if (row == NULL)
return NULL;
Py_INCREF(self);
row->index = i;
row->result = self;
return row;
}
static Py_ssize_t
Result___len__(Result *self)
{
return self->row_count;
}
static Row *
Result___getitem__(Result *self, Py_ssize_t i)
{
if (i >= self->row_count)
return NULL;
return Result_row(self, i);
}
static ResultIterator *
Result___iter__(Result *self)
{
if (!b::type::ensure_ready(&ResultIterator_type))
return NULL;
ResultIterator *iterator = (ResultIterator *)ResultIterator_type.tp_alloc(&ResultIterator_type, 0);
if (iterator == NULL)
return NULL;
Py_INCREF(self);
iterator->result = self;
iterator->index = 0;
return iterator;
}
static PySequenceMethods
Result_as_sequence = {
/* sq_length */ (lenfunc)Result___len__,
/* sq_concat */ 0,
/* sq_repeat */ 0,
/* sq_item */ (ssizeargfunc)Result___getitem__,
/* sq_ass_item */ 0,
/* sq_contains */ 0,
/* sq_inplace_concat */ 0,
/* sq_inplace_repeat */ 0,
};
static PyTypeObject
Result_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.Result",
/* tp_basicsize */ sizeof(Result),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)Result___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ &Result_as_sequence,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ Result___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ (getiterfunc)Result___iter__,
/* tp_iternext */ 0,
/* tp_methods */ 0,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
static inline Result *
Result_new(PGresult *pg_result)
{
ExecStatusType status = PQresultStatus(pg_result);
// Fast path the common cases outside of a switch
if (status != PGRES_TUPLES_OK) {
if (status == PGRES_COMMAND_OK) {
// TODO: own type?
Py_INCREF(Py_None);
return (Result *)Py_None;
}
ExecutionError_set(pg_result);
return NULL;
}
if (!b::type::ensure_ready(&Result_type))
return NULL;
Result *self = (Result *)Result_type.tp_alloc(&Result_type, 0);
if (self == NULL)
return NULL;
self->pg_result = pg_result;
self->column_count = PQnfields(pg_result);
self->row_count = PQntuples(pg_result);
return self;
}
/* Transaction */
PyDoc_STRVAR(
Transaction___doc__,
"A transaction context manager");
static void
Transaction___del__(Transaction *self)
{
Py_DECREF(self->database);
return Py_TYPE(self)->tp_free((PyObject *)self);
}
static Transaction *
Transaction___enter__(Transaction *self)
{
PGresult *pg_result = PQexec(self->database->pg_conn, "BEGIN");
if (PQresultStatus(pg_result) != PGRES_COMMAND_OK) {
ExecutionError_set(pg_result);
return NULL;
}
PQclear(pg_result);
Py_INCREF(self);
return self;
}
static PyObject *
Transaction___exit__(Transaction *self, PyObject *args)
{
if (PyTuple_GET_SIZE(args) == 3) { // Sanity
PGresult *pg_result = PQexec(self->database->pg_conn,
PyTuple_GET_ITEM(args, 0) == Py_None ? "COMMIT" : "ROLLBACK");
if (PQresultStatus(pg_result) != PGRES_COMMAND_OK) {
ExecutionError_set(pg_result);
return NULL;
}
PQclear(pg_result);
}
Py_RETURN_NONE;
}
static PyMethodDef
Transaction_methods[] = {
{"__enter__", (PyCFunction)Transaction___enter__, METH_NOARGS, NULL},
{"__exit__", (PyCFunction)Transaction___exit__, METH_VARARGS, NULL},
{NULL}
};
static PyTypeObject
Transaction_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.Transaction",
/* tp_basicsize */ sizeof(Transaction),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)Transaction___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ Transaction___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ Transaction_methods,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
/* Schema */
PyDoc_STRVAR(
Schema___doc__,
"A Database schema");
static PyMethodDef
Schema_methods[] = {
{NULL}
};
static PyTypeObject
Schema_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.Schema",
/* tp_basicsize */ sizeof(Schema),
/* tp_itemsize */ 0,
/* tp_dealloc */ 0,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ Schema___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ Schema_methods,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ 0,
/* tp_free */ 0,
};
/* Database */
PyDoc_STRVAR(
Database___doc__,
"Object encapsulating a single PostgreSQL database.");
static int
Database___init__(Database *self, PyObject *args, PyDictObject *kwargs)
{
static b::Identifier id_dbname("dbname");
static b::Identifier id_host("host");
static b::Identifier id_name("name");
static b::Identifier id_password("password");
static b::Identifier id_port("port");
static b::Identifier id_user("user");
char *keywords[6];
char *values [6];
size_t i = 0;
PGconn *pg_conn;
if (PyTuple_GET_SIZE(args) != 0) {
PyErr_Format(PyExc_TypeError, "'%s' takes no positional arguments, got: %R", Py_TYPE(self)->tp_name, args);
return -1;
}
if (kwargs != NULL) {
PyObject *o;
o = id_host.get(kwargs);
if (o != NULL) {
if (!PyUnicode_Check(o)) {
PyErr_Format(PyExc_TypeError, "expecting string, got: %s=%R", id_host.ascii, o);
return -1;
}
if ((values[i] = PyUnicode_AsUTF8AndSize(o, NULL)) == NULL)
return -1;
keywords[i++] = (char *)id_host.ascii;
}
o = id_name.get(kwargs);
if (o != NULL) {
if (!PyUnicode_Check(o)) {
PyErr_Format(PyExc_TypeError, "expecting string, got: %s=%R", id_name.ascii, o);
return -1;
}
if ((values[i] = PyUnicode_AsUTF8AndSize(o, NULL)) == NULL)
return -1;
keywords[i++] = (char *)id_dbname.ascii;
}
o = id_password.get(kwargs);
if (o != NULL) {
if (!PyUnicode_Check(o)) {
PyErr_Format(PyExc_TypeError, "expecting string, got: %s=%R", id_password.ascii, o);
return -1;
}
if ((values[i] = PyUnicode_AsUTF8AndSize(o, NULL)) == NULL)
return -1;
keywords[i++] = (char *)id_password.ascii;
}
o = id_port.get(kwargs);
if (o != NULL) {
if (!PyLong_Check(o)) {
PyErr_Format(PyExc_TypeError, "expecting integer, got: %s=%R", id_port.ascii, o);
return -1;
}
TODO();
return -1;
keywords[i++] = (char *)id_port.ascii;
}
o = id_user.get(kwargs);
if (o != NULL) {
if (!PyUnicode_Check(o)) {
PyErr_Format(PyExc_TypeError, "expecting string, got: %s=%R", id_user.ascii, o);
return -1;
}
if ((values[i] = PyUnicode_AsUTF8AndSize(o, NULL)) == NULL)
return -1;
keywords[i++] = (char *)id_user.ascii;
}
}
keywords[i] = NULL;
values [i] = NULL;
pg_conn = PQconnectdbParams((const char **)keywords, (const char **)values, 0);
if (PQstatus(pg_conn) != CONNECTION_OK) {
ConnectionError_set(pg_conn);
return -1;
}
// Re-initialized?
if (self->pg_conn != NULL) {
PQfinish(self->pg_conn);
}
self->pg_conn = pg_conn;
return 0;
}
static void
Database___del__(Database *self)
{
Py_XDECREF(self->host);
Py_XDECREF(self->name);
Py_XDECREF(self->user);
if (self->pg_conn != NULL)
PQfinish(self->pg_conn);
Py_TYPE(self)->tp_free((PyObject *)self);
}
/* Database_getset */
static PyTypeObject *
Database_ExecutionError(Database *self)
{
PyTypeObject *cls = &ExecutionError_type;
if (!b::type::ensure_ready(cls))
return NULL;
Py_INCREF(cls);
return cls;
}
PyDoc_STRVAR(
Database_host___doc__,
"The server host name of the connection (or None)");
static PyObject *
Database_host(Database *self)
{
PyObject *x = self->host;
if (x == NULL) {
char *bytes = PQhost(self->pg_conn);
if (bytes == NULL)
x = self->host = Py_None;
else
x = self->host = PyUnicode_FromString(bytes);
}
Py_INCREF(x);
return x;
}
PyDoc_STRVAR(
Database_name___doc__,
"The database name of the connection");
static PyUnicodeObject *
Database_name(Database *self)
{
PyUnicodeObject *x = self->name;
if (x == NULL) {
x = self->name = (PyUnicodeObject *)PyUnicode_FromString(PQdb(self->pg_conn));
if (x == NULL)
return NULL;
}
Py_INCREF(x);
return x;
}
PyDoc_STRVAR(
Database_user___doc__,
"The user name of the connection");
static PyUnicodeObject *
Database_user(Database *self)
{
PyUnicodeObject *x = self->user;
if (x == NULL) {
x = self->user = (PyUnicodeObject *)PyUnicode_FromString(PQuser(self->pg_conn));
if (x == NULL)
return NULL;
}
Py_INCREF(x);
return x;
}
static PyGetSetDef
Database_getset[] = {
{(char *)"ExecutionError", (getter)Database_ExecutionError, NULL, NULL},
{(char *)"host", (getter)Database_host, NULL, Database_host___doc__},
{(char *)"name", (getter)Database_name, NULL, Database_name___doc__},
{(char *)"user", (getter)Database_user, NULL, Database_user___doc__},
{NULL}
};
/* Methods */
PyDoc_STRVAR(
Database_schema___doc__,
"Return a named Schema...");
static Schema *
Database_schema(Database *self, PyObject *name)
{
if (!PyUnicode_Check(name)) {
PyErr_Format(PyExc_TypeError, "expecting string, got: %R", name);
return NULL;
}
TODO();
return NULL;
if (!b::type::ensure_ready(&Schema_type))
return NULL;
Schema *schema = (Schema *)Schema_type.tp_alloc(&Schema_type, 0);
if (schema == NULL)
return NULL;
Py_INCREF(self);
schema->database = self;
return schema;
}
PyDoc_STRVAR(
Database_transaction___doc__,
"Return a new Transaction for this Database.");
static Transaction *
Database_transaction(Database *self)
{
if (!b::type::ensure_ready(&Transaction_type))
return NULL;
Transaction *transaction = (Transaction *)Transaction_type.tp_alloc(&Transaction_type, 0);
if (transaction == NULL)
return NULL;
Py_INCREF(self);
transaction->database = self;
return transaction;
}
static PyMethodDef
Database_methods[] = {
{"schema", (PyCFunction)Database_schema, METH_O, Database_schema___doc__},
{"transaction", (PyCFunction)Database_transaction, METH_NOARGS, Database_transaction___doc__},
{NULL}
};
static Result *
Database___call__(Database *self, PyObject *args, PyObject *kwargs)
{
if (kwargs != NULL) {
PyErr_SetString(PyExc_TypeError, "__call__ does not take keyword arguments");
return NULL;
}
Py_ssize_t n = PyTuple_GET_SIZE(args);
if (n == 0) {
PyErr_SetString(PyExc_TypeError, "expecting at least 1 positional argument");
return NULL;
}
PyObject *o = PyTuple_GET_ITEM(args, 0);
if (!PyUnicode_Check(o)) {
PyErr_Format(PyExc_TypeError, "command must be a string, got: %R", o);
return NULL;
}
if (PyUnicode_READY(o) == -1)
return NULL;
char *command;
if (PyUnicode_IS_COMPACT_ASCII(o)) {
// Inline fast path for ASCII strings
command = (char *)((PyASCIIObject *)o + 1);
} else {
TODO();
return NULL;
}
PGresult *pg_result;
if (n == 1) {
pg_result = PQexecParams(
self->pg_conn,
command,
0,
NULL,
NULL,
NULL,
NULL,
1);
} else if (n == 2) {
postgresql::parameters::Static<1> p1;
if (!p1.append(PyTuple_GET_ITEM(args, 1)))
return NULL;
pg_result = PQexecParams(
self->pg_conn,
command,
1,
p1.types,
p1.values,
p1.lengths,
p1.formats,
1);
} else {
postgresql::parameters::Dynamic pn(n - 1);
for (Py_ssize_t i = 1; i < n; i++) {
if (!pn.append(PyTuple_GET_ITEM(args, i)))
return NULL;
}
pg_result = PQexecParams(
self->pg_conn,
command,
n - 1,
pn.types,
pn.values,
pn.lengths,
pn.formats,
1);
}
if (pg_result == NULL)
return NULL;
return Result_new(pg_result);
}
/* Database_type */
static PyTypeObject
Database_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "postgresql.Database",
/* tp_basicsize */ sizeof(Database),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)Database___del__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ (ternaryfunc)Database___call__,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT,
/* tp_doc */ Database___doc__,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklist_offset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ Database_methods,
/* tp_members */ 0,
/* tp_getset */ Database_getset,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ (initproc)Database___init__,
/* tp_alloc */ 0,
/* tp_new */ PyType_GenericNew,
/* tp_free */ 0,
};
/* module */
PyDoc_STRVAR(
module___doc__,
"A Python PostgreSQL front end");
static struct PyModuleDef
module_definition = {
PyModuleDef_HEAD_INIT,
"postgresql",
module___doc__,
-1,
};
PyMODINIT_FUNC
PyInit_postgresql(void)
{
if (!b::type::ensure_ready(&Database_type) ||
!b::type::ensure_ready(&ConnectionError_type))
return NULL;
PyObject *module = PyModule_Create(&module_definition);
if (module == NULL)
return NULL;
PyModule_AddObject(module, "ConnectionError", (PyObject *)&ConnectionError_type);
PyModule_AddObject(module, "Database", (PyObject *)&Database_type);
return module;
};
|
f81e7b3d3dcb3056ed504a00d17816af502246ee | c79c1b95213b83a0e5a1ba612a578cb6f132a9ea | /Lab11/code/player_sprite.h | 208a9781a9dbb28290a2da04a8b5260ed5d08158 | [] | no_license | japaolillo/Mario1 | e6c65dd9e136bd42139876340076625e07b5ab4f | 701cca23a70c301736f4d80bafd45bdf51b98742 | refs/heads/master | 2020-03-11T22:03:23.414286 | 2018-05-03T22:42:10 | 2018-05-03T22:42:10 | 130,281,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 841 | h | player_sprite.h | #ifndef __CDS_PLAYER_SPRITE_H
#define __CDS_PLAYER_SPRITE_H
#include "phys_sprite.h"
#include <allegro5/allegro_acodec.h>
#include <allegro5/allegro_audio.h>
namespace csis3700 {
class player_sprite : public phys_sprite {
public:
player_sprite(float initial_x=0, float initial_y=0);
virtual void advance_by_time(double dt);
bool is_player() const;
bool is_enemy() const;
bool is_coin() const {return false;};
void kill_player();
private:
void create_image_sequence();
void create_image_sequence_switch();
int player_floor;
image_sequence walk;
image_sequence stand;
image_sequence lwalk;
image_sequence lstand;
image_sequence dead;
bool is_luigi=false;
double ltime=0;
bool is_alive = true;
ALLEGRO_SAMPLE* jumpp = nullptr;
};
}
#endif /* PLAYER_SPRITE_H */
|
9196a9a44498ff6939bcd13b64df36cdfa3435fe | 3a3aed5d61271f5e222bf282775da998f5046e25 | /CPP/d03/ex03/ClapTrap.cpp | b271e548969174c65247ddad2ac30d095ce4e106 | [] | no_license | Nariom/42 | 6d1b7dd06dd9545066898a2dacc0c233faa1b0ca | a5990e7f3a5651a2df79c6e567831a62d295023b | refs/heads/master | 2020-09-08T22:18:26.392378 | 2019-11-12T16:21:08 | 2019-11-12T16:21:08 | 221,257,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,888 | cpp | ClapTrap.cpp | #include "ClapTrap.hpp"
ClapTrap::ClapTrap( void ) :
_hp(100),
_maxHp(100),
_level(1),
_name("ClapTrap")
{
std::cout << "ClapTrap " << this->_name << " - constructed.";
std::cout << std::endl;
return;
}
ClapTrap::ClapTrap( ClapTrap const & src ) {
*this = src;
std::cout << "ClapTrap " << this->_name << " - constructed.";
std::cout << std::endl;
return;
}
ClapTrap::ClapTrap( std::string str ) :
_hp(100),
_maxHp(100),
_level(1),
_name(str)
{
std::cout << "ClapTrap " << this->_name << " - constructed.";
std::cout << std::endl;
return;
}
ClapTrap::~ClapTrap( void ) {
std::cout << "ClapTrap " << this->_name << " - destructed.";
std::cout << std::endl;
return;
}
unsigned int ClapTrap::getHp( void ) const {
return this->_hp;
}
void ClapTrap::setHp( unsigned int val ) {
if (val <= this->_maxHp)
this->_hp = val;
else
this->_hp = this->_maxHp;
return;
}
unsigned int ClapTrap::getMaxHp( void ) const {
return this->_maxHp;
}
void ClapTrap::setMaxHp( unsigned int val ) {
this->_maxHp = val;
if (this->_hp > val)
this->_hp = val;
return;
}
unsigned int ClapTrap::getEp( void ) const {
return this->_ep;
}
void ClapTrap::setEp( unsigned int val ) {
if (val <= this->_maxEp)
this->_ep = val;
else
this->_ep = this->_maxEp;
return;
}
unsigned int ClapTrap::getMaxEp( void ) const {
return this->_maxEp;
}
void ClapTrap::setMaxEp( unsigned int val ) {
this->_maxEp = val;
if (this->_ep > val)
this->_ep = val;
return;
}
unsigned int ClapTrap::getLevel( void ) const {
return this->_level;
}
void ClapTrap::setLevel( unsigned int val ) {
this->_level = val;
return;
}
std::string ClapTrap::getName( void ) const {
return this->_name;
}
void ClapTrap::setName( std::string val ) {
this->_name = val;
return;
}
unsigned int ClapTrap::getMDmg( void ) const {
return this->_mDmg;
}
void ClapTrap::setMDmg( unsigned int val ) {
this->_mDmg = val;
return;
}
unsigned int ClapTrap::getRDmg( void ) const {
return this->_rDmg;
}
void ClapTrap::setRDmg( unsigned int val ) {
this->_rDmg = val;
return;
}
unsigned int ClapTrap::getDmgReduct( void ) const {
return this->_dmgReduct;
}
void ClapTrap::setDmgReduct( unsigned int val ) {
this->_dmgReduct = val;
return;
}
void ClapTrap::takeDamage( unsigned int amount ) {
std::cout << this->_name;
amount = (amount > this->_dmgReduct) ? amount - this->_dmgReduct : 0;
amount = (amount > this->_hp) ? this->_hp : amount;
if (amount > 0) {
std::cout << " - took " << amount << " damage(s).";
this->setHp(this->_hp - amount);
}
else
std::cout << " - was hit but armor took it all.";
std::cout << std::endl;
return;
}
void ClapTrap::beRepaired( unsigned int amount ) {
std::cout << this->_name;
amount = (amount + this->_hp > this->_maxHp) ? this->_maxHp - this->_hp : amount;
if (amount > 0) {
std::cout << " - repair for " << amount << " hp.";
this->setHp(this->_hp + amount);
}
else
std::cout << " - try to repair but is full health.";
std::cout << std::endl;
return;
}
unsigned int ClapTrap::_melee( std::string const & target ) const {
std::cout << this->_name << " - attacks ";
std::cout << target << " at melee, causing " << this->_mDmg;
std::cout << " points of damage !" << std::endl;
return this->_mDmg;
}
unsigned int ClapTrap::_ranged( std::string const & target ) const {
std::cout << this->_name << " - attacks ";
std::cout << target << " at range, causing " << this->_rDmg;
std::cout << " points of damage !" << std::endl;
return this->_rDmg;
}
ClapTrap & ClapTrap::operator=(ClapTrap const & rhs) {
this->_hp = rhs.getHp();
this->_maxHp = rhs.getMaxHp();
this->_ep = rhs.getEp();
this->_maxEp = rhs.getMaxEp();
this->_level = rhs.getLevel();
this->_name = rhs.getName();
this->_mDmg = rhs.getMDmg();
this->_rDmg = rhs.getRDmg();
this->_dmgReduct = rhs.getDmgReduct();
return *this;
} |
3f5ddc3e97b653ff96db7511e42fb762df3f82be | 2efe73e573da0bf48fbec9ee83283d8dea9804f3 | /MyThreadTimer/mythreadtimerwidget.cpp | 75ad247995f04908860869bc5f4aa3860e0705d5 | [] | no_license | yamero/qtexamples | 1559195d92f52bac5a7e1aaf33b7eb979bea25a0 | 868aa0cc1b9133d0ecad43c50d6b142d4aaa4c01 | refs/heads/master | 2020-09-30T17:53:23.573797 | 2019-12-11T10:54:20 | 2019-12-11T10:54:20 | 227,340,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,214 | cpp | mythreadtimerwidget.cpp | #include "mythreadtimerwidget.h"
#include "ui_mythreadtimerwidget.h"
#include <QThread>
#include <QDebug>
MyThreadTimerWidget::MyThreadTimerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MyThreadTimerWidget)
{
ui->setupUi(this);
myTimer = new MyTimer; // 实例化自己写的定时器类
QThread *thread = new QThread(this); // 创建一个子线程
myTimer->moveToThread(thread); // 将定时器类投递到子线程中,注意,这时子线程还没有启动
connect(myTimer, &MyTimer::myTimeout, [=](){ // 监听定时器类的myTimeout信号
static int i = 0;
ui->lcdNumber->display(i++);
});
connect(ui->startPushButton, &QPushButton::clicked, [=](){ // 监听开始按钮点击信号
if (thread->isRunning()) { // 如果子线程正在运行,则直接返回
return;
}
qDebug() << QThread::currentThread();
myTimer->setFlag(true);
myTimer->setInterval(500); // 设置时间间隔,毫秒
thread->start(); // 启动子线程
emit startThreadTask(); // 触发自定义的信号
});
connect(this, &MyThreadTimerWidget::startThreadTask, myTimer, &MyTimer::myTimer); // 监听自定义信号
connect(ui->stopPushButton, &QPushButton::clicked, [=](){ // 监听停止按钮点击信号
if (!thread->isRunning()) { // 如果子线程已停止运行,则直接返回
return;
}
myTimer->setFlag(false);
thread->quit(); // 平滑结束子线程
thread->wait(); // 等待子线程任务处理完毕再结束子线程
delete myTimer; // 这个对象没有指定父对象,手动释放一下
});
connect(this, &QWidget::destroyed, [=](){ // 监听窗口销毁信号
if (!thread->isRunning()) { // 如果子线程已停止运行,则直接返回
return;
}
myTimer->setFlag(false);
thread->quit(); // 平滑结束子线程
thread->wait(); // 等待子线程任务处理完毕再结束子线程
delete myTimer; // 这个对象没有指定父对象,手动释放一下
});
}
MyThreadTimerWidget::~MyThreadTimerWidget()
{
delete ui;
}
|
77690bebfa897635248486ffd29fc1ab2e0a6f98 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_old_hunk_1847.cpp | 7ac8ecbd0b2d6883c9cc58d1c53a197194ba547d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | git_old_hunk_1847.cpp | fn->name = xmemdupz(name, namelen);
fn->fn = ll_ext_merge;
*ll_user_merge_tail = fn;
ll_user_merge_tail = &(fn->next);
}
if (!strcmp("name", key)) {
if (!value)
return error("%s: lacks value", var);
fn->description = xstrdup(value);
return 0;
}
if (!strcmp("driver", key)) {
if (!value)
return error("%s: lacks value", var);
/*
* merge.<name>.driver specifies the command line:
|
bf8044eb43937dd6407ce00726175c388cd108a4 | fcdfe976c9ed60b18def889692a17dc18a8dd6d7 | /cpp/misc/kbhit-test.cpp | e9464f99a5f85a4067e6eb63ef9542edf6759d57 | [] | no_license | akihikoy/ay_test | 4907470889c9bda11cdc84e8231ef3156fda8bd7 | a24dfb720960bfedb94be3b4d147e37616e7f39a | refs/heads/master | 2023-09-02T19:24:47.832392 | 2023-08-27T06:45:20 | 2023-08-27T06:45:20 | 181,903,332 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,866 | cpp | kbhit-test.cpp | //-------------------------------------------------------------------------------------------
/*! \file kbhit-test.cpp
\brief certain c++ source file
\author Akihiko Yamaguchi, akihiko-y@is.naist.jp / ay@akiyam.sakura.ne.jp
\version 0.1
\date Dec.03, 2013
compile:
x++ -slora kbhit-test.cpp
usage:
./a.out
*/
//-------------------------------------------------------------------------------------------
#include <lora/sys.h>
// #include <iostream>
// #include <iomanip>
//-------------------------------------------------------------------------------------------
namespace loco_rabbits
{
}
//-------------------------------------------------------------------------------------------
using namespace std;
// using namespace boost;
using namespace loco_rabbits;
//-------------------------------------------------------------------------------------------
// #define print(var) PrintContainer((var), #var"= ")
// #define print(var) std::cout<<#var"= "<<(var)<<std::endl
//-------------------------------------------------------------------------------------------
int main(int argc, char**argv)
{
cout<<"hit space > "<<flush;
WaitKBHit(' ');
cout<<"ok."<<endl;
cout<<"hit any key > "<<flush;
char s= WaitKBHit();
cout<<"ok.(\'"<<s<<"\' has been hit)"<<endl;
{
cout<<"no-wait mode using KBHit(). hit any key to stop.."<<endl;
while(true)
{
cout<<"+"<<flush;
int c= KBHit();
if(c=='q') break;
}
cout<<"stopped"<<endl;
}
{
cout<<"no-wait mode using TKBHit. hit any key to stop.."<<endl;
TKBHit kbhit(false); // no-wait
while(true)
{
cout<<"+"<<flush;
int c= kbhit();
if(c=='q') break;
}
}
cout<<"stopped"<<endl;
return 0;
}
//-------------------------------------------------------------------------------------------
|
935586902011cafa2ba12b04e93f1acf1d5f7bf0 | b80322e91645595c1f93b474acfcfbe1fb28066d | /Graph/Medium/no_of_islands.cpp | b55ce725f6005d26e5cee0b79f9255cdf5da1ee0 | [] | no_license | Priyanshu-24/Data-Structures-Level-2 | 4e012ddeb3dd6cd9fc3e517cc2a310fceecae7f9 | 3586b54cf84bdb9681cda5522b442c9c91f804bd | refs/heads/main | 2023-06-19T05:34:50.797798 | 2021-07-19T11:49:27 | 2021-07-19T11:49:27 | 331,359,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,704 | cpp | no_of_islands.cpp | // we have to find the no islands
// islands are group with 1
// 1 = island, 0 = water
// just traverse the whole matrix using dfs and increase the count as we encounter another island
// as soon as we encounter a 1 we mark it as visited as a part a island part so that in next iteration
// it will not be counted
void dfs(int i,int j,vector<vector<int>> &vis,int n,int m,vector<vector<char>>& grid)
{
if(i<0 || j<0 || i>=n || j>=m)
return;
if(grid[i][j]=='0')
return;
if(vis[i][j]==0) // if we reach here then we have 1
{
vis[i][j]=1;
dfs(i+1,j,vis,n,m,grid);
dfs(i-1,j,vis,n,m,grid);
dfs(i+1,j+1,vis,n,m,grid);
dfs(i,j+1,vis,n,m,grid);
dfs(i,j-1,vis,n,m,grid);
dfs(i-1,j+1,vis,n,m,grid);
dfs(i-1,j-1,vis,n,m,grid);
dfs(i+1,j-1,vis,n,m,grid);
}
}
int numIslands(vector<vector<char>>& grid) {
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> vis( n , vector<int> (m, 0)); // visited vector
int count=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(vis[i][j]==0 && grid[i][j]=='1')
{
dfs(i,j,vis,n,m,grid);
count++;
}
}
}
return count;
}
// In gfg we have to check 8 sides i.e. digonally too, whereas in leetcode we just have to check in 4 directions
// Time and Space = O(n*m) or O(row*column) |
a5d63b7503dcca6e24ce9ff37f1ce59ff9c82af6 | bca98f9cfc1b87f393c8c446f56a4f43db1e7baa | /thread/mutual.cpp | a41facabc1009469c7beef22401aa311f081ec19 | [] | no_license | jaye1944/lcpp | ccc4209d1b935f1686b38bbe8dbf4d3f52f917d0 | 0349e7da48ecdbf7302f84c8dd649edd019ff166 | refs/heads/master | 2021-01-10T08:55:25.487973 | 2017-09-13T09:14:02 | 2017-09-13T09:14:02 | 44,486,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,815 | cpp | mutual.cpp | #include <iostream>
#include <map>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>
#include <memory>
#define NO_THREAD 10
#define ELEMENTS 10000
// std::this_thread::sleep_for(std::chrono::milliseconds(10));
/*
5 thread write to map and other 5 threads read from map
*/
std::map<std::string, std::string> g_keyResult;
std::mutex g_keyResult_mutex;
void set_page(const std::string &url,int tid)
{
// simulate writing
std::string t_id = std::to_string(tid);
std::string result = "write to map " + t_id;
std::lock_guard<std::mutex> guard(g_keyResult_mutex);
for (int k = 0; k < ELEMENTS ; k++)
{
std::string ke = std::to_string(k);
g_keyResult[ke] = result;
}
}
void get_page(const std::string &url,int tid)
{
// simulate reading
std::lock_guard<std::mutex> guard(g_keyResult_mutex);
for (const auto &pair : g_keyResult) {
std::cout << "Thread - " << tid << " " << pair.first << " => " << pair.second << '\n';
}
}
int main()
{
std::thread art[NO_THREAD];
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
//read from map
for (int i = 0; i < NO_THREAD; ++i) {
if(i%2 != 0)
{
std::cout << "read i " << i << std::endl;
art[i] = std::thread(get_page, "read from map",i);
}
else
{
std::cout << "Write i " << i << std::endl;
art[i] = std::thread(set_page, "add to map",i);
}
}
//join to main
for (int i = 0; i < NO_THREAD; ++i) {
art[i].join();
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
auto mili = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed_seconds);
std::cout << elapsed_seconds.count() << std::endl;
std::cout << mili.count() << std::endl;
//t1.join();
}
|
cb3789a747e9223f9a2dc5d428b118ba664cc1b7 | f1f3eb170abdee28d74e31d80d847f8ef19329b3 | /FBXConverterProject1/FBXConverterProject/Manager1.cpp | 3ea624cb17c7cfdbaa6ade336db476d5802f5af2 | [] | no_license | RavioliFinoli/FBXConverter | 58655d3e44042acca01d38a319cff8b2f702b876 | 84bbaaf3de709ca791484b8d7972e83229682f1d | refs/heads/master | 2020-03-30T06:38:07.466893 | 2018-12-12T15:40:22 | 2018-12-12T15:40:22 | 150,876,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73,672 | cpp | Manager1.cpp | #include "Manager.h"
#include <windows.h>
#define EXPORT_DIRECTORY "C:/Repos/RipTag/Assets/"
#define COPY_DOUBLE_FLOAT(COUNT, PTR1, PTR2) \
{ \
int counter = -1; while(counter++ < COUNT-1) PTR2[counter] = (float)PTR1[counter]; \
};
Converter::Converter(const char* fileName)
{
sdk_Manager = FbxManager::Create();
sdk_IOSettings = FbxIOSettings::Create(sdk_Manager, IOSROOT);
sdk_Manager->SetIOSettings(sdk_IOSettings);
sdk_importer = FbxImporter::Create(sdk_Manager, "");
sdk_scene = FbxScene::Create(sdk_Manager, "");
FbxAxisSystem axisSystem;
axisSystem = FbxAxisSystem::DirectX;
axisSystem.ConvertScene(sdk_scene);
int shit = 1;
auto poop = sdk_scene->GetGlobalSettings().GetAxisSystem().GetCoorSystem() ;
if (!sdk_importer->Initialize(fileName, -1, sdk_Manager->GetIOSettings())) {
printf("Call to FbxImporter::Initialize() failed.\n");
printf("Error returned: %s\n\n", sdk_importer->GetStatus().GetErrorString());
exit(-1);
}
sdk_importer->Import(sdk_scene);
sdk_importer->Destroy();
scene_rootNode = sdk_scene->GetRootNode();
}
Converter::~Converter()
{
sdk_Manager->Destroy();
}
void Converter::convertFileToCustomFormat()
{
//getGroups(scene_rootNode);
//getCamera(scene_rootNode);
//if (cameras.size() > 0)
// createCameraFiles(cameras);
//getLight(scene_rootNode);
//if (lights.size() > 0)
// createLightFile(lights);
getSceneMeshes(scene_rootNode);
std::vector<std::vector<Transform>> animation_key_vectors;
getSceneAnimationData(scene_rootNode, animation_key_vectors) ? printf("GetSceneANimationData run\n") : printf("GetSceneANimationData failed in main\n ");
if(animation_key_vectors.size()>0)
createAnimationFile(animation_key_vectors);
}
void Converter::getSceneMeshes(FbxNode* scene_node)
{
if (!scene_node)
{
std::cout << "Error in getSceneMeshes \n";
return;
}
FbxMesh* scene_mesh = scene_node->GetMesh();
if (scene_mesh)
{
/*getCustomAttributes(scene_node);
createMaterialsFile(scene_node);*/
std::vector<FbxVector4> normals;
std::vector<FbxVector2> UV;
std::vector<FbxVector4> Positions;
FbxVector4* vertices = scene_mesh->GetControlPoints();
std::vector<int> polygon_vertices_indices;
std::vector<int> tempVertexIndices;
int* polyVertices = scene_mesh->GetPolygonVertices();
for (int polygonIndex = 0; polygonIndex < scene_mesh->GetPolygonCount(); polygonIndex++)
{
int start = scene_mesh->GetPolygonVertexIndex(polygonIndex);
for (int polyvertexindex = 0; polyvertexindex < scene_mesh->GetPolygonSize(polygonIndex); polyvertexindex++)
{
Positions.push_back(vertices[scene_mesh->GetPolygonVertex(polygonIndex, polyvertexindex)]);
polygon_vertices_indices.push_back(polyVertices[start + polyvertexindex]);
FbxVector4 tempVec;
scene_mesh->GetPolygonVertexNormal(polygonIndex, polyvertexindex, tempVec);
normals.push_back(tempVec);
FbxStringList scene_mesh_uv_set_list;
scene_mesh->GetUVSetNames(scene_mesh_uv_set_list);
const char* lUVSetName = scene_mesh_uv_set_list.GetStringAt(0);
FbxGeometryElementUV* lUVElement = scene_mesh->GetElementUV(lUVSetName);
if (!lUVElement)
printf("No UVS\n");
FbxVector2 tempUV;
bool yayornay = false;
scene_mesh->GetPolygonVertexUV(polygonIndex, polyvertexindex, lUVSetName, tempUV, yayornay);
UV.push_back(tempUV);
}
tempVertexIndices.clear();
}
const char* node_name = scene_node->GetName();
FbxDeformer* mesh_deformer = (scene_mesh->GetDeformer(0));
if (!mesh_deformer)
{
createMeshFiles(scene_mesh->GetPolygonCount() * 3, Positions, normals, UV, node_name)
? printf("Binary mesh file created\n")
: printf("Could not create file");
}
else
{
FbxSkin* mesh_skin = (FbxSkin*)(scene_mesh->GetDeformer(0, FbxDeformer::eSkin));
if (mesh_skin)
createAnimatedMeshFile(scene_node, scene_mesh->GetPolygonCount() * 3, Positions, normals, UV, node_name, polygon_vertices_indices) ? printf("Animated Mesh file created!\n") : printf("Animated Mesh file could not be created");
}
}
for (int i = 0; i < scene_node->GetChildCount(); i++)
{
getSceneMeshes(scene_node->GetChild(i));
}
return;
}
bool Converter::createAnimatedMeshFile(FbxNode * scene_node, int nrOfVertices, std::vector<FbxVector4> Positions, std::vector<FbxVector4> normals, std::vector<FbxVector2> UV, const char * node_name, std::vector<int> weight_indices_vector)
{
std::vector<AnimatedVertex> skin_bound_vertices = std::vector<AnimatedVertex>(nrOfVertices);
for (int i = 0; i < nrOfVertices; i++)
{
COPY_DOUBLE_FLOAT(3, Positions[i], skin_bound_vertices[i].vertex_position);
COPY_DOUBLE_FLOAT(3, normals[i], skin_bound_vertices[i].vertex_normal);
COPY_DOUBLE_FLOAT(2, UV[i], skin_bound_vertices[i].vertex_UVCoord);
skin_bound_vertices[i].joint_weights[0] = 0.0f;
skin_bound_vertices[i].joint_weights[1] = 0.0f;
skin_bound_vertices[i].joint_weights[2] = 0.0f;
skin_bound_vertices[i].joint_weights[3] = 0.0f;
skin_bound_vertices[i].influencing_joint[0] = 0;
skin_bound_vertices[i].influencing_joint[1] = 0;
skin_bound_vertices[i].influencing_joint[2] = 0;
skin_bound_vertices[i].influencing_joint[3] = 0;
}
FbxMesh* scene_mesh = scene_node->GetMesh();
if (scene_mesh)
{
std::vector<FbxAMatrix> skeleton_joints_temp_vector;
std::vector<std::string> skeleton_joint_names;
std::vector<FbxNode*> skeleton_joint_parent_names;
FbxAMatrix transformation_matrix;
transformation_matrix.SetT(scene_node->LclTranslation.Get());
transformation_matrix.SetR(scene_node->LclRotation.Get());
transformation_matrix.SetS(scene_node->LclScaling.Get());
FbxCluster * skin_cluster = nullptr;
int skin_count = scene_node->GetMesh()->GetDeformerCount(FbxDeformer::eSkin);
std::vector<int> indicesVector;
std::vector<double> weightVector;
std::vector<int> correspondingJointVec;
std::vector<FbxVector4> controlPointsVector;
FbxAMatrix tempMat;
for (int i = 0; i < skin_count; i++)
{
FbxSkin* mesh_skin = (FbxSkin*)(scene_mesh->GetDeformer(i, FbxDeformer::eSkin));
if (!mesh_skin)
continue;
FbxAMatrix temp;
temp.SetIdentity();
for (int j = 0; j < mesh_skin->GetClusterCount(); j++)
{
std::cout << "HELLO " << j << std::endl;
skin_cluster = mesh_skin->GetCluster(j);
std::string connectedJointName = skin_cluster->GetLink()->GetName();
std::string parent_name = skin_cluster->GetLink()->GetParent()->GetName();
FbxAMatrix transformation;
FbxAMatrix linked_Transformation;
///OLD
skin_cluster->GetTransformMatrix(transformation);
skin_cluster->GetTransformLinkMatrix(linked_Transformation);
linked_Transformation.SetR(skin_cluster->GetLink()->EvaluateLocalRotation());
FbxAMatrix inverse_bind_pose = linked_Transformation.Inverse() * transformation * transformation_matrix;
//FbxAMatrix transformMatrix;
//FbxAMatrix transformLinkMatrix;
//FbxAMatrix globalBindposeInverseMatrix;
//skin_cluster->GetTransformMatrix(transformMatrix); // The transformation of the mesh at binding time
//skin_cluster->GetTransformLinkMatrix(transformLinkMatrix); // The transformation of the cluster(joint) at binding time from joint space to world space
//FbxAMatrix inverse_bind_pose = transformLinkMatrix.Inverse() * transformMatrix;
// Update the information in mSkeleton
//
//inverse_bind_pose = linked_Transformation;
//inverse_bind_pose.SetR(skin_cluster->GetLink()->EvaluateLocalRotation());
//if (j == 0)
//{
// inverse_bind_pose.SetIdentity();
//}
//else
//{
// inverse_bind_pose *= skin_cluster->GetLink()->GetParent()->EvaluateLocalTransform().Inverse();
//}
// inverse_bind_pose = skin_cluster->GetLink()->EvaluateGlobalTransform();
//FbxAMatrix pre;
//pre.SetR(skin_cluster->GetLink()->PreRotation.Get());
//FbxAMatrix post;
//post.SetR(skin_cluster->GetLink()->GetPostTargetRotation());
////inverse_bind_pose = pre * linked_Transformation * post;
//inverse_bind_pose.set
////inverse_bind_pose.SetR(skin_cluster->GetLink()->GetPreRotation(FbxNode::eSourcePivot));
////inverse_bind_pose *= skin_cluster->GetLink()->EvaluateLocalTransform(FBXSDK_TIME_INFINITE).Inverse();
////inverse_bind_pose = skin_cluster->GetLink()->EvaluateLocalTransform(FBXSDK_TIME_INFINITE);
//std::cout << skin_cluster->GetLink()->GetName() << std::endl;
//JOINT INFORMATION
skeleton_joint_names.push_back(connectedJointName);
skeleton_joints_temp_vector.push_back(inverse_bind_pose);
skeleton_joint_parent_names.push_back(skin_cluster->GetLink());
std::cout << connectedJointName << std::endl;
//getNames(scene_node);
// printf("Iteration on: %d\n", i);
//printf("| [%f, %f, %f, %f |\n", inverse_bind_pose[0][0], inverse_bind_pose[0][1], inverse_bind_pose[0][2], inverse_bind_pose[0][3]);
//printf("| [%f, %f, %f, %f |\n", inverse_bind_pose[1][0], inverse_bind_pose[1][1], inverse_bind_pose[1][2], inverse_bind_pose[1][3]);
//printf("| [%f, %f, %f, %f |\n", inverse_bind_pose[2][0], inverse_bind_pose[2][1], inverse_bind_pose[2][2], inverse_bind_pose[2][3]);
//printf("| [%f, %f, %f, %f |\n", inverse_bind_pose[3][0], inverse_bind_pose[3][1], inverse_bind_pose[3][2], inverse_bind_pose[3][3]);
double * weights = skin_cluster->GetControlPointWeights();
int *indices = skin_cluster->GetControlPointIndices();
for (int k = 0; k < skin_bound_vertices.size(); k++)
{
for (int x = 0; x < skin_cluster->GetControlPointIndicesCount(); x++)
{
auto ControlPointIndexCount = skin_cluster->GetControlPointIndicesCount();
if (indices[x] == weight_indices_vector[k])
{
for (int m = 0; m < 4; m++)
{
if (skin_bound_vertices[k].influencing_joint[m] == 0)
{
skin_bound_vertices[k].influencing_joint[m] = j + 1;
skin_bound_vertices[k].joint_weights[m] = weights[x];
m = 4;
}
}
}
}
}
}
}
// #createSkeletonFile_call
createSkeletonFile(skeleton_joint_names, skeleton_joints_temp_vector, skeleton_joint_names.size(), skeleton_joint_parent_names);
int nrOfVerts = nrOfVertices;
const char * temp = "_Mesh";
std::string filename = std::string(EXPORT_DIRECTORY) + std::string(node_name) + "_ANIMATION_Mesh.bin";
std::ofstream outfile(filename, std::ofstream::binary);
std::string readable_file_name = std::string(EXPORT_DIRECTORY) + std::string(node_name) + "_ANIMATION_Mesh.txt";
std::ofstream readable_file(readable_file_name);
std::cout << "Found mesh: " << node_name << " Nr of verts: " << nrOfVerts << "\n";
if (!outfile)
{
printf("No file could be opened. Manager.cpp line 122");
return false;
}
if (!readable_file)
{
printf("No file could be opened. Manager.cpp line 122");
return false;
}
/*readable_file << "Name of Mesh: " << node_name << "\n";
readable_file << "Number of vertices: " << nrOfVerts << "\n";*/
readable_file << "NrOfverts: " << nrOfVerts << "\n";
//readable_file.write((const char*)&nrOfVertices, sizeof(nrOfVerts));
readable_file.write((const char*)node_name, sizeof(char[100]));
readable_file << "\n";
for (int i = 0; i < nrOfVerts; i++)
{
/* readable_file << i << ": Position: X " << Positions[i][0] << " Y " << Positions[i][1] << " Z " << Positions[i][2] << "\n"
"Normals: X " << normals[i][0] << " Y" << normals[i][1] << " Z " << normals[i][2] << "\n"
" U: " << UV[i][0] << " V: " << UV[i][1] << " \n";
*/
}
outfile.write((const char*)&nrOfVerts, sizeof(int));
outfile.write((const char*)node_name, sizeof(const char[100]));
float tan[3];
float dVec1[3];
float dVec2[3];
float vec1[3];
float vec2[3];
float uVec1[2];
float uVec2[2];
std::vector<float> tanVec;
for (int i = 0; i < nrOfVerts; i += 3)
{
vec1[0] = Positions[i + 1][0] - Positions[i][0];
vec1[1] = Positions[i + 1][1] - Positions[i][1];
vec1[2] = Positions[i + 1][2] - Positions[i][2];
vec2[0] = Positions[i + 2][0] - Positions[i][0];
vec2[1] = Positions[i + 2][1] - Positions[i][1];
vec2[2] = Positions[i + 2][2] - Positions[i][2];
uVec1[0] = UV[i + 1][0] - UV[i][0];
uVec1[1] = UV[i + 1][1] - UV[i][1];
uVec2[0] = UV[i + 2][0] - UV[i][0];
uVec2[1] = UV[i + 2][1] - UV[i][1];
float denominator = (uVec1[0] * uVec2[1]) - (uVec1[1] * uVec2[0]);
float someFloat = 1.0f / denominator;
dVec1[0] = vec1[0] * uVec2[1];
dVec1[1] = vec1[1] * uVec2[1];
dVec1[2] = vec1[2] * uVec2[1];
dVec2[0] = vec2[0] * uVec1[1];
dVec2[1] = vec2[1] * uVec1[1];
dVec2[2] = vec2[2] * uVec1[1];
tan[0] = dVec1[0] - dVec2[0];
tan[1] = dVec1[1] - dVec2[1];
tan[2] = dVec1[2] - dVec2[2];
tan[0] = tan[0] * someFloat;
tan[1] = tan[1] * someFloat;
tan[2] = tan[2] * someFloat;
for (int j = 0; j < 3; j++)
{
for (int x = 0; x < 3; x++)
{
tanVec.push_back(tan[x]);
}
}
//readable_file << i << ": Tan: X " << tan[0] << " Y " << tan[1] << " Z " << tan[2] << "\n";
}
for (int i = 0; i < nrOfVerts; i++)
{
//TODO READ/WRITE FLOAT INSTEAD DOUBLES->PAIR WITH ENGINE
float temp[4];
unsigned int tempWeights[4];
for (int j = 0; j < 4; j++)
{
tempWeights[j] = skin_bound_vertices[i].influencing_joint[j];
}
COPY_DOUBLE_FLOAT(3, skin_bound_vertices[i].vertex_position, temp);
outfile.write((const char*)&skin_bound_vertices[i].vertex_position[0], sizeof(float));
outfile.write((const char*)&skin_bound_vertices[i].vertex_position[1], sizeof(float));
outfile.write((const char*)&skin_bound_vertices[i].vertex_position[2], sizeof(float));
readable_file << i << ": Position: X " << temp[0] << " Y " << temp[1] << " Z " << temp[2] << "\n";
COPY_DOUBLE_FLOAT(2, UV[i], temp);
outfile.write((const char*)&skin_bound_vertices[i].vertex_UVCoord[0], sizeof(float));
outfile.write((const char*)&skin_bound_vertices[i].vertex_UVCoord[1], sizeof(float));
readable_file << i << ": UV: U " << temp[0] << "V " << temp[1] << "\n";
COPY_DOUBLE_FLOAT(3, normals[i], temp);
outfile.write((const char*)&skin_bound_vertices[i].vertex_normal[0], sizeof(float));
outfile.write((const char*)&skin_bound_vertices[i].vertex_normal[1], sizeof(float));
outfile.write((const char*)&skin_bound_vertices[i].vertex_normal[2], sizeof(float));
readable_file << i << ": Normals: X " << skin_bound_vertices[i].vertex_normal[0] << " Y " << skin_bound_vertices[i].vertex_normal[1] << " Z " << skin_bound_vertices[i].vertex_normal[2] << "\n";
auto first = tanVec.begin();
auto last = tanVec.begin() + 3;
std::vector<float> x(first, last);
tanVec.erase(first, last);
outfile.write((const char*)&x[0], sizeof(float));
outfile.write((const char*)&x[1], sizeof(float));
outfile.write((const char*)&x[2], sizeof(float));
readable_file << i << ": tan: X " << x[0] << " Y " << x[1] << " Z " << x[2] << "\n";
outfile.write((const char*)&tempWeights[0], sizeof(unsigned int));
outfile.write((const char*)&tempWeights[1], sizeof(unsigned int));
outfile.write((const char*)&tempWeights[2], sizeof(unsigned int));
outfile.write((const char*)&tempWeights[3], sizeof(unsigned int));
COPY_DOUBLE_FLOAT(4, skin_bound_vertices[i].joint_weights, temp);
outfile.write((const char*)&temp[0], sizeof(float));
outfile.write((const char*)&temp[1], sizeof(float));
outfile.write((const char*)&temp[2], sizeof(float));
outfile.write((const char*)&temp[3], sizeof(float));
readable_file << i << ": Weights: 1: " << temp[0] << " 2: " << temp[1] << " 3: " << temp[2] << " 4: " << temp[3] << "\n";
readable_file << i << ": Influencing indices: 1: " << tempWeights[0] << " 2: " << tempWeights[1] << " 3: " << tempWeights[2] << " 4: " << tempWeights[3] << "\n";
}
readable_file.close();
outfile.close();
}
return true;
}
bool Converter::createMeshFiles(int nrOfVertices, std::vector<FbxVector4>Positions, std::vector<FbxVector4>normals, std::vector<FbxVector2>UV, const char* node_name)
{
int nrOfVerts = nrOfVertices;
const char * temp = "_Mesh";
std::string filename = std::string(node_name) + "_Mesh.bin";
std::ofstream outfile(filename, std::ofstream::binary);
std::string readable_file_name = std::string(node_name) + "_Mesh.txt";
std::ofstream readable_file(readable_file_name);
std::cout << "Found mesh: " << node_name << " Nr of verts: " << nrOfVerts << "\n";
if (!outfile)
{
return false;
}
if (!readable_file)
{
return false;
}
readable_file << "NrOfverts: " << nrOfVerts << "\n";
readable_file.write((const char*)node_name, sizeof(char[100]));
readable_file << "\n";
outfile.write((const char*)&nrOfVerts, sizeof(int));
outfile.write((const char*)node_name, sizeof(const char[100]));
float tan[3];
float dVec1[3];
float dVec2[3];
float vec1[3];
float vec2[3];
float uVec1[2];
float uVec2[2];
std::vector<float> tanVec;
for (int i = 0; i < nrOfVerts; i += 3)
{
vec1[0] = Positions[i + 1][0] - Positions[i][0];
vec1[1] = Positions[i + 1][1] - Positions[i][1];
vec1[2] = Positions[i + 1][2] - Positions[i][2];
vec2[0] = Positions[i + 2][0] - Positions[i][0];
vec2[1] = Positions[i + 2][1] - Positions[i][1];
vec2[2] = Positions[i + 2][2] - Positions[i][2];
uVec1[0] = UV[i + 1][0] - UV[i][0];
uVec1[1] = UV[i + 1][1] - UV[i][1];
uVec2[0] = UV[i + 2][0] - UV[i][0];
uVec2[1] = UV[i + 2][1] - UV[i][1];
float denominator = (uVec1[0] * uVec2[1]) - (uVec1[1] * uVec2[0]);
float someFloat = 1.0f / denominator;
dVec1[0] = vec1[0] * uVec2[1];
dVec1[1] = vec1[1] * uVec2[1];
dVec1[2] = vec1[2] * uVec2[1];
dVec2[0] = vec2[0] * uVec1[1];
dVec2[1] = vec2[1] * uVec1[1];
dVec2[2] = vec2[2] * uVec1[1];
tan[0] = dVec1[0] - dVec2[0];
tan[1] = dVec1[1] - dVec2[1];
tan[2] = dVec1[2] - dVec2[2];
tan[0] = tan[0] * someFloat;
tan[1] = tan[1] * someFloat;
tan[2] = tan[2] * someFloat;
for (int j = 0; j < 3; j++)
{
for (int x = 0; x < 3; x++)
{
tanVec.push_back(tan[x]);
}
}
//readable_file << i << ": Tan: X " << tan[0] << " Y " << tan[1] << " Z " << tan[2] << "\n";
}
int a = tanVec.size();
for (int i = 0; i < nrOfVerts; i++)
{
float temp[3];
COPY_DOUBLE_FLOAT(3, Positions[i], temp);
outfile.write((const char*)&temp[0], sizeof(float));
outfile.write((const char*)&temp[1], sizeof(float));
outfile.write((const char*)&temp[2], sizeof(float));
readable_file << i << ": Position: X " << temp[0] << " Y " << temp[1] << " Z " << temp[2] << "\n";
COPY_DOUBLE_FLOAT(2, UV[i], temp);
outfile.write((const char*)&temp[0], sizeof(float));
outfile.write((const char*)&temp[1], sizeof(float));
readable_file << i << ": UV: U " << temp[0] << "V " << temp[1] << "\n";
COPY_DOUBLE_FLOAT(3, normals[i], temp);
outfile.write((const char*)&temp[0], sizeof(float));
outfile.write((const char*)&temp[1], sizeof(float));
outfile.write((const char*)&temp[2], sizeof(float));
readable_file << i << ": Normals: X " << temp[0] << " Y " << temp[1] << " Z " << temp[2] << "\n";
auto first = tanVec.begin();
auto last = tanVec.begin() + 3;
std::vector<float> x(first, last);
tanVec.erase(first, last);
outfile.write((const char*)&x[0], sizeof(float));
outfile.write((const char*)&x[1], sizeof(float));
outfile.write((const char*)&x[2], sizeof(float));
readable_file << i << ": tan: X " << x[0] << " Y " << x[1] << " Z " << x[2] << "\n";
}
readable_file.close();
outfile.close();
return true;
}
void Converter::getNames(FbxNode * scene_node)
{
printf("Node name:\t%s \t", scene_node->GetName());
printf("Node type:\t%s\n", scene_node->GetTypeName());
}
bool Converter::getSceneAnimationData(FbxNode * scene_node, std::vector<std::vector<Transform>> &transform_vector)
{
FbxScene * scene = sdk_scene;
FbxAnimStack* anim_stack = scene->GetCurrentAnimationStack();
FbxAnimLayer* anim_layer = anim_stack->GetMember<FbxAnimLayer>();
FbxAnimCurve* anim_curve_rotY = scene_node->LclRotation.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_Y);
if (anim_curve_rotY)
{
std::vector<Transform> transform_temp;
std::vector<FbxVector4> temp_translations;
std::vector<FbxVector4> temp_rotations;
std::vector<FbxVector4> temp_scaling;
FbxAnimCurve* anim_curve_rotZ = scene_node->LclRotation.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_Z);
FbxAnimCurve* anim_curve_rotX = scene_node->LclRotation.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_X);
FbxAnimCurve* anim_curve_translateY = scene_node->LclTranslation.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_Y);
FbxAnimCurve* anim_curve_translateX = scene_node->LclTranslation.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_X);
FbxAnimCurve* anim_curve_translateZ = scene_node->LclTranslation.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_Z);
FbxAnimCurve* anim_curve_scaleY = scene_node->LclScaling.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_Y);
FbxAnimCurve* anim_curve_scaleX = scene_node->LclScaling.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_X);
FbxAnimCurve* anim_curve_scaleZ = scene_node->LclScaling.GetCurve(anim_layer, FBXSDK_CURVENODE_COMPONENT_Z);
std::vector<FbxAMatrix> matrices;
FbxAMatrix matrix;
for (int i = 0; i < anim_curve_rotY->KeyGetCount(); i++)
{
FbxVector4 translation((double)anim_curve_translateX->KeyGetValue(i), (double)anim_curve_translateY->KeyGetValue(i), (double)anim_curve_translateZ->KeyGetValue(i), 1);
FbxVector4 rotation((double)anim_curve_rotX->KeyGetValue(i), (double)anim_curve_rotY->KeyGetValue(i), (double)anim_curve_rotZ->KeyGetValue(i), 0);
FbxVector4 scale((double)anim_curve_scaleX->KeyGetValue(i), (double)anim_curve_scaleY->KeyGetValue(i), (double)anim_curve_scaleZ->KeyGetValue(i), 0);
Transform transform_to_push_back;
transform_to_push_back.transform_position[0] = (float)anim_curve_translateX->KeyGetValue(i);
transform_to_push_back.transform_position[1] = (float)anim_curve_translateY->KeyGetValue(i);
transform_to_push_back.transform_position[2] = (float)anim_curve_translateZ->KeyGetValue(i);
transform_to_push_back.transform_rotation[0] = (float)anim_curve_rotX->KeyGetValue(i);
transform_to_push_back.transform_rotation[1] = (float)anim_curve_rotY->KeyGetValue(i);
transform_to_push_back.transform_rotation[2] = (float)anim_curve_rotZ->KeyGetValue(i);
transform_to_push_back.transform_scale[0] = (float)anim_curve_scaleX->KeyGetValue(i);
transform_to_push_back.transform_scale[1] = (float)anim_curve_scaleY->KeyGetValue(i);
transform_to_push_back.transform_scale[2] = (float)anim_curve_scaleZ->KeyGetValue(i);
transform_temp.push_back(transform_to_push_back);
matrix.SetTRS(translation, rotation, scale);
}
transform_vector.push_back(transform_temp);
}
int yo = scene_node->GetChildCount();
for (int i = 0; i < scene_node->GetChildCount(); i++)
{
getSceneAnimationData(scene_node->GetChild(i), transform_vector);
}
return true;
}
void PrintMatrix(FbxAMatrix& matrix)
{
auto mat = matrix.Double44();
for (int col = 0; col < 4; col++)
{
for (int row = 0; row < 4; row++)
{
std::cout << mat[col][row] << " ";
}
std::cout << std::endl;
}
}
bool Converter::createSkeletonFile(std::vector<std::string> names, std::vector<FbxAMatrix> joint_matrices, int nrOfJoints, std::vector<FbxNode*> parent_name_list)
{
const char * temp = "_Skeleton";
std::string filename = std::string(EXPORT_DIRECTORY) + std::string(names[0]) + "_Skeleton.bin";
std::ofstream outfile(filename, std::ofstream::binary);
std::string readable_file_name = std::string(EXPORT_DIRECTORY) + std::string(names[0]) + "_Skeleton.txt";
std::ofstream readable_file(readable_file_name);
std::cout << "Found Skeleton: " << names[0] << "_Skeleton! Number of joints in skeleton: " << nrOfJoints << std::endl;
std::vector<int> parent_index_vector(nrOfJoints);
std::vector<std::string> tempParentNames;
for (int i = 0; i < nrOfJoints; i++)
{
tempParentNames.push_back(parent_name_list[i]->GetParent()->GetName());
}
parent_index_vector[0] = 0;
for (int i = 0; i < nrOfJoints; i++)
{
for (int j = 0; j < nrOfJoints; j++)
{
if(names[j] == tempParentNames[i])
parent_index_vector[i] = j;
}
}
std::vector<FbxAMatrix> tempMultiplied;
for (int i = 0; i < joint_matrices.size(); i++)
{
FbxAMatrix temp = joint_matrices[i];
tempMultiplied.push_back(temp);
}
std::cout << "Matrices: " << std::endl;
for (int i = 0; i < tempMultiplied.size(); i++)
{
//std::cout << "ORIENTATION!: ";
//std::cout << "X: " << tempMultiplied[i].GetR()[0] << " Y: " << tempMultiplied[i].GetR()[1] << " Z: " << tempMultiplied[i].GetR()[2] << std::endl;
//std::cout << "tX: " << tempMultiplied[i].GetT()[0] << " tY: " << tempMultiplied[i].GetT()[1] << " tZ: " << tempMultiplied[i].GetT()[2] << std::endl;
PrintMatrix(tempMultiplied[i]);
}
printf("Joint names depth first:\n");
std::cout << names[0] << std::endl;
std::cout << nrOfJoints << std::endl;
readable_file << nrOfJoints << "\n";
const char * nameForBinary = names[0].c_str();
outfile.write((const char*)&nrOfJoints, sizeof(int));
outfile.write((const char*)nameForBinary, sizeof(char[100]));
Transform temp_transform;
COPY_DOUBLE_FLOAT(3, joint_matrices[0].GetS(), temp_transform.transform_scale);
COPY_DOUBLE_FLOAT(3, joint_matrices[0].GetT(), temp_transform.transform_position);
COPY_DOUBLE_FLOAT(3, joint_matrices[0].GetR(), temp_transform.transform_rotation);
outfile.write((const char*)nameForBinary, sizeof(char[100]));
outfile.write((const char*)&temp_transform, sizeof(Transform));
outfile.write((const char*)&parent_index_vector[0], sizeof(unsigned int));
readable_file << names[0] << "\n";
readable_file << " Rotation: ";
readable_file << temp_transform.transform_rotation[0] << " ";
readable_file << temp_transform.transform_rotation[1] << " ";
readable_file << temp_transform.transform_rotation[2] << " Position: ";
readable_file << temp_transform.transform_position[0] << " ";
readable_file << temp_transform.transform_position[1] << " ";
readable_file << temp_transform.transform_position[2] << " Scale: ";
readable_file << temp_transform.transform_scale[0] << " ";
readable_file << temp_transform.transform_scale[1] << " ";
readable_file << temp_transform.transform_scale[2] << " \n";
readable_file << "Parent index: " << names[parent_index_vector[0]] << "\n";
for (int i = 1; i < nrOfJoints; i++)
{
COPY_DOUBLE_FLOAT(3, joint_matrices[i].GetS(), temp_transform.transform_scale);
COPY_DOUBLE_FLOAT(3, joint_matrices[i].GetT(), temp_transform.transform_position);
COPY_DOUBLE_FLOAT(3, joint_matrices[i].GetR(), temp_transform.transform_rotation);
readable_file << names[i] << "\n";
readable_file << " Rotation: ";
//TODO
{
//{
// temp_transform.transform_rotation[0] = 0.0;
// temp_transform.transform_rotation[1] = 0.0;
// temp_transform.transform_rotation[2] = 0.0;
//}
//if (i == 2)
//{
// temp_transform.transform_position[0] = -2;
// temp_transform.transform_position[1] = 0;
//}
}
readable_file << (float)temp_transform.transform_rotation[0] << " ";
readable_file << (float)temp_transform.transform_rotation[1] << " ";
readable_file << (float)temp_transform.transform_rotation[2] << " Position ";
readable_file << (float)temp_transform.transform_position[0] << " ";
readable_file << (float)temp_transform.transform_position[1] << " ";
readable_file << (float)temp_transform.transform_position[2] << " Scale: ";
readable_file << (float)temp_transform.transform_scale[0] << " ";
readable_file << (float)temp_transform.transform_scale[1] << " ";
readable_file << (float)temp_transform.transform_scale[2] << " \n";
readable_file << "Parent index: " << names[parent_index_vector[i]] << "\n";
const char * nameForBinary = names[i].c_str();
outfile.write((const char*)nameForBinary, sizeof(char[100]));
outfile.write((const char*)&temp_transform, sizeof(Transform));
int temp = parent_index_vector[i];
outfile.write((const char*)&temp, sizeof(int));
std::cout << "namn";
std::cout << nameForBinary << std::endl;
}
outfile.close();
readable_file.close();
return true;
}
void Converter::storeChildren(std::vector<std::string>* vector, FbxNode* scene_node)
{
vector->push_back(scene_node->GetName());
for (int i = 0; i < scene_node->GetChildCount(); i++)
{
storeChildren(vector, scene_node->GetChild(i));
}
}
void Converter::createAnimationFile(std::vector<std::vector<Transform>> keys)
{
const char * temp = "Animation";
std::string filename = std::string(EXPORT_DIRECTORY) + std::string("ANIMATION") + "_ANIMATION.bin";
std::ofstream outfile(filename, std::ofstream::binary);
std::string readable_file_name = std::string(EXPORT_DIRECTORY) + std::string("ANIMATION") + "_ANIMATION.txt";
std::ofstream readable_file(readable_file_name);
int nrOf = keys[0].size();
outfile.write((const char*)&nrOf, sizeof(unsigned int));
readable_file << keys[0].size() << "\n";
Transform temp_transform;
for (int i = 0; i < keys[0].size(); i++)
{
for (int j = 0; j < keys.size(); j++)
{
COPY_DOUBLE_FLOAT(3, keys[j][i].transform_position, temp_transform.transform_position);
COPY_DOUBLE_FLOAT(3, keys[j][i].transform_rotation, temp_transform.transform_rotation);
COPY_DOUBLE_FLOAT(3, keys[j][i].transform_scale, temp_transform.transform_scale);
outfile.write((const char*)&temp_transform.transform_position[0], sizeof(float));
outfile.write((const char*)&temp_transform.transform_position[1], sizeof(float));
outfile.write((const char*)&temp_transform.transform_position[2], sizeof(float));
outfile.write((const char*)&temp_transform.transform_rotation[0], sizeof(float));
outfile.write((const char*)&temp_transform.transform_rotation[1], sizeof(float));
outfile.write((const char*)&temp_transform.transform_rotation[2], sizeof(float));
outfile.write((const char*)&temp_transform.transform_scale[0], sizeof(float));
outfile.write((const char*)&temp_transform.transform_scale[1], sizeof(float));
outfile.write((const char*)&temp_transform.transform_scale[2], sizeof(float));
readable_file << "Translation: " << "X:\t" << (float)keys[j][i].transform_position[0] << " Y:\t" << (float)keys[j][i].transform_position[1] << " Z:\t" << (float)keys[j][i].transform_position[2] << "\n";
readable_file << "Rotation: " << "X:\t" << (float)keys[j][i].transform_rotation[0] << " Y:\t" << (float)keys[j][i].transform_rotation[1] << " Z:\t" << (float)keys[j][i].transform_rotation[2] << "\n";
readable_file << "Scale: " << "X:\t" << (float)keys[j][i].transform_scale[0] << " Y:\t" << (float)keys[j][i].transform_scale[1] << " Z:\t" << (float)keys[j][i].transform_scale[2] << "\n";
}
}
outfile.close();
readable_file.close();
}
//void Converter::getCamera(FbxNode * scene_node)
//{
// FbxCamera * cam = scene_node->GetCamera();
// Camera camera;
//
// if (cam)
// {
//
// for (int i = 0; i < 100; i++)
// {
// camera.cam_name[i] = cam->GetName()[i];
// std::cout << camera.cam_name[i];
// }
// std::cout << std::endl;
//
// FbxDouble3 translation = scene_node->LclTranslation.Get();
// FbxDouble3 rotation = scene_node->LclRotation.Get();
// FbxDouble3 scaling = scene_node->LclScaling.Get();
//
// camera.cam_transform.transform_position[0] = (float)translation[0];
// camera.cam_transform.transform_position[1] = (float)translation[1];
// camera.cam_transform.transform_position[2] = (float)translation[2]; camera.cam_transform.transform_rotation[0] = (float)rotation[0];
// camera.cam_transform.transform_rotation[1] = (float)rotation[1];
// camera.cam_transform.transform_rotation[2] = (float)rotation[2];
//
// camera.cam_transform.transform_scale[0] = (float)scaling[0];
// camera.cam_transform.transform_scale[1] = (float)scaling[1];
// camera.cam_transform.transform_scale[2] = (float)scaling[2];
//
// std::cout << "Cam: Translation: X: " << camera.cam_transform.transform_position[0] << " Y: " << camera.cam_transform.transform_position[1] << " Z: " << camera.cam_transform.transform_position[2] << std::endl;
// std::cout << "Cam: Rotation: X: " << camera.cam_transform.transform_rotation[0] << " Y: " << camera.cam_transform.transform_rotation[1] << " Z: " << camera.cam_transform.transform_rotation[2] << std::endl;
// std::cout << "Cam: Scale: X: " << camera.cam_transform.transform_scale[0] << " Y: " << camera.cam_transform.transform_scale[1] << " Z: " << camera.cam_transform.transform_scale[2] << std::endl;
//
// camera.cam_FOV = cam->FieldOfView.Get();
//
//
// cameras.push_back(camera);
//
// }
//
// for (int i = 0; i < scene_node->GetChildCount(); i++)
// {
// getCamera(scene_node->GetChild(i));
// }
//
//}
//
//bool Converter::createCameraFiles(std::vector<Camera> camera)
//{
// const char * temp = "_Camera";
// std::string filename = std::string("CAMERAS") + "_Camera.bin";
// std::ofstream outfile(filename, std::ofstream::binary);
// std::string readable_file_name = std::string("CAMERAS") + "_Camera.txt";
// std::ofstream readable_file(readable_file_name);
// int nrOfCameras = camera.size();
// readable_file << nrOfCameras << "\n";
// outfile.write((const char*)&nrOfCameras, sizeof(unsigned int));
// for (int i = 0; i < camera.size(); i++)
// {
//
//
// if (!outfile)
// {
// return false;
// }
// if (!readable_file)
// {
// return false;
// }
//
// readable_file.write((const char*)camera[i].cam_name, sizeof(char[100]));
// readable_file << "\n";
//
// readable_file << "Position: X " << camera[i].cam_transform.transform_position[0] << " Y " << camera[i].cam_transform.transform_position[1] << " Z " << camera[i].cam_transform.transform_position[2] << "\n"
// "Rotation: X " << camera[i].cam_transform.transform_rotation[0] << " Y " << camera[i].cam_transform.transform_rotation[1] << " Y " << camera[i].cam_transform.transform_rotation[2] << "\n"
// "Scale: X " << camera[i].cam_transform.transform_scale[0] << " Y " << camera[i].cam_transform.transform_scale[1] << " Z " << camera[i].cam_transform.transform_scale[2] << "\n";
//
// outfile.write((const char*)camera[i].cam_name, sizeof(char[100]));
//
//
// outfile.write((const char*)&camera[i].cam_transform.transform_position[0], sizeof(float));
// outfile.write((const char*)&camera[i].cam_transform.transform_position[1], sizeof(float));
// outfile.write((const char*)&camera[i].cam_transform.transform_position[2], sizeof(float));
//
//
// outfile.write((const char*)&camera[i].cam_transform.transform_rotation[0], sizeof(float));
// outfile.write((const char*)&camera[i].cam_transform.transform_rotation[1], sizeof(float));
// outfile.write((const char*)&camera[i].cam_transform.transform_rotation[2], sizeof(float));
//
// outfile.write((const char*)&camera[i].cam_transform.transform_scale[0], sizeof(float));
// outfile.write((const char*)&camera[i].cam_transform.transform_scale[1], sizeof(float));
// outfile.write((const char*)&camera[i].cam_transform.transform_scale[2], sizeof(float));
//
//
// outfile.write((const char*)&camera[i].cam_FOV, sizeof(float));
//
//
//
// }
// readable_file.close();
// outfile.close();
//
// return true;
//}
//
//void Converter::getLight(FbxNode * scene_node)
//{
// FbxLight * light = scene_node->GetLight();
//
//
// if (light) {
// Light lightStruct;
// for(int i = 0; i < 100; i++)
// lightStruct.light_name[i] = scene_node->GetName()[i];
// //Transform
// FbxDouble3 translation = scene_node->LclTranslation.Get();
// FbxDouble3 rotation = scene_node->LclRotation.Get();
// FbxDouble3 scaling = scene_node->LclScaling.Get();
//
// lightStruct.light_transform.transform_position[0] = (float)translation.mData[0];
// lightStruct.light_transform.transform_position[1] = (float)translation.mData[1];
// lightStruct.light_transform.transform_position[2] = (float)translation.mData[2];
//
// lightStruct.light_transform.transform_rotation[0] = (float)rotation.mData[0];
// lightStruct.light_transform.transform_rotation[1] = (float)rotation.mData[1];
// lightStruct.light_transform.transform_rotation[2] = (float)rotation.mData[2];
//
// lightStruct.light_transform.transform_scale[0] = (float)scaling.mData[0];
// lightStruct.light_transform.transform_scale[1] = (float)scaling.mData[1];
// lightStruct.light_transform.transform_scale[2] = (float)scaling.mData[2];
//
// //Light
// lightStruct.light_color[0] = (float)light->Color.Get().mData[0];
// lightStruct.light_color[1] = (float)light->Color.Get().mData[1];
// lightStruct.light_color[2] = (float)light->Color.Get().mData[2];
// lightStruct.light_color[3] = (float)light->Intensity.Get() / 100.0;
//
//
//
// lights.push_back(lightStruct);
// std::cout << light->GetName() << std::endl;
// }
//
// for (int i = 0; i < scene_node->GetChildCount(); i++)
// {
// getLight(scene_node->GetChild(i));
// }
//
//}
//
//bool Converter::createLightFile(std::vector<Light> lights)
//{
//
// const char * temp = "_Light";
// const char* node_name = "Lights file";
// std::string filename = std::string("LIGHTFILE") + "_Light.bin";
// std::ofstream outfile(filename, std::ofstream::binary);
// std::string readable_file_name = std::string(node_name) + "_Light.txt";
// std::ofstream readable_file(readable_file_name);
//
// int nrOfLights = lights.size();
// outfile.write((const char*)&nrOfLights, sizeof(unsigned int));
// readable_file << nrOfLights;
// if (!outfile)
// {
// printf("No file could be opened. Manager.cpp line 958");
// return false;
// }
// if (!readable_file)
// {
// printf("No file could be opened. Manager.cpp line 958");
// return false;
// }
//
// for (int i = 0; i < lights.size(); i++)
// {
// readable_file.write((const char*)lights[i].light_name, sizeof(char[100]));
// readable_file << "\n";
//
// readable_file << "Position: X " << lights[i].light_transform.transform_position[0] << " Y " << lights[i].light_transform.transform_position[1] << " Z " << lights[i].light_transform.transform_position[2] << "\n"
// "Rotation: X " << lights[i].light_transform.transform_rotation[0] << " Y " << lights[i].light_transform.transform_rotation[1] << " Z " << lights[i].light_transform.transform_rotation[2] << "\n"
// "Scale: X " << lights[i].light_transform.transform_scale[0] << " Y " << lights[i].light_transform.transform_scale[1] << " Z " << lights[i].light_transform.transform_scale[2] << "\n"
// "Color: R " << lights[i].light_color[0] << " G " << lights[i].light_color[1] << " B " << lights[i].light_color[2] << " Intensity " << lights[i].light_color[3] << "\n";
// outfile.write((const char*)lights[i].light_name, sizeof(const char[100]));
//
// outfile.write((const char*)&lights[i].light_transform.transform_position[0], sizeof(float));
// outfile.write((const char*)&lights[i].light_transform.transform_position[1], sizeof(float));
// outfile.write((const char*)&lights[i].light_transform.transform_position[2], sizeof(float));
//
// outfile.write((const char*)&lights[i].light_transform.transform_rotation[0], sizeof(float));
// outfile.write((const char*)&lights[i].light_transform.transform_rotation[1], sizeof(float));
// outfile.write((const char*)&lights[i].light_transform.transform_rotation[2], sizeof(float));
//
// outfile.write((const char*)&lights[i].light_transform.transform_scale[0], sizeof(float));
// outfile.write((const char*)&lights[i].light_transform.transform_scale[1], sizeof(float));
// outfile.write((const char*)&lights[i].light_transform.transform_scale[2], sizeof(float));
//
// outfile.write((const char*)&lights[i].light_color[0], sizeof(float));
// outfile.write((const char*)&lights[i].light_color[1], sizeof(float));
// outfile.write((const char*)&lights[i].light_color[2], sizeof(float));
// outfile.write((const char*)&lights[i].light_color[3], sizeof(float));
// }
//
// readable_file.close();
// outfile.close();
//
// return true;
//}
//
//bool Converter::createBlendShapeFiles(FbxMesh * mesh_node, FbxAnimLayer* anim_layer)
//{
//
// std::vector<std::vector<Vertex>> targets;
//
// //base shape
// std::vector<Vertex> base;
// for (int h = 0; h < mesh_node->GetControlPointsCount(); h++)
// {
// Vertex vertex;
// vertex.vertex_position[0] = mesh_node->GetControlPointAt(h).mData[0];
// vertex.vertex_position[1] = mesh_node->GetControlPointAt(h).mData[1];
// vertex.vertex_position[2] = mesh_node->GetControlPointAt(h).mData[2];
//
//
// FbxLayerElementArrayTemplate<FbxVector4>* nrms;
// mesh_node->GetNormals(&nrms);
// vertex.vertex_normal[0] = nrms->GetAt(h).mData[0];
// vertex.vertex_normal[1] = nrms->GetAt(h).mData[1];
// vertex.vertex_normal[2] = nrms->GetAt(h).mData[2];
//
// vertex.vertex_UVCoord[0] = 0;
// vertex.vertex_UVCoord[1] = 0;
// base.push_back(vertex);
// }
// targets.push_back(base);
//
//
// //other shapes
// int blendCount = mesh_node->GetDeformerCount(FbxDeformer::eBlendShape);
// for (int h = 0; h < blendCount; h++)
// {
// FbxBlendShape* mesh_blend_shape = (FbxBlendShape*)(mesh_node->GetDeformer(0, FbxDeformer::eBlendShape));
// if (mesh_blend_shape) {
// int channelCount = mesh_blend_shape->GetBlendShapeChannelCount();
// for (int i = 0; i < channelCount; i++)
// {
// FbxBlendShapeChannel *blendChannel = mesh_blend_shape->GetBlendShapeChannel(i);
// if (blendChannel) {
// FbxAnimCurve* animCurve = mesh_node->GetShapeChannel(h, i, anim_layer);
// if (!animCurve) continue;
//
// int keyCount = animCurve->KeyGetCount();
// for (int j = 0; j < keyCount; j++)
// {
// FbxAnimCurveKey key = animCurve->KeyGet(j);
// int value = key.GetValue();
//
//
// FbxShape* shape = blendChannel->GetTargetShape(j);
// if (shape) {
// int ctrlCount = shape->GetControlPointsCount();
// FbxVector4* controlPointsArr = shape->GetControlPoints();
//
// FbxLayerElementArrayTemplate<FbxVector4>* nrms;
// shape->GetNormals(&nrms);
//
//
// std::vector<Vertex> othershape;
// for (int h = 0; h < mesh_node->GetControlPointsCount(); h++)
// {
// Vertex vertex;
// vertex.vertex_position[0] = shape->GetControlPointAt(h).mData[0];
// vertex.vertex_position[1] = shape->GetControlPointAt(h).mData[1];
// vertex.vertex_position[2] = shape->GetControlPointAt(h).mData[2];
//
//
// FbxLayerElementArrayTemplate<FbxVector4>* nrms;
// shape->GetNormals(&nrms);
// vertex.vertex_normal[0] = nrms->GetAt(h).mData[0];
// vertex.vertex_normal[1] = nrms->GetAt(h).mData[1];
// vertex.vertex_normal[2] = nrms->GetAt(h).mData[2];
//
// vertex.vertex_UVCoord[0] = 0;
// vertex.vertex_UVCoord[1] = 0;
// othershape.push_back(vertex);
// }
// targets.push_back(othershape);
//
//
//
// }
// }
//
//
// }
// }
// }
//
// }
//
//
//
// const char * temp = "_BlendShape";
// const char* node_name = mesh_node->GetName();
// std::string filename = std::string(node_name) + "_BlendShape.bin";
// std::ofstream outfile(filename, std::ofstream::binary);
// std::string readable_file_name = std::string(node_name) + "_BlendShape.txt";
// std::ofstream readable_file(readable_file_name);
//
// if (!outfile)
// {
// return false;
// }
// if (!readable_file)
// {
// return false;
// }
//
//
// //Write files
// readable_file.write((const char*)node_name, sizeof(char[100]));
// readable_file << "\n";
//
// for (int h = 0; h < targets.size(); h++)
// {
// readable_file << "Shape " << h << std::endl;
//
// for (int index = 0; index < targets[h].size(); index++)
// {
// readable_file << "Position x" << targets[h][index].vertex_position[0] << " y" << targets[h][index].vertex_position[1] << " z" << targets[h][index].vertex_position[2] << std::endl;
// readable_file << "uv u" << targets[h][index].vertex_UVCoord[0] << " v" << targets[h][index].vertex_UVCoord[1] << std::endl;
// readable_file << "normal x" << targets[h][index].vertex_normal[0] << " y" << targets[h][index].vertex_normal[1] << " z" << targets[h][index].vertex_normal[2] << std::endl;
//
// }
//
// }
//
// //nrOfShapes
// int shapes = targets.size();
// outfile.write((const char*)node_name, sizeof(char[100]));
// int verts = targets[0].size() * shapes;
// outfile.write((const char*)&verts, sizeof(int));
// for (int h = 0; h < targets.size(); h++)
// {
//
// //nrOfVertices
// for (int index = 0; index < targets[h].size(); index++)
// {
// outfile.write((const char*)&targets[h][index].vertex_position[0], sizeof(float));
// outfile.write((const char*)&targets[h][index].vertex_position[1], sizeof(float));
// outfile.write((const char*)&targets[h][index].vertex_position[2], sizeof(float));
//
// outfile.write((const char*)&targets[h][index].vertex_UVCoord[0], sizeof(float));
// outfile.write((const char*)&targets[h][index].vertex_UVCoord[1], sizeof(float));
//
// outfile.write((const char*)&targets[h][index].vertex_normal[0], sizeof(float));
// outfile.write((const char*)&targets[h][index].vertex_normal[1], sizeof(float));
// outfile.write((const char*)&targets[h][index].vertex_normal[2], sizeof(float));
//
//
//
// }
//
// }
//
// readable_file.close();
// outfile.close();
//
// std::cout << "Done" << std::endl;
//
// return false;
//}
//
//void Converter::getCustomAttributes(FbxNode* scene_node)
//{
//#pragma warning(disable:4996)
// FbxProperty property = scene_node->GetFirstProperty();
// int i = 0;
// std::string file;
// CustomAttributes customAttributes;
//
// while (property.IsValid())
// {
// if (i > 70)
// {
// switch (property.GetPropertyDataType().GetType())
// {
// case eFbxBool:
// customAttributes.customBool = property.Get<FbxBool>();
// break;
//
// case eFbxDouble:
// customAttributes.customFloat = property.Get<FbxFloat>();
// break;
//
// case eFbxInt:
// customAttributes.customInt = property.Get<FbxInt>();
// break;
//
// case eFbxEnum:
// customAttributes.customEnum = property.Get<FbxEnum>();
// break;
//
// case eFbxDouble3:
// customAttributes.customVector[0] = property.Get<FbxDouble3>()[0];
// customAttributes.customVector[1] = property.Get<FbxDouble3>()[1];
// customAttributes.customVector[2] = property.Get<FbxDouble3>()[2];
// break;
//
// case eFbxString:
// std::strcpy(customAttributes.customString, property.Get<FbxString>());
// break;
//
// default:
// std::cout << "def \n";
// break;
// }
//
//
// file += "Mesh: " + std::string(scene_node->GetName()) + "\n" + "Custom Attribut " + std::to_string(i) + "\n" +
// "Display Name: " + std::string(property.GetLabel()) + "\n" + "Type: " + std::string(property.GetPropertyDataType().GetName()) + "\n";
//
// if (property.GetPropertyDataType().GetType() == eFbxDouble3)
// {
// FbxDouble3 vector = property.Get<FbxDouble3>();
// file += "Vector Value X: " + std::to_string(vector[0]) + "\n";
// file += "Vector Value y: " + std::to_string(vector[1]) + "\n";
// file += "Vector Value z: " + std::to_string(vector[2]) + "\n";
// }
// else
// {
// file += "Value: " + property.Get<FbxString>() + "\n";
// }
//
// file += "\n\n";
// }
// i++;
// property = scene_node->GetNextProperty(property);
// }
// std::cout << file;
//
// for (int i = 0; i < scene_node->GetChildCount(); i++)
// {
// getCustomAttributes(scene_node->GetChild(i));
// }
// customAttributes.nrOfCustomAttributes = (i - 70);
// createCustomAttributesFiles(scene_node, file, customAttributes);
//
// return;
//}
//bool Converter::createCustomAttributesFiles(FbxNode* scene_node, std::string data, CustomAttributes customAttributes)
//{
// const char * temp = "_CustomAttributes";
// const char * node_name = scene_node->GetName();
// std::string filename = std::string(node_name) + "_CustomAttributes.bin";
// std::ofstream outfile(filename, std::ofstream::binary);
// std::string readable_file_name = std::string(node_name) + "_CustomAttributes.txt";
// std::ofstream readable_file(readable_file_name);
//
// if (!outfile)
// {
// return false;
// }
//
// if (!readable_file)
// {
// return false;
// }
//
// readable_file << data;
//
// outfile.write((const char*)&customAttributes.customBool, sizeof(bool));
// outfile.write((const char*)&customAttributes.customFloat, sizeof(float));
// outfile.write((const char*)&customAttributes.customInt, sizeof(int));
// outfile.write((const char*)&customAttributes.customEnum, sizeof(int));
// outfile.write((const char*)&customAttributes.customVector, sizeof(float[3]));
// outfile.write((const char*)&customAttributes.customString, sizeof(char[128]));
//
//
// readable_file.close();
// outfile.close();
//
// return true;
//}
//
//void Converter::createMaterialsFile(FbxNode* scene_node)
//{
//
// if (!scene_node)
// {
// std::cout << "Error in printMaterials \n";
// return;
// }
// else
// {
// MaterialHeader MatHead;
// std::vector<Material> MatVector;
// FbxSurfaceMaterial* tempMaterial;
// int nrOfChilds = scene_node->GetChildCount();
// FbxPropertyT<FbxDouble3> Double3Variable;
// FbxPropertyT<FbxDouble> Double1Variable;
// FbxPropertyT<FbxCharPtr> CharPointerVariable;
// FbxColor ColorVariable;
// int nrOfTextures = 0, nrOfMaterials = 0;
//
//
// const char* bumpName = nullptr;
// const char* TextureName = nullptr;
//
// //Getting the information about FBX.
// FbxGeometry *scene_mesh = scene_node->GetMesh();
//
// FbxNode* TempNode = scene_node;
//
// std::string filename = (std::string)TempNode->GetName() + "_Material.bin";
// std::ofstream outfile(filename, std::ofstream::binary);
//
// std::string readable_file_name = (std::string)TempNode->GetName() + "_Material.txt";
// std::ofstream readable_file(readable_file_name);
//
//
// printf("\nMesh found: {%s}, It has [%d] material(s)\n\n", TempNode->GetName(), TempNode->GetMaterialCount());
// nrOfMaterials = TempNode->GetMaterialCount();
// nrOfTextures = sdk_scene->GetTextureCount();
//
// MatHead.material_nrOfMaterials = nrOfMaterials;
// MatHead.material_nrOfTextures = nrOfTextures;
//
// readable_file << "NrOfMaterials: " << nrOfMaterials << " in Mesh.\n";
// readable_file << "NrOfTextures: " << nrOfTextures << " in scene.\n";
// outfile.write((const char*)&nrOfMaterials, sizeof(int));
// outfile.write((const char*)&nrOfTextures, sizeof(int));
//
// std::cout << "NrOfMaterials: " << nrOfMaterials << " in Mesh.\n";
// std::cout << "NrOfTextures: " << nrOfTextures << " in scene.\n";
//
// //MATERIAL
// for (int i = 0; i < nrOfMaterials; i++)
// {
// FbxSurfaceMaterial *tempMaterial = TempNode->GetMaterial(i);
// Material NewMaterial = { 0,0,0,0,0,0,0 };
//
// if (tempMaterial->GetClassId().Is(FbxSurfacePhong::ClassId))
// {
// std::cout << "\nMaterial(" << i << ")" << "is an PHONG" << " in scene.\n";
// std::cout << "\nThis material is holding these variables:\n";
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->AmbientFactor;
// std::cout << "AmbientFactor: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.AmbientFactor = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Ambient;
// std::cout << "AmbientColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.AmbientColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.AmbientColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.AmbientColor[2] = (float)Double3Variable.Get()[2];
//
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->DiffuseFactor;
// std::cout << "DiffuseFactor: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.DiffuseFactor = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Diffuse;
// std::cout << "DiffuseColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.DiffuseColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.DiffuseColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.DiffuseColor[2] = (float)Double3Variable.Get()[2];
//
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->EmissiveFactor;
// std::cout << "EmissiveFactor: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.EmissiveFactor = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Emissive;
// std::cout << "EmissiveColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.EmissiveColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.EmissiveColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.EmissiveColor[2] = (float)Double3Variable.Get()[2];
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->TransparencyFactor;
// std::cout << "Transparency(Factor): " << (float)Double1Variable.Get() << "\n";
// NewMaterial.Transparency = (float)Double1Variable.Get();
//
// //Phong Only
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->SpecularFactor;
// std::cout << "SpecularFactor: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.SpecularFactor = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Specular;
// std::cout << "SpecularColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.SpecularColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.SpecularColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.SpecularColor[2] = (float)Double3Variable.Get()[2];
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->Shininess;
// std::cout << "Shininess(Cosine Power): " << (float)Double1Variable.Get() << "\n";
// NewMaterial.Shininess = (float)Double1Variable.Get();
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->ReflectionFactor;
// std::cout << "Reflection: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.Reflection = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Reflection;
// std::cout << "ReflectionColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.ReflectionColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.ReflectionColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.ReflectionColor[2] = (float)Double3Variable.Get()[2];
//
// for (unsigned int j = 0; j < nrOfTextures; j++)
// {
// FbxProperty propertyS;
// propertyS = tempMaterial->FindProperty(FbxSurfacePhong::sBump);
// FbxTexture *testTextureBump = propertyS.GetSrcObject<FbxTexture>();
//
// if (testTextureBump)
// {
// FbxFileTexture* TestFileTexture = FbxCast<FbxFileTexture>(testTextureBump);
// bumpName = TestFileTexture->GetRelativeFileName();
// const char* temp = TestFileTexture->GetFileName();
// for (unsigned int d = 0; d < strlen(temp); d++)
// {
// NewMaterial.BumpPath[d] = temp[d];
// }
// }
// else
// {
// const char* temp = "Empty.";
// for (unsigned int o = 0; o < strlen(temp); o++)
// {
// NewMaterial.BumpPath[o] = temp[o];
// }
// }
//
// propertyS = tempMaterial->FindProperty(FbxSurfacePhong::sDiffuse);
// FbxTexture *testTexture = propertyS.GetSrcObject<FbxTexture>();
//
// if (testTexture)
// {
// FbxFileTexture* TestFileTexture = FbxCast<FbxFileTexture>(testTexture);
// TextureName = TestFileTexture->GetRelativeFileName();
// const char* temp = TestFileTexture->GetFileName();
// for (unsigned int d = 0; d < strlen(temp); d++)
// {
// NewMaterial.TexturePath[d] = temp[d];
// }
// }
// else
// {
// const char* temp = "Empty.";
// for (unsigned int o = 0; o < strlen(temp); o++)
// {
// NewMaterial.TexturePath[o] = temp[o];
// }
// }
// }
//
// std::cout << std::endl;
// MatVector.push_back(NewMaterial);
// }
// else if (tempMaterial->GetClassId().Is(FbxSurfaceLambert::ClassId))
// {
// std::cout << "\nMaterial(" << i << ")" << "is an LAMBERT" << " in scene.\n";
// std::cout << "\nThis material is holding these variables:\n";
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->AmbientFactor;
// std::cout << "AmbientFactor: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.AmbientFactor = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Ambient;
// std::cout << "AmbientColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.AmbientColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.AmbientColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.AmbientColor[2] = (float)Double3Variable.Get()[2];
//
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->DiffuseFactor;
// std::cout << "DiffuseFactor: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.DiffuseFactor = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Diffuse;
// std::cout << "DiffuseColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.DiffuseColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.DiffuseColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.DiffuseColor[2] = (float)Double3Variable.Get()[2];
//
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->EmissiveFactor;
// std::cout << "EmissiveFactor: " << (float)Double1Variable.Get() << "\n";
// NewMaterial.EmissiveFactor = (float)Double1Variable.Get();
// Double3Variable = ((FbxSurfacePhong *)tempMaterial)->Emissive;
// std::cout << "EmissiveColor: " << (float)Double3Variable.Get()[0] << ", " << (float)Double3Variable.Get()[1] << ", " << (float)Double3Variable.Get()[2] << "\n";
// NewMaterial.EmissiveColor[0] = (float)Double3Variable.Get()[0]; NewMaterial.EmissiveColor[1] = (float)Double3Variable.Get()[1]; NewMaterial.EmissiveColor[2] = (float)Double3Variable.Get()[2];
//
// Double1Variable = ((FbxSurfacePhong *)tempMaterial)->TransparencyFactor;
// std::cout << "Transparency(Factor): " << (float)Double1Variable.Get() << "\n";
// NewMaterial.Transparency = (float)Double1Variable.Get();
//
// NewMaterial.SpecularFactor = 0;
// NewMaterial.SpecularColor[0] = 0; NewMaterial.SpecularColor[1] = 0; NewMaterial.SpecularColor[2] = 0;
// NewMaterial.Shininess = 0;
// NewMaterial.Reflection = 0;
// NewMaterial.ReflectionColor[0] = 0; NewMaterial.ReflectionColor[1] = 0; NewMaterial.ReflectionColor[2] = 0;
//
// for (unsigned int j = 0; j < nrOfTextures; j++)
// {
// FbxProperty propertyS;
// propertyS = tempMaterial->FindProperty(FbxSurfacePhong::sBump);
// FbxTexture *testTextureBump = propertyS.GetSrcObject<FbxTexture>();
//
// if (testTextureBump)
// {
// FbxFileTexture* TestFileTexture = FbxCast<FbxFileTexture>(testTextureBump);
// bumpName = TestFileTexture->GetRelativeFileName();
// const char* temp = TestFileTexture->GetFileName();
// for (unsigned int d = 0; d < strlen(temp); d++)
// {
// NewMaterial.BumpPath[d] = temp[d];
// }
// }
// else
// {
// const char* temp = "Empty.";
// for (unsigned int o = 0; o < strlen(temp); o++)
// {
// NewMaterial.BumpPath[o] = temp[o];
// }
// }
//
// propertyS = tempMaterial->FindProperty(FbxSurfacePhong::sDiffuse);
// FbxTexture *testTexture = propertyS.GetSrcObject<FbxTexture>();
//
// if (testTexture)
// {
// FbxFileTexture* TestFileTexture = FbxCast<FbxFileTexture>(testTexture);
// TextureName = TestFileTexture->GetRelativeFileName();
// const char* temp = TestFileTexture->GetFileName();
// for (unsigned int d = 0; d < strlen(temp); d++)
// {
// NewMaterial.TexturePath[d] = temp[d];
// }
// }
// else
// {
// const char* temp = "Empty.";
// for (unsigned int o = 0; o < strlen(temp); o++)
// {
// NewMaterial.TexturePath[o] = temp[o];
// }
// }
// }
//
// std::cout << std::endl;
// MatVector.push_back(NewMaterial);
// }
// else
// {
// std::cout << "Material(" << i << ")" << "is an UNKNOWN" << " in scene.\n ERROR!";
// }
// }
//
//
//
// //Copying / moving files to the custom file folder.
// for (unsigned int y = 0; y < MatVector.size(); y++)
// {
// char NewFolderPathTexture[150];
// char NewFolderPathBump[150];
//
// if (TextureName)
// {
// GetCurrentDirectoryA(150, NewFolderPathTexture);
// strcat_s(NewFolderPathTexture, "/Materials&Textures/");
// std::string tempString = MatVector.at(y).TexturePath;
// tempString = getFileName(tempString.c_str());
// TextureName = tempString.c_str();
// strcat_s(NewFolderPathTexture, TextureName);
//
// if (CopyFile((const char*)&MatVector.at(y).TexturePath, (const char*)&NewFolderPathTexture, false))
// {
// std::cout << "Material(" << y + 1 << ") Copied Diffuse Texture File: Success!" << std::endl << std::endl;
// for (unsigned int i = 0; i < 150; i++)
// MatVector.at(y).TexturePath[i] = NewFolderPathTexture[i];
// }
// else
// {
// std::cout << "Material(" << y + 1 << ") Copied Diffuse Texture File: Failed!" << std::endl;
// }
// }
//
// if (bumpName)
// {
// GetCurrentDirectoryA(150, NewFolderPathBump);
// strcat_s(NewFolderPathBump, "/Materials&Textures/");
// std::string tempString = MatVector.at(y).BumpPath;
// tempString = getFileName(tempString.c_str());
// bumpName = tempString.c_str();
// strcat_s(NewFolderPathBump, bumpName);
//
// if (CopyFile((const char*)&MatVector.at(y).BumpPath, (const char*)&NewFolderPathBump, false))
// {
// std::cout << "Material(" << y + 1 << ") Copied Bump Texture File: Success!" << std::endl << std::endl;
// for (unsigned int i = 0; i < 150; i++)
// MatVector.at(y).BumpPath[i] = NewFolderPathBump[i];
// }
// else
// {
// std::cout << "Material(" << y + 1 << ") Copied Bump Texture File: Failed!" << std::endl;
// }
// }
// }
//
//
// //Exporting to custom format.
// for (unsigned int y = 0; y < MatVector.size(); y++)
// {
// readable_file << "AmbientFactor: ";
// outfile.write((const char*)&MatVector.at(y).AmbientFactor, sizeof(float));
// readable_file << MatVector.at(y).AmbientFactor << std::endl;
// readable_file << "AmbientColor: ";
// outfile.write((const char*)&MatVector.at(y).AmbientColor[0], sizeof(float));
// readable_file << MatVector.at(y).AmbientColor[0] << ", ";
// outfile.write((const char*)&MatVector.at(y).AmbientColor[1], sizeof(float));
// readable_file << MatVector.at(y).AmbientColor[1] << ", ";
// outfile.write((const char*)&MatVector.at(y).AmbientColor[2], sizeof(float));
// readable_file << MatVector.at(y).AmbientColor[2] << std::endl;
//
//
// readable_file << "DiffuseFactor: ";
// outfile.write((const char*)&MatVector.at(y).DiffuseFactor, sizeof(float));
// readable_file << MatVector.at(y).DiffuseFactor << std::endl;
// readable_file << "DiffuseColor: ";
// outfile.write((const char*)&MatVector.at(y).DiffuseColor[0], sizeof(float));
// readable_file << MatVector.at(y).DiffuseColor[0] << ", ";
// outfile.write((const char*)&MatVector.at(y).DiffuseColor[1], sizeof(float));
// readable_file << MatVector.at(y).DiffuseColor[1] << ", ";
// outfile.write((const char*)&MatVector.at(y).DiffuseColor[2], sizeof(float));
// readable_file << MatVector.at(y).DiffuseColor[2] << std::endl;
//
//
// readable_file << "EmissiveFactor: ";
// outfile.write((const char*)&MatVector.at(y).EmissiveFactor, sizeof(float));
// readable_file << MatVector.at(y).EmissiveFactor << std::endl;
// readable_file << "EmissiveColor: ";
// outfile.write((const char*)&MatVector.at(y).EmissiveColor[0], sizeof(float));
// readable_file << MatVector.at(y).EmissiveColor[0] << ", ";
// outfile.write((const char*)&MatVector.at(y).EmissiveColor[1], sizeof(float));
// readable_file << MatVector.at(y).EmissiveColor[1] << ", ";
// outfile.write((const char*)&MatVector.at(y).EmissiveColor[2], sizeof(float));
// readable_file << MatVector.at(y).EmissiveColor[2] << std::endl;
//
//
// readable_file << "Transparency: ";
// outfile.write((const char*)&MatVector.at(y).Transparency, sizeof(float));
// readable_file << MatVector.at(y).Transparency << std::endl;
//
// //Phong Part.
//
// readable_file << "SpecularFactor: ";
// outfile.write((const char*)&MatVector.at(y).SpecularFactor, sizeof(float));
// readable_file << MatVector.at(y).SpecularFactor << std::endl;
// readable_file << "SpecularColor: ";
// outfile.write((const char*)&MatVector.at(y).SpecularColor[0], sizeof(float));
// readable_file << MatVector.at(y).SpecularColor[0] << ", ";
// outfile.write((const char*)&MatVector.at(y).SpecularColor[1], sizeof(float));
// readable_file << MatVector.at(y).SpecularColor[1] << ", ";
// outfile.write((const char*)&MatVector.at(y).SpecularColor[2], sizeof(float));
// readable_file << MatVector.at(y).SpecularColor[2] << std::endl;
//
//
// readable_file << "Shininess: ";
// outfile.write((const char*)&MatVector.at(y).Shininess, sizeof(float));
// readable_file << MatVector.at(y).Shininess << std::endl;
//
//
// readable_file << "Reflection: ";
// outfile.write((const char*)&MatVector.at(y).Reflection, sizeof(float));
// readable_file << MatVector.at(y).Reflection << std::endl;
// readable_file << "ReflectionColor: ";
// outfile.write((const char*)&MatVector.at(y).ReflectionColor[0], sizeof(float));
// readable_file << MatVector.at(y).ReflectionColor[0] << ", ";
// outfile.write((const char*)&MatVector.at(y).ReflectionColor[1], sizeof(float));
// readable_file << MatVector.at(y).ReflectionColor[1] << ", ";
// outfile.write((const char*)&MatVector.at(y).ReflectionColor[2], sizeof(float));
// readable_file << MatVector.at(y).ReflectionColor[2] << std::endl;
//
// //Texture Paths part.
// std::cout << "Diffuse Texture Path: " << MatVector.at(y).TexturePath << std::endl;
// readable_file << "Diffuse Texture Path: " << MatVector.at(y).TexturePath << std::endl;
// outfile.write((const char*)&MatVector.at(y).TexturePath, sizeof(const char[150]));
//
// std::cout << "Bump Texture Path: " << MatVector.at(y).BumpPath << std::endl;
// readable_file << "Bump Texture Path: " << MatVector.at(y).BumpPath << std::endl;
// outfile.write((const char*)&MatVector.at(y).BumpPath, sizeof(const char[150]));
// }
// MatVector.clear();
// readable_file.close();
// outfile.close();
//
//
// }
//
//
//}
//void Converter::getGroups(FbxNode * scene_node, std::string par)
//{
// std::string nodeName = scene_node->GetName(); // used for debugging purposes
// std::cout << "NODE: " << nodeName << std::endl << std::endl;
//
// for (size_t i = 0; i < scene_node->GetChildCount(); i++)
// {
// FbxNode* child = scene_node->GetChild(i);
// Group group;
//
// std::string type = child->GetTypeName();
// std::string parent = child->GetParent()->GetName();
//
// if (type == "Null") // has no special attribute like Mesh etc...
// {
// if (parent == "RootNode" || parent == par) // and it's rooted to the scene... We've got a group!
// {
// if (child->GetChildCount() == 0) continue;
//
// FbxDouble3 translation = scene_node->LclTranslation.Get();
// FbxDouble3 rotation = scene_node->LclRotation.Get();
// FbxDouble3 scaling = scene_node->LclScaling.Get();
//
// // Translation
// group.group_transform.transform_position[0] = (float)translation.mData[0];
// group.group_transform.transform_position[1] = (float)translation.mData[1];
// group.group_transform.transform_position[2] = (float)translation.mData[2];
//
// // Rotation
// group.group_transform.transform_rotation[0] = (float)rotation.mData[0];
// group.group_transform.transform_rotation[1] = (float)rotation.mData[1];
// group.group_transform.transform_rotation[2] = (float)rotation.mData[2];
//
// // Scaling
// group.group_transform.transform_scale[0] = (float)scaling.mData[0];
// group.group_transform.transform_scale[1] = (float)scaling.mData[1];
// group.group_transform.transform_scale[2] = (float)scaling.mData[2];
//
// for (size_t j = 0; j < child->GetChildCount(); j++)
// {
// groupChild tempChild;
// std::string tempString = child->GetChild(j)->GetName();
//
// for (int x = 0; x < tempString.size(); x++)
// tempChild.name[x] = tempString[x];
// group.children_names.push_back(tempChild);
// }
//
// //group.children.push_back(c_child); // throw in all children (non child in child) into the group
//
// createGroupFiles(child, &group);
//
// std::cout << "The group has name: " << child->GetName() << " and has " << child->GetChildCount() << " children!" << std::endl;
// getGroups(child, child->GetName());
// }
// }
// }
//}
//
//bool Converter::createGroupFiles(FbxNode * scene_node, Group * group)
//{
// const char * temp = "_Group";
// const char* node_name = scene_node->GetName();
// std::string filename = std::string(node_name) + "_Group.bin";
// std::ofstream outfile(filename, std::ofstream::binary);
// std::string readable_file_name = std::string(node_name) + "_Group.txt";
// std::ofstream readable_file(readable_file_name);
//
//
// std::string groupName = scene_node->GetName();
// int childCount = group->children_names.size();
//
//
// std::cout << "Children count: " << group->children_names.size() << std::endl;
//
// outfile.write((const char*)&childCount, sizeof(int));
//
// outfile.write((const char*)&group->group_transform.transform_position[0], sizeof(float));
// outfile.write((const char*)&group->group_transform.transform_position[1], sizeof(float));
// outfile.write((const char*)&group->group_transform.transform_position[2], sizeof(float));
//
// outfile.write((const char*)&group->group_transform.transform_rotation[0], sizeof(float));
// outfile.write((const char*)&group->group_transform.transform_rotation[1], sizeof(float));
// outfile.write((const char*)&group->group_transform.transform_rotation[2], sizeof(float));
//
// outfile.write((const char*)&group->group_transform.transform_scale[0], sizeof(float));
// outfile.write((const char*)&group->group_transform.transform_scale[1], sizeof(float));
// outfile.write((const char*)&group->group_transform.transform_scale[2], sizeof(float));
//
//
// for (size_t i = 0; i < group->children_names.size(); i++)
// {
// readable_file << "Child " << std::to_string(i) << ": " << group->children_names[i].name << std::endl;
// outfile.write((const char*)group->children_names[i].name, sizeof(char[100]));
// }
// readable_file.close();
// outfile.close();
//
// return true;
//} |
efe6cf0f928d32e90578e520ce8e340ad79f2840 | 43c4a41448dc7ddcec8441f38b5ae0a86f8db7dc | /AutoDiff/back_up/VariableInfo.hpp | 862297dcec752d8d85ce92928de4adca517e4c02 | [] | no_license | msupernaw/ATL1 | 4473c9f7ba1b64f6562e8406d7b0dfe639911e56 | 72cf1f73725eb3e8eb69c3ddd0445ee28eaa46e5 | refs/heads/master | 2021-06-13T18:26:45.568944 | 2017-02-23T14:02:28 | 2017-02-23T14:02:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,030 | hpp | VariableInfo.hpp | /*
* File: DerivativePointer.hpp
* Author: matthewsupernaw
*
* Created on April 8, 2015, 12:12 PM
*/
#ifndef DERIVATIVEPOINTER_HPP
#define DERIVATIVEPOINTER_HPP
#include <atomic>
#include <mutex>
#include <stack>
#include "../Utilities/Platform.hpp"
#ifndef ATL_WINDOWS
#include "third_party/clfmalloc.h"
#endif
#include "../Utilities/flat_map.hpp"
namespace atl {
/*!
* Creates a unique identifier for variables. Identifiers are recyclable.
* @return
*/
class VariableIdGenerator {
#ifdef USE_TBB
tbb::concurrent_vector<uint32_t> available;
#else
std::stack<uint32_t> available;
#endif
std::atomic<uint32_t> available_size;
static std::mutex mutex_g;
public:
static std::shared_ptr<VariableIdGenerator> instance();
const uint32_t next() {
mutex_g.lock();
uint32_t ret;
if (!available.empty()> 0) {
ret = available.top();
available.pop();
} else {
ret = ++_id;
}
mutex_g.unlock();
return ret;//(++_id);
}
void release(const uint32_t& id) {
mutex_g.lock();
available.push(id);
available_size++;
mutex_g.unlock();
}
const uint32_t current() {
return _id;
}
// private:
VariableIdGenerator() : _id(0), available_size(0) {
}
std::atomic<uint32_t> _id;
};
std::mutex VariableIdGenerator::mutex_g;
static std::shared_ptr<VariableIdGenerator> only_copy;
inline std::shared_ptr<VariableIdGenerator>
VariableIdGenerator::instance() {
if (!only_copy) {
only_copy = std::make_shared<VariableIdGenerator>();
}
return only_copy;
}
template<typename REAL_T>
class VariableInfo {
public:
static std::mutex mutex_g;
std::atomic<uint32_t> count;
static std::mutex vinfo_mutex_g;
static std::vector<VariableInfo<REAL_T>* > freed;
REAL_T dvalue;
REAL_T vvalue;
typedef flat_map<VariableInfo<REAL_T>*, REAL_T> HessianInfo;
HessianInfo hessian_row;
typedef typename HessianInfo::iterator row_iterator;
uint32_t id;
VariableInfo() : vvalue(0.0),dvalue(0.0), count(1), id(VariableIdGenerator::instance()->next()) {
}
inline void Aquire() {
count++;
}
inline REAL_T GetHessianRowValue(VariableInfo<REAL_T>* var){
row_iterator it = hessian_row.find(var);
if(it != hessian_row.end()){
return (*it).second;
}else{
return static_cast<REAL_T>(0.0);
}
}
inline void Release() {
count--;
if ((count) == 0) {
VariableInfo<REAL_T>::vinfo_mutex_g.lock();
freed.push_back(this);
VariableInfo<REAL_T>::vinfo_mutex_g.unlock();
}
}
static void FreeAll() {
for (int i = 0; i < freed.size(); i++) {
VariableIdGenerator::instance()->release(freed[i]->id);
delete freed[i];
}
freed.resize(0);
}
void* operator new(size_t size) {
return malloc(size);
}
void operator delete(void* ptr) {
free(ptr);
}
};
template<typename REAL_T>
std::vector<VariableInfo<REAL_T>* > VariableInfo<REAL_T>::freed;
template<typename REAL_T>
std::mutex VariableInfo<REAL_T>::vinfo_mutex_g;
template<typename REAL_T>
std::mutex VariableInfo<REAL_T>::mutex_g;
}
#endif /* DERIVATIVEPOINTER_HPP */
|
ffba77f7e490a510d2dfd165a873795448ee43a3 | e8d783d45ac0f3ef7f38eadc5b44b7e2a595179f | /libuv/echo_client.cpp | d65dbbd521793511040296f048b0ee648f18d4dc | [
"Zlib"
] | permissive | osom8979/example | e3be7fd355e241be6b829586b93d3cbcb1fbf3a5 | 603bb7cbbc6427ebdc7de28f57263c47d583c2e4 | refs/heads/master | 2023-07-21T19:55:55.590941 | 2023-07-20T02:06:42 | 2023-07-20T02:06:42 | 52,238,897 | 2 | 1 | NOASSERTION | 2023-07-20T02:06:43 | 2016-02-22T01:42:09 | C++ | UTF-8 | C++ | false | false | 1,235 | cpp | echo_client.cpp | // TCP echo client.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
#define DEFAULT_PORT 7000
#define DEFAULT_BACKLOG 128
uv_loop_t * loop;
uv_tcp_t * tcp_client;
uv_write_t write_request;
void write_cb(uv_write_t * req, int status)
{
uv_close((uv_handle_t*) req->handle, NULL);
}
void on_connect(uv_connect_t * req, int status)
{
if (status < 0) {
fprintf(stderr, "Connection error %s\n", uv_strerror(status));
// error!
return;
}
char ECHO_STRING[] = "HELLO";
uv_buf_t buf = { ECHO_STRING, 5 };
uv_write(&write_request
, (uv_stream_t *) tcp_client
, &buf
, 1
, write_cb);
}
int main()
{
loop = uv_default_loop();
tcp_client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
uv_tcp_init(loop, tcp_client);
uv_connect_t * connect = (uv_connect_t*)malloc(sizeof(uv_connect_t));
struct sockaddr_in dest;
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, &dest);
int r = uv_tcp_connect(connect, tcp_client, (const struct sockaddr*)&dest, on_connect);
if (r) {
fprintf(stderr, "Listen error %s\n", uv_strerror(r));
return 1;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
|
a88aa475bad0842bc751db97779c7aec9c00e2b2 | 8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076 | /code/RenderDevice/fxRenderDevice.cpp | 364c6e9173b6f756aa31b95a581627bcf862877d | [] | no_license | BackupTheBerlios/insane | fb4c5c6a933164630352295692bcb3e5163fc4bc | 7dc07a4eb873d39917da61e0a21e6c4c843b2105 | refs/heads/master | 2016-09-05T11:28:43.517158 | 2001-01-31T20:46:38 | 2001-01-31T20:46:38 | 40,043,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | cpp | fxRenderDevice.cpp | //---------------------------------------------------------------------------
#include "fxRenderDevice.h"
#include <assert.h>
//---------------------------------------------------------------------------
void fxRenderDevice::CloseWindow(void)
{
assert(wnd);
delete wnd;
wnd = NULL;
}
|
c3a6443d4be5230ec2228b98665bb53910600da2 | 8ca1d9752b1ff9f6df5ec954de2685f18b4015ee | /AMS_cpp_hpp/AMS_CalcClothoid_template.cpp | 6106722e45d13d95170fb06f07e557f8506462b8 | [] | no_license | sunsided/bht-ams-sommer | 0d3754733a43ec3124e048d24b4b4c33124217ca | d9c96f259a18fa72f856f6ec0d981da0004b99df | refs/heads/master | 2020-06-01T05:55:18.133385 | 2014-01-30T12:30:47 | 2014-01-30T12:30:47 | 15,311,458 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,267 | cpp | AMS_CalcClothoid_template.cpp | /// Beuth Hochschule für Technik Berlin
/// Autonome Mobile Systeme
/// Prof. Dr.-Ing. Volker Sommer
#include "AMS_Robot.hpp"
#include <newmat/newmatap.h> // Linear algebra
using namespace AMS;
AMS_Robot robot; // Roboterobjekt
int main(int argc, char **argv)
{
ColumnVector P0(2); // Startpunkt der Bahnkurve
ColumnVector P1(2); // Scheitelpunkt des krümmungsstetigen Übergangs
ColumnVector P2(2); // Endpunkt der Bahnkurve
ColumnVector V01(2); // Vektor vom Punkt 0 zum Punkt 1
ColumnVector V12(2); // Vektor vom Punkt 1 zum Punkt 2
ColumnVector Pc0(2); // Startpunkt des krümmungsstetigen Übergangs
ColumnVector Pc1(2); // Endpunkt des krümmungsstetigen Übergangs
double Rmin; // Kurvenradius im Scheitelpunkt der Bahnkurve (=Kehrwert der max. Krümmung)
double L01, L12; // Längen der Vektoren V01 und V12
double theta; // Winkel der Tangente an die Klothoide
double thetaL; // Tangentenwinkel der Klothoiden am Scheitelpunkt
double L; // Länge der Klothoide
double k; // Krümmungsparameter für Klothoide
double xL, yL; // Parameter für Klothoide
double delta; // Abstand zwischen dem Beginn der Klothoiden und Punkt P1
double L1, L2; // Länge der Geradenstücke vor und hinter der Klothoiden
double phi1, phi2; // Richtungswinkel der Geradenstücke vor und hinter der Klothoiden
double s, xs=0, ys=0; // Hilfsparameter zum Zeichnen
double px, py; // Plotkoordinaten
const double ds = 0.01; // Abstand der Punkte beim Plotten der Trajektorie
// Roboter initialisieren
if( !(robot.read_config(argc, argv) && robot.connect()) ) {
robot.log.notice("Call with -h to see the available options.");
return -1;
}
// Eckpunkte für krümmungsstetigen Übergang vorgeben
P0(1) = 0.0; // Startpunkt x-Koordinate
P0(2) = 2.0; // Startpunkt y-Koordinate
P1(1) = 3.0; // Scheitelpunkt x-Koordinate
P1(2) = 1.0; // Scheitelpunkt y-Koordinate
P2(1) = 2.5; // Endpunkt x-Koordinate
P2(2) = -3.0; // Endpunkt y-Koordinate
robot.init_push_mode();
/********************* Fügen Sie ab hier eigenen Quellcode ein **********************/
// Minimalen Krümmungsradius aus maximaler Bahn und Winkelgeschwindigkeit berechnen
Rmin =
// Vektoren zwischen den Punkten P0 und P1 sowie P1 und P2 festlegen und deren Längen berechnen
V01 =
V12 =
L01 =
L12 =
// Tangentenwinkel im Scheitelpunkt mittels Skalarprodukt und inverser Cosinusfunktion berechnen
// z-Komponente des Vektorproduktes liefert zusätzlich das Vorzeichen von thetaL
thetaL =
// Parameter für krümmungsstetigen Übergang mit Klothoide berechnen
L =
xL =
yL =
delta =
// Berechnung des Start- und des Endpunktes der Klothoiden
Pc0 =
Pc1 =
/******************** Ende des zusätzlich eingefügten Quellcodes ********************/
// Abbruch, falls delta_x die Länge des Vektors V01 oder die des Vektors V12 übersteigt.
// In diesem Fall kann der krümmungsstetige Übergang mit dem vorgegebenem Radius nicht berechnet werden
if( delta > L01 || delta > L12 ) {
robot.log.errorStream() << "Fehler: Gewählter minimaler Radius nicht möglich.\n";
return -1;
}
// Zeichnen des ersten Geradenstücks bis zum Beginn der Klothoide
L1 = (Pc0-P0).NormFrobenius();
phi1 = atan2(V01(2),V01(1)); // Orientierung des Geradenstücks, d.h. des Vektors V01 berechnen
for( s=0; s<L1; s+=ds) {
px = P0(1) + s*cos(phi1);
py = P0(2) + s*sin(phi1);
robot.draw_point(px, py, 0, 255, 0); // Punkt zeichnen
}
// Zeichnen der Klothoiden
k = 0.5/(thetaL*Rmin*Rmin); // Parameter der Klothoide (Vorzeichen von thetaL bestimmt Krümmungsrichtung)
for( s=0; s<=L*2; s+=ds ) { // Schleife über Punkte auf Klothoide
if( s<=L )
theta = 0.5*k*s*s; // 1. Hälfte: Zunahme der Krümmung
else
theta = thetaL*2 - 0.5*k*(s-L*2)*(s-L*2); // 2. Hälfte: Abnahme der Krümmung
xs += cos(theta)*ds;
ys += sin(theta)*ds;
/********************* Fügen Sie ab hier eigenen Quellcode ein **********************/
// Koordinatentransformation mit Berücksichtigung des Startpunktes Pc0 und der Richtung phi1
px =
py =
/******************** Ende des zusätzlich eingefügten Quellcodes ********************/
robot.draw_point(px, py, 255, 0, 255);
}
// Zeichnen des zweiten Geradenstücks hinter der Klothoide
phi2 = atan2(V12(2),V12(1));
L2 = (P2-Pc1).NormFrobenius();
for( s=0; s<L2; s+=ds) {
px = Pc1(1) + s*cos(phi2);
py = Pc1(2) + s*sin(phi2);
robot.draw_point(px, py, 0, 255, 0);
}
// Ausgabe der berechneten Teillängen
robot.log.info("Length of 1st straight line: %.2lf m.", L1);
robot.log.info("Length of clothoide: %.2lf m.", L*2);
robot.log.info("Length of 2nd straight line: %.2lf m.", L2);
while(1); // Endlosschleife
}
|
ac0cf3db101ed2f2c0604d7649702225c002b901 | 2ac707be53115c7fe21fe722582750b0e4205c3f | /examples/Better-Callbacks/TraditionalCallbacks/SimpleTimer.h | 0dabcebfa3a6139ce90f723e8e14c0bf92e39dbd | [] | no_license | TeensyUser/doc | db3dd34783fdd992046ac19cdde9c619d2bb1ed2 | 546708fae3b675ee6cf98291feb6a05420eef745 | refs/heads/master | 2022-02-20T11:07:02.539904 | 2022-01-11T10:08:33 | 2022-01-11T10:08:33 | 246,367,593 | 68 | 6 | null | 2021-04-01T07:38:08 | 2020-03-10T17:40:15 | null | UTF-8 | C++ | false | false | 427 | h | SimpleTimer.h | #pragma once
#include "Arduino.h"
using callback_t = void (*)(void); // c++ way to define a function pointer (since c++11)
//typedef void (*callback_t)(void); // traditional C typedef way works as well
class SimpleTimer
{
public:
void begin(unsigned period, callback_t callback);
void tick(); // call this as often as possible
protected:
unsigned period;
elapsedMicros timer;
callback_t callback;
}; |
961da01bfbdea530357c42663bdbdde6cc5e98dd | efe1928f5f3a38e37e6127c38f3ddab4f3953b41 | /src/nnfusion/engine/pass/graph/manager.hpp | b51972441b20467787f0173fa6aae7b42e41c2a2 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | xiezhq-hermann/nnfusion | 8cdf0b6d03b6a43a781caa061e0b7b3e4caed45e | 1b2c23b0732bee295e37b990811719e0c4c6e993 | refs/heads/osdi20_artifact | 2023-01-19T06:25:09.755500 | 2020-09-05T09:49:54 | 2020-09-05T09:49:54 | 293,049,048 | 0 | 0 | MIT | 2020-09-23T07:43:08 | 2020-09-05T10:01:08 | null | UTF-8 | C++ | false | false | 1,354 | hpp | manager.hpp | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "graph_pass_base.hpp"
#include "nnfusion/core/graph/graph.hpp"
namespace nnfusion
{
namespace pass
{
namespace graph
{
class GraphPassManager
{
public:
GraphPassManager();
~GraphPassManager();
void initialize_default_passes();
template <typename T, class... Args>
void register_pass(Args&&... args)
{
static_assert(std::is_base_of<GraphPassBase, T>::value,
"pass not derived from graph pass base");
auto pass = std::make_shared<T>(std::forward<Args>(args)...);
auto pass_base = std::static_pointer_cast<GraphPassBase>(pass);
m_pass_list.push_back(pass_base);
m_pass_names.push_back(typeid(T).name());
}
bool run_passes(std::vector<std::shared_ptr<nnfusion::graph::Graph>>& graph_vec);
private:
std::vector<std::string> m_pass_names;
std::vector<std::shared_ptr<GraphPassBase>> m_pass_list;
};
} //namespace pass
} // namespace graph
} // namespace nnfusion |
29f3e7dd85546724f283ae9f0f3143e724798b17 | 9eb2245869dcc3abd3a28c6064396542869dab60 | /benchspec/CPU/621.wrf_s/build/build_base_mytest-64.0001/inc/state_subtypes.inc | b9c6e8216cd6d10a8c7171b48eab989cbc419a95 | [] | no_license | lapnd/CPU2017 | 882b18d50bd88e0a87500484a9d6678143e58582 | 42dac4b76117b1ba4a08e41b54ad9cfd3db50317 | refs/heads/master | 2023-03-23T23:34:58.350363 | 2021-03-24T10:01:03 | 2021-03-24T10:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,051 | inc | state_subtypes.inc | !STARTOFREGISTRYGENERATEDINCLUDE 'inc/state_subtypes.inc'
!
! WARNING This file is generated automatically by use_registry
! using the data base in the file named Registry.
! Do not edit. Your changes to this file will be lost.
!
TYPE fdob_type
integer :: domain_tot
integer :: ieodi
integer :: iwtsig
integer :: nstat
integer :: nstaw
integer :: ktaur
integer :: levidn(max_domains)
integer :: refprt(max_domains)
real :: window
real :: rtlast
real :: datend
logical :: nudge_uv_pbl
logical :: nudge_t_pbl
logical :: nudge_q_pbl
integer :: sfc_scheme_horiz
integer :: sfc_scheme_vert
real :: max_sndng_gap
real :: sfcfact
real :: sfcfacr
real :: rinfmn
real :: rinfmx
real :: pfree
real :: dcon
real :: dpsmx
real :: tfaci
real :: known_lat
real :: known_lon
character(LEN=256) :: sdate
real :: xtime_at_rest
real :: vif_uv(6)
real :: vif_t(6)
real :: vif_q(6)
real :: vif_fullmin
real :: vif_rampmin
real :: vif_max
real ,DIMENSION(:,:) ,POINTER :: varobs
real ,DIMENSION(:,:) ,POINTER :: errf
real ,DIMENSION(:) ,POINTER :: timeob
real ,DIMENSION(:) ,POINTER :: nlevs_ob
real ,DIMENSION(:) ,POINTER :: lev_in_ob
real ,DIMENSION(:) ,POINTER :: plfo
real ,DIMENSION(:) ,POINTER :: elevob
real ,DIMENSION(:) ,POINTER :: rio
real ,DIMENSION(:) ,POINTER :: rjo
real ,DIMENSION(:) ,POINTER :: rko
integer ,DIMENSION(:) ,POINTER :: obsprt
real ,DIMENSION(:) ,POINTER :: latprt
real ,DIMENSION(:) ,POINTER :: lonprt
real ,DIMENSION(:) ,POINTER :: mlatprt
real ,DIMENSION(:) ,POINTER :: mlonprt
integer ,DIMENSION(:,:) ,POINTER :: stnidprt
real ,DIMENSION(:) ,POINTER :: base_state
END TYPE fdob_type
!ENDOFREGISTRYGENERATEDINCLUDE
|
fa3c7b9a7440822b3080998c43e29d228686a7d6 | e55a8acd526b5489a421cde6ce2faad97faefea1 | /gltt/GLTTGlyphPolygonizerHandler.h | f8bcc9bc1d62c19d9620aa90df062a37f7238643 | [] | no_license | sgooding/HighSchoolProjects | 5d042f2490d68066c786ae352d27c6e03ce76ab5 | 3d487443dfa2075d5042664a379e795c6a7e54fd | refs/heads/master | 2022-11-11T05:27:09.680977 | 2022-10-28T03:21:35 | 2022-10-28T03:21:35 | 22,287,066 | 0 | 0 | null | 2022-10-28T03:18:09 | 2014-07-26T13:23:46 | C | UTF-8 | C++ | false | false | 1,770 | h | GLTTGlyphPolygonizerHandler.h | /*
* gltt graphics library
* Copyright (C) 1998-1999 Stephane Rehel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __GLTTGlyphPolygonizerHandler_h
#define __GLTTGlyphPolygonizerHandler_h
#ifndef __GLTTboolean_h
#include "GLTTboolean.h"
#endif
#ifndef __FTGlyphVectorizer_h
#include "FTGlyphVectorizer.h"
#endif
/////////////////////////////////////////////////////////////////////////////
// Mmh, this class name is a bit long... /SR
class GLTTGlyphPolygonizerHandler
{
friend class GLTTGlyphPolygonizer;
protected:
GLTTboolean verbose;
//GLTTGlyphPolygonizer* polygonizer; // set by GLTTGlyphPolygonizer
void* polygonizer; // set by GLTTGlyphPolygonizer
public:
GLTTGlyphPolygonizerHandler( GLTTboolean _verbose = GLTT_FALSE );
virtual ~GLTTGlyphPolygonizerHandler();
virtual void begin( int type );
virtual void vertex( FTGlyphVectorizer::POINT* point );
virtual void end();
virtual void error( int error );
};
/////////////////////////////////////////////////////////////////////////////
#endif // ifndef __GLTTGlyphPolygonizerHandler_h
|
25a67f74bcb8a975f44799c792256379b1781f71 | cadb9fa72959531e04757c28593467733f419b52 | /halfling.cc | 824836e4c3a3ae8ddf104550748d14c9cbc4ad67 | [] | no_license | Tengzin/cc3k | 27489d37a280bc59e3e152a0ba3d6994a4fab38a | 829923758b112531c7d23d79c79b774be5075ad0 | refs/heads/master | 2022-01-21T01:48:46.256138 | 2019-06-15T14:20:56 | 2019-06-15T14:20:56 | 111,860,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 662 | cc | halfling.cc | #include "halfling.h"
#include "maplayout.h"
#include "player.h"
#include <ctime>
#include <cstdlib>
#include <string>
using std::string;
int RandomNumberH(int n) {
srand(time(0));
int randNum;
randNum = 1 + (rand() % n);
return randNum;
}
Halfling::Halfling():
Enemy{ 100, 15, 20 } {}
char Halfling::whatType(Interactable *i) { return 'L'; }
void Halfling::beStruckBy(Player *pc) {
// 50% chance for this to happen, use random function
const int miss = RandomNumberH(2);
if (miss == 1) {
const int dmg = pc->getAtk();
damaged(dmg);
if (this->checkDead() == true) pc->autoLoot();
}
else { cout << "The attack missed!" << endl; }
}
|
7d42d8471c3dc2a87f4c7e894191a7d52ecd0780 | 6fb9a64452c83fc2ae26f9cf98057b87d381caa3 | /ASCIIRogueLike/RogueLikeMain.cpp | 079663bb2122f14b534804feeaef1f551ad970b9 | [] | no_license | pladams9/Game_ASCIIRogueLike | 483a6f160e251240f1853b93b330f6251fab26b1 | 165e831083cab942f9cb93adc3412d2e8d7b6ed9 | refs/heads/master | 2020-09-02T23:06:39.970435 | 2019-11-03T18:42:34 | 2019-11-03T18:42:34 | 219,327,968 | 0 | 0 | null | 2019-11-03T16:10:32 | 2019-11-03T16:10:32 | null | UTF-8 | C++ | false | false | 232 | cpp | RogueLikeMain.cpp | #include <iostream>
#include <conio.h>
#include "GameManager.h"
int main()
{
GameManager gameManger("../levels/Level_test.level");
gameManger.runGame();
std::cout << "\nPress ENTER to continue...\n";
_getch();
return 0;
}
|
1bb7d93d8dcd1d1fad15b2b45b6327abf24cea2b | ec915bf2f3fc0f9b05ff7e9f7b13d39fce78c7be | /batch/main.cc.norun | 3f46e90329db8ed5c08f106f12c6f750a27e82e2 | [] | no_license | cmstas/SSAnalysis | ed85d6ecd2ccc9c191482bf53a586c41ee1c8941 | 658798ad51b8ca508ed38e23c6116178580ce9f2 | refs/heads/master | 2020-04-04T07:28:51.773617 | 2018-02-21T00:42:07 | 2018-02-21T00:42:07 | 30,431,428 | 1 | 0 | null | 2016-06-15T17:16:28 | 2015-02-06T20:24:36 | C++ | UTF-8 | C++ | false | false | 69,066 | norun | main.cc.norun |
#include "./CORE/CMS3.h"
#include "./CORE/SSSelections.h"
#include "TTree.h"
#include "TFile.h"
#include "helper_babymaker.h"
#include "base.h"
#include "CORE/Tools/goodrun.h"
#include "CORE/Tools/JetCorrector.h"
#include "CORE/Tools/jetcorr/JetCorrectionUncertainty.h"
#include "CORE/Tools/jetcorr/SimpleJetCorrectionUncertainty.h"
int main(int argc, char *argv[]){
int which_in = 0;
int file = 2;
unsigned int nevents_max = 0;
if (argc > 2) {
which_in = atoi(argv[1]);
file = atoi(argv[2]);
if (argc > 3) {
nevents_max = atoi(argv[3]);
}
}
else {
cout << "not enough arguments!" << endl;
return 0;
}
sample_t which = static_cast<sample_t>(which_in);
babyMaker *mylooper = new babyMaker();
//Path, filename, suffix
string path="/store/group/snt/run2_25ns_MiniAODv2/";
string name = "";
string shortname = "";
char* filename = Form("merged_ntuple_%i.root", file);
const char* suffix = file < 0 ? "" : Form("_%i", file);
string tag="V07-04-08";
bool isData = false;
int isSignal = 0;
//Info for each sample
switch (which){
case SYNCH_TTW:
name="TTW76_TTW76-SSDL2016-forSynch_Private76X";
path="/store/group/snt/run2_ss_synch/";
tag="V07-06-03_MC";
shortname="synch_ttw";
break;
case SYNCH_TTW80:
name="TTW80_TTW80-SSDL2016-forSynch_Private80Xv2";
path="/store/group/snt/run2_ss_synch/";
tag="V08-00-05";
shortname="synch_ttw_80";
break;
case TTH_M350:
name="TTH_ttH-m350-MINIAOD_Private80Xv2";
path="/store/group/snt/run2_25ns_80Private/";
tag="V08-00-05";
shortname="tth_m350";
break;
case THW_M350:
name="THW_tHW-m350-MINIAOD_Private80Xv2";
path="/store/group/snt/run2_25ns_80Private/";
tag="V08-00-05";
shortname="thw_m350";
break;
case TTH_SCAN:
name="TTH_ttH-scan-MINIAOD_Private80Xv2_v2";
path="/store/group/snt/run2_25ns_80Private/";
tag="V08-00-05";
shortname="tth_scan";
break;
case THW_SCAN:
name="THW_tHW-scan-MINIAOD_Private80Xv2";
path="/store/group/snt/run2_25ns_80Private/";
tag="V08-00-05";
shortname="thw_scan";
break;
case THQ_SCAN:
name="THQ_tHq-scan-MINIAOD_Private80Xv2_v2";
path="/store/group/snt/run2_25ns_80Private/";
tag="V08-00-09";
shortname="thq_scan";
break;
case TTBAR:
name="TTJets_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8_RunIISpring16MiniAODv1-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v2";
path="/store/group/snt/run2_25ns_80MiniAODv1/";
tag="V08-00-01";
shortname="ttbar";
break;
case TTW:
name="ttWJets_13TeV_madgraphMLM_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
tag="V08-00-05";
shortname="ttw";
break;
case TTZ:
name="ttZJets_13TeV_madgraphMLM_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
tag="V08-00-05";
shortname="ttz";
break;
case WZ:
name="WZTo3LNu_TuneCUETP8M1_13TeV-powheg-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wz";
break;
case DY_low: // FIXME FIXME
name="DYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
tag="V08-00-05";
shortname="dy_low";
break;
case DY_high:
name="DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v2";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="dy_high";
break;
case DY_high_LO:
name="DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIIFall15MiniAODv2-PU25nsData2015v1_76X_mcRun2_asymptotic_v12-v1";
tag="V07-06-03_MC";
path="/store/group/snt/run2_25ns_76MiniAODv2/";
shortname="dy_high_LO";
break;
case WJets:
name="WJetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wjets";
break;
case TTZQ:
name="TTZToQQ_TuneCUETP8M1_13TeV-amcatnlo-pythia8";
tag="CMS3_V07-06-03";
path="/store/group/snt/run2_25ns_76MiniAODv2/TTV/";
shortname="ttzq";
break;
case TTWQQ:
name="TTWJetsToQQ_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8";
tag="CMS3_V07-06-03";
path="/store/group/snt/run2_25ns_76MiniAODv2/TTV/";
shortname="ttwqq";
break;
case TTG:
name="TTGJets_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="ttg";
break;
case SINGLETOP1:
name="ST_tW_top_5f_NoFullyHadronicDecays_13TeV-powheg_TuneCUETP8M1";
tag="CMS3_V07-06-03";
path="/store/group/snt/run2_25ns_76MiniAODv2/T/";
shortname="singletop1";
break;
case SINGLETOP2:
name="ST_tW_antitop_5f_NoFullyHadronicDecays_13TeV-powheg_TuneCUETP8M1";
tag="CMS3_V07-06-03";
path="/store/group/snt/run2_25ns_76MiniAODv2/T/";
shortname="singletop2";
break;
case SINGLETOP3:
name="ST_t-channel_antitop_4f_leptonDecays_13TeV-powheg-pythia8_TuneCUETP8M1_RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1";
tag="V07-04-11";
shortname="singletop3";
break;
case SINGLETOP4:
name="ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1_RunIIFall15MiniAODv2-PU25nsData2015v1_76X_mcRun2_asymptotic_v12-v1";
tag="V07-06-03_MC";
path="/store/group/snt/run2_25ns_76MiniAODv2/";
shortname="singletop4";
break;
case SINGLETOP5:
name="ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1_RunIIFall15MiniAODv2-PU25nsData2015v1_76X_mcRun2_asymptotic_v12-v1";
tag="V07-06-03_MC";
path="/store/group/snt/run2_25ns_76MiniAODv2/";
shortname="singletop5";
break;
case QQWW:
name="WpWpJJ_EWK-QCD_TuneCUETP8M1_13TeV-madgraph-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="qqww";
break;
case TTTT: // FIXME FIXME
name="TTTT_TuneCUETP8M2T4_13TeV-amcatnlo-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="tttt";
break;
case WWDPS:
name="WWTo2L2Nu_DoubleScattering_13TeV-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wwdps";
break;
case TTBAR_PH:
name="TT_TuneCUETP8M2T4_13TeV-powheg-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="ttbar_ph";
break;
case ZZ:
name="ZZTo4L_13TeV_powheg_pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="zz";
break;
case TG:
name="TGJets_TuneCUETP8M1_13TeV_amcatnlo_madspin_pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="tg";
break;
case ZG: // FIXME FIXME
name="ZGTo2LG_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="zg";
break;
case WZZ:
name="WZZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wzz";
break;
case WWZ:
name="WWZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wwz";
break;
case WGToLNuG:
name="WGToLNuG_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wgtolnug";
break;
case TZQ:
name="tZq_ll_4f_13TeV-amcatnlo-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="tzq";
break;
case TTHtoNonBB:
name="ttHToNonbb_M125_TuneCUETP8M2_ttHtranche3_13TeV-powheg-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="tthtononbb";
break;
case VHtoNonBB:
name="VHToNonbb_M125_13TeV_amcatnloFXFX_madspin_pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="vhtononbb";
break;
case TTZlow:
name="TTZToLL_M-1to10_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="ttzlow";
break;
case GGHtoZZto4L:
name="GluGluHToZZTo4L_M125_13TeV_powheg2_JHUgenV6_pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="gghtozzto4l";
break;
case WGMG:
name="WGToLNuG_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8";
tag="CMS3_V07-06-03";
path="/store/group/snt/run2_25ns_76MiniAODv2/VV/";
shortname="wgmg";
break;
case ZZZ:
name="ZZZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="zzz";
break;
case WWW:
name="WWW_4F_TuneCUETP8M1_13TeV-amcatnlo-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="www";
break;
case TTZnlo:
name="TTZToLLNuNu_M-10_TuneCUETP8M1_13TeV-amcatnlo-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="ttznlo";
break;
case TTWnlo:
name="TTWJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v3";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="ttwnlo";
break;
case TTZlofix:
name="ttZJets_13TeV_madgraphMLM_RunIISummer16MiniAODv2-80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
tag="V08-00-16";
path="/store/group/snt/run2_moriond17/";
shortname="ttzlofix";
break;
case WJets100To200:
name="WJetsToLNu_HT-100To200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wjets100to200";
break;
case WJets200To400:
name="WJetsToLNu_HT-200To400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext2-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wjets200to400";
break;
case WJets400To600:
name="WJetsToLNu_HT-400To600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wjets400to600";
break;
case WJets600To800:
name="WJetsToLNu_HT-600To800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wjets600to800";
break;
case WJets800To1200:
name="WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="wjets800to1200";
break;
case WJets1: //
name="W1JetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
tag="V08-00-05";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
shortname="wjets1";
break;
case WJets2: //
name="W2JetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
tag="V08-00-05";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
shortname="wjets2";
break;
case WJets3: //
name="W3JetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
tag="V08-00-05";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
shortname="wjets3";
break;
case WJets4: //
name="W4JetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
tag="V08-00-05";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
shortname="wjets4";
break;
case WZLO:
name="WZ_TuneCUETP8M1_13TeV-pythia8_RunIISpring16MiniAODv2-PUSpring16_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
tag="V08-00-05";
path="/store/group/snt/run2_25ns_80MiniAODv2/";
shortname="wzlo";
break;
case TWZ:
name="ST_tWll_5f_LO_13TeV-MadGraph-pythia8_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1";
path="/store/group/snt/run2_moriond17/";
tag="V08-00-16";
shortname="twz";
break;
//Signal
case T1TTTT_1500:
name="SMS-T1tttt_mGluino-1500_mLSP-100_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1";
shortname="t1tttt_1500";
tag="V07-04-11";
break;
case T1TTTT_1200:
name="SMS-T1tttt_mGluino-1200_mLSP-800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1";
tag="V07-04-11";
shortname="t1tttt_1200";
break;
case T5QQQQWWDeg_1000_315_300:
name="T5qqqqWWDeg_mGo1000_mCh315_mChi300_dilep";
tag="";
path="/nfs-7/userdata/ss2015/signalSamples/V07-04-08/";
shortname="t5qqqqwwdeg_1000_315_300";
break;
case T5QQQQWW_1200_1000_800:
name="T5qqqqWW_mGo1200_mCh1000_mChi800_dilep";
path="/nfs-7/userdata/ss2015/signalSamples/V07-04-08/";
tag="";
shortname="t5qqqqww_1200_1000_800";
break;
case T5ttttDeg_1000_300_285_280:
name="T5ttttDeg_mGo1000_mStop300_mCh285_mChi280_23bodydec";
path="/nfs-7/userdata/ss2015/signalSamples/V07-04-08/";
shortname="t5ttttdeg_1000_300_285_280";
tag="";
break;
case T6TTWW_600_425_50:
name="T6ttWW_600_425_50";
path="/nfs-7/userdata/ss2015/signalSamples/V07-04-08/";
tag="";
shortname="t6ttww_600_425_50";
break;
case T6TTWW_650_150_50:
name="T6ttWW_650_150_50";
path="/nfs-7/userdata/ss2015/signalSamples/V07-04-08/";
shortname="t6ttww_650_150_50";
tag="";
break;
//Data
// ######################################
// ############## Era B #################
// ######################################
case DataDoubleEGv1:
name="Run2016B_DoubleEG_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-04";
path="/store/group/snt/run2_data/";
shortname="datadoubleegv1";
isData = true;
break;
case DataDoubleMuonv1:
name="Run2016B_DoubleMuon_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-04";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonv1";
isData = true;
break;
case DataMuonEGv1:
name="Run2016B_MuonEG_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-04";
path="/store/group/snt/run2_data/";
shortname="datamuonegv1";
isData = true;
break;
case DataDoubleEGv2:
name="Run2016B_DoubleEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-06";
path="/store/group/snt/run2_data/";
shortname="datadoubleegv2";
isData = true;
break;
case DataDoubleMuonv2:
name="Run2016B_DoubleMuon_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-06";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonv2";
isData = true;
break;
case DataMuonEGv2:
name="Run2016B_MuonEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-06";
path="/store/group/snt/run2_data/";
shortname="datamuonegv2";
isData = true;
break;
// ######################################
// ############## Era C #################
// ######################################
case DataDoubleEGC:
name="Run2016C_DoubleEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-07";
path="/store/group/snt/run2_data/";
shortname="datadoubleegc";
isData = true;
break;
case DataDoubleMuonC:
name="Run2016C_DoubleMuon_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-07";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonc";
isData = true;
break;
case DataMuonEGC:
name="Run2016C_MuonEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-07";
path="/store/group/snt/run2_data/";
shortname="datamuonegc";
isData = true;
break;
// ######################################
// ############## Era D #################
// ######################################
case DataDoubleEGD:
name="Run2016D_DoubleEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-08";
path="/store/group/snt/run2_data/";
shortname="datadoubleegd";
isData = true;
break;
case DataDoubleMuonD:
name="Run2016D_DoubleMuon_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-08";
path="/store/group/snt/run2_data/";
shortname="datadoublemuond";
isData = true;
break;
case DataMuonEGD:
name="Run2016D_MuonEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-08";
path="/store/group/snt/run2_data/";
shortname="datamuonegd";
isData = true;
break;
// ######################################
// ############## Era E #################
// ######################################
case DataDoubleEGE:
name="Run2016E_DoubleEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-10";
path="/store/group/snt/run2_data/";
shortname="datadoubleege";
isData = true;
break;
case DataDoubleMuonE:
name="Run2016E_DoubleMuon_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-10";
path="/store/group/snt/run2_data/";
shortname="datadoublemuone";
isData = true;
break;
case DataMuonEGE:
name="Run2016E_MuonEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-10";
path="/store/group/snt/run2_data/";
shortname="datamuonege";
isData = true;
break;
// ######################################
// ############## Era F #################
// ######################################
case DataDoubleEGF:
name="Run2016F_DoubleEG_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-11";
path="/store/group/snt/run2_data/";
shortname="datadoubleegf";
isData = true;
break;
case DataDoubleMuonF:
name="Run2016F_DoubleMuon_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-11";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonf";
isData = true;
break;
case DataMuonEGF:
name="Run2016F_MuonEG_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-11";
path="/store/group/snt/run2_data/";
shortname="datamuonegf";
isData = true;
break;
// ######################################
// ############## Era G #################
// ######################################
case DataDoubleEGG:
name="Run2016G_DoubleEG_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-12";
path="/store/group/snt/run2_data/";
shortname="datadoubleegg";
isData = true;
break;
case DataDoubleMuonG:
name="Run2016G_DoubleMuon_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-12";
path="/store/group/snt/run2_data/";
shortname="datadoublemuong";
isData = true;
break;
case DataMuonEGG:
name="Run2016G_MuonEG_MINIAOD_PromptReco-v1/merged/";
tag="V08-00-12";
path="/store/group/snt/run2_data/";
shortname="datamuonegg";
isData = true;
break;
// ######################################
// ############## Era H #################
// ######################################
case DataDoubleEGH:
name="Run2016H_DoubleEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoubleegh";
isData = true;
break;
case DataDoubleMuonH:
name="Run2016H_DoubleMuon_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonh";
isData = true;
break;
case DataMuonEGH:
name="Run2016H_MuonEG_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datamuonegh";
isData = true;
break;
case DataDoubleEGHv3:
name="Run2016H_DoubleEG_MINIAOD_PromptReco-v3/merged/";
tag="V08-00-15";
path="/store/group/snt/run2_data/";
shortname="datadoubleeghv3";
isData = true;
break;
case DataDoubleMuonHv3:
name="Run2016H_DoubleMuon_MINIAOD_PromptReco-v3/merged/";
tag="V08-00-15";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonhv3";
isData = true;
break;
case DataMuonEGHv3:
name="Run2016H_MuonEG_MINIAOD_PromptReco-v3/merged/";
tag="V08-00-15";
path="/store/group/snt/run2_data/";
shortname="datamuoneghv3";
isData = true;
break;
case DataJetHTH:
name="Run2016H_JetHT_MINIAOD_PromptReco-v2/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datajethth";
isData = true;
break;
case DataJetHTHv3:
name="Run2016H_JetHT_MINIAOD_PromptReco-v3/merged/";
tag="V08-00-15";
path="/store/group/snt/run2_data/";
shortname="datajeththv3";
isData = true;
break;
// ######################################
// ############## Rereco #################
// ######################################
case DataDoubleEGRerecoB:
name="Run2016B_DoubleEG_MINIAOD_23Sep2016-v3/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoubleegrerecob";
isData = true;
break;
case DataDoubleMuonRerecoB:
name="Run2016B_DoubleMuon_MINIAOD_23Sep2016-v3/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonrerecob";
isData = true;
break;
case DataMuonEGRerecoB:
name="Run2016B_MuonEG_MINIAOD_23Sep2016-v3/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datamuonegrerecob";
isData = true;
break;
case DataDoubleEGRerecoC:
name="Run2016C_DoubleEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoubleegrerecoc";
isData = true;
break;
case DataDoubleMuonRerecoC:
name="Run2016C_DoubleMuon_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonrerecoc";
isData = true;
break;
case DataMuonEGRerecoC:
name="Run2016C_MuonEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datamuonegrerecoc";
isData = true;
break;
case DataDoubleEGRerecoD:
name="Run2016D_DoubleEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoubleegrerecod";
isData = true;
break;
case DataDoubleMuonRerecoD:
name="Run2016D_DoubleMuon_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonrerecod";
isData = true;
break;
case DataMuonEGRerecoD:
name="Run2016D_MuonEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datamuonegrerecod";
isData = true;
break;
case DataDoubleEGRerecoE:
name="Run2016E_DoubleEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoubleegrerecoe";
isData = true;
break;
case DataDoubleMuonRerecoE:
name="Run2016E_DoubleMuon_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonrerecoe";
isData = true;
break;
case DataMuonEGRerecoE:
name="Run2016E_MuonEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datamuonegrerecoe";
isData = true;
break;
case DataDoubleEGRerecoF:
name="Run2016F_DoubleEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoubleegrerecof";
isData = true;
break;
case DataDoubleMuonRerecoF:
name="Run2016F_DoubleMuon_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonrerecof";
isData = true;
break;
case DataMuonEGRerecoF:
name="Run2016F_MuonEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datamuonegrerecof";
isData = true;
break;
case DataDoubleEGRerecoG:
name="Run2016G_DoubleEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoubleegrerecog";
isData = true;
break;
case DataDoubleMuonRerecoG:
name="Run2016G_DoubleMuon_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datadoublemuonrerecog";
isData = true;
break;
case DataMuonEGRerecoG:
name="Run2016G_MuonEG_MINIAOD_23Sep2016-v1/merged/";
tag="V08-00-14";
path="/store/group/snt/run2_data/";
shortname="datamuonegrerecog";
isData = true;
break;
case T1TTTT_main:
shortname="t1tttt_main";
name="SMS-T1tttt_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16Fast_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
isSignal=1;
break;
case T1TTTT_1100_1to775:
shortname="t1tttt_1100_1to775";
name="SMS-T1tttt_mGluino-1100_mLSP-1to775_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1175_950:
shortname="t1tttt_1175_950";
name="SMS-T1tttt_mGluino-1175_mLSP-950_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1275_900to975:
shortname="t1tttt_1275_900to975";
name="SMS-T1tttt_mGluino-1275_mLSP-900to975_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1300_1to1075:
shortname="t1tttt_1300_1to1075";
name="SMS-T1tttt_mGluino-1300_mLSP-1to1075_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1300to1325_700to1100:
shortname="t1tttt_1300to1325_700to1100";
name="SMS-T1tttt_mGluino-1300to1325_mLSP-700to1100_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1350to1375_50to1025:
shortname="t1tttt_1350to1375_50to1025";
name="SMS-T1tttt_mGluino-1350to1375_mLSP-50to1025_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1500to1525_50to1125:
shortname="t1tttt_1500to1525_50to1125";
name="SMS-T1tttt_mGluino-1500to1525_mLSP-50to1125_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1800to1850_1to1450:
shortname="t1tttt_1800to1850_1to1450";
name="SMS-T1tttt_mGluino-1800to1850_mLSP-1to1450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1100to1125_700to900:
shortname="t1tttt_1100to1125_700to900";
name="SMS-T1tttt_mGluino-1100to1125_mLSP-700to900_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_625_275to375:
shortname="t1tttt_625_275to375";
name="SMS-T1tttt_mGluino-625_mLSP-275to375_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_625to650_200to400:
shortname="t1tttt_625to650_200to400";
name="SMS-T1tttt_mGluino-625to650_mLSP-200to400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_650to675_250to425:
shortname="t1tttt_650to675_250to425";
name="SMS-T1tttt_mGluino-650to675_mLSP-250to425_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_700to750_200to500:
shortname="t1tttt_700to750_200to500";
name="SMS-T1tttt_mGluino-700to750_mLSP-200to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1150_1to800:
shortname="t1tttt_1150_1to800";
name="SMS-T1tttt_mGluino-1150_mLSP-1to800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1150to1175_750to925:
shortname="t1tttt_1150to1175_750to925";
name="SMS-T1tttt_mGluino-1150to1175_mLSP-750to925_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1200_1to825:
shortname="t1tttt_1200_1to825";
name="SMS-T1tttt_mGluino-1200_mLSP-1to825_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1200to1225_800to1000:
shortname="t1tttt_1200to1225_800to1000";
name="SMS-T1tttt_mGluino-1200to1225_mLSP-800to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1250to1275_700to1050:
shortname="t1tttt_1250to1275_700to1050";
name="SMS-T1tttt_mGluino-1250to1275_mLSP-700to1050_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1325to1350_1to1125:
shortname="t1tttt_1325to1350_1to1125";
name="SMS-T1tttt_mGluino-1325to1350_mLSP-1to1125_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1400_1to1175:
shortname="t1tttt_1400_1to1175";
name="SMS-T1tttt_mGluino-1400_mLSP-1to1175_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1400to1425_50to1100:
shortname="t1tttt_1400to1425_50to1100";
name="SMS-T1tttt_mGluino-1400to1425_mLSP-50to1100_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1425to1450_1to1200:
shortname="t1tttt_1425to1450_1to1200";
name="SMS-T1tttt_mGluino-1425to1450_mLSP-1to1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1450to1475_50to1075:
shortname="t1tttt_1450to1475_50to1075";
name="SMS-T1tttt_mGluino-1450to1475_mLSP-50to1075_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1475to1500_1to1250:
shortname="t1tttt_1475to1500_1to1250";
name="SMS-T1tttt_mGluino-1475to1500_mLSP-1to1250_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1525to1550_1to1300: //bad
shortname="t1tttt_1525to1550_1to1300";
name="SMS-T1tttt_mGluino-1525to1550_mLSP-1to1300_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1600to1650_1to1350:
shortname="t1tttt_1600to1650_1to1350";
name="SMS-T1tttt_mGluino-1600to1650_mLSP-1to1350_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1650to1700_1to1400:
shortname="t1tttt_1650to1700_1to1400";
name="SMS-T1tttt_mGluino-1650to1700_mLSP-1to1400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1700to1750_1to1450:
shortname="t1tttt_1700to1750_1to1450";
name="SMS-T1tttt_mGluino-1700to1750_mLSP-1to1450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1750_50to1450:
shortname="t1tttt_1750_50to1450";
name="SMS-T1tttt_mGluino-1750_mLSP-50to1450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1850to1900_1to1450:
shortname="t1tttt_1850to1900_1to1450";
name="SMS-T1tttt_mGluino-1850to1900_mLSP-1to1450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1900to1950_0to1450:
shortname="t1tttt_1900to1950_0to1450";
name="SMS-T1tttt_mGluino-1900to1950_mLSP-0to1450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_600_250to325:
shortname="t1tttt_600_250to325";
name="SMS-T1tttt_mGluino-600_mLSP-250to325_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_675_325to450:
shortname="t1tttt_675_325to450";
name="SMS-T1tttt_mGluino-675_mLSP-325to450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_700_1to450:
shortname="t1tttt_700_1to450";
name="SMS-T1tttt_mGluino-700_mLSP-1to450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_750to775_350to525:
shortname="t1tttt_750to775_350to525";
name="SMS-T1tttt_mGluino-750to775_mLSP-350to525_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_775_475to550:
shortname="t1tttt_775_475to550";
name="SMS-T1tttt_mGluino-775_mLSP-475to550_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_800to825_1to575:
shortname="t1tttt_800to825_1to575";
name="SMS-T1tttt_mGluino-800to825_mLSP-1to575_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_825to850_200to600:
shortname="t1tttt_825to850_200to600";
name="SMS-T1tttt_mGluino-825to850_mLSP-200to600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_850to875_450to625:
shortname="t1tttt_850to875_450to625";
name="SMS-T1tttt_mGluino-850to875_mLSP-450to625_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_875to900_1to650:
shortname="t1tttt_875to900_1to650";
name="SMS-T1tttt_mGluino-875to900_mLSP-1to650_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_950to975_350to725:
shortname="t1tttt_950to975_350to725";
name="SMS-T1tttt_mGluino-950to975_mLSP-350to725_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_975_600to750:
shortname="t1tttt_975_600to750";
name="SMS-T1tttt_mGluino-975_mLSP-600to750_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1375_950to1150:
shortname="t1tttt_1375_950to1150";
name="SMS-T1tttt_mGluino-1375_mLSP-950to1150_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1000to1050_1to800:
shortname="t1tttt_1000to1050_1to800";
name="SMS-T1tttt_mGluino-1000to1050_mLSP-1to800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1000_1to700:
shortname="t1tttt_1000_1to700";
name="SMS-T1tttt_mGluino-1000_mLSP-1to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1050_50to775:
shortname="t1tttt_1050_50to775";
name="SMS-T1tttt_mGluino-1050_mLSP-50to775_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1050to1075_650to850:
shortname="t1tttt_1050to1075_650to850";
name="SMS-T1tttt_mGluino-1050to1075_mLSP-650to850_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1225to1250_1to1025:
shortname="t1tttt_1225to1250_1to1025";
name="SMS-T1tttt_mGluino-1225to1250_mLSP-1to1025_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_1550to1575_500to1175:
shortname="t1tttt_1550to1575_500to1175";
name="SMS-T1tttt_mGluino-1550to1575_mLSP-500to1175_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_600_1to225:
shortname="t1tttt_600_1to225";
name="SMS-T1tttt_mGluino-600_mLSP-1to225_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_600to625_250to375:
shortname="t1tttt_600to625_250to375";
name="SMS-T1tttt_mGluino-600to625_mLSP-250to375_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T1TTTT_900to950_200to700:
shortname="t1tttt_900to950_200to700";
name="SMS-T1tttt_mGluino-900to950_mLSP-200to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=1;
break;
case T5QQQQVV_main:
shortname="t5qqqqvv_main";
name="SMS-T5qqqqVV_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16Fast_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
isSignal=2;
break;
case T5QQQQVV_dm20:
shortname="t5qqqqvv_dm20";
name="SMS-T5qqqqVV_dM20_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16Fast_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
isSignal=3;
break;
case T5QQQQVV_1200To1275_1to1150:
shortname="t5qqqqvv_1200to1275_1to1150";
name="SMS-T5qqqqVV_mGluino-1200To1275_mLSP-1to1150_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=2;
break;
case T5QQQQVV_1300To1375_1to1250:
shortname="t5qqqqvv_1300to1375_1to1250";
name="SMS-T5qqqqVV_mGluino-1300To1375_mLSP-1to1250_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=2;
break;
case T5QQQQVV_1400To1550_1To1275:
shortname="t5qqqqvv_1400to1550_1to1275";
name="SMS-T5qqqqVV_mGluino-1400To1550_mLSP-1To1275_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=2;
break;
case T5QQQQVV_1600To1750_1To950:
shortname="t5qqqqvv_1600to1750_1to950";
name="SMS-T5qqqqVV_mGluino-1600To1750_mLSP-1To950_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=2;
break;
case T5QQQQVV_600To675_1to550:
shortname="t5qqqqvv_600to675_1to550";
name="SMS-T5qqqqVV_mGluino-600To675_mLSP-1to550_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=2;
break;
case T5QQQQVV_700To775_1To650:
shortname="t5qqqqvv_700to775_1to650";
name="SMS-T5qqqqVV_mGluino-700To775_mLSP-1To650_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=2;
break;
case T5QQQQVV_800To975_1To850:
shortname="t5qqqqvv_800to975_1to850";
name="SMS-T5qqqqVV_mGluino-800To975_mLSP-1To850_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=2;
break;
case T6TTWW_main:
shortname="t6ttww_main";
name="SMS-T6ttWW_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16Fast_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
isSignal=10;
break;
case T6TTWW_50_300to600_75to125:
shortname="t6ttww_50_300to600_75to125";
name="SMS-T6ttWW_mLSP50_mSbottom-300to600_mChargino-75to125_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=3;
break;
case T6TTWW_50_350to600_150to400:
shortname="t6ttww_50_350to600_150to400";
name="SMS-T6ttWW_mLSP50_mSbottom-350to600_mChargino-150to400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=3;
break;
case T6TTWW_50_625to950_500to850:
shortname="t6ttww_50_625to950_500to850";
name="SMS-T6ttWW_mLSP50_mSbottom-625to950_mChargino-500to850_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=3;
break;
case T6TTWW_50_625to950_550to875:
shortname="t6ttww_50_625to950_550to875";
name="SMS-T6ttWW_mLSP50_mSbottom-625to950_mChargino-550to875_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=3;
break;
case T6TTWW_50_625to950_75to125:
shortname="t6ttww_50_625to950_75to125";
name="SMS-T6ttWW_mLSP50_mSbottom-625to950_mChargino-75to125_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=3;
break;
case T6TTWW_50_650to950_150to750:
shortname="t6ttww_50_650to950_150to750";
name="SMS-T6ttWW_mLSP50_mSbottom-650to950_mChargino-150to750_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=3;
break;
case T6TTWW_50_300to600_150to500:
shortname="t6ttww_50_300to600_150to500";
name="SMS-T6ttWW_mLSP50_mSbottom-300to600_mChargino-150to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=3;
break;
case T5QQQQWW_1025to1200_0to1175:
shortname="t5qqqqww_1025to1200_0to1175";
name="SMS-T5qqqqWW_mGl-1025to1200_mLSP-0to1175_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=4;
break;
case T5QQQQWW_1225to1400_0to1175:
shortname="t5qqqqww_1225to1400_0to1175";
name="SMS-T5qqqqWW_mGl-1225to1400_mLSP-0to1175_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=4;
break;
case T5QQQQWW_1425to1600_0to1175:
shortname="t5qqqqww_1425to1600_0to1175";
name="SMS-T5qqqqWW_mGl-1425to1600_mLSP-0to1175_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=4;
break;
case T5QQQQWW_1650to1700_0to1150:
shortname="t5qqqqww_1650to1700_0to1150";
name="SMS-T5qqqqWW_mGl-1650to1700_mLSP-0to1150_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=4;
break;
case T5QQQQWW_600to800_0to725:
shortname="t5qqqqww_600to800_0to725";
name="SMS-T5qqqqWW_mGl-600to800_mLSP-0to725_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=4;
break;
case T5QQQQWW_825to1000_0to925:
shortname="t5qqqqww_825to1000_0to925";
name="SMS-T5qqqqWW_mGl-825to1000_mLSP-0to925_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=4;
break;
case T1TTBB_main:
shortname="t1ttbb_main";
name="SMS-T1ttbb_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16Fast_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
isSignal=6;
break;
case T1TTBB_1425to1600_0to1250:
shortname="t1ttbb_1425to1600_0to1250";
isSignal=5;
name="SMS-T1ttbb_mGl-1425to1600_mLSP-0to1250_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
break;
case T1TTBB_1425to1600_1100to1350:
shortname="t1ttbb_1425to1600_1100to1350";
isSignal=5;
name="SMS-T1ttbb_mGl-1425to1600_mLSP-1100to1350_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
break;
case T1TTBB_600to800_275to575:
shortname="t1ttbb_600to800_275to575";
isSignal=5;
name="SMS-T1ttbb_mGl-600to800_mLSP-275to575_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
break;
case T1TTBB_1225to1400_900to1175:
shortname="t1ttbb_1225to1400_900to1175";
name="SMS-T1ttbb_mGl-1225to1400_mLSP-900to1175_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1/";
isSignal=5;
break;
case T1TTBB_1650to2000_0to1450:
shortname="t1ttbb_1650to2000_0to1450";
name="SMS-T1ttbb_mGl-1650to2000_mLSP-0to1450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1/";
isSignal=5;
break;
case T1TTBB_825to1000_500to775:
shortname="t1ttbb_825to1000_500to775";
name="SMS-T1ttbb_mGl-825to1000_mLSP-500to775_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1/";
isSignal=5;
break;
case T1TTBB_1650to1750_1350to1450:
shortname="t1ttbb_1650to1750_1350to1450";
name="SMS-T1ttbb_mGl-1650to1750_mLSP-1350to1450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=5;
break;
case T1TTBB_825to1000_0to625:
shortname="t1ttbb_825to1000_0to625";
name="SMS-T1ttbb_mGl-825to1000_mLSP-0to650_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=5;
break;
case T1TTBB_600to800_0to450:
shortname="t1ttbb_600to800_0to450";
name="SMS-T1ttbb_mGl-600to800_mLSP-0to450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=5;
break;
case T1TTBB_1025to1200_700to975:
shortname="t1ttbb_1025to1200_700to975";
name="SMS-T1ttbb_mGl-1025to1200_mLSP-700to975_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=5;
break;
case T1TTBB_1025to1200_0to850:
name="SMS-T1ttbb_mGl-1025to1200_mLSP-0to850_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15FSPremix-MCRUN2_74_V9-v1";
shortname="t1ttbb_1025to1200_0to850";
isSignal=5;
break;
case T5TTTT_dm175:
shortname="t5tttt_dm175";
name="SMS-T5tttt_dM175_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16Fast_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v1";
isSignal=5;
break;
case T5ttttDM175_1025to1200_700to925:
shortname="t5ttttdm175_1025to1200_700to925";
name="SMS-T5ttttDM175_mGl-1025to1200_mLSP-700to925_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_1225to1400_0to1050:
shortname="t5ttttdm175_1225to1400_0to1050";
name="SMS-T5ttttDM175_mGl-1225to1400_mLSP-0to1050_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_1225to1400_900to1125:
shortname="t5ttttdm175_1225to1400_900to1125";
name="SMS-T5ttttDM175_mGl-1225to1400_mLSP-900to1125_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_1425to1625_1100to1300:
shortname="t5ttttdm175_1425to1625_1100to1300";
name="SMS-T5ttttDM175_mGl-1425to1625_mLSP-1100to1300_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_600to800_275to525:
shortname="t5ttttdm175_600to800_275to525";
name="SMS-T5ttttDM175_mGl-600to800_mLSP-275to525_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_825to1000_0to650:
shortname="t5ttttdm175_825to1000_0to650";
name="SMS-T5ttttDM175_mGl-825to1000_mLSP-0to650_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_1425to1600_0to1250:
shortname="t5ttttdm175_1425to1600_0to1250";
name="SMS-T5ttttDM175_mGl-1425to1600_mLSP-0to1250_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_1025to1200_0to850:
shortname="t5ttttdm175_1025to1200_0to850";
name="SMS-T5ttttDM175_mGl-1025to1200_mLSP-0to850_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_600to800_0to450:
shortname="t5ttttdm175_600to800_0to450";
name="SMS-T5ttttDM175_mGl-600to800_mLSP-0to450_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5ttttDM175_1625to1700_0to1300:
shortname="t5ttttdm175_1625to1700_0to1300";
name="SMS-T5ttttDM175_mGl-1625to1700_mLSP-0to1300_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=6;
break;
case T5tttt_degen_1225to1400_1075to1275:
shortname="t5tttt_degen_1225to1400_1075to1275";
name="SMS-T5tttt_degen_mGl-1225to1400_mLSP-1075to1275_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_1425to1600_1275to1375:
shortname="t5tttt_degen_1425to1600_1275to1375";
name="SMS-T5tttt_degen_mGl-1425to1600_mLSP-1275to1375_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_825to1000_0to825:
shortname="t5tttt_degen_825to1000_0to825";
name="SMS-T5tttt_degen_mGl-825to1000_mLSP-0to825_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_825to1000_675to875:
shortname="t5tttt_degen_825to1000_675to875";
name="SMS-T5tttt_degen_mGl-825to1000_mLSP-675to875_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_1225to1400_0to1225:
shortname="t5tttt_degen_1225to1400_0to1225";
name="SMS-T5tttt_degen_mGl-1225to1400_mLSP-0to1225_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_600to800_450to675:
shortname="t5tttt_degen_600to800_450to675";
name="SMS-T5tttt_degen_mGl-600to800_mLSP-450to675_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_1425to1600_0to1350:
shortname="t5tttt_degen_1425to1600_0to1350";
name="SMS-T5tttt_degen_mGl-1425to1600_mLSP-0to1350_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_1650to1700_0to1350:
shortname="t5tttt_degen_1650to1700_0to1350";
name="SMS-T5tttt_degen_mGl-1650to1700_mLSP-0to1350_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_1025to1200_0to1025:
shortname="t5tttt_degen_1025to1200_0to1025";
name="SMS-T5tttt_degen_mGl-1025to1200_mLSP-0to1025_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=7;
break;
case T5tttt_degen_600to800_0to625:
name="SMS-T5tttt_degen_mGl-600to800_mLSP-0to625_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
shortname="t5tttt_degen_600to800_0to625";
isSignal=7;
break;
case T5tttt_degen_1025to1200_875to1075:
name="SMS-T5tttt_degen_mGl-1025to1200_mLSP-875to1075_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v2";
shortname="t5tttt_degen_1025to1200_875to1075";
isSignal=7;
break;
case T5TTCC_main:
shortname="t5ttcc_main";
name="SMS-T5ttcc_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring16MiniAODv2-PUSpring16Fast_80X_mcRun2_asymptotic_2016_miniAODv2_v0-v3";
isSignal=4;
break;
case T5ttcc_1025to1200_875to1075:
shortname="t5ttcc_1025to1200_875to1075";
name="SMS-T5ttcc_mGl-1025to1200_mLSP-875to1075_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_825to1000_0to825:
shortname="t5ttcc_825to1000_0to825";
name="SMS-T5ttcc_mGl-825to1000_mLSP-0to825_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_600to800_450to675:
shortname="t5ttcc_600to800_450to675";
name="SMS-T5ttcc_mGl-600to800_mLSP-450to675_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_1225to1400_1075to1225:
shortname="t5ttcc_1225to1400_1075to1225";
name="SMS-T5ttcc_mGl-1225to1400_mLSP-1075to1225_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_1225to1400_0to1225:
shortname="t5ttcc_1225to1400_0to1225";
name="SMS-T5ttcc_mGl-1225to1400_mLSP-0to1225_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_1650to1700_0to1350:
shortname="t5ttcc_1650to1700_0to1350";
name="SMS-T5ttcc_mGl-1650to1700_mLSP-0to1350_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_1425to1525_1275to1375:
shortname="t5ttcc_1425to1525_1275to1375";
name="SMS-T5ttcc_mGl-1425to1525_mLSP-1275to1375_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_1025to1200_0to1025:
shortname="t5ttcc_1025to1200_0to1025";
name="SMS-T5ttcc_mGl-1025to1200_mLSP-0to1025_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15MiniAODv2-FastAsympt25ns_74X_mcRun2_asymptotic_v2-v1";
isSignal=8;
break;
case T5ttcc_600to800_0to625:
shortname="t5ttcc_600to800_0to625";
name="SMS-T5ttcc_mGl-600to800_mLSP-0to625_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15FSPremix-MCRUN2_74_V9-v1";
isSignal=8;
break;
case T5ttcc_1425to1600_0to1350:
shortname="t5ttcc_1425to1600_0to1350";
name="SMS-T5ttcc_mGl-1425to1600_mLSP-0to1350_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_RunIISpring15FSPremix-MCRUN2_74_V9-v1";
isSignal=8;
break;
case ANA1:
shortname="ana1";
name="ana_test1";
isSignal=100;
break;
case ANA2:
shortname="ana2";
name="ana_test2";
isSignal=101;
break;
case ANA3:
shortname="ana3";
name="ana_test3";
isSignal=102;
break;
default:
name="dummy";
path="/store/group/snt/run2_25ns/";
break;
}
if (isSignal >= 100) filename = Form("ntuple_%i.root", file);
//Path for signal
if (isSignal > 0){
path="/store/group/snt/run2_25ns_80MiniAODv2_fastsim";
tag="V08-00-09";
}
//Set up file and tree
cout << "Using xrootd " << endl;
mylooper->MakeBabyNtuple(Form("%s%s", shortname.c_str(), suffix), isSignal);
TFile *f;
if (path.find("nfs") < path.length()) f = TFile::Open(Form("%s/%s/%s/%s", path.c_str(), name.c_str(), tag.c_str(), filename));
else f = TFile::Open(Form("root://cmsxrootd.fnal.gov//%s/%s/%s/%s", path.c_str(), name.c_str(), tag.c_str(), filename));
cout << "File opened...." << endl;
TTree *tree = (TTree*)f->Get("Events");
cms3.Init(tree);
//Event Counting
unsigned int nEvents = tree->GetEntries();
unsigned int nEventsTotal = 0;
cout << "nEvents: " << tree->GetEntries() << endl;
//Add good run list
set_goodrun_file("goldenJson_2016rereco_36p46ifb.txt");
// string jecEra = "Fall15_25nsV2";
string jecEra = "Spring16_25nsV6";
//Make Jet Energy Uncertainties
JetCorrectionUncertainty *jecUnc = 0;
if ( isData) jecUnc = new JetCorrectionUncertainty("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_DATA_Uncertainty_AK4PFchs.txt");
if (!isData) jecUnc = new JetCorrectionUncertainty("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_MC_Uncertainty_AK4PFchs.txt");
if (isSignal > 0) jecUnc = new JetCorrectionUncertainty("CORE/Tools/jetcorr/data/run2_25ns/Spring16_FastSimV1_Uncertainty_AK4PFchs.txt");
//Init MVA
// createAndInitMVA("./CORE", true, true); // ICHEP
createAndInitMVA("./CORE", true, false, 80); // Moriond
//JEC files -- 25 ns MC
std::vector<std::string> jetcorr_filenames_25ns_MC_pfL1L2L3;
jetcorr_filenames_25ns_MC_pfL1L2L3.push_back ("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_MC_L1FastJet_AK4PFchs.txt");
jetcorr_filenames_25ns_MC_pfL1L2L3.push_back ("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_MC_L2Relative_AK4PFchs.txt");
jetcorr_filenames_25ns_MC_pfL1L2L3.push_back ("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_MC_L3Absolute_AK4PFchs.txt");
//JEC files -- 25 ns DATA
std::vector<std::string> jetcorr_filenames_25ns_DATA_pfL1L2L3;
jetcorr_filenames_25ns_DATA_pfL1L2L3.push_back("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_DATA_L1FastJet_AK4PFchs.txt");
jetcorr_filenames_25ns_DATA_pfL1L2L3.push_back("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_DATA_L2Relative_AK4PFchs.txt");
jetcorr_filenames_25ns_DATA_pfL1L2L3.push_back("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_DATA_L3Absolute_AK4PFchs.txt");
jetcorr_filenames_25ns_DATA_pfL1L2L3.push_back("CORE/Tools/jetcorr/data/run2_25ns/"+jecEra+"_DATA_L2L3Residual_AK4PFchs.txt");
//JEC files -- 25 ns FASTSIM
std::vector<std::string> jetcorr_filenames_25ns_FASTSIM_pfL1L2L3;
jetcorr_filenames_25ns_FASTSIM_pfL1L2L3.push_back("CORE/Tools/jetcorr/data/run2_25ns/Spring16_FastSimV1_L1FastJet_AK4PFchs.txt");
jetcorr_filenames_25ns_FASTSIM_pfL1L2L3.push_back("CORE/Tools/jetcorr/data/run2_25ns/Spring16_FastSimV1_L2Relative_AK4PFchs.txt");
jetcorr_filenames_25ns_FASTSIM_pfL1L2L3.push_back("CORE/Tools/jetcorr/data/run2_25ns/Spring16_FastSimV1_L3Absolute_AK4PFchs.txt");
//JECs
std::vector<std::string> filenames;
if ( isData ) filenames = jetcorr_filenames_25ns_DATA_pfL1L2L3;
if (!isData ) filenames = jetcorr_filenames_25ns_MC_pfL1L2L3;
if (isSignal > 0) filenames = jetcorr_filenames_25ns_FASTSIM_pfL1L2L3;
FactorizedJetCorrector *jetCorrAG;
jetCorrAG = makeJetCorrector(filenames);
//Histograms for cross-section calculation
struct csErr_info_t { TH1F* cs; float cs_scale_up; float cs_scale_dn; float cs_pdf[102]; TH1F* results; int nEntries; int mGluino; int mLSP;};
vector <csErr_info_t> csErr_info_v;
bool haveMadeErrStruct = false;
//Event Loop
for(unsigned int eventAG=0; eventAG < nEvents; eventAG++){
if ((nevents_max > 0) && (eventAG > nevents_max)) break;
//Get Event Content
cms3.GetEntry(eventAG);
nEventsTotal++;
//See if mass point exists already
int idx = -1;
if (isSignal > 0){
int mGluino = tas::sparm_values().at(0);
int mLSP = tas::sparm_values().at(1);
for (unsigned int i = 0; i < csErr_info_v.size(); i++){
if (mGluino == csErr_info_v[i].mGluino && mLSP == csErr_info_v[i].mLSP){ idx = i; break; }
}
if (idx < 0){
csErr_info_t csErr;
csErr.cs = new TH1F(Form("cs_%i_%i", mGluino, mLSP), Form("cs_%i_%i", mGluino, mLSP), 1, 0, 1);
csErr.cs->Sumw2();
csErr.cs_scale_up = 0;
csErr.cs_scale_dn = 0;
for (int i = 0; i < 102; i++) csErr.cs_pdf[i] = 0;
csErr.results = new TH1F(Form("csErr_%i_%i", mGluino, mLSP), Form("csErr_%i_%i", mGluino, mLSP), 16000, 0, 16000);
csErr.results->Sumw2();
csErr.nEntries = 0;
csErr.mGluino = mGluino;
csErr.mLSP = mLSP;
idx = csErr_info_v.size();
csErr_info_v.push_back(csErr);
}
} else if (!(tas::evt_isRealData())) {
if (!haveMadeErrStruct) {
csErr_info_t csErr;
csErr.cs = new TH1F("cs","cs", 1, 0, 1);
csErr.cs->Sumw2();
csErr.cs_scale_up = 0;
csErr.cs_scale_dn = 0;
for (int i = 0; i < 102; i++) csErr.cs_pdf[i] = 0;
csErr.results = new TH1F("csErr","csErr", 16000, 0, 16000);
csErr.results->Sumw2();
csErr.nEntries = 0;
idx = 0;
csErr_info_v.push_back(csErr);
haveMadeErrStruct = true;
}
}
//If data, check good run list
if (tas::evt_isRealData() && !goodrun(tas::evt_run(), tas::evt_lumiBlock())) continue;
//Progress bar
CMS3::progress(nEventsTotal, nEvents);
csErr_t csErr = mylooper->ProcessBaby(name, jetCorrAG, jecUnc, file, isSignal);
int SR = csErr.SR;
bool isGood = csErr.isGood;
//c-s error variables
if (isSignal > 0 || haveMadeErrStruct){
if (haveMadeErrStruct) idx = 0;
csErr_info_v[idx].results->Fill(0.5, 1);
csErr_info_v[idx].results->Fill(3.5, csErr.cs_scale_up);
csErr_info_v[idx].results->Fill(4.5, csErr.cs_scale_dn);
if (SR > 0 && isGood) csErr_info_v[idx].results->Fill(200+SR-0.5, csErr.cs_scale_no);
if (SR > 0 && isGood) csErr_info_v[idx].results->Fill(400+SR-0.5, csErr.cs_scale_up);
if (SR > 0 && isGood) csErr_info_v[idx].results->Fill(600+SR-0.5, csErr.cs_scale_dn);
for (unsigned int i = 0; i < 100; i++){
if (SR > 0 && isGood) csErr_info_v[idx].results->Fill(1000+100*(SR-1)+i-0.5, csErr.cs_pdf[i]);
csErr_info_v[idx].results->Fill(6+i-0.5, csErr.cs_pdf[i]);
}
if (SR > 0 && isGood) csErr_info_v[idx].results->Fill(15600+SR-0.5, csErr.cs_pdf[100]);
if (SR > 0 && isGood) csErr_info_v[idx].results->Fill(15700+SR-0.5, csErr.cs_pdf[101]);
}
}//event loop
if (isSignal > 0 || haveMadeErrStruct){
for (unsigned int j = 0; j < csErr_info_v.size(); j++){
//bin 1: nEntries
//bin 2: cross-section
csErr_info_v[j].results->SetBinContent(2, csErr_info_v[j].cs->Integral());
//bin 3: cross-section stat err
csErr_info_v[j].results->SetBinError(3, csErr_info_v[j].cs->GetBinError(1));
//bin 4: cross-section scale up
//bin 5: cross-section scale dn
//bin 6-107: cross-section PDF error
//bin 201-266: yield in each SR (for cross-check)
//bin 401-466: scale up in each SR
//bin 601-666: scale dn in each SR
//bin 1000-1099: SR1 PDF weights
//bin 1100-1199: SR2 PDF weights
//bin 7500-7599: SR66 PDF weights
//bin 15600-15666: alpha_s up in each SR
//bin 15700-15766: alpha_s dn in each SR
}
}
//Delete Chain
mylooper->CloseBabyNtuple();
//Open the baby file again
TFile* BabyFile = new TFile(Form("%s_%i.root", shortname.c_str(), file), "UPDATE");
BabyFile->cd();
for (unsigned int j = 0; j < csErr_info_v.size(); j++){
csErr_info_v[j].results->Write();
}
return 0;
}
/* vim: set ft=cpp: */
|
aa41166b0c7db247771c6ac8dbd2a216ff97c8e1 | 9063052d8e2c294efa3b501d42aef2ac59d84fa0 | /jiju_algo_practice/7급adv/7급adv/hamming.cpp | 22fd161f92e72e44f1e5dc7cb8122e892c752e03 | [] | no_license | yes99/practice2020 | ffe5502d23038eabea834ebc2b18ff724f849c4a | 100ac281f4fe6d0f991213802fbd8524451f1ac2 | refs/heads/master | 2021-07-08T00:54:19.728874 | 2021-06-13T05:52:07 | 2021-06-13T05:52:07 | 245,789,109 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 1,154 | cpp | hamming.cpp | #include <iostream>
#include<fstream>
#include<string>
#include <math.h>
using namespace std;
// ii >>
// oo <<
int main()
{
string hamming;
//ifstream ii("C:\\이현석\\input.txt");
ifstream ii("input.txt");
//ofstream oo("C:\\이현석\\output.txt");
ofstream oo("output.txt");
getline(ii, hamming);
int c1=0, c2=0, c3=0;
int i, j, k;
int check[3];
int h;
for (i = 0; i < 7; i=i+2)
{
if ( hamming[i] == 49)
{
c1++;
}
}
if (c1 % 2 == 1)
{
check[2] = 1;
}
else
{
check[2] = 0;
}
for (j = 1; j < 7; j++)
{
if (hamming[j] == 49)
{
c2++;
}
if (j == 2)
{
j = j + 2;
}
}
if (c2 % 2 == 1)
{
check[1] = 1;
}
else
{
check[1] = 0;
}
for (k = 3; k < 7; k++)
{
if (hamming[k] == 49)
{
c3++;
}
}
if (c3 % 2 == 1)
{
check[0] = 1;
}
else
{
check[0] = 0;
}
//그래서 나온 2진수
//oo << check[0]<<check[1]<<check[2] << endl;
int error = 4 * check[0] + 2 * check[1] + check[2] -1;
if (hamming[error] == 49)
{
hamming[error] = 48;
}
else
{
hamming[error] = 49;
}
int f;
for (f = 0; f < 7; f++)
{
oo << hamming[f];
}
ii.close();
oo.close();
return 0;
} |
db63c7c1f3876c01f2c79b97b0e6e94b91fea032 | 62c8d47803da82bc6b7a276e0c54796601c66276 | /src/sound/sounddriver.h | b5825bf5a4797ac3da107f01574bb3a0d31a8d2e | [
"MIT",
"GPL-2.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | autc04/executor | a01d1c5081251a331067596141422568159a7596 | ada40683c14d9dfb2a660e52378e9864e0d51357 | refs/heads/master | 2023-07-21T14:33:48.612380 | 2023-05-07T21:33:31 | 2023-05-07T21:33:31 | 106,850,181 | 125 | 9 | MIT | 2023-07-07T14:12:07 | 2017-10-13T16:48:51 | C++ | UTF-8 | C++ | false | false | 978 | h | sounddriver.h | #if !defined(_RSYS_SOUNDDRIVER_H_)
#define _RSYS_SOUNDDRIVER_H_
#include <sound/soundopts.h>
namespace Executor
{
struct HungerInfo
{
snd_time t2; /* Time of earliest sample which can be provided */
snd_time t3; /* Time of latest sample which must be provided */
unsigned char *buf; /* nullptr means there is no buffer; just "pretend" */
int bufsize; /* to fill it in; (!buf && bufsize) is possible! */
int rate;
};
class SoundDriver
{
public:
virtual bool sound_init() = 0;
virtual void sound_shutdown() = 0;
virtual bool sound_works() = 0;
virtual bool sound_silent() = 0;
virtual void sound_go() = 0;
virtual void sound_stop() = 0;
virtual HungerInfo HungerStart() = 0;
virtual void HungerFinish() = 0;
virtual void sound_clear_pending() {};
virtual ~SoundDriver();
};
/* Current sound driver in use. */
extern SoundDriver *sound_driver;
extern void sound_init(void);
}
#endif /* !_RSYS_SOUNDDRIVER_H_ */
|
11201e0a6a4d26a5f07d2225c13baa3b5e4d96fd | 0ab72b7740337ec0bcfec102aa7c740ce3e60ca3 | /include/km/step-propagator/property-name.h | 48cbd8269560c3f7a923ad19bda307143a6ba10d | [] | no_license | junwang-nju/mysimulator | 1d1af4ad7ddbe114433ebdadd92de8bb3a45c04f | 9c99970173ce87c249d2a2ca6e6df3a29dfc9b86 | refs/heads/master | 2021-01-10T21:43:01.198526 | 2012-12-15T23:22:56 | 2012-12-15T23:22:56 | 3,367,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | h | property-name.h |
#ifndef _Step_Propagator_Property_Name_H_
#define _Step_Propagator_Property_Name_H_
namespace mysimulator {
enum MassPropertyName {
UniqueMass=0,
ArrayMass,
UnknownMassProperty
};
enum FrictionPropertyName {
UniqueFriction=0,
ArrayFriction,
UnknownFrictionProperty
};
}
#endif
|
4273a2c8add9d13e85d0a10c747dd16f034513eb | f1aaed1e27416025659317d1f679f7b3b14d654e | /MenuMate/MenuMate/Source/ManagerMenus.cpp | f807c5ed686d673ffc5c8980e5f1fe1f0d5ebd47 | [] | no_license | radtek/Pos | cee37166f89a7fcac61de9febb3760d12b823ce5 | f117845e83b41d65f18a4635a98659144d66f435 | refs/heads/master | 2020-11-25T19:49:37.755286 | 2016-09-16T14:55:17 | 2016-09-16T14:55:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61,408 | cpp | ManagerMenus.cpp | //---------------------------------------------------------------------------
#pragma hdrstop
#include "ManagerMenus.h"
#include "MMLogging.h"
#include "MMUtilFunc.h"
#include "MM_Menu.h"
#include "ItemSize.h"
#include "ListCourse.h"
#include "enumMenu.h"
#include "ItemRecipe.h"
#include "ItemSizeCategory.h"
#include "DeviceRealControl.h"
#include <stdexcept>
#include <cassert>
#ifdef MenuMate
#include "PhoenixHotelSystem.h"
#endif
#include <vector>
#include <i_item_definition.hh>
#include <i_item_definition_factory.hh>
#include <i_item_manager.hh>
#include <i_menu_manager.hh>
#include <i_size_definition.hh>
#include <i_size_definition_factory.hh>
#include <item_management_booter.hh>
using item_management::i_item_definition;
using item_management::i_item_definition_factory;
using item_management::i_item_manager;
using item_management::i_menu_manager;
using item_management::i_size_definition;
using item_management::i_size_definition_factory;
//---------------------------------------------------------------------------
#pragma package(smart_init)
std::pair<UnicodeString, bool>
TManagerMenus::MenuName(const int menu_key)
const
{
std::pair<UnicodeString, bool> name_pair;
Database::TDBTransaction tr(
TDeviceRealControl::ActiveInstance().DBControl);
TIBSQL *q = tr.Query(tr.AddQuery());
q->SQL->Text = "select menu_name "
" from menu "
" where menu_key = :key;";
tr.StartTransaction();
q->ParamByName("key")->AsInteger = menu_key;
if ((name_pair.second = (q->ExecQuery(), q->RecordCount)))
name_pair.first = q->FieldByName("menu_name")->AsString;
tr.Commit();
q->Close();
return name_pair;
}
TItemSize *
TManagerMenus::FetchItemSizeByBarcode(
const UnicodeString barcode)
{
return Current->FetchItemSizeByBarcode(barcode);
}
std::auto_ptr<std::vector<TItem *> >
TManagerMenus::FetchItemsBySetMenuMask(
const unsigned long set_menu_mask)
{
return Current->FetchItemsBySetMenuMask(set_menu_mask);
}
std::auto_ptr<std::vector<TItem *> >
TManagerMenus::FetchItemsBySetMenuMaskByMenu(
const unsigned long set_menu_mask,
const UnicodeString menu_name)
{
return Current->FetchItemsBySetMenuMaskByMenu(set_menu_mask,
menu_name);
}
void
TManagerMenus::GetMenuList(
std::vector<std::pair<UnicodeString, int> > &destination,
const TMenuType menu_type,
const bool include_deleted,
const bool only_palmable)
{
Database::TDBTransaction tr(
TDeviceRealControl::ActiveInstance().DBControl);
TIBSQL *qr = tr.Query(tr.AddQuery());
qr->SQL->Text = "select menu_key, "
" menu_name "
" from menu "
" where menu_type = :menu_type ";
if (!include_deleted)
qr->SQL->Text = qr->SQL->Text
+ "and deleted = 'F' ";
if (only_palmable)
qr->SQL->Text = qr->SQL->Text
+ "and palmable = 'T' ";
qr->SQL->Text = qr->SQL->Text
+ "order by menu_name, "
" menu_key ";
tr.StartTransaction();
qr->ParamByName("menu_type")->AsInteger = static_cast<int>(menu_type);
for (qr->ExecQuery(); !qr->Eof; qr->Next())
destination.push_back(
std::pair<UnicodeString, int>(
qr->FieldByName("menu_name")->AsString,
qr->FieldByName("menu_key")->AsInteger));
tr.Commit();
}
void
TManagerMenus::GetMenuList(std::vector<UnicodeString> &destination)
const
{
Database::TDBTransaction tr(
TDeviceRealControl::ActiveInstance().DBControl);
TIBSQL *qr = tr.Query(tr.AddQuery());
qr->SQL->Text = "select menu_name "
" from menu "
" where deleted = 'F';";
for (tr.StartTransaction(), qr->ExecQuery(); !qr->Eof; qr->Next())
destination.push_back(qr->FieldByName("menu_name")->AsString);
tr.Commit();
}
void
TManagerMenus::GetMenuList(
std::vector<std::pair<UnicodeString, int> > &destination)
{
Database::TDBTransaction tr(
TDeviceRealControl::ActiveInstance().DBControl);
TIBSQL *qr = tr.Query(tr.AddQuery());
qr->SQL->Text = "select menu_key, "
" menu_name "
" from menu "
" where deleted = 'F';";
for (tr.StartTransaction(), qr->ExecQuery(); !qr->Eof; qr->Next())
destination.push_back(
std::pair<UnicodeString, int>(qr->FieldByName("menu_name")->AsString,
qr->FieldByName("menu_key")->AsInteger));
tr.Commit();
}
TItemSize *
TManagerMenus::FetchItemSizeByName(
const UnicodeString &size_name,
long inItemKey)
{
TItem *item = FetchItemByKey(inItemKey);
assert(size_name.Length() != 0);
assert(item != NULL);
return item->Sizes->SizeGet(size_name);
}
TItem *
TManagerMenus::FetchItemByID(long inItemID)
{
TItem *item = NULL;
for (int i = 0, j = Current->Count; !item && i < j; i++)
item = Current->MenuGet(i)->FetchItemByID(inItemID);
return item;
}
TItem *
TManagerMenus::FetchItemByKey(long inItemKey)
{
TItem *item = NULL;
for (int i = 0, j = Current->Count; !item && i < j; i++)
item = Current->MenuGet(i)->FetchItemByKey(inItemKey);
return item;
}
TManagerMenus::TManagerMenus() : Current(new TListMenuContainer), New(new TListMenuContainer)
{
}
TManagerMenus::Initialise(Database::TDBTransaction &DBTransaction)
{
DefaultServingCourse = LoadDefaultServingCourse(DBTransaction);
}
// ---------------------------------------------------------------------------
int TManagerMenus::GetMenuServingCourse(Database::TDBTransaction &DBTransaction, int MenuKey, int ServingCourseKey)
{
int MenuServingCourseKey = 0;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT MENUSERVINGCOURSES_KEY " "FROM MENUSERVINGCOURSES " "WHERE " "MENU_KEY = :MENU_KEY AND "
"SERVINGCOURSES_KEY = :SERVINGCOURSES_KEY";
IBInternalQuery->ParamByName("MENU_KEY")->AsInteger = MenuKey;
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount)
{
MenuServingCourseKey = IBInternalQuery->FieldByName("SERVINGCOURSES_KEY")->AsInteger;
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return MenuServingCourseKey;
}
UnicodeString TManagerMenus::GetServingCourseKitchenName(Database::TDBTransaction &DBTransaction, int ServingCourseKey)
{
UnicodeString ServingCourse = "";
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text =
"SELECT SERVINGCOURSE_KITCHEN_NAME " "FROM SERVINGCOURSES " "WHERE " "SERVINGCOURSES_KEY = :SERVINGCOURSES_KEY";
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount)
{
ServingCourse = UTF8ToUnicodeString((AnsiString)IBInternalQuery->FieldByName("SERVINGCOURSE_KITCHEN_NAME")->AsString);
}
if (ServingCourse == "")
{
ServingCourse = GetServingCourseName(DBTransaction, ServingCourseKey);
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return ServingCourse;
}
TServingCourse TManagerMenus::GetServingCourseFromDB(Database::TDBTransaction &DBTransaction, int ServingCourseKey)
{
TServingCourse ServingCourse;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text =
"SELECT SERVINGCOURSES_KEY,SERVINGCOURSE_NAME,SERVINGCOURSE_KITCHEN_NAME, " "DELETED,SELECTABLE,DISPLAY_ORDER,COLOUR " "FROM SERVINGCOURSES " "WHERE " "SERVINGCOURSES_KEY = :SERVINGCOURSES_KEY";
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount)
{
ServingCourse.ServingCourseKey = IBInternalQuery->FieldByName("SERVINGCOURSES_KEY")->AsInteger;
ServingCourse.Name = IBInternalQuery->FieldByName("SERVINGCOURSE_NAME")->AsString;
ServingCourse.KitchenName = UTF8ToUnicodeString((AnsiString)IBInternalQuery->FieldByName("SERVINGCOURSE_KITCHEN_NAME")->AsString);
/* ServingCourse.Name = IBInternalQuery->FieldByName("SERVINGCOURSE_NAME")->AsString;
ServingCourse.KitchenName = IBInternalQuery->FieldByName("SERVINGCOURSE_KITCHEN_NAME")->AsString; */
if (ServingCourse.KitchenName == UnicodeString(""))
{
ServingCourse.KitchenName = ServingCourse.Name;
}
ServingCourse.Deleted = IBInternalQuery->FieldByName("DELETED")->AsString.UpperCase() == "F" ? false : true;
ServingCourse.Selectable = IBInternalQuery->FieldByName("SELECTABLE")->AsString.UpperCase() == "F" ? false : true;
ServingCourse.SCOO = IBInternalQuery->FieldByName("DISPLAY_ORDER")->AsInteger;
ServingCourse.Colour = (TColor)IBInternalQuery->FieldByName("COLOUR")->AsInteger;
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return ServingCourse;
}
int TManagerMenus::GetServingCourseDisplayOrder(Database::TDBTransaction &DBTransaction, int ServingCourseKey)
{
int DisplayOrder = 0;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT DISPLAY_ORDER " "FROM SERVINGCOURSES " "WHERE " "SERVINGCOURSES_KEY = :SERVINGCOURSES_KEY";
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount)
{
DisplayOrder = IBInternalQuery->FieldByName("DISPLAY_ORDER")->AsInteger;
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return DisplayOrder;
}
TColor TManagerMenus::GetServingCourseColour(Database::TDBTransaction &DBTransaction, int ServingCourseKey)
{
TColor Colour = clMaroon;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT COLOUR " "FROM SERVINGCOURSES " "WHERE " "SERVINGCOURSES_KEY = :SERVINGCOURSES_KEY";
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount)
{
Colour = (TColor)IBInternalQuery->FieldByName("COLOUR")->AsInteger;
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return Colour;
}
int TManagerMenus::SetServingCourse(Database::TDBTransaction &DBTransaction, UnicodeString ServingCourse,
UnicodeString ServingCourseKitchenName, int SCOO, bool Deleted, bool Selectable, TColor ServingCourseColour)
{
int ServingCourseKey = 0;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
ServingCourseKey = GetServingCourseByName(DBTransaction, ServingCourse);
if (ServingCourseKey == 0)
{
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT GEN_ID(GEN_SERVINGCOURSES, 1) FROM RDB$DATABASE";
IBInternalQuery->ExecQuery();
ServingCourseKey = IBInternalQuery->Fields[0]->AsInteger;
IBInternalQuery->Close();
IBInternalQuery->SQL->Text =
"INSERT INTO SERVINGCOURSES (" "SERVINGCOURSES_KEY," "SERVINGCOURSE_NAME," "SERVINGCOURSE_KITCHEN_NAME,"
"DELETED," "DISPLAY_ORDER," "SELECTABLE," "COLOUR) " "VALUES (" ":SERVINGCOURSES_KEY," ":SERVINGCOURSE_NAME,"
":SERVINGCOURSE_KITCHEN_NAME," ":DELETED," ":DISPLAY_ORDER," ":SELECTABLE," ":COLOUR);";
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ParamByName("SERVINGCOURSE_NAME")->AsString = ServingCourse;
// Conversion not required as ServingCourseKitchenName is already in UTF8 Format from the Menu.csv
// IBInternalQuery->ParamByName("SERVINGCOURSE_KITCHEN_NAME")->AsString = UnicodeToUTF8AnsiString(ServingCourseKitchenName);
IBInternalQuery->ParamByName("SERVINGCOURSE_KITCHEN_NAME")->AsString = ServingCourseKitchenName;
IBInternalQuery->ParamByName("DELETED")->AsString = Deleted ? "T" : "F";
IBInternalQuery->ParamByName("SELECTABLE")->AsString = Selectable ? "T" : "F";
IBInternalQuery->ParamByName("DISPLAY_ORDER")->AsInteger = SCOO;
IBInternalQuery->ParamByName("COLOUR")->AsInteger = (int)ServingCourseColour;
IBInternalQuery->ExecQuery();
}
else
{
bool UpdateRequired = false;
TServingCourse CurrentServingCourse = GetServingCourseFromDB(DBTransaction, ServingCourseKey);
if (CurrentServingCourse.Deleted != Deleted)
UpdateRequired = true;
if (CurrentServingCourse.Name != ServingCourse)
UpdateRequired = true;
if (CurrentServingCourse.KitchenName != UTF8ToUnicodeString((AnsiString)ServingCourseKitchenName))
UpdateRequired = true;
if (CurrentServingCourse.Selectable != Selectable)
UpdateRequired = true;
if (CurrentServingCourse.SCOO != SCOO)
UpdateRequired = true;
if (CurrentServingCourse.Colour != ServingCourseColour)
UpdateRequired = true;
if (UpdateRequired)
{
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "UPDATE " "SERVINGCOURSES " "SET " "SERVINGCOURSE_NAME = :SERVINGCOURSE_NAME, "
"SERVINGCOURSE_KITCHEN_NAME = :SERVINGCOURSE_KITCHEN_NAME, " "DELETED = :DELETED, " "SELECTABLE = :SELECTABLE, "
"DISPLAY_ORDER = :DISPLAY_ORDER, " "COLOUR = :COLOUR " "WHERE " "SERVINGCOURSES_KEY = :SERVINGCOURSES_KEY";
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ParamByName("SERVINGCOURSE_NAME")->AsString = ServingCourse;
IBInternalQuery->ParamByName("SERVINGCOURSE_KITCHEN_NAME")->AsString = ServingCourseKitchenName;
//IBInternalQuery->ParamByName("SERVINGCOURSE_KITCHEN_NAME")->AsString = UnicodeToUTF8AnsiString(ServingCourseKitchenName);
IBInternalQuery->ParamByName("DELETED")->AsString = Deleted ? "T" : "F";
IBInternalQuery->ParamByName("SELECTABLE")->AsString = Selectable ? "T" : "F";
IBInternalQuery->ParamByName("DISPLAY_ORDER")->AsInteger = SCOO;
IBInternalQuery->ParamByName("COLOUR")->AsInteger = (int)ServingCourseColour;
IBInternalQuery->ExecQuery();
}
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return ServingCourseKey;
}
int TManagerMenus::SetServingCourseToMenu(Database::TDBTransaction &DBTransaction, int MenuKey, int ServingCourseKey)
{
if (MenuKey == 0)
return 0;
if (ServingCourseKey == 0)
return 0;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
if (GetMenuServingCourse(DBTransaction, MenuKey, ServingCourseKey) == 0)
{
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT GEN_ID(GEN_MENUSERVINGCOURSES, 1) FROM RDB$DATABASE";
IBInternalQuery->ExecQuery();
int MenuServingCourseKey = IBInternalQuery->Fields[0]->AsInteger;
IBInternalQuery->Close();
IBInternalQuery->SQL->Text =
"INSERT INTO MENUSERVINGCOURSES (" "MENUSERVINGCOURSES_KEY," "MENU_KEY," "SERVINGCOURSES_KEY) "
"VALUES (" ":MENUSERVINGCOURSES_KEY," ":MENU_KEY," ":SERVINGCOURSES_KEY);";
IBInternalQuery->ParamByName("MENUSERVINGCOURSES_KEY")->AsInteger = MenuServingCourseKey;
IBInternalQuery->ParamByName("MENU_KEY")->AsInteger = MenuKey;
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ExecQuery();
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return ServingCourseKey;
}
TServingCourse TManagerMenus::LoadDefaultServingCourse(Database::TDBTransaction &DBTransaction)
{
TServingCourse ServingCourse;
// Find the Emergency Backup Serving Course. It should be the 'No serving course' course.
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "Select * From SERVINGCOURSES Order By SERVINGCOURSES_KEY";
IBInternalQuery->Close();
IBInternalQuery->ExecQuery();
if (IBInternalQuery->Eof)
{ // There is no serving course so add one and use that.
TIBSQL *IBQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBQuery->Close();
IBQuery->SQL->Text = "SELECT GEN_ID(GEN_SERVINGCOURSES, 1) FROM RDB$DATABASE";
IBQuery->ExecQuery();
ServingCourse.ServingCourseKey = IBQuery->Fields[0]->AsInteger;
ServingCourse.Name = "No Serving Course";
ServingCourse.KitchenName = "No Serving Course";
ServingCourse.Colour = (int)clOlive;
ServingCourse.Deleted = false;
ServingCourse.Selectable = false;
IBQuery->Close();
IBQuery->ParamCheck = true;
IBQuery->SQL->Clear();
IBQuery->SQL->Text =
"INSERT INTO SERVINGCOURSES (" "SERVINGCOURSES_KEY," "SERVINGCOURSE_NAME, "
"SERVINGCOURSE_KITCHEN_NAME, " "DELETED, " "SELECTABLE, " "DISPLAY_ORDER, " "COLOUR) " "VALUES ("
":SERVINGCOURSES_KEY," ":SERVINGCOURSE_NAME, " ":SERVINGCOURSE_KITCHEN_NAME, " ":DELETED, " ":SELECTABLE, " ":DISPLAY_ORDER, "
":COLOUR);";
IBQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourse.ServingCourseKey;
IBQuery->ParamByName("SERVINGCOURSE_NAME")->AsString = ServingCourse.Name;
IBQuery->ParamByName("SERVINGCOURSE_KITCHEN_NAME")->AsString = UnicodeToUTF8AnsiString(ServingCourse.KitchenName);
IBQuery->ParamByName("DELETED")->AsString = ServingCourse.Deleted ? "T" : "F";
IBQuery->ParamByName("SELECTABLE")->AsString = ServingCourse.Selectable ? "T" : "F";
IBQuery->ParamByName("DISPLAY_ORDER")->AsInteger = 0;
IBQuery->ParamByName("COLOUR")->AsInteger = ServingCourse.Colour;
IBQuery->ExecQuery();
}
else
{
ServingCourse.ServingCourseKey = IBInternalQuery->FieldByName("ServingCourses_Key")->AsInteger;
ServingCourse.Name = IBInternalQuery->FieldByName("ServingCourse_Name")->AsString;
ServingCourse.KitchenName = UTF8ToUnicodeString((AnsiString)IBInternalQuery->FieldByName("ServingCourse_Kitchen_Name")->AsString);
ServingCourse.Colour = (TColor)IBInternalQuery->FieldByName("Colour")->AsInteger;
ServingCourse.Deleted = false;
ServingCourse.Selectable = false;
}
IBInternalQuery->Close();
return ServingCourse;
}
/* void TManagerMenus::LoadServingCourse(Database::TDBTransaction &DBTransaction, TListMenu *Menu)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT SERVINGCOURSES_KEY FROM MENUSERVINGCOURSES WHERE MENU_KEY = :MENU_KEY";
IBInternalQuery->ParamByName("MENU_KEY")->AsInteger = Menu->MenuKey;
IBInternalQuery->ExecQuery();
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
TServingCourse ServingCourse = GetServingCourseFromDB(DBTransaction,
IBInternalQuery->FieldByName("SERVINGCOURSES_KEY")->AsInteger);
Menu->ServingCourses.push_back(ServingCourse);
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
} */
int TManagerMenus::GetServingCourseByName(Database::TDBTransaction &DBTransaction, UnicodeString ServingCourse)
{
int ServingCourseKey = 0;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT SERVINGCOURSES_KEY " "FROM SERVINGCOURSES " "WHERE " "SERVINGCOURSE_NAME = :SERVINGCOURSE_NAME";
IBInternalQuery->ParamByName("SERVINGCOURSE_NAME")->AsString = ServingCourse;
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount)
{
ServingCourseKey = IBInternalQuery->FieldByName("SERVINGCOURSES_KEY")->AsInteger;
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return ServingCourseKey;
}
UnicodeString TManagerMenus::GetServingCourseName(Database::TDBTransaction &DBTransaction, int ServingCourseKey)
{
UnicodeString ServingCourse = "";
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT SERVINGCOURSE_NAME " "FROM SERVINGCOURSES " "WHERE " "SERVINGCOURSES_KEY = :SERVINGCOURSES_KEY";
IBInternalQuery->ParamByName("SERVINGCOURSES_KEY")->AsInteger = ServingCourseKey;
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount)
{
ServingCourse = IBInternalQuery->FieldByName("SERVINGCOURSE_NAME")->AsString;
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return ServingCourse;
}
void TManagerMenus::GetCourseList(Database::TDBTransaction &DBTransaction, int MenuKey, TStringList *CourseList)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT COURSE_KEY,COURSE_NAME " "FROM COURSE " "WHERE " "MENU_KEY = :MENU_KEY";
IBInternalQuery->ParamByName("MENU_KEY")->AsInteger = MenuKey;
IBInternalQuery->ExecQuery();
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
CourseList->AddObject(IBInternalQuery->FieldByName("COURSE_NAME")->AsString,
(TObject*)(IBInternalQuery->FieldByName("COURSE_KEY")->AsInteger));
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
}
// ---------------------------------------------------------------------------
void TManagerMenus::GetCourseKitchenNameList(Database::TDBTransaction &DBTransaction, int MenuKey, TStringList *CourseList)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text =
"Select COURSE_KEY,cast(COURSE_KITCHEN_NAME as varchar(200)) COURSE_NAME From COURSE Where"
" MENU_KEY = :MENU_KEY and COURSE_KITCHEN_NAME IS NOT NULL and COURSE_KITCHEN_NAME != '' ";
IBInternalQuery->ParamByName("MENU_KEY")->AsInteger = MenuKey;
IBInternalQuery->ExecQuery();
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
if (CourseList->IndexOf(UTF8ToUnicodeString((AnsiString)IBInternalQuery->FieldByName("COURSE_NAME")->AsString)) == -1)
{
CourseList->AddObject(UTF8ToUnicodeString((AnsiString)IBInternalQuery->FieldByName("COURSE_NAME")->AsString),
(TObject*)(IBInternalQuery->FieldByName("COURSE_KEY")->AsInteger));
}
}
IBInternalQuery->Close();
IBInternalQuery->SQL->Text =
" Select COURSE_KEY,cast(COURSE_NAME as varchar(200)) COURSE_NAME From COURSE Where MENU_KEY = :MENU_KEY and "
" (COURSE_KITCHEN_NAME IS NULL OR COURSE_KITCHEN_NAME = '')";
IBInternalQuery->ParamByName("MENU_KEY")->AsInteger = MenuKey;
IBInternalQuery->ExecQuery();
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
if (CourseList->IndexOf(IBInternalQuery->FieldByName("COURSE_NAME")->AsString) == -1)
{
CourseList->AddObject( IBInternalQuery->FieldByName("COURSE_NAME")->AsString.Unique(),(TObject*)(IBInternalQuery->FieldByName("COURSE_KEY")->AsInteger));
}
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
}
// ---------------------------------------------------------------------------
void TManagerMenus::GetMenuList(Database::TDBTransaction &DBTransaction, TStringList *MenuList)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT MENU_KEY,MENU_NAME " "FROM MENU";
IBInternalQuery->ExecQuery();
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
MenuList->AddObject(UnicodeString(IBInternalQuery->FieldByName("MENU_NAME")->AsString),
(TObject*)(IBInternalQuery->FieldByName("MENU_KEY")->AsInteger));
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
}
// ---------------------------------------------------------------------------
void TManagerMenus::GetMenuList(Database::TDBTransaction &DBTransaction, TStringList *MenuList, TMenuType MenuType)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT " "MENU_KEY," "MENU_NAME " "FROM " "MENU " "Where " "Menu_Type = :Menu_Type " "Order By "
"Menu_Name";
IBInternalQuery->ParamByName("Menu_Type")->AsInteger = MenuType;
IBInternalQuery->ExecQuery();
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
MenuList->AddObject(IBInternalQuery->FieldByName("MENU_NAME")->AsString,
(TObject*)(IBInternalQuery->FieldByName("MENU_KEY")->AsInteger));
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
}
// ---------------------------------------------------------------------------
bool TManagerMenus::IsAValidMenu(Database::TDBTransaction &DBTransaction, int MenuKey)
{
bool RetVal = false;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = " SELECT MENU_KEY " " FROM MENU " " WHERE " " MENU_KEY = :MENU_KEY";
IBInternalQuery->ParamByName("MENU_KEY")->AsInteger = MenuKey;
IBInternalQuery->ExecQuery();
RetVal = (IBInternalQuery->RecordCount != 0);
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return RetVal;
}
bool TManagerMenus::IsAPendingMenu(int inMenu_Key)
{
for (int i = 0; i < New->Count; i++)
{
TListMenu *Menu = New->MenuGet(i);
if (Menu->MenuKey == inMenu_Key)
{
return true;
}
}
return false;
}
bool TManagerMenus::IsAPendingMenu(UnicodeString inMenu_Name)
{
for (int i = 0; i < New->Count; i++)
{
TListMenu *Menu = New->MenuGet(i);
if (Menu->MenuName == inMenu_Name)
{
return true;
}
}
return false;
}
bool TManagerMenus::GetMenusExist(Database::TDBTransaction &DBTransaction)
{
bool Retval = false;
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT MENU_KEY,MENU_NAME " "FROM MENU";
IBInternalQuery->ExecQuery();
if (IBInternalQuery->RecordCount > 0)
{
Retval = true;
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
return Retval;
}
// ---------------------------------------------------------------------------
TListMenu *TManagerMenus::LoadMenuFromDB(Database::TDBControl &DBControl, const UnicodeString &MenuName, eMenuCommand Command)
{
Menu::TMenuLoadDB MenuEnumerator(DBControl);
i_item_manager &im_item_manager =
item_management::kickstarter::get_item_manager();
const i_item_definition_factory &im_item_definition_factory =
im_item_manager.get_item_definition_factory();
const i_size_definition_factory &im_size_definition_factory =
im_item_manager.get_size_definition_factory();
i_menu_manager &im_menu_manager =
item_management::kickstarter::get_menu_manager();
Menu::TMenusInfo MenusInfo;
Menu::TMenusInfo::iterator iMenus;
MenuEnumerator.EnumMenus(MenusInfo);
// Find the menu key based on name.
#ifdef MenuMate
PhoenixHM->ClearCodesTestedOk();
#endif
for (iMenus = MenusInfo.begin(); iMenus != MenusInfo.end(); iMenus++)
{
if (iMenus->Menu_Name == MenuName)
{
Menu::TMenuInfo MenuInfo;
Menu::TSizesInfo SizesInfo;
Menu::TCategoriesInfo CategoriesInfo;
Menu::TLocationsInfo LocationsInfo;
Menu::TServingCoursesInfo ServingCoursesInfo;
Menu::TMenuLoadDB MenuLoader(DBControl, iMenus->Key);
if (MenuLoader.GetMenu(&MenuInfo, &SizesInfo, &CategoriesInfo, &LocationsInfo, &ServingCoursesInfo))
{
TListMenu *Menu = new TListMenu;
Menu->MenuName = MenuInfo.Menu_Name;
Menu->MenuKey = MenuInfo.Key;
Menu->Menu_Type = static_cast <TMenuType> (MenuInfo.Menu_Type);
Menu->Description = MenuInfo.Menu_Name;
Menu->SwapInCommand = Command;
if (im_menu_manager.is_menu_loaded(MenuInfo.Key))
im_menu_manager.remove_menu(MenuInfo.Key);
im_menu_manager.add_menu(MenuInfo.Key);
int PalmsID = 1;
// Import New Printing Order.
TManagerLogs::Instance().Add(__FUNC__, "Menu Change", "Menu will change to " + (Menu->MenuName));
for (unsigned i = 0; i < SizesInfo.Sizes.size(); i++)
{
TItemSize *Size = new TItemSize;
Size->Name = SizesInfo.Sizes[i].Size_Name;
Size->Size_ID = SizesInfo.Sizes[i].Size_ID;
Size->Palm_ID = SizesInfo.Sizes[i].PalmID;
Size->Weighted = SizesInfo.Sizes[i].Weighted_Size;
Menu->Sizes->SizeAdd(Size);
}
for (unsigned i = 0; i < ServingCoursesInfo.ServingCourses.size(); i++)
{
if (ServingCoursesInfo.ServingCourses[i].Enabled && !ServingCoursesInfo.ServingCourses[i].Deleted)
{
TServingCourse ServingCourse;
ServingCourse.ServingCourseKey = ServingCoursesInfo.ServingCourses[i].Key;
ServingCourse.Name = ServingCoursesInfo.ServingCourses[i].ServingCourse_Name;
ServingCourse.KitchenName = ServingCoursesInfo.ServingCourses[i].ServingCourse_Kitchen_Name;
if (ServingCourse.KitchenName == UnicodeString(""))
{
ServingCourse.KitchenName = ServingCourse.Name;
}
ServingCourse.Colour = ServingCoursesInfo.ServingCourses[i].Colour;
ServingCourse.Selectable = ServingCoursesInfo.ServingCourses[i].Selectable;
ServingCourse.ServingCourseID = ServingCourse.ServingCourseKey & 0xFFFF;
ServingCourse.SCOO = i;
Menu->ServingCourses.push_back(ServingCourse);
}
}
Menu::TCourseInfo CourseInfo;
while (MenuLoader.GetNextCourse(&CourseInfo))
{
TListCourse *Course = new TListCourse;
Course->Course_Name = CourseInfo.Course_Name;
Course->CourseKitchenName = CourseInfo.Course_Kitchen_Name;
if (Course->CourseKitchenName == UnicodeString(""))
{
Course->CourseKitchenName = Course->Course_Name;
}
Course->Course_Key = CourseInfo.Key;
Course->ViewableLocations = CourseInfo.View_Location;
Course->DefaultServingCourseKey = CourseInfo.ServingCourses_Key;
Course->No_Default_Serving_Course = CourseInfo.No_Default_Serving_Course;
PalmsID++;
int ItemOptionGroup = 0; // Added for POS
Menu::TItemInfo ItemInfo;
std::vector<i_item_definition *> im_item_definitions;
bool isItemPresent = false;
while (MenuLoader.GetNextItem(&ItemInfo))
{
TItem *Item = new TItem(Course);
Item->ItemKey = ItemInfo.Key;
Item->Item_ID = ItemInfo.Item_ID;
Item->Palm_ID = (PalmsID++) | (Menu->Menu_Type == Menu::mtBeverageMenu ? 0x4000 : 0); // ItemInfo.Item_ID;
Item->Item = ItemInfo.Item_Name;
Item->ItemKitchenName = ItemInfo.Item_Kitchen_Name;
if (Item->ItemKitchenName == UnicodeString(""))
{
Item->ItemKitchenName = Item->Item;
}
Item->SetColour = ItemInfo.Button_Colour;
Item->PrintChitNumber = ItemInfo.Print_Chit;
Item->DisplaySizes = ItemInfo.Display_Sizes;
Item->Enabled = ItemInfo.Enabled;
Item->ExclusivelyAsSide = ItemInfo.Exclusively_As_Side;
// Menu_Key Only used for printing.
Item->MenuKey = Menu->MenuKey;
Item->Course_Key = Course->Course_Key;
Item->Course = Course->Course_Name;
Item->PrintingGroupOrder = CourseInfo.Course_ID;
Item->CourseKitchenName = Course->CourseKitchenName;
Item->ViewableLocations = Course->ViewableLocations;
Item->MenuName = Menu->MenuName;
Item->ItemType = static_cast <TItemType> (Menu->Menu_Type);
Item->Note = "";
// Added for POS
Item->OptionGroup = ItemOptionGroup++;
Item->ItemAppearanceOrder = ItemInfo.IAO;
Item->FontInfo.Underlined = ItemInfo.Print_Underlined;
Item->FontInfo.Bold = ItemInfo.Print_Bold;
Item->FontInfo.Width = ItemInfo.Print_Double_Width ? fsDoubleSize : fsNormalSize;
Item->FontInfo.Height = ItemInfo.Print_Double_Height ? fsDoubleSize : fsNormalSize;
Item->FontInfo.Colour = (ItemInfo.Print_Colour == 0) ? fcBlack : fcRed;
Item->FontInfo.Font = (ItemInfo.Print_Font == 0) ? ftFontA : ftFontB;
// end added for POS
std::vector<i_size_definition *> im_size_definitions;
Menu::TItemSizeInfo ItemSizeInfo;
bool isSizePresent = false;
while (MenuLoader.GetNextItemSize(&ItemSizeInfo))
{
im_size_definitions.push_back(
im_size_definition_factory.create(
ItemSizeInfo.available_quantity,
ItemSizeInfo.default_quantity,
ItemSizeInfo.enabled,
ItemSizeInfo.Key,
ItemSizeInfo.Size_Name,
ItemSizeInfo.Price,
ItemSizeInfo.MaxRetailPrice,
ItemSizeInfo.Special_Price,
ItemSizeInfo.warning_quantity));
if(!ItemSizeInfo.IsInvisible)
{
isSizePresent = true;
TItemSize *Size = new TItemSize(ItemInfo.Key);
Size->ItemSizeKey = ItemSizeInfo.Key;
Size->Size_ID = ItemSizeInfo.Size_ID;
Size->Name = ItemSizeInfo.Size_Name;
Size->SizeKitchenName = ItemSizeInfo.Size_Kitchen_Name;
if (Size->SizeKitchenName == UnicodeString(""))
{
Size->SizeKitchenName = Size->Name;
}
if(Menu->Sizes->SizeGet(Size->Name) != NULL)
{
Size->Palm_ID = Menu->Sizes->SizeGet(Size->Name)->Palm_ID;
}
if(Menu->Sizes->SizeGet(Size->Name) != NULL)
{
Size->Weighted = Menu->Sizes->SizeGet(Size->Name)->Weighted;
}
Size->Price = ItemSizeInfo.Price;
Size->MaxRetailPrice = ItemSizeInfo.MaxRetailPrice;
Size->Cost = ItemSizeInfo.Cost;
Size->PLU = ItemSizeInfo.PLU;
Size->CostGSTPercent = ItemSizeInfo.Cost_GST_Percent;
Size->GSTPercent = ItemSizeInfo.GST_Percent;
Size->TaxProfiles = ItemSizeInfo.TaxProfiles;
Size->Barcode = ItemSizeInfo.Barcode; // Added for POS
Size->HappyPrice = ItemSizeInfo.Special_Price;
Size->Available_As_Standard = ItemSizeInfo.Available_As_Standard;
Size->SetMenuMask = ItemSizeInfo.Setmenu_Mask;
Size->PointsPercent = ItemSizeInfo.Points_Percent;
Size->ThirdPartyKey = ItemSizeInfo.ThirdPartyCodes_Key;
Size->ThirdPartyCode = ItemSizeInfo.ThirdPartyCode;
Size->MemberFreeSaleCount = ItemSizeInfo.Mem_Sale_Count;
Size->MemberFreeSaleDiscount = ItemSizeInfo.Mem_Discount_Percent;
Size->LocationFreeSaleCount = ItemSizeInfo.Loc_Sale_Count;
Size->LocationFreeSaleDiscount = ItemSizeInfo.Loc_Discount_Percent;
Size->TareWeight = ItemSizeInfo.Tare_Weight;
Size->PLU = ItemSizeInfo.PLU;
Size->CanBePaidForUsingPoints = ItemSizeInfo.CanBePaidForUsingPoints;
Size->DefaultPatronCount(ItemSizeInfo.DefaultPatronCount);
Size->Categories->FinancialCategoryKey = ItemSizeInfo.CategoryKey;
Size->Categories->FinancialCategory = ItemSizeInfo.Category;
Size->Categories->FinancialCategoryGLCode = ItemSizeInfo.GLCode;
Size->Categories->FinancialCategoryGroup = ItemSizeInfo.Category_Group_Name;
Size->PriceLevels = ItemSizeInfo.PriceLevels;
if (Size->Categories->FinancialCategory == "")
{
throw Exception("Unable to Load, A Blank Financial Category is not allowed.");
}
Size->SetMenuItem = false;
Size->SetMenuMaster = false;
if (TST_PROMO_MASTER(Size->SetMenuMask)) // Is a master.
{
Size->SetMenuMaster = true;
}
else if (Size->SetMenuMask != 0)
{
Size->SetMenuItem = true;
}
#ifdef MenuMate
// Check the Size Thridparty key with the Phoenix system.
Database::TDBTransaction DBTransaction(DBControl);
DBTransaction.StartTransaction();
UnicodeString Code = Size->ThirdPartyCode;
DBTransaction.Commit();
if (!PhoenixHM->TestCode(Code))
{
throw Exception("Unable to Load Menu " + Menu->MenuName + ". The Third Party Code : " + Code +
" is not found in the PMS System");
} // end Added for POS
#endif
for (unsigned i = 0; i < ItemSizeInfo.Recipes.size(); i++)
{
TItemRecipe *RecipeItem = new TItemRecipe;
RecipeItem->StockCode = ItemSizeInfo.Recipes[i].Stock_Code;
RecipeItem->StockLocation = ItemSizeInfo.Recipes[i].Stock_Location;
RecipeItem->Qty = ItemSizeInfo.Recipes[i].Qty;
RecipeItem->Cost = ItemSizeInfo.Recipes[i].Stock_Unit_Cost * ItemSizeInfo.Recipes[i].Qty;
RecipeItem->CostGSTPercent = ItemSizeInfo.Recipes[i].Stock_GST_Percent;
Size->Recipes->RecipeAdd(RecipeItem);
}
for (unsigned i = 0; i < ItemSizeInfo.Categories.size(); i++)
{
TItemSizeCategory *SizeCat = new TItemSizeCategory;
SizeCat->CategoryKey = ItemSizeInfo.Categories[i].Key;
SizeCat->Category = ItemSizeInfo.Categories[i].Category;
Size->Categories->CategoryAdd(SizeCat);
}
Size->CostForPoints = ItemSizeInfo.PriceForPoints; // add cost for points.
Item->Sizes->SizeAdd(Size);
}
}
// COuld be faster ways of doing this! (Refer to Office)
for (unsigned i = 0; i < ItemInfo.Sides.size(); i++)
{
Item->Sides->SideAdd(Item, ItemInfo.Sides[i].Master_Item_Key, ItemInfo.Sides[i].Item_Key, i,
ItemInfo.Sides[i].Group_Number, ItemInfo.Sides[i].Max_Select, ItemInfo.Sides[i].Allow_Skip);
}
int PalmOptionID = 1;
for (unsigned i = 0; i < CourseInfo.Options.size(); i++)
{
TItemOption *ItemOption = new TItemOption;
ItemOption->OptionKey = CourseInfo.Options[i].Key;
ItemOption->Palm_ID = PalmOptionID++;
ItemOption->OptionID = CourseInfo.Options[i].Option_ID;
ItemOption->Name = CourseInfo.Options[i].Option_Name;
ItemOption->KitchenName = CourseInfo.Options[i].Option_Kitchen_Name;
if (ItemOption->KitchenName == UnicodeString(""))
{
ItemOption->KitchenName = ItemOption->Name;
}
ItemOption->Enabled = true; // CourseInfo.Options[i].Enabled, Not supported at the mo.;
ItemOption->IsPlus = true;
ItemOption->ForcedMask = CourseInfo.Options[i].Forced_Mask;
ItemOption->Flags = CourseInfo.Options[i].Flags;
ItemOption->GroupNumber = CourseInfo.Options[i].GroupNumber;
ItemOption->PlusOption = CourseInfo.Options[i].PlusOption;
ItemOption->MinusOption = CourseInfo.Options[i].MinusOption;
ItemOption->AllowSkip = CourseInfo.Options[i].Allow_Skip; // Added for POS
ItemOption->DisallowMuliSelect = CourseInfo.Options[i].Max_Select; // Added for POS
ItemOption->FontInfo.Underlined = CourseInfo.Options[i].Print_Underlined;
ItemOption->FontInfo.Bold = CourseInfo.Options[i].Print_Bold;
ItemOption->FontInfo.Width = CourseInfo.Options[i].Print_Double_Width ? fsDoubleSize : fsNormalSize;
ItemOption->FontInfo.Height = CourseInfo.Options[i].Print_Double_Height ? fsDoubleSize : fsNormalSize;
ItemOption->FontInfo.Colour = (CourseInfo.Options[i].Print_Colour == 0) ? fcBlack : fcRed;
ItemOption->FontInfo.Font = (CourseInfo.Options[i].Print_Font == 0) ? ftFontA : ftFontB;
ItemOption->OptionOrder = CourseInfo.Options[i].Option_order;
ItemOption->Owner = Item->Options;
Item->Options->OptionAdd(ItemOption);
}
im_item_definitions.push_back( im_item_definition_factory.create(ItemInfo.Item_Name, im_size_definitions, ItemInfo.Key));
if(isSizePresent)
{
Course->ItemAdd(Item);
isItemPresent = true;
}
}
im_menu_manager.add_course(CourseInfo.Course_ID, MenuInfo.Key);
im_menu_manager.add_item_definitions(MenuInfo.Key, CourseInfo.Course_ID, im_item_definitions);
im_item_definitions.clear();
if(isItemPresent)
Menu->CourseAdd(Course);
}
New->MenuAdd(Menu);
return Menu;
}
}
}
return NULL;
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
void TManagerMenus::BuildXMLMenu(Database::TDBControl &DBControl, TPOS_XMLBase &Data, int SiteID)
{
Menu::TMenuLoadDB MenuEnumerator(DBControl);
Menu::TMenusInfo MenusInfo;
Menu::TMenusInfo::iterator iMenus;
MenuEnumerator.EnumMenus(MenusInfo);
// Find the menu key based on name.
#ifdef MenuMate
PhoenixHM->ClearCodesTestedOk();
#endif
Data.Doc.Clear();
TiXmlDeclaration * decl = new TiXmlDeclaration(_T("1.0"), _T("UTF-8"), _T(""));
Data.Doc.LinkEndChild(decl);
// Insert DOCTYPE definiation here.
TiXmlElement * List = new TiXmlElement(xmlEleListProductTypes);
List->SetAttribute(xmlAttrID, AnsiString(Data.IntaMateID).c_str());
List->SetAttribute(xmlAttrSiteID, SiteID);
for (iMenus = MenusInfo.begin(); iMenus != MenusInfo.end(); iMenus++)
{
Menu::TMenuInfo MenuInfo;
Menu::TSizesInfo SizesInfo;
Menu::TCategoriesInfo CategoriesInfo;
Menu::TLocationsInfo LocationsInfo;
Menu::TServingCoursesInfo ServingCoursesInfo;
Menu::TMenuLoadDB MenuLoader(DBControl, iMenus->Key);
if (MenuLoader.GetMenu(&MenuInfo, &SizesInfo, &CategoriesInfo, &LocationsInfo, &ServingCoursesInfo))
{
TiXmlElement *EleMenu = new TiXmlElement(xmlAttrMenu);
EleMenu->SetAttribute(xmlAttrID, _T(""));
EleMenu->SetAttribute(xmlAttrName, MenuInfo.Menu_Name.t_str());
EleMenu->SetAttribute(xmlMenuType, (MenuInfo.Menu_Type == Menu::mtFoodMenu) ? _T("Food") : _T("Beverage"));
List->LinkEndChild(EleMenu);
TiXmlElement *EleSizes = new TiXmlElement(xmlAttrSizes);
for (unsigned i = 0; i < SizesInfo.Sizes.size(); i++)
{
TiXmlElement *EleSize = new TiXmlElement(xmlAttrSize);
EleSize->SetAttribute(xmlAttrID, SizesInfo.Sizes[i].Size_ID);
EleSize->SetAttribute(xmlAttrName, SizesInfo.Sizes[i].Size_Name.t_str());
EleSize->SetAttribute(xmlAttrByWeight, SizesInfo.Sizes[i].Weighted_Size ? _T("Yes") : _T("No"));
EleSizes->LinkEndChild(EleSize);
}
EleMenu->LinkEndChild(EleSizes);
TiXmlElement *EleServingCourses = new TiXmlElement(xmlEleServingCourses);
for (unsigned i = 0; i < ServingCoursesInfo.ServingCourses.size(); i++)
{
if (ServingCoursesInfo.ServingCourses[i].Enabled && !ServingCoursesInfo.ServingCourses[i].Deleted)
{
TiXmlElement *EleServingCourse = new TiXmlElement(xmlEleServingCourse);
EleServingCourse->SetAttribute(xmlAttrXmlID, ServingCoursesInfo.ServingCourses[i].Key);
EleServingCourse->SetAttribute(xmlAttrName, ServingCoursesInfo.ServingCourses[i].ServingCourse_Name.t_str());
// EleServingCourse->SetAttribute(xmlAttrKitchenName, UnicodeToUTF8AnsiString(ServingCoursesInfo.ServingCourses[i].ServingCourse_Kitchen_Name).c_str() );
EleServingCourse->SetAttribute(xmlAttrKitchenName, ServingCoursesInfo.ServingCourses[i].ServingCourse_Kitchen_Name.t_str());
if (ServingCoursesInfo.ServingCourses[i].ServingCourse_Kitchen_Name == UnicodeString(""))
{
EleServingCourse->SetAttribute(xmlAttrKitchenName, ServingCoursesInfo.ServingCourses[i].ServingCourse_Name.t_str());
}
EleServingCourse->SetAttribute(xmlAttrColour, ServingCoursesInfo.ServingCourses[i].Colour);
EleServingCourse->SetAttribute(xmlAttrSelectable, ServingCoursesInfo.ServingCourses[i].Selectable ? _T("Yes") : _T("No"));
EleServingCourse->SetAttribute(xmlAttrApperanceOrder, i);
EleServingCourses->LinkEndChild(EleServingCourse);
}
}
EleMenu->LinkEndChild(EleServingCourses);
TiXmlElement *EleCourses = new TiXmlElement(xmlEleCourses);
Menu::TCourseInfo CourseInfo;
while (MenuLoader.GetNextCourse(&CourseInfo))
{
TiXmlElement *EleCourse = new TiXmlElement(xmlEleCourse);
EleCourse->SetAttribute(xmlAttrID, _T(""));
EleCourse->SetAttribute(xmlAttrName, CourseInfo.Course_Name.t_str());
// EleCourse->SetAttribute(xmlAttrKitchenName, UnicodeToUTF8AnsiString(CourseInfo.Course_Kitchen_Name).c_str() );
EleCourse->SetAttribute(xmlAttrKitchenName, CourseInfo.Course_Kitchen_Name.t_str());
if (CourseInfo.Course_Kitchen_Name == UnicodeString(""))
{
EleCourse->SetAttribute(xmlAttrKitchenName, CourseInfo.Course_Name.t_str());
}
EleCourse->SetAttribute(xmlAttrDefaultServingCourse, CourseInfo.ServingCourses_Key);
EleCourses->LinkEndChild(EleCourse);
int ItemOptionGroup = 0; // Added for POS
TiXmlElement *EleItems = new TiXmlElement(xmlEleItems);
Menu::TItemInfo ItemInfo;
while (MenuLoader.GetNextItem(&ItemInfo))
{
TiXmlElement *EleItem = new TiXmlElement(xmlEleItem);
EleItem->SetAttribute(xmlAttrID, _T(""));
EleItem->SetAttribute(xmlAttrXmlID, ItemInfo.Key);
EleItem->SetAttribute(xmlAttrName, ItemInfo.Item_Name.t_str());
// EleItem->SetAttribute(xmlAttrKitchenName, UnicodeToUTF8AnsiString(ItemInfo.Item_Kitchen_Name).c_str() );
EleItem->SetAttribute(xmlAttrKitchenName, ItemInfo.Item_Kitchen_Name.t_str());
if (ItemInfo.Item_Kitchen_Name == UnicodeString(""))
{
EleItem->SetAttribute(xmlAttrKitchenName, ItemInfo.Item_Name.t_str());
}
EleItem->SetAttribute(xmlAttrColour, ItemInfo.Button_Colour);
EleItem->SetAttribute(xmlAttrPrintChitNumber, ItemInfo.Print_Chit ? _T("Yes") : _T("No"));
EleItem->SetAttribute(xmlAttrDisplaySizes, ItemInfo.Display_Sizes ? _T("Yes") : _T("No"));
EleItem->SetAttribute(xmlAttrEnabled, ItemInfo.Enabled ? _T("Yes") : _T("No"));
EleItem->SetAttribute(xmlAttrExclusivelySide, ItemInfo.Exclusively_As_Side ? _T("Yes") : _T("No"));
EleItem->SetAttribute(xmlAttrApperanceOrder, ItemInfo.IAO);
TiXmlElement *EleFontInfo = new TiXmlElement(xmlEleFontInfo);
EleFontInfo->SetAttribute(xmlAttrUnderLine, ItemInfo.Print_Underlined);
EleFontInfo->SetAttribute(xmlAttrBold, ItemInfo.Print_Bold);
EleFontInfo->SetAttribute(xmlAttrWidth, ItemInfo.Print_Double_Width ? _T("Double") : _T("Normal"));
EleFontInfo->SetAttribute(xmlAttrHight, ItemInfo.Print_Double_Height ? _T("Double") : _T("Normal"));
EleFontInfo->SetAttribute(xmlAttrColour, (ItemInfo.Print_Colour == 0) ? _T("Black") : _T("Red"));
EleFontInfo->SetAttribute(xmlAttrFont, (ItemInfo.Print_Font == 0) ? _T("FontA") : _T("FontB"));
EleItem->LinkEndChild(EleFontInfo);
TiXmlElement *EleSizes = new TiXmlElement(xmlAttrSizes);
Menu::TItemSizeInfo ItemSizeInfo;
while (MenuLoader.GetNextItemSize(&ItemSizeInfo))
{
TiXmlElement *EleSize = new TiXmlElement(xmlAttrSize);
EleSize->SetAttribute(xmlAttrID, ItemSizeInfo.Size_ID);
EleSize->SetAttribute(xmlAttrName, ItemSizeInfo.Size_Name.t_str());
EleSize->SetAttribute(xmlAttrKitchenName, UTF8String(ItemSizeInfo.Size_Kitchen_Name).c_str());
if (ItemSizeInfo.Size_Kitchen_Name == UnicodeString(""))
{
EleSize->SetAttribute(xmlAttrKitchenName, ItemSizeInfo.Size_Name.t_str());
}
EleSize->SetAttribute(xmlAttrPrice, FormatFloat("0.00", ItemSizeInfo.Price).t_str());
//EleSize->SetAttribute(xmlAttrGSTPercent, FormatFloat("0.00", ItemSizeInfo.GST_Percent).t_str());
EleSize->SetAttribute(xmlAttrCost, FormatFloat("0.00", ItemSizeInfo.Cost).t_str());
EleSize->SetAttribute(xmlAttrGSTCost, FormatFloat("0.00", ItemSizeInfo.Cost_GST_Percent).t_str());
EleSize->SetAttribute(xmlAttrBarCode, ItemSizeInfo.Barcode.t_str());
EleSize->SetAttribute(xmlAttrSpecialPrice, FormatFloat("0.00", ItemSizeInfo.Special_Price).t_str());
EleSize->SetAttribute(xmlAttrAvailableAsStandard, ItemSizeInfo.Available_As_Standard ? _T("Yes") : _T("No"));
EleSize->SetAttribute(xmlAttrSetMenuMask, ItemSizeInfo.Setmenu_Mask);
EleSize->SetAttribute(xmlAttrPointsPercent, FormatFloat("0.00", ItemSizeInfo.Points_Percent).t_str());
EleSize->SetAttribute(xmlAttrCode, ItemSizeInfo.ThirdPartyCode.t_str());
EleSize->SetAttribute(xmlAttrMembSaleCount, ItemSizeInfo.Mem_Sale_Count);
EleSize->SetAttribute(xmlAttrMemDiscountPercent, FormatFloat("0.00", ItemSizeInfo.Mem_Discount_Percent).t_str());
EleSize->SetAttribute(xmlAttrLocSaleCount, ItemSizeInfo.Loc_Sale_Count);
EleSize->SetAttribute(xmlAttrLocDiscountPercent, FormatFloat("0.00", ItemSizeInfo.Loc_Discount_Percent).t_str());
EleSize->SetAttribute(xmlAttrTareWeight, ItemSizeInfo.Tare_Weight.AsKiloGrams());
EleSize->SetAttribute(xmlAttrPLU, ItemSizeInfo.PLU);
EleSize->SetAttribute(xmlAttrCategoryName, ItemSizeInfo.Category.t_str());
EleSize->SetAttribute(xmlAttrCategoryID, ItemSizeInfo.CategoryKey);
EleSize->SetAttribute(xmlAttrGroupName, ItemSizeInfo.Category_Group_Name.t_str());
EleSize->SetAttribute(xmlAttrGroupID, ItemSizeInfo.Category_Group_Key);
bool SetMenuItem = false;
bool SetMenuMaster = false;
if (TST_PROMO_MASTER(ItemSizeInfo.Setmenu_Mask)) // Is a master.
{
SetMenuMaster = true;
}
else if (ItemSizeInfo.Setmenu_Mask != 0)
{
SetMenuItem = true;
}
EleSize->SetAttribute(xmlAttrSetMenuMaster, SetMenuMaster ? _T("Yes") : _T("No"));
EleSize->SetAttribute(xmlAttrSetMenuItem, SetMenuItem ? _T("Yes") : _T("No"));
TiXmlElement *EleRecipes = new TiXmlElement(xmlEleRecipes);
for (unsigned i = 0; i < ItemSizeInfo.Recipes.size(); i++)
{
TiXmlElement *EleRecipe = new TiXmlElement(xmlEleRecipe);
EleRecipe->SetAttribute(xmlAttrStockCode, ItemSizeInfo.Recipes[i].Stock_Code.t_str());
EleRecipe->SetAttribute(xmlAttrStockLocation, ItemSizeInfo.Recipes[i].Stock_Location.t_str());
EleRecipe->SetAttribute(xmlAttrStockQty, FormatFloat("0.00", ItemSizeInfo.Recipes[i].Qty).t_str());
EleRecipe->SetAttribute(xmlAttrCost,
FormatFloat("0.00", ItemSizeInfo.Recipes[i].Stock_Unit_Cost * ItemSizeInfo.Recipes[i].Qty).t_str());
EleRecipe->SetAttribute(xmlAttrGSTCost, FormatFloat("0.00", ItemSizeInfo.Recipes[i].Stock_GST_Percent).t_str());
EleRecipes->LinkEndChild(EleRecipe);
}
EleSize->LinkEndChild(EleRecipes);
TiXmlElement *EleCategories = new TiXmlElement(xmlEleCategories);
for (unsigned i = 0; i < ItemSizeInfo.Categories.size(); i++)
{
TiXmlElement *EleCategory = new TiXmlElement(xmlEleCategory);
EleCategory->SetAttribute(xmlAttrName, ItemSizeInfo.Categories[i].Category.t_str());
EleCategories->LinkEndChild(EleCategory);
}
EleSize->LinkEndChild(EleCategories);
EleSizes->LinkEndChild(EleSize);
}
EleItem->LinkEndChild(EleSizes);
TiXmlElement *EleSides = new TiXmlElement(xmlEleSides);
for (unsigned i = 0; i < ItemInfo.Sides.size(); i++)
{
TiXmlElement *EleSide = new TiXmlElement(xmlEleSide);
EleSide->SetAttribute(xmlAttrMasterItemXmlID, ItemInfo.Sides[i].Master_Item_Key);
EleSide->SetAttribute(xmlAttrItemXmlID, ItemInfo.Sides[i].Item_Key);
EleSide->SetAttribute(xmlAttrGroupNumber, ItemInfo.Sides[i].Group_Number);
EleSide->SetAttribute(xmlAttrMaxSelect, ItemInfo.Sides[i].Max_Select);
EleSide->SetAttribute(xmlAttrAllowSkip, ItemInfo.Sides[i].Allow_Skip);
EleSides->LinkEndChild(EleSide);
}
EleItem->LinkEndChild(EleSides);
TiXmlElement *EleOptions = new TiXmlElement(xmlEleOptions);
for (unsigned i = 0; i < CourseInfo.Options.size(); i++)
{
TiXmlElement *EleOption = new TiXmlElement(xmlEleOption);
EleOption->SetAttribute(xmlAttrID, CourseInfo.Options[i].Option_ID);
EleOption->SetAttribute(xmlAttrName, CourseInfo.Options[i].Option_Name.t_str());
// EleOption->SetAttribute(xmlAttrKitchenName, UnicodeToUTF8AnsiString(CourseInfo.Options[i].Option_Kitchen_Name).c_str() );
EleOption->SetAttribute(xmlAttrKitchenName, CourseInfo.Options[i].Option_Kitchen_Name.t_str());
if (CourseInfo.Options[i].Option_Kitchen_Name == UnicodeString(""))
{
EleOption->SetAttribute(xmlAttrKitchenName, CourseInfo.Options[i].Option_Name.t_str());
}
EleOption->SetAttribute(xmlAttrFlags, CourseInfo.Options[i].Flags);
EleOption->SetAttribute(xmlAttrGroupNumber, CourseInfo.Options[i].GroupNumber);
EleOption->SetAttribute(xmlAttrPlusOption, CourseInfo.Options[i].PlusOption);
EleOption->SetAttribute(xmlAttrMinusOption, CourseInfo.Options[i].MinusOption);
EleOption->SetAttribute(xmlAttrAllowSkip, CourseInfo.Options[i].Allow_Skip);
EleOption->SetAttribute(xmlAttrMaxSelect, CourseInfo.Options[i].Max_Select);
EleOption->SetAttribute(xmlAttrForcedMask, CourseInfo.Options[i].Forced_Mask);
TiXmlElement *EleFontInfo = new TiXmlElement(xmlEleFontInfo);
EleFontInfo->SetAttribute(xmlAttrUnderLine, CourseInfo.Options[i].Print_Underlined);
EleFontInfo->SetAttribute(xmlAttrBold, CourseInfo.Options[i].Print_Bold);
EleFontInfo->SetAttribute(xmlAttrWidth, CourseInfo.Options[i].Print_Double_Width ? _T("Double") : _T("Normal"));
EleFontInfo->SetAttribute(xmlAttrHight, CourseInfo.Options[i].Print_Double_Height ? _T("Double") : _T("Normal"));
EleFontInfo->SetAttribute(xmlAttrColour, (CourseInfo.Options[i].Print_Colour == 0) ? _T("Black") : _T("Red"));
EleFontInfo->SetAttribute(xmlAttrFont, (CourseInfo.Options[i].Print_Font == 0) ? _T("FontA") : _T("FontB"));
EleOption->LinkEndChild(EleFontInfo);
EleOptions->LinkEndChild(EleOption);
}
EleItem->LinkEndChild(EleOptions);
EleItems->LinkEndChild(EleItem);
}
EleCourse->LinkEndChild(EleItems);
}
EleMenu->LinkEndChild(EleCourses);
}
}
Data.Doc.LinkEndChild(List);
}
void TManagerMenus::BuildXMLListCategories(Database::TDBTransaction &DBTransaction, TPOS_XMLBase &Data, int SiteID)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT * FROM ARCCATEGORIES " " LEFT JOIN CATEGORYGROUPS ON "
" CATEGORYGROUPS.CATEGORYGROUPS_KEY = ARCCATEGORIES.CATEGORYGROUPS_KEY";
IBInternalQuery->ExecQuery();
// Update the IntaMate ID with the Invoice Number.
Data.Doc.Clear();
TiXmlDeclaration * decl = new TiXmlDeclaration(_T("1.0"), _T("UTF-8"), _T(""));
Data.Doc.LinkEndChild(decl);
// Insert DOCTYPE definiation here.
TiXmlElement * List = new TiXmlElement(xmlEleListCategories);
List->SetAttribute(xmlAttrID, AnsiString(Data.IntaMateID).c_str());
List->SetAttribute(xmlAttrSiteID, SiteID);
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
TiXmlElement *EleCategory = new TiXmlElement(xmlEleCategory);
EleCategory->SetAttribute(xmlAttrID, IBInternalQuery->FieldByName("CATEGORY_KEY")->AsString.t_str());
EleCategory->SetAttribute(xmlAttrName, IBInternalQuery->FieldByName("CATEGORY")->AsString.t_str());
EleCategory->SetAttribute(xmlAttrGroupID, IBInternalQuery->FieldByName("CATEGORYGROUPS_KEY")->AsString.t_str());
EleCategory->SetAttribute(xmlAttrGroupName, IBInternalQuery->FieldByName("NAME")->AsString.t_str());
EleCategory->SetAttribute(xmlAttrEnabled, (IBInternalQuery->FieldByName("VISIBLE")->AsString == "T") ? _T("Yes") : _T("No"));
List->LinkEndChild(EleCategory);
}
Data.Doc.LinkEndChild(List);
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
}
void TManagerMenus::BuildXMLListGroup(Database::TDBTransaction &DBTransaction, TPOS_XMLBase &Data,int SiteID)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = "SELECT * FROM CATEGORYGROUPS ";
IBInternalQuery->ExecQuery();
// Update the IntaMate ID with the Invoice Number.
Data.Doc.Clear();
TiXmlDeclaration * decl = new TiXmlDeclaration(_T("1.0"), _T("UTF-8"), _T(""));
Data.Doc.LinkEndChild(decl);
// Insert DOCTYPE definiation here.
TiXmlElement * List = new TiXmlElement(xmlEleCategoryGroups);
List->SetAttribute(xmlAttrID, AnsiString(Data.IntaMateID).c_str());
List->SetAttribute(xmlAttrSiteID, SiteID);
for (; !IBInternalQuery->Eof; IBInternalQuery->Next())
{
TiXmlElement *ElePaymnet = new TiXmlElement(xmlEleGroup);
ElePaymnet->SetAttribute(xmlAttrGroupID, IBInternalQuery->FieldByName("CATEGORYGROUPS_KEY")->AsString.t_str());
ElePaymnet->SetAttribute(xmlAttrGroupName, IBInternalQuery->FieldByName("NAME")->AsString.t_str());
ElePaymnet->SetAttribute(xmlAttrEnabled, (IBInternalQuery->FieldByName("VISIBLE")->AsString == "T") ? _T("Yes") : _T("No"));
List->LinkEndChild(ElePaymnet);
}
Data.Doc.LinkEndChild(List);
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
throw;
}
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
bool
TManagerMenus::MenuInCurrent(const UnicodeString &name)
{
return Current->MenuGet(name) != NULL;
}
std::vector<UnicodeString>
TManagerMenus::GetCurrentMenus()
{
TListMenuContainer &list = *Current;
std::vector<UnicodeString> menus;
for (int i = 0; i < list.Count; i++)
menus.push_back(list.MenuGet(i)->MenuName);
return menus;
}
void TManagerMenus::SetMenuList(Database::TDBTransaction &DBTransaction, int DeviceKey)
{
try
{
TIBSQL *IBInternalQuery = DBTransaction.Query(DBTransaction.AddQuery());
if (DeviceKey != 0)
{
IBInternalQuery->Close();
IBInternalQuery->SQL->Text = " DELETE " " FROM " " DEVICESMENUS " " WHERE " " DEVICE_KEY = :DEVICE_KEY ";
IBInternalQuery->ParamByName("DEVICE_KEY")->AsInteger = DeviceKey;
IBInternalQuery->ExecQuery();
for (int i = 0; i < Current->Count; i++)
{
TListMenu *Menu = Current->MenuGet(i);
IBInternalQuery->Close();
IBInternalQuery->SQL->Clear();
IBInternalQuery->SQL->Add("INSERT INTO DEVICESMENUS (DEVICE_KEY , MENU_NAME ) ");
IBInternalQuery->SQL->Add("VALUES ( :DEVICE_KEY, :THIS_MENU );");
IBInternalQuery->ParamByName("DEVICE_KEY")->AsInteger = DeviceKey;
IBInternalQuery->ParamByName("THIS_MENU")->AsString = Menu->MenuName;
IBInternalQuery->ExecQuery();
}
}
}
catch(Exception & E)
{
TManagerLogs::Instance().Add(__FUNC__, EXCEPTIONLOG, E.Message);
}
}
|
208796b291bfbca22a75f664fc102bd9aba3b365 | d1605c2576e479fc81da1dcf74d42c8a4edbac28 | /strategies/src/strategies/forexalpha/faparameters.h | 7817b4e1232ca63ca18a940df6e8c4a5abcf7cb2 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | simhaonline/siis-rev | 5532aaf51527d504b20fdaa86fdd8c44c901ece3 | b73897fdeae7d0b36746cb62c43ea0218833f856 | refs/heads/master | 2020-08-07T11:30:30.410693 | 2019-09-11T14:45:38 | 2019-09-11T14:45:38 | 213,432,105 | 1 | 2 | null | 2019-10-07T16:25:10 | 2019-10-07T16:25:10 | null | UTF-8 | C++ | false | false | 4,667 | h | faparameters.h | /**
* @brief SiiS strategy forexalpha default parameters.
* @copyright Copyright (C) 2019 SiiS
* @author Frederic SCHERMA (frederic.scherma@gmail.com)
* @date 2019-03-17
*/
#ifndef SIIS_FAPARAMETERS_H
#define SIIS_FAPARAMETERS_H
namespace siis {
/**
* @brief Strategy forexalpha default parameters.
* @author Frederic Scherma
* @date 2019-03-17
*/
static const char* ForexAlphaParameters = R"JSON(
{
"reversal": true,
"pyramided": 0,
"hedging": false,
"maxTrades": 3,
"tradeDelay": 30,
"minTimeframe": 0,
"needUpdate": false,
"minVol24h": 0,
"minPrice": 0,
"timeframes": {
"weekly": {
"enabled": true,
"timeframe": "1w",
"subTimeframe": "daily",
"mode": "C",
"depth": 22,
"history": 22,
"indicators": {
"price": {"method": "HLC"},
"volumeEma": {"len": 8},
"rsi": {"len": 21},
"stochRsi": {"len": 13, "fastK_Len": 13, "fastD_Len": 13},
"sma": {"len": 20},
"ema": {"len": 21},
"atr": {"len": 14, "factor": 2.5}
}
},
"daily": {
"enabled": true,
"timeframe": "1d",
"subTimeframe": "4h",
"mode": "A",
"depth": 41,
"history": 41,
"indicators": {
"price": {"method": "HLC"},
"volumeEma": {"len" : 8},
"rsi": {"len" : 21},
"stochRsi": {"len": 13, "fastK_Len": 13, "fastD_Len": 13},
"sma": {"len": 20},
"ema": {"len": 8},
"atr": {"len": 14, "factor": 2.5}
}
},
"4hours": {
"enabled": true,
"timeframe": "4h",
"subTimeframe": "1h",
"mode": "D",
"depth": 56,
"history": 56,
"indicators": {
"price": {"method": "HLC"},
"volumeEma": {"len" : 8},
"rsi": {"len" : 21},
"stochRsi": {"len": 13, "fastK_Len": 13, "fastD_Len": 13},
"slowSma": {"len": 200},
"midSma": {"len": 55},
"sma": {"len": 20},
"ema": {"len": 8},
"atr": {"len": 14, "factor": 2.5}
}
},
"hourly": {
"enabled": true,
"timeframe": "1h",
"subTimeframe": "15m",
"mode": "A",
"depth": 41,
"history": 41,
"indicators": {
"price": {"method": "HLC"},
"volumeEma": {"len" : 8},
"rsi": {"len" : 21},
"stochRsi": {"len": 13, "fastK_Len": 13, "fastD_Len": 13},
"sma": {"len": 20},
"ema": {"len": 8},
"atr": {"len": 14, "factor": 2.5}
}
},
"15min": {
"enabled": true,
"timeframe": "15m",
"subTimeframe": "5m",
"mode": "A",
"depth": 41,
"history": 41,
"indicators": {
"price": {"method": "HLC"},
"volumeEma": {"len" : 8},
"rsi": {"len" : 21},
"stochRsi": {"len": 13, "fastK_Len": 13, "fastD_Len": 13},
"sma": {"len": 20},
"ema": {"len": 8},
"atr": {"len": 14, "factor": 2.5}
}
},
"5min": {
"enabled": true,
"timeframe": "5m",
"subTimeframe": "1m",
"mode": "A",
"depth": 41,
"history": 41,
"indicators": {
"price": {"method": "HLC"},
"volumeEma": {"len" : 8},
"rsi": {"len" : 21},
"stochRsi": {"len": 13, "fastK_Len": 13, "fastD_Len": 13},
"sma": {"len": 20},
"ema": {"len": 8},
"atr": {"len": 14, "factor": 2.5}
}
},
"1min": {
"enabled": false,
"timeframe": "1m",
"subTimeframe": "t",
"mode": "B",
"depth": 20,
"history": 20,
"indicators": {
"price": {"method": "HLC"},
"rsi": {"len" : 8},
"stochRsi": {"len": 13, "fastK_Len": 13, "fastD_Len": 13},
"sma": {"len": 20},
"ema": {"len": 8},
"atr": {"len": 14, "factor": 2.5}
}
}
}
})JSON";
} // namespace siis
#endif // SIIS_FAPARAMETERS_H
|
6db8598d812151c95e68007f2db3162db8928e6a | 0d0fd5bebda3a6305c3f8d5017b99c0f28c4667e | /800/Magnets.cpp | 0a9ce087de98ba7477dc82598797a316f72f3818 | [] | no_license | manmeet-kaur18/CodeForces_Leetcode | 9b7b88daa8ba8ecca48d92a665bf2ac11a437f0a | 8c129d6a6d1ffb57e224f573177c443baf835ad6 | refs/heads/master | 2023-07-13T09:50:42.888171 | 2021-08-26T05:00:44 | 2021-08-26T05:00:44 | 287,578,703 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | Magnets.cpp |
#include <iostream>
using namespace std;
int main()
{
int NofMagnatics;
cin>>NofMagnatics;
int counter=1;
int arr[100000];
for(int i=0;i<NofMagnatics;i++){
cin>>arr[i];
}
for(int i=0;i<NofMagnatics-1;i++){
if(arr[i]!=arr[i+1])
counter++;
}
cout<<counter<<endl;
}
|
bd1f086b447eb9bf775392e55e6666f049e0a1c2 | d668209e9951d249020765c011a836f193004c01 | /src/layer/riscv/clip_riscv.cpp | 8c43e06a4d823dc17fb6353556129d83ef834c1d | [
"BSD-3-Clause",
"Zlib",
"BSD-2-Clause"
] | permissive | Tencent/ncnn | d8371746c00439304c279041647362a723330a79 | 14b000d2b739bd0f169a9ccfeb042da06fa0a84a | refs/heads/master | 2023-08-31T14:04:36.635201 | 2023-08-31T04:19:23 | 2023-08-31T04:19:23 | 95,879,426 | 18,818 | 4,491 | NOASSERTION | 2023-09-14T15:44:56 | 2017-06-30T10:55:37 | C++ | UTF-8 | C++ | false | false | 4,212 | cpp | clip_riscv.cpp | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "clip_riscv.h"
#if __riscv_vector
#include <riscv_vector.h>
#include "rvv_mathfun.h"
#include "rvv_mathfun_fp16s.h"
#endif // __riscv_vector
namespace ncnn {
Clip_riscv::Clip_riscv()
{
#if __riscv_vector
support_packing = true;
#if __riscv_zfh
support_fp16_storage = true;
#endif
#endif // __riscv_vector
}
int Clip_riscv::forward_inplace(Mat& bottom_top_blob, const Option& opt) const
{
#if __riscv_vector && __riscv_zfh
int elembits = bottom_top_blob.elembits();
if (opt.use_fp16_storage && elembits == 16)
{
if (opt.use_fp16_arithmetic)
return forward_inplace_fp16sa(bottom_top_blob, opt);
else
return forward_inplace_fp16s(bottom_top_blob, opt);
}
#endif
int w = bottom_top_blob.w;
int h = bottom_top_blob.h;
int d = bottom_top_blob.d;
int channels = bottom_top_blob.c;
int elempack = bottom_top_blob.elempack;
int size = w * h * d * elempack;
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
float* ptr = bottom_top_blob.channel(q);
#if __riscv_vector
int n = size;
while (n > 0)
{
size_t vl = vsetvl_e32m8(n);
vfloat32m8_t _p = vle32_v_f32m8(ptr, vl);
_p = vfmax_vf_f32m8(_p, min, vl);
_p = vfmin_vf_f32m8(_p, max, vl);
vse32_v_f32m8(ptr, _p, vl);
ptr += vl;
n -= vl;
}
#else // __riscv_vector
for (int i = 0; i < size; i++)
{
if (*ptr < min)
*ptr = min;
if (*ptr > max)
*ptr = max;
ptr++;
}
#endif // __riscv_vector
}
return 0;
}
#if __riscv_vector && __riscv_zfh
int Clip_riscv::forward_inplace_fp16s(Mat& bottom_top_blob, const Option& opt) const
{
int w = bottom_top_blob.w;
int h = bottom_top_blob.h;
int d = bottom_top_blob.d;
int channels = bottom_top_blob.c;
int elempack = bottom_top_blob.elempack;
int size = w * h * d * elempack;
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
__fp16* ptr = bottom_top_blob.channel(q);
int n = size;
while (n > 0)
{
size_t vl = vsetvl_e16m4(n);
vfloat32m8_t _p = vfwcvt_f_f_v_f32m8(vle16_v_f16m4(ptr, vl), vl);
_p = vfmax_vf_f32m8(_p, min, vl);
_p = vfmin_vf_f32m8(_p, max, vl);
vse16_v_f16m4(ptr, vfncvt_f_f_w_f16m4(_p, vl), vl);
ptr += vl;
n -= vl;
}
}
return 0;
}
int Clip_riscv::forward_inplace_fp16sa(Mat& bottom_top_blob, const Option& opt) const
{
int w = bottom_top_blob.w;
int h = bottom_top_blob.h;
int d = bottom_top_blob.d;
int channels = bottom_top_blob.c;
int elempack = bottom_top_blob.elempack;
int size = w * h * d * elempack;
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
__fp16* ptr = bottom_top_blob.channel(q);
int n = size;
while (n > 0)
{
size_t vl = vsetvl_e16m8(n);
vfloat16m8_t _p = vle16_v_f16m8(ptr, vl);
_p = vfmax_vf_f16m8(_p, min, vl);
_p = vfmin_vf_f16m8(_p, max, vl);
vse16_v_f16m8(ptr, _p, vl);
ptr += vl;
n -= vl;
}
}
return 0;
}
#endif // __riscv_vector && __riscv_zfh
} //namespace ncnn
|
beacde2d318fa1c1b2c13417104dd51e1e0f956c | 3434f05df84d8335b6bc46ffd22c8e9c90ba093c | /blog/code/2022-02-25-data-from-mic-macos/main.cpp | a5e5ebff75f016f85f66768c5da705edb90cf6fa | [] | no_license | kunigami/kunigami.github.io | d3058f132ed305e10d47c36587d428bb3718f127 | 6970151977b428635b16501f74652e5c764428f2 | refs/heads/master | 2023-08-10T03:30:46.509819 | 2023-08-05T19:20:35 | 2023-08-05T19:20:35 | 18,582,971 | 13 | 13 | null | 2022-09-26T16:50:56 | 2014-04-09T02:48:32 | CSS | UTF-8 | C++ | false | false | 6,275 | cpp | main.cpp | #include <AudioToolbox/AudioToolbox.h>
#include <fstream>
#include <iostream>
struct Options {
double bufferSizeInSecs;
int bufferCount;
};
// generic error handler - if error is nonzero, prints error message and exits
// program.
static void CheckError(OSStatus error, const char *operation) {
if (error == noErr) return;
char errorString[20];
// see if it appears to be a 4-char-code
*(UInt32 *)(errorString + 1) = CFSwapInt32HostToBig(error);
if (isprint(errorString[1]) && isprint(errorString[2]) &&
isprint(errorString[3]) && isprint(errorString[4])) {
errorString[0] = errorString[5] = '\'';
errorString[6] = '\0';
} else
// no, format it as an integer
sprintf(errorString, "%d", (int)error);
fprintf(stderr, "Error: %s (%s)\n", operation, errorString);
exit(1);
}
/**
* Abstraction over AudioQueue for getting PCM data (via the OnReceiveData()
* callback). Needs to be implemented by children class.
*/
class PCMQueue {
private:
// Whether the audio queue is running
bool running_ = FALSE;
// Audio format the queue is working with
AudioStreamBasicDescription format_ = {0};
AudioQueueRef queue_ = {0};
void CallbackWithThis(AudioQueueRef inQueue, AudioQueueBufferRef inBuffer,
UInt32 inNumPackets) {
OnReceiveData(inBuffer, inNumPackets);
// if we're not stopping, re-enqueue the buffer so that it gets filled again
if (running_)
CheckError(AudioQueueEnqueueBuffer(inQueue, inBuffer, 0, NULL),
"AudioQueueEnqueueBuffer failed");
}
static void CallbackWithoutThis(
void *inUserData, AudioQueueRef inQueue, AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime, UInt32 inNumPackets,
const AudioStreamPacketDescription *inPacketDesc) {
static_cast<PCMQueue *>(inUserData)
->CallbackWithThis(inQueue, inBuffer, inNumPackets);
}
void RegisterCallback() {
CheckError(AudioQueueNewInput(&format_, *PCMQueue::CallbackWithoutThis,
(void *)this, NULL, NULL, 0, &queue_),
"AudioQueueNewInput failed");
}
void AddBuffer(int sizeInBytes) {
AudioQueueBufferRef buffer;
CheckError(AudioQueueAllocateBuffer(queue_, sizeInBytes, &buffer),
"AudioQueueAllocateBuffer failed");
CheckError(AudioQueueEnqueueBuffer(queue_, buffer, 0, NULL),
"AudioQueueEnqueueBuffer failed");
}
void InitializePCMFormat(AudioStreamBasicDescription *format) {
memset(format, 0, sizeof(*format));
format->mFormatID = kAudioFormatLinearPCM;
format->mFormatFlags = kAudioFormatFlagIsSignedInteger;
format->mChannelsPerFrame = 1;
format->mFramesPerPacket = 1;
format->mBitsPerChannel = 32;
format->mBytesPerFrame = 4;
format->mBytesPerPacket = 4;
format->mReserved = 0;
AudioDeviceID deviceID = GetDefaultInputDeviceID();
format->mSampleRate = GetDeviceSampleRate(deviceID);
}
AudioDeviceID GetDefaultInputDeviceID() {
AudioDeviceID deviceID = 0;
AudioObjectPropertyAddress propertyAddress = {
.mSelector = kAudioHardwarePropertyDefaultInputDevice,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = 0,
};
UInt32 propertySize = sizeof(AudioDeviceID);
OSStatus error =
AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress,
0, NULL, &propertySize, &deviceID);
if (error) throw error;
return deviceID;
}
Float64 GetDeviceSampleRate(AudioDeviceID deviceID) {
Float64 outSampleRate = 0;
AudioObjectPropertyAddress propertyAddress = {
.mSelector = kAudioDevicePropertyNominalSampleRate,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = 0,
};
UInt32 propertySize = sizeof(Float64);
OSStatus error = AudioObjectGetPropertyData(
deviceID, &propertyAddress, 0, NULL, &propertySize, &outSampleRate);
if (error) throw error;
return outSampleRate;
}
void InitializePCMFormatWithQueue() {
UInt32 size = sizeof(format_);
CheckError(AudioQueueGetProperty(
queue_, kAudioConverterCurrentOutputStreamDescription,
&format_, &size),
"couldn't get queue's format");
}
void AddBuffers(const Options *options) {
// How many samples we'll have to store in the queue
int bufferByteSize =
(int)ceil(options->bufferSizeInSecs * format_.mSampleRate);
for (int bufferIndex = 0; bufferIndex < options->bufferCount;
++bufferIndex) {
AddBuffer(bufferByteSize);
}
}
protected:
virtual void OnReceiveData(AudioQueueBufferRef inBuffer,
UInt32 inNumPackets) = 0;
public:
PCMQueue(const Options *options) {
InitializePCMFormat(&format_);
RegisterCallback();
// According to the Learning Core Audio Book (Adamson, Avila), some fields
// of the format (ASBD) can only be filled when the queue is has registered
// its input.
InitializePCMFormatWithQueue();
AddBuffers(options);
}
~PCMQueue() {
running_ = FALSE;
AudioQueueDispose(queue_, TRUE);
}
void Start() {
running_ = TRUE;
CheckError(AudioQueueStart(queue_, NULL), "AudioQueueStart failed");
}
void Stop() {
running_ = FALSE;
CheckError(AudioQueueStop(queue_, TRUE), "AudioQueueStop failed");
}
};
/**
* Implementation of the PCMQueue that writes the PCM data to disk.
*/
class PCMWriter : public PCMQueue {
private:
std::ofstream samplesFile;
public:
PCMWriter(const Options *options) : PCMQueue(options) {
samplesFile = std::ofstream("samples.csv");
}
void OnReceiveData(AudioQueueBufferRef inBuffer, UInt32 inNumPackets) {
if (inNumPackets <= 0 || !samplesFile.is_open()) return;
int *amplitudes = (int *)inBuffer->mAudioData;
for (int i = 0; i < inNumPackets; i++) {
samplesFile << amplitudes[i] << std::endl;
}
}
};
int main(int argc, const char *argv[]) {
const Options options = {.bufferSizeInSecs = 0.5, .bufferCount = 3};
auto queue = new PCMWriter(&options);
queue->Start();
printf("Recording, press <return> to stop:\n");
getchar();
queue->Stop();
delete queue;
return 0;
}
|
4dbe71b91ef4e8614e4d09e6bd50138ba3353630 | a91e7a6f4555dada1df77fd3d422cad85f24eaff | /source/matrixForms/denseForms.cpp | abdd035bef0d893b55e1bffed92633cc6fcc4019 | [] | no_license | TedStudley/mc-mini | 405093be855b01692a4a1bb698b191c0cdffaef9 | 72e40fb3c88e97560610ada5755db8133c12b919 | refs/heads/master | 2020-04-06T04:35:35.542552 | 2016-01-04T23:47:30 | 2016-01-04T23:47:30 | 15,949,815 | 2 | 5 | null | 2016-01-04T18:44:52 | 2014-01-15T21:58:12 | C++ | UTF-8 | C++ | false | false | 10,070 | cpp | denseForms.cpp | #include <iostream>
#include <Eigen/Dense>
#include "geometry/dataWindow.h"
#include "matrixForms/denseForms.h"
#include "debug.h"
using namespace Eigen;
using namespace std;
namespace DenseForms {
void makeStokesMatrix (Ref<MatrixXd> stokesMatrix,
const int M,
const int N,
const double h,
const double * viscosityData) {
#ifdef DEBUG
cout << "<Creating " << 3 * M * N - M - N << "x" << 3 * M * N - M - N << " stokesMatrix>" << endl << endl;
#endif
stokesMatrix = MatrixXd::Zero (3 * M * N - M - N, 3 * M * N - M - N);
makeLaplacianXBlock (stokesMatrix.block (0, 0, M * (N - 1), M * (N - 1)), M, N, h, viscosityData);
makeLaplacianYBlock (stokesMatrix.block (M * (N - 1), M * (N - 1), (M - 1) * N, (M - 1) * N), M, N, h, viscosityData);
makeGradXBlock (stokesMatrix.block (0, 2 * M * N - M - N, M * (N - 1), M * N), M, N, h);
makeGradYBlock (stokesMatrix.block (M * (N - 1), 2 * M * N - M - N, (M - 1) * N, M * N), M, N, h);
makeDivXBlock (stokesMatrix.block (2 * M * N - M - N, 0, M * N, M * (N - 1)), M, N, h);
makeDivYBlock (stokesMatrix.block (2 * M * N - M - N, M * (N - 1), M * N, (M - 1) * N), M, N, h);
#ifdef DEBUG
cout << endl;
#endif
}
void makeLaplacianXBlock (Ref<MatrixXd> laplacian,
const int M,
const int N,
const double h,
const double * viscosityData) {
#ifdef DEBUG
cout << "<Creating " << M * (N - 1) << "x" << M * (N - 1) << " LaplacianXBlock>" << endl;
#endif
DataWindow<const double> viscosityWindow (viscosityData, N + 1, M + 1);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < (N - 1); ++j) {
double viscosity = (viscosityWindow (j + 1, i) + viscosityWindow (j + 1, i + 1)) / 2;
// First and last rows are non-standard because the laplacian would sample points which
// do not exist in our gridding.
if (i == 0 || i == (M - 1))
laplacian (i * (N - 1) + j, i * (N - 1) + j) = viscosity * 5 / (h * h);
else
laplacian (i * (N - 1) + j, i * (N - 1) + j) = viscosity * 4 / (h * h);
// First and last rows are missing a neighbor in one of two directions
if (i > 0)
laplacian (i * (N - 1) + j, (i - 1) * (N - 1) + j) = -viscosity / (h * h);
if (i < (M - 1))
laplacian (i * (N - 1) + j, (i + 1) * (N - 1) + j) = -viscosity / (h * h);
// First and last elements of each row are missing a neighbor in one of two directions
if (j > 0)
laplacian (i * (N - 1) + j, i * (N - 1) + (j - 1)) = -viscosity / (h * h);
if (j < N - 2)
laplacian (i * (N - 1) + j, i * (N - 1) + (j + 1)) = -viscosity / (h * h);
}
}
}
void makeLaplacianYBlock (Ref<MatrixXd> laplacian,
const int M,
const int N,
const double h,
const double * viscosityData) {
#ifdef DEBUG
cout << "<Creating " << (M - 1) * N << "x" << (M - 1) * N << " LaplacianYBlock>" << endl;
#endif
DataWindow<const double> viscosityWindow (viscosityData, N + 1, M + 1);
for (int i = 0; i < (M - 1); ++i) {
for (int j = 0; j < N; ++j) {
double viscosity = (viscosityWindow (j, i + 1) + viscosityWindow (j + 1, i + 1)) / 2;
// The first and last elements of each row are non-standard because the four-point
// laplacian relies upon points not included in our gridding
if ((j == 0) || (j == (N - 1)))
laplacian (i * N + j, i * N + j) = viscosity * 5 / (h * h);
else
laplacian (i * N + j, i * N + j) = viscosity * 4 / (h * h);
// First and last elements of each row are missing a neighbor in one of two directions
if (j > 0)
laplacian (i * N + j, i * N + (j - 1)) = -viscosity / (h * h);
if (j < (N - 1))
laplacian (i * N + j, i * N + (j + 1)) = -viscosity / (h * h);
// Elements of the first and last rows are missing a neighbor in one of two directions
if (i > 0)
laplacian (i * N + j, (i - 1) * N + j) = -viscosity / (h * h);
if (i < (M - 2))
laplacian (i * N + j, (i + 1) * N + j) = -viscosity / (h * h);
}
}
}
void makeGradXBlock (Ref<MatrixXd> grad,
const int M,
const int N,
const double h) {
#ifdef DEBUG
cout << "<Creating " << M * (N - 1) << "x" << M * N << " GradXBLock>" << endl;
#endif
for (int i = 0; i < M; ++i) {
for (int j = 0; j < (N - 1); ++j) {
grad (i * (N - 1) + j, i * N + j) = -1 / h;
grad (i * (N - 1) + j, i * N + (j + 1)) = 1 / h;
}
}
}
void makeGradYBlock (Ref<MatrixXd> grad,
const int M,
const int N,
const double h) {
#ifdef DEBUG
cout << "<Creating " << (M - 1) * N << "x" << M * N << " GradYBlock>" << endl;
#endif
for (int i = 0; i < (M - 1) * N; ++i) {
grad (i, i) = -1 / h;
grad (i, i + N) = 1 / h;
}
}
void makeDivXBlock (Ref<MatrixXd> div,
const int M,
const int N,
const double h) {
#ifdef DEBUG
cout << "<Creating " << M * N << "x" << M * (N - 1) << " DivXBLock>" << endl;
#endif
for (int i = 0; i < M; ++i) {
for (int j = 0; j < (N - 1); ++j) {
div (i * N + j, i * (N - 1) + j) = 1 / h;
div (i * N + (j + 1), i * (N - 1) + j) = -1 / h;
}
}
}
void makeDivYBlock (Ref<MatrixXd> div,
const int M,
const int N,
const double h) {
#ifdef DEBUG
cout << "<Creating " << M * N << "x" << (M - 1) * N << " DivYBlock>" << endl;
#endif
for (int i = 0; i < (M - 1) * N; ++i) {
div (i, i) = 1 / h;
div (i + N, i) = -1 / h;
}
}
void makeForcingMatrix (Ref<MatrixXd> forcingMatrix,
const int M,
const int N) {
#ifdef DEBUG
cout << "<Creating " << 3 * M * N - M - N << "x" << 2 * M * N - M - N << " ForcingMatrix>" << endl;
#endif
forcingMatrix = MatrixXd::Zero (3 * M * N - M - N, 2 * M * N - M - N);
for (int i = 0; i < 2 * M * N - M - N; ++i)
forcingMatrix (i, i) = 1;
#ifdef DEBUG
cout << endl;
#endif
}
void makeBoundaryMatrix (Ref<MatrixXd> boundaryMatrix,
const int M,
const int N,
const double h,
const double * viscosityData) {
#ifdef DEBUG
cout << "<Creating " << 3 * M * N - M - N << "x" << 2 * M + 2 * N << " BoundaryMatrix>" << endl;
#endif
boundaryMatrix = MatrixXd::Zero (3 * M * N - M - N, 2 * M + 2 * N);
makeBCLaplacianXBlock (boundaryMatrix.block (0, 0, M * (N - 1), 2 * M), M, N, h, viscosityData);
makeBCLaplacianYBlock (boundaryMatrix.block (M * (N - 1), 2 * M, (M - 1) * N, 2 * N), M, N, h, viscosityData);
makeBCDivXBlock (boundaryMatrix.block (2 * M * N - M - N, 0, M * N, 2 * M), M, N, h);
makeBCDivYBlock (boundaryMatrix.block (2 * M * N - M - N, 2 * M, M * N, 2 * N), M, N, h);
}
void makeBCLaplacianXBlock (Ref<MatrixXd> laplacianBC,
const int M,
const int N,
const double h,
const double * viscosityData) {
#ifdef DEBUG
cout << "<Creating " << M * (N - 1) << "x" << 2 * M << " BCLaplacianXBlock>" << endl;
#endif
DataWindow<const double> viscosityWindow (viscosityData, N + 1, M + 1);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < 2; ++j) {
double viscosity = (viscosityWindow (j * N, i) + viscosityWindow (j * N, i + 1)) / 2;
laplacianBC (i * (N - 1) + j * (N - 2), i * 2 + j) = viscosity / (h * h);
}
}
}
void makeBCLaplacianYBlock (Ref<MatrixXd> laplacianBC,
const int M,
const int N,
const double h,
const double * viscosityData) {
#ifdef DEBUG
cout << "<Creating " << (M - 1) * N << "x" << 2 * N << " BCLaplacianYBlock>" << endl;
#endif
DataWindow<const double> viscosityWindow (viscosityData, N + 1, M + 1);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < N; ++j) {
double viscosity = (viscosityWindow (j, i * M) + viscosityWindow (j + 1, i * M)) / 2;
laplacianBC (i * (M - 2) * N + j, i * N + j) = viscosity / (h * h);
}
}
}
void makeBCDivXBlock (Ref<MatrixXd> divBC,
const int M,
const int N,
const double h) {
#ifdef DEBUG
cout << "<Creating " << M * N << "x" << 2 * M << " BCDivXBlock>" << endl;
#endif
for (int i = 0; i < M; ++i) {
divBC (i * N, i * 2) = 1 / h;
divBC ((i + 1) * N - 1, i * 2 + 1) = -1 / h;
}
}
void makeBCDivYBlock (Ref<MatrixXd> divBC,
const int M,
const int N,
const double h) {
#ifdef DEBUG
cout << "<Creating " << M * N << "x" << 2 * N << " BCDivYBlock>" << endl;
#endif
for (int i = 0; i < N; ++i) {
divBC ( i, i) = 1 / h;
divBC ((M - 1) * N + i, N + i) = -1 / h;
}
}
}
|
fac5ec8460add94e16c0d7bf19767147f0f9030a | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /Graphs/2469.cpp | 10213eec63d69d6050886071738a37445af6dead | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | 2469.cpp |
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define ff first
#define ss second
ll n,u,v,col[10005],cnt;
vector<ll> adj[10005];
void dfs(ll ver,ll par,ll color)
{
if(col[ver]!=color)
cnt++;
for(ll i=0;i<adj[ver].size();++i)
{
ll re=adj[ver][i];
if(re!=par)
dfs(re,ver,col[ver]);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for(ll i=2;i<=n;++i)
{
cin>>u;
adj[i].pb(u);
adj[u].pb(i);
}
for(ll i=1;i<=n;++i)
cin>>col[i];
cnt=0;
dfs(1,-1,-1);
cout<<cnt<<endl;
return 0;
}
|
5b38e7dded63fee076c39e3c1183eaa765629302 | 40bb05c86ce83769172b4dfe0ef26c9239c156db | /src/utils/SslHelper.cpp | 7cba795d4342dc24f806aaf552402ecafebf7ea6 | [
"Apache-2.0"
] | permissive | xDimon/primitive | 204d5763db9e292e8c2dd5a2e78435ebaf786f2a | 092e9158444710cdde45c57c4115efa06c85e161 | refs/heads/master | 2022-03-28T09:24:10.728615 | 2019-05-30T16:27:00 | 2019-05-30T16:27:00 | 103,276,659 | 12 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,597 | cpp | SslHelper.cpp | // Copyright © 2017-2019 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.04.06
// SslHelper.cpp
#include "SslHelper.hpp"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <cassert>
static std::string certificate = R"(-----BEGIN CERTIFICATE-----
MIIGJzCCBA+gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBsjELMAkGA1UEBhMCRlIx
DzANBgNVBAgMBkFsc2FjZTETMBEGA1UEBwwKU3RyYXNib3VyZzEYMBYGA1UECgwP
d3d3LmZyZWVsYW4ub3JnMRAwDgYDVQQLDAdmcmVlbGFuMS0wKwYDVQQDDCRGcmVl
bGFuIFNhbXBsZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxIjAgBgkqhkiG9w0BCQEW
E2NvbnRhY3RAZnJlZWxhbi5vcmcwHhcNMTIwNDI3MTAzMTE4WhcNMjIwNDI1MTAz
MTE4WjB+MQswCQYDVQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRgwFgYDVQQKDA93
d3cuZnJlZWxhbi5vcmcxEDAOBgNVBAsMB2ZyZWVsYW4xDjAMBgNVBAMMBWFsaWNl
MSIwIAYJKoZIhvcNAQkBFhNjb250YWN0QGZyZWVsYW4ub3JnMIICIjANBgkqhkiG
9w0BAQEFAAOCAg8AMIICCgKCAgEA3W29+ID6194bH6ejLrIC4hb2Ugo8v6ZC+Mrc
k2dNYMNPjcOKABvxxEtBamnSaeU/IY7FC/giN622LEtV/3oDcrua0+yWuVafyxmZ
yTKUb4/GUgafRQPf/eiX9urWurtIK7XgNGFNUjYPq4dSJQPPhwCHE/LKAykWnZBX
RrX0Dq4XyApNku0IpjIjEXH+8ixE12wH8wt7DEvdO7T3N3CfUbaITl1qBX+Nm2Z6
q4Ag/u5rl8NJfXg71ZmXA3XOj7zFvpyapRIZcPmkvZYn7SMCp8dXyXHPdpSiIWL2
uB3KiO4JrUYvt2GzLBUThp+lNSZaZ/Q3yOaAAUkOx+1h08285Pi+P8lO+H2Xic4S
vMq1xtLg2bNoPC5KnbRfuFPuUD2/3dSiiragJ6uYDLOyWJDivKGt/72OVTEPAL9o
6T2pGZrwbQuiFGrGTMZOvWMSpQtNl+tCCXlT4mWqJDRwuMGrI4DnnGzt3IKqNwS4
Qyo9KqjMIPwnXZAmWPm3FOKe4sFwc5fpawKO01JZewDsYTDxVj+cwXwFxbE2yBiF
z2FAHwfopwaH35p3C6lkcgP2k/zgAlnBluzACUI+MKJ/G0gv/uAhj1OHJQ3L6kn1
SpvQ41/ueBjlunExqQSYD7GtZ1Kg8uOcq2r+WISE3Qc9MpQFFkUVllmgWGwYDuN3
Zsez95kCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFFlfyRO6G8y5qEFKikl5
ajb2fT7XMB8GA1UdIwQYMBaAFCNsLT0+KV14uGw+quK7Lh5sh/JTMA0GCSqGSIb3
DQEBBQUAA4ICAQAT5wJFPqervbja5+90iKxi1d0QVtVGB+z6aoAMuWK+qgi0vgvr
mu9ot2lvTSCSnRhjeiP0SIdqFMORmBtOCFk/kYDp9M/91b+vS+S9eAlxrNCB5VOf
PqxEPp/wv1rBcE4GBO/c6HcFon3F+oBYCsUQbZDKSSZxhDm3mj7pb67FNbZbJIzJ
70HDsRe2O04oiTx+h6g6pW3cOQMgIAvFgKN5Ex727K4230B0NIdGkzuj4KSML0NM
slSAcXZ41OoSKNjy44BVEZv0ZdxTDrRM4EwJtNyggFzmtTuV02nkUj1bYYYC5f0L
ADr6s0XMyaNk8twlWYlYDZ5uKDpVRVBfiGcq0uJIzIvemhuTrofh8pBQQNkPRDFT
Rq1iTo1Ihhl3/Fl1kXk1WR3jTjNb4jHX7lIoXwpwp767HAPKGhjQ9cFbnHMEtkro
RlJYdtRq5mccDtwT0GFyoJLLBZdHHMHJz0F9H7FNk2tTQQMhK5MVYwg+LIaee586
CQVqfbscp7evlgjLW98H+5zylRHAgoH2G79aHljNKMp9BOuq6SnEglEsiWGVtu2l
hnx8SB3sVJZHeer8f/UQQwqbAO+Kdy70NmbSaqaVtp8jOxLiidWkwSyRTsuU6D8i
DiH5uEqBXExjrj0FslxcVKdVj5glVcSmkLwZKbEU1OKwleT/iXFhvooWhQ==
-----END CERTIFICATE-----)";
static std::string key = R"(-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEA3W29+ID6194bH6ejLrIC4hb2Ugo8v6ZC+Mrck2dNYMNPjcOK
ABvxxEtBamnSaeU/IY7FC/giN622LEtV/3oDcrua0+yWuVafyxmZyTKUb4/GUgaf
RQPf/eiX9urWurtIK7XgNGFNUjYPq4dSJQPPhwCHE/LKAykWnZBXRrX0Dq4XyApN
ku0IpjIjEXH+8ixE12wH8wt7DEvdO7T3N3CfUbaITl1qBX+Nm2Z6q4Ag/u5rl8NJ
fXg71ZmXA3XOj7zFvpyapRIZcPmkvZYn7SMCp8dXyXHPdpSiIWL2uB3KiO4JrUYv
t2GzLBUThp+lNSZaZ/Q3yOaAAUkOx+1h08285Pi+P8lO+H2Xic4SvMq1xtLg2bNo
PC5KnbRfuFPuUD2/3dSiiragJ6uYDLOyWJDivKGt/72OVTEPAL9o6T2pGZrwbQui
FGrGTMZOvWMSpQtNl+tCCXlT4mWqJDRwuMGrI4DnnGzt3IKqNwS4Qyo9KqjMIPwn
XZAmWPm3FOKe4sFwc5fpawKO01JZewDsYTDxVj+cwXwFxbE2yBiFz2FAHwfopwaH
35p3C6lkcgP2k/zgAlnBluzACUI+MKJ/G0gv/uAhj1OHJQ3L6kn1SpvQ41/ueBjl
unExqQSYD7GtZ1Kg8uOcq2r+WISE3Qc9MpQFFkUVllmgWGwYDuN3Zsez95kCAwEA
AQKCAgBymEHxouau4z6MUlisaOn/Ej0mVi/8S1JrqakgDB1Kj6nTRzhbOBsWKJBR
PzTrIv5aIqYtvJwQzrDyGYcHMaEpNpg5Rz716jPGi5hAPRH+7pyHhO/Watv4bvB+
lCjO+O+v12+SDC1U96+CaQUFLQSw7H/7vfH4UsJmhvX0HWSSWFzsZRCiklOgl1/4
vlNgB7MU/c7bZLyor3ZuWQh8Q6fgRSQj0kp1T/78RrwDl8r7xG4gW6vj6F6m+9bg
ro5Zayu3qxqJhWVvR3OPvm8pVa4hIJR5J5Jj3yZNOwdOX/Saiv6tEx7MvB5bGQlC
6co5SIEPPZ/FNC1Y/PNOWrb/Q4GW1AScdICZu7wIkKzWAJCo59A8Luv5FV8vm4R2
4JkyB6kXcVfowrjYXqDF/UX0ddDLLGF96ZStte3PXX8PQWY89FZuBkGw6NRZInHi
xinN2V8cm7Cw85d9Ez2zEGB4KC7LI+JgLQtdg3XvbdfhOi06eGjgK2mwfOqT8Sq+
v9POIJXTNEI3fi3dB86af/8OXRtOrAa1mik2msDI1Goi7cKQbC3fz/p1ISQCptvs
YvNwstDDutkA9o9araQy5b0LC6w5k+CSdVNbd8O2EUd0OBOUjblHKvdZ3Voz8EDF
ywYimmNGje1lK8nh2ndpja5q3ipDs1hKg5UujoGfei2gn0ch5QKCAQEA8O+IHOOu
T/lUgWspophE0Y1aUJQPqgK3EiKB84apwLfz2eAPSBff2dCN7Xp6s//u0fo41LE5
P0ds/5eu9PDlNF6HH5H3OYpV/57v5O2OSBQdB/+3TmNmQGYJCSzouIS3YNOUPQ1z
FFvRateN91BW7wKFHr0+M4zG6ezfutAQywWNoce7oGaYTT8z/yWXqmFidDqng5w5
6d8t40ScozIVacGug+lRi8lbTC+3Tp0r+la66h49upged3hFOvGXIOybvYcE98K2
GpNl9cc4q6O1WLdR7QC91ZNflKOKE8fALLZ/stEXL0p2bixbSnbIdxOEUch/iQhM
chxlsRFLjxV1dwKCAQEA60X6LyefIlXzU3PA+gIRYV0g8FOxzxXfvqvYeyOGwDaa
p/Ex50z76jIJK8wlW5Ei7U6xsxxw3E9DLH7Sf3H4KiGouBVIdcv9+IR0LcdYPR9V
oCQ1Mm5a7fjnm/FJwTokdgWGSwmFTH7/jGcNHZ8lumlRFCj6VcLT/nRxM6dgIXSo
w1D9QGC9V+e6KOZ6VR5xK0h8pOtkqoGrbFLu26GPBSuguPJXt0fwJt9PAG+6VvxJ
89NLML/n+g2/jVKXhfTT1Mbb3Fx4lnbLnkP+JrvYIaoQ1PZNggILYCUGJJTLtqOT
gkg1S41/X8EFg671kAB6ZYPbd5WnL14Xp0a9MOB/bwKCAQEA6WVAl6u/al1/jTdA
R+/1ioHB4Zjsa6bhrUGcXUowGy6XnJG+e/oUsS2kr04cm03sDaC1eOSNLk2Euzw3
EbRidI61mtGNikIF+PAAN+YgFJbXYK5I5jjIDs5JJohIkKaP9c5AJbxnpGslvLg/
IDrFXBc22YY9QTa4YldCi/eOrP0eLIANs95u3zXAqwPBnh1kgG9pYsbuGy5Fh4kp
q7WSpLYo1kQo6J8QQAdhLVh4B7QIsU7GQYGm0djCR81Mt2o9nCW1nEUUnz32YVay
ASM/Q0eip1I2kzSGPLkHww2XjjjkD1cZfIhHnYZ+kO3sV92iKo9tbFOLqmbz48l7
RoplFQKCAQEA6i+DcoCL5A+N3tlvkuuQBUw/xzhn2uu5BP/kwd2A+b7gfp6Uv9lf
P6SCgHf6D4UOMQyN0O1UYdb71ESAnp8BGF7cpC97KtXcfQzK3+53JJAWGQsxcHts
Q0foss6gTZfkRx4EqJhXeOdI06aX5Y5ObZj7PYf0dn0xqyyYqYPHKkYG3jO1gelJ
T0C3ipKv3h4pI55Jg5dTYm0kBvUeELxlsg3VM4L2UNdocikBaDvOTVte+Taut12u
OLaKns9BR/OFD1zJ6DSbS5n/4A9p4YBFCG1Rx8lLKUeDrzXrQWpiw+9amunpMsUr
rlJhfMwgXjA7pOR1BjmOapXMEZNWKlqsPQKCAQByVDxIwMQczUFwQMXcu2IbA3Z8
Czhf66+vQWh+hLRzQOY4hPBNceUiekpHRLwdHaxSlDTqB7VPq+2gSkVrCX8/XTFb
SeVHTYE7iy0Ckyme+2xcmsl/DiUHfEy+XNcDgOutS5MnWXANqMQEoaLW+NPLI3Lu
V1sCMYTd7HN9tw7whqLg18wB1zomSMVGT4DkkmAzq4zSKI1FNYp8KA3OE1Emwq+0
wRsQuawQVLCUEP3To6kYOwTzJq7jhiUK6FnjLjeTrNQSVdoqwoJrlTAHgXVV3q7q
v3TGd3xXD9yQIjmugNgxNiwAZzhJs/ZJy++fPSJ1XQxbd9qPghgGoe/ff6G7
-----END RSA PRIVATE KEY-----)";
SslHelper::SslHelper()
{
SSL_load_error_strings();
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
SSL_library_init();
BIO *cbio = BIO_new_mem_buf(const_cast<char *>(certificate.data()), -1);
X509 *cert = PEM_read_bio_X509(cbio, nullptr, 0, nullptr);
BIO_free(cbio);
assert(cert != nullptr);
BIO *kbio = BIO_new_mem_buf(const_cast<char *>(key.data()), -1);
RSA *rsa = PEM_read_bio_RSAPrivateKey(kbio, nullptr, 0, nullptr);
BIO_free(kbio);
assert(rsa != nullptr);
struct SSL_CTX_Deleter {
void operator()(SSL_CTX* ctx) const {
SSL_CTX_free(ctx);
}
};
_serverContext = std::shared_ptr<SSL_CTX>(SSL_CTX_new(SSLv23_server_method()), SSL_CTX_Deleter());
SSL_CTX_set_options(_serverContext.get(), SSL_OP_SINGLE_DH_USE);
SSL_CTX_use_certificate(_serverContext.get(), cert);
SSL_CTX_use_RSAPrivateKey(_serverContext.get(), rsa);
X509_free(cert);
RSA_free(rsa);
}
SslHelper::~SslHelper()
{
_serverContext.reset();
ERR_free_strings();
EVP_cleanup();
}
std::shared_ptr<SSL_CTX> SslHelper::getClientContext()
{
getInstance();
struct SSL_CTX_Deleter {
void operator()(SSL_CTX* ctx) const {
SSL_CTX_free(ctx);
}
};
return std::shared_ptr<SSL_CTX>(
SSL_CTX_new(SSLv23_client_method()), SSL_CTX_Deleter()
);
}
|
204a19ac86e19bf0cdfd82d9b59fe85bccea9706 | 76376635cac89942001870eacaaebf5a1ca6edcd | /DicomTest/dicom_test/data/string_converter/detail/RangeAssignment.h | 79d6e95b996774d1f0d370f8f69227093ec7a210 | [
"MIT",
"BSL-1.0"
] | permissive | drleq/CppDicom | e22678a6b6a2ef3c1ab5ee2a3c0beddfd15e98a7 | e320fad8414fabfb51c5eb80964f8b6def578247 | refs/heads/master | 2020-04-12T16:28:17.237266 | 2019-01-09T17:49:40 | 2019-01-09T17:49:40 | 162,613,526 | 0 | 0 | MIT | 2019-01-09T17:50:11 | 2018-12-20T17:55:46 | C++ | UTF-8 | C++ | false | false | 819 | h | RangeAssignment.h | #pragma once
namespace dicom_test::data::string_converter::detail {
class RangeAssignment
{
public:
RangeAssignment(
const std::string& start_byte_sequence,
const std::string& end_byte_sequence,
uint32_t start_unicode,
uint32_t end_unicode
);
const std::string& StartByteSequence() const { return m_start_byte_sequence; }
const std::string& EndByteSequence() const { return m_end_byte_sequence; }
uint32_t StartUnicode() const { return m_start_unicode; }
uint32_t EndUnicode() const { return m_end_unicode; }
private:
std::string m_start_byte_sequence;
std::string m_end_byte_sequence;
uint32_t m_start_unicode;
uint32_t m_end_unicode;
};
} |
fc3b7b3f75cf1857782fd3787f3f8291cb69dd36 | a3f13cad42d0e7288a95e28ce5d83ef5029754a8 | /src/Compiler/Frontend/Scanner.cpp | 7b5fde6135a9e1135b152c326791a35434945092 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | HeYuHan/XShaderCompiler | 3f8039d5b6ad1f46a08f940276c0ccb7fa97bc30 | c1d5018f80beaaf7eca8f6b1ab6952b3f2841be5 | refs/heads/master | 2022-03-13T17:36:35.416287 | 2019-09-05T23:46:36 | 2019-09-05T23:46:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,916 | cpp | Scanner.cpp | /*
* Scanner.cpp
*
* This file is part of the XShaderCompiler project (Copyright (c) 2014-2018 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "Scanner.h"
#include "Helper.h"
#include "ReportIdents.h"
#include <cctype>
namespace Xsc
{
Scanner::Scanner(Log* log) :
log_ { log }
{
}
bool Scanner::ScanSource(const SourceCodePtr& source)
{
if (source && source->IsValid())
{
/* Store source stream and take first character */
source_ = source;
TakeIt();
return true;
}
return false;
}
void Scanner::PushTokenString(const TokenPtrString& tokenString)
{
tokenStringItStack_.push_back(tokenString.Begin());
}
void Scanner::PopTokenString()
{
tokenStringItStack_.pop_back();
}
TokenPtrString::ConstIterator Scanner::TopTokenStringIterator() const
{
for (auto it = tokenStringItStack_.rbegin(); it != tokenStringItStack_.rend(); ++it)
{
if (!(*it).ReachedEnd())
return *it;
}
return TokenPtrString::ConstIterator();
}
TokenPtr Scanner::ActiveToken() const
{
return activeToken_;
}
TokenPtr Scanner::PreviousToken() const
{
return prevToken_;
}
/*
* ======= Protected: =======
*/
//private
TokenPtr Scanner::NextToken(bool scanComments, bool scanWhiteSpaces)
{
TokenPtr tkn;
/* Store previous token */
prevToken_ = activeToken_;
for (auto it = tokenStringItStack_.rbegin(); it != tokenStringItStack_.rend(); ++it)
{
if (!it->ReachedEnd())
{
/* Scan next token from token string */
auto& tokenStringIt = tokenStringItStack_.back();
tkn = *(tokenStringIt++);
break;
}
}
if (!tkn)
{
/* Scan next token from token sub-scanner */
tkn = NextTokenScan(scanComments, scanWhiteSpaces);
}
/* Store new active token */
activeToken_ = tkn;
return tkn;
}
//private
TokenPtr Scanner::NextTokenScan(bool scanComments, bool scanWhiteSpaces)
{
while (true)
{
try
{
/* Ignore white spaces and comments */
comment_.clear();
commentFirstLine_ = true;
bool hasComments = true;
do
{
/* Scan or ignore white spaces */
if (scanWhiteSpaces && std::isspace(UChr()))
{
StoreStartPos();
return ScanWhiteSpaces(false);
}
else
IgnoreWhiteSpaces();
/* Check for end-of-file */
if (Is(0))
{
StoreStartPos();
return Make(Tokens::EndOfStream);
}
/* Scan commentaries */
if (Is('/'))
{
StoreStartPos();
commentStartPos_ = nextStartPos_.Column();
auto prevChr = TakeIt();
if (Is('/'))
{
auto tkn = ScanCommentLine(scanComments);
if (tkn)
return tkn;
}
else if (Is('*'))
{
auto tkn = ScanCommentBlock(scanComments);
if (tkn)
return tkn;
}
else
{
std::string spell;
spell += prevChr;
if (Is('='))
{
spell += TakeIt();
return Make(Tokens::AssignOp, spell);
}
return Make(Tokens::BinaryOp, spell);
}
}
else
hasComments = false;
}
while (hasComments);
/* Scan next token */
StoreStartPos();
return ScanToken();
}
catch (const Report& err)
{
/* Add to error and scan next token */
if (log_)
log_->SubmitReport(err);
}
}
return nullptr;
}
//private
void Scanner::StoreStartPos()
{
/* Store current source position as start position for the next token */
nextStartPos_ = source_->Pos();
}
char Scanner::Take(char chr)
{
if (chr_ != chr)
ErrorUnexpected(chr);
return TakeIt();
}
char Scanner::TakeIt()
{
/* Get next character and return previous one */
auto prevChr = chr_;
chr_ = source_->Next();
return prevChr;
}
TokenPtr Scanner::Make(const Token::Types& type, bool takeChr)
{
if (takeChr)
{
std::string spell;
spell += TakeIt();
return std::make_shared<Token>(Pos(), type, std::move(spell));
}
return std::make_shared<Token>(Pos(), type);
}
TokenPtr Scanner::Make(const Token::Types& type, std::string& spell, bool takeChr)
{
if (takeChr)
spell += TakeIt();
return std::make_shared<Token>(Pos(), type, std::move(spell));
}
TokenPtr Scanner::Make(const Token::Types& type, std::string& spell, const SourcePosition& pos, bool takeChr)
{
if (takeChr)
spell += TakeIt();
return std::make_shared<Token>(pos, type, std::move(spell));
}
/* ----- Report Handling ----- */
[[noreturn]]
void Scanner::Error(const std::string& msg)
{
throw Report(ReportTypes::Error, R_LexicalError + " (" + Pos().ToString() + ") : " + msg);
}
[[noreturn]]
void Scanner::ErrorUnexpected()
{
auto chr = TakeIt();
Error(R_UnexpectedChar(std::string(1, chr)));
}
[[noreturn]]
void Scanner::ErrorUnexpected(char expectedChar)
{
auto chr = TakeIt();
Error(R_UnexpectedChar(std::string(1, chr), std::string(1, expectedChar)));
}
[[noreturn]]
void Scanner::ErrorUnexpectedEOS()
{
Error(R_UnexpectedEndOfStream);
}
/* ----- Scanning ----- */
void Scanner::Ignore(const std::function<bool(char)>& pred)
{
while (pred(Chr()))
TakeIt();
}
void Scanner::IgnoreWhiteSpaces(bool includeNewLines)
{
while ( std::isspace(UChr()) && ( includeNewLines || !IsNewLine() ) )
TakeIt();
}
TokenPtr Scanner::ScanWhiteSpaces(bool includeNewLines)
{
/* Scan new-line character (if separated from other white spaces) */
if (!includeNewLines && IsNewLine())
return Make(Tokens::NewLine, true);
/* Scan other white spaces */
std::string spell;
while ( std::isspace(UChr()) && ( includeNewLines || !IsNewLine() ) )
spell += TakeIt();
return Make(Tokens::WhiteSpace, spell);
}
TokenPtr Scanner::ScanCommentLine(bool scanComments)
{
std::string spell;
TakeIt(); // Ignore second '/' from commentary line beginning
while (!IsNewLine())
spell += TakeIt();
/* Store commentary string */
AppendComment(spell);
if (scanComments)
{
spell = "//" + spell;
return Make(Tokens::Comment, spell);
}
return nullptr;
}
TokenPtr Scanner::ScanCommentBlock(bool scanComments)
{
std::string spell;
TakeIt(); // Ignore first '*' from commentary block beginning
while (!Is(0))
{
/* Scan comment block ending */
if (Is('*'))
{
TakeIt();
if (Is('/'))
{
TakeIt();
break;
}
else
spell += '*';
}
else
spell += TakeIt();
}
/* Store commentary string */
AppendMultiLineComment(spell);
if (scanComments)
{
spell = "/*" + spell + "*/";
return Make(Tokens::Comment, spell);
}
return nullptr;
}
TokenPtr Scanner::ScanStringLiteral()
{
std::string spell;
spell += Take('\"');
while (!Is('\"'))
{
if (Is(0))
ErrorUnexpectedEOS();
spell += TakeIt();
}
spell += Take('\"');
return Make(Tokens::StringLiteral, spell);
}
TokenPtr Scanner::ScanCharLiteral()
{
std::string spell;
spell += Take('\'');
while (!Is('\''))
{
if (Is(0))
ErrorUnexpectedEOS();
spell += TakeIt();
}
spell += Take('\'');
return Make(Tokens::CharLiteral, spell);
}
// see https://msdn.microsoft.com/de-de/library/windows/desktop/bb509567(v=vs.85).aspx
TokenPtr Scanner::ScanNumber(bool startWithPeriod)
{
std::string spell;
/* Parse integer or floating-point number */
auto type = Tokens::IntLiteral;
auto preDigits = false;
auto postDigits = false;
if (!startWithPeriod)
preDigits = ScanDigitSequence(spell);
/* Check for exponent part (without fractional part) */
if ( !startWithPeriod && ( Is('e') || Is('E') ) )
startWithPeriod = true;
/* Check for fractional part */
if (startWithPeriod || Is('.'))
{
type = Tokens::FloatLiteral;
/* Scan period for floating-points */
if (startWithPeriod)
spell += '.';
else
spell += TakeIt();
/* Scan (optional) right hand side digit-sequence */
postDigits = ScanDigitSequence(spell);
if (!preDigits && !postDigits)
Error(R_MissingDecimalPartInFloat);
/* Check for exponent-part */
if (Is('e') || Is('E'))
{
spell += TakeIt();
/* Check for sign */
if (Is('-') || Is('+'))
spell += TakeIt();
/* Scan exponent digit sequence */
if (!ScanDigitSequence(spell))
Error(R_MissingDigitSequenceAfterExpr);
}
/* Check for floating-suffix */
if (Is('f') || Is('F') || Is('h') || Is('H') || Is('l') || Is('L'))
spell += TakeIt();
}
else
{
/* Check for hex numbers */
if (spell == "0" && Is('x'))
{
spell += TakeIt();
while ( std::isdigit(UChr()) || ( Chr() >= 'a' && Chr() <= 'f' ) || ( Chr() >= 'A' && Chr() <= 'F' ) )
spell += TakeIt();
}
/* Check for integer-suffix */
if (Is('u') || Is('U') || Is('l') || Is('L'))
spell += TakeIt();
}
/* Create number token */
return Make(type, spell);
}
TokenPtr Scanner::ScanNumberOrDot()
{
std::string spell;
spell += Take('.');
if (Is('.'))
return ScanVarArg(spell);
if (std::isdigit(UChr()))
return ScanNumber(true);
return Make(Tokens::Dot, spell);
}
TokenPtr Scanner::ScanVarArg(std::string& spell)
{
spell += Take('.');
spell += Take('.');
return Make(Tokens::VarArg, spell);
}
bool Scanner::ScanDigitSequence(std::string& spell)
{
bool result = (std::isdigit(UChr()) != 0);
while (std::isdigit(UChr()))
spell += TakeIt();
return result;
}
/*
* ======= Private: =======
*/
void Scanner::AppendComment(const std::string& s)
{
if (commentFirstLine_)
commentFirstLine_ = false;
else
comment_ += '\n';
if (commentStartPos_ > 0)
{
/* Append left-trimed commentary string */
auto firstNot = s.find_first_not_of(" \t");
if (firstNot == std::string::npos)
comment_ += s;
else
comment_ += s.substr(std::min(firstNot, static_cast<std::size_t>(commentStartPos_ - 1)));
}
else
{
/* Append full commentary string */
comment_ += s;
}
}
void Scanner::AppendMultiLineComment(const std::string& s)
{
std::size_t start = 0, end = 0;
while (end < s.size())
{
/* Get next comment line */
end = s.find('\n', start);
AppendComment(end < s.size() ? s.substr(start, end - start) : s.substr(start));
start = end + 1;
}
}
} // /namespace Xsc
// ================================================================================
|
af81959d6533402ff63cea7a72f991a9719fdd1b | 61a9a2e8727111b5cf18296217cd3b3eda891162 | /Practica2/esqueleto/OtherIsAliveCondition.h | 59464b1ea0089b82c4e1dd66e3ceccac1378c4ed | [] | no_license | Lepticidio/StateMachineExercise | 750b2842fb942d99c0cdb7db9123b95636653a36 | 8def11d401078b2495cee3e4843f7d6a30f1f6f9 | refs/heads/master | 2022-11-08T03:05:19.714076 | 2020-06-29T08:51:25 | 2020-06-29T08:51:25 | 275,401,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | h | OtherIsAliveCondition.h | #pragma once
#include "Condition.h"
class Character;
class OtherIsAliveCondition : public Condition
{
Character* m_pOther;
public:
OtherIsAliveCondition(Character* _pOther);
bool check() const;
};
|
5d4e5bf934a7a62abaada80b42866bd721e939a7 | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/SOC/2008/graphs/branches/tagged/boost/graphs/adjacency_list/undirected/vertex.hpp | 72a930f6eb774ad7d30a650dd8b9e3b1826c71e4 | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 6,228 | hpp | vertex.hpp |
#ifndef BOOST_GRAPHS_ADJACENCY_LIST_UNDIRECTED_VERTEX_HPP
#define BOOST_GRAPHS_ADJACENCY_LIST_UNDIRECTED_VERTEX_HPP
// #include <boost/graphs/adjacency_list/vertex.hpp>
namespace boost {
namespace graphs {
namespace adj_list {
template <typename VertexProps, typename EdgeStore>
struct undirected_vertex
{
};
#if 0
/**
*/
template <
typename VertexProps,
typename EdgeProps,
typename VertexDesc,
typename EdgeDesc,
template <typename> class VertexEdgeStore
>
class undirected_vertex
: public vertex<VertexProps>
{
public:
typedef VertexDesc descriptor_type;
typedef EdgeDesc edge_descriptor;
typedef typename vertex<VertexProps>::properties_type properties_type;
private:
typedef VertexEdgeStore<edge_descriptor> vertex_edge_store;
public:
// Edge iterator types
typedef typename vertex_edge_store::const_iterator incidence_iterator;
typedef std::pair<incidence_iterator, incidence_iterator> incidence_range;
typedef typename vertex_edge_store::size_type degree_type;
undirected_vertex();
undirected_vertex(VertexProps const& vp);
// Connection interface.
void connect_to(edge_descriptor e);
void connect_from(edge_descriptor e);
// Disconnection interface.
void disconnect_to(edge_descriptor e);
void disconnect_from(edge_descriptor e);
void disconnect_all();
std::pair<incidence_iterator, incidence_iterator> incident_edges() const;
incidence_iterator begin_incident_edges() const;
incidence_iterator end_incident_edges() const;
degree_type degree() const;
private:
vertex_edge_store _edges;
};
// Functions
#define BOOST_GRAPH_UV_PARAMS \
typename VP, typename EP, typename V, typename E, template <typename> class VES
template <BOOST_GRAPH_UV_PARAMS>
undirected_vertex<VP,EP,V,E,VES>::undirected_vertex()
: vertex<VP>()
, _edges()
{ }
template <BOOST_GRAPH_UV_PARAMS>
undirected_vertex<VP,EP,V,E,VES>::undirected_vertex(VP const& vp)
: vertex<VP>(vp)
, _edges()
{ }
/**
* Connect this vertex to the vertex at the opposite end of this edge. Note
* that this vertex is neither truly the source nor target of the edge. This
* does not guarantee that source(e) == this.
*/
template <BOOST_GRAPH_UV_PARAMS>
void
undirected_vertex<VP,EP,V,E,VES>::connect_to(edge_descriptor e)
{
_edges.add(e);
}
/**
* Connect this vertex to the vertex at the opposite end of the edge. Note that
* this does not guarantee that the target(e) == this.
*/
template <BOOST_GRAPH_UV_PARAMS>
void
undirected_vertex<VP,EP,V,E,VES>::connect_from(edge_descriptor e)
{
_edges.add(e);
}
/**
* Locally remove the given edge that connects this vertex to another endpoint.
*/
template <BOOST_GRAPH_UV_PARAMS>
void
undirected_vertex<VP,EP,V,E,VES>::disconnect_to(edge_descriptor e)
{
_edges.remove(e);
}
/**
* Locally remove the given edge that connects this vertex to another endpoint.
*/
template <BOOST_GRAPH_UV_PARAMS>
void
undirected_vertex<VP,EP,V,E,VES>::disconnect_from(edge_descriptor e)
{
_edges.remove(e);
}
/**
* Locally disconnect of all the incident edges from this vertex. Note that
* this is really only used by the disconnect algorithm.
*/
template <BOOST_GRAPH_UV_PARAMS>
void
undirected_vertex<VP,EP,V,E,VES>::disconnect_all()
{
_edges.clear();
}
/**
* Get an iterator range over the incident edges of this vertex.
*/
template <BOOST_GRAPH_UV_PARAMS>
std::pair<
typename undirected_vertex<VP,EP,V,E,VES>::incidence_iterator,
typename undirected_vertex<VP,EP,V,E,VES>::incidence_iterator
>
undirected_vertex<VP,EP,V,E,VES>::incident_edges() const
{
return std::make_pair(_edges.begin(), _edges.end());
}
/**
* Get an iterator to the first incident edge.
*/
template <BOOST_GRAPH_UV_PARAMS>
typename undirected_vertex<VP,EP,V,E,VES>::incidence_iterator
undirected_vertex<VP,EP,V,E,VES>::begin_incident_edges() const
{
return _edges.begin();
}
/**
* Get an iterator pas the end of the incident edges.
*/
template <BOOST_GRAPH_UV_PARAMS>
typename undirected_vertex<VP,EP,V,E,VES>::incidence_iterator
undirected_vertex<VP,EP,V,E,VES>::end_incident_edges() const
{
return _edges.end();
}
/**
* Return the degree of this vertex. The degree of the vertex is the number
* of incident edges.
*/
template <BOOST_GRAPH_UV_PARAMS>
typename undirected_vertex<VP,EP,V,E,VES>::degree_type
undirected_vertex<VP,EP,V,E,VES>::degree() const
{
return _edges.size();
}
/**
* Disconnect the given vertex from the given graph. This is not part of the
* public interface to this function.
*
* @todo This is actually kind of a generic algorithm.
*/
template <typename Graph>
void
disconnect(Graph& g, typename Graph::vertex_type& u, undirected_tag)
{
// Undirected - iterate over each of the incident edges I and get the
// opposite vertex w. Remove all edges from the adjacent vertex that
// connect to v. Remove all edges I from E.
typedef typename Graph::vertex_type vertex;
typedef typename vertex::descriptor_type vertex_descriptor;
typedef typename Graph::edge_type edge;
typedef typename edge::descriptor_type edge_descriptor;
// typedef typename Graph::edge_store edge_store;
typedef typename vertex::incidence_iterator incidence_iterator;
// Get a descriptor for this vertex.
vertex_descriptor ud = g.descriptor(u);
incidence_iterator
i = u.begin_incident_edges(),
end = u.end_incident_edges();
for( ; i != end; ++i) {
// Get the vertex at the opposite end of the current edge.
edge_descriptor ed = *i;
edge& e = g.edge(ed);
vertex& v = g.vertex(e.opposite(ud));
// Remove the edge containing this vertex from v.
v.disconnect_from(ed);
// Remove this edge from the graph's edge set. Note that this is
// basically just discards the edge from the edge set without actually
// trying to disconnect it from the edges.
g.template Graph::edge_store::remove_edge(ed);
}
u.disconnect_all();
}
#undef BOOST_GRAPH_UV_PARAMS
#endif
} /* namespace adj_list */
} /* namespace graphs */
} /* namespace boost */
#endif
|
425d98a90d4e068ec2389cae6fdc24f8275697a1 | 0de3ff33c6098ef2d7461b99c17fe000f75edd9d | /GetLowEngine.Engine/TextureManager.h | e4fe74827195a4ec14f3a0a808e6f68c60880cdd | [
"MIT"
] | permissive | ticticboooom/GetLowEngine | 0e1ca507937a91eaf1eb4342cd2319729ea583de | 3303bc414a8b89c605161193d7284b6f91c4a5b6 | refs/heads/master | 2023-06-26T22:22:59.266248 | 2021-07-31T16:55:17 | 2021-07-31T16:55:17 | 215,819,241 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | h | TextureManager.h | #pragma once
class TextureManager
{
public:
TextureManager();
static std::shared_ptr<TextureManager> GetInstance();
int CreateSRVFromTextureFile(std::wstring texturePath);
private:
static std::shared_ptr<TextureManager> instance;
int m_SRVSlot;
};
|
e0e4e9149286c17f36884dee3679ac67a9581fa0 | 4c4ac45dadd143c2de854a6b6087250a249f2706 | /src/cores/virtuanes/NES/Mapper/Mapper000.h | 1054f9d05d3faa25f2425ac66adc18a2ddb66933 | [] | no_license | TBirdSoars/VirtuaNES | 5cf9e5a88115e9d5dccfb7844ed26b00cfe50958 | cc4e5fa9e003f75d8b000bb22adb37961f33bf3e | refs/heads/master | 2023-05-29T13:33:35.601498 | 2023-05-03T03:30:47 | 2023-05-03T03:30:47 | 208,385,383 | 20 | 2 | null | 2020-05-08T00:52:14 | 2019-09-14T03:51:29 | C++ | UTF-8 | C++ | false | false | 1,105 | h | Mapper000.h | //////////////////////////////////////////////////////////////////////////
// Mapper000 //
//////////////////////////////////////////////////////////////////////////
class Mapper000 : public Mapper
{
public:
Mapper000( NES* parent ) : Mapper(parent) {}
void Reset();
BYTE sram;
BYTE ram;
BYTE bram;
BYTE reg[4];
void _OutDebug(WORD A,BYTE V)
{
DEBUGOUT("W %.4X %.2X\n",A,V);
}
void _OutDebug(WORD A)
{
DEBUGOUT("R %.4X\n",A);
}
// $8000-$FFFF Memory write
void Write( WORD A, BYTE V )
{
_OutDebug(A,V);
}
// $8000-$FFFF Memory read
BYTE Read( WORD A)
{
return CPU_MEM_BANK[A>>13][A&0x1FFF];
}
// $4100-$7FFF Lower Memory read/write
BYTE ReadLow ( WORD A )
{
_OutDebug(A);
return Mapper::ReadLow(A);
}
void WriteLow( WORD A, BYTE V )
{
_OutDebug(A,V);
}
// $4018-$40FF Extention register read/write
//BYTE ExRead ( WORD A ) { return 0x00; }
void ExWrite( WORD A, BYTE V )
{
//if(A>0x4017)
//_OutDebug(A,V);
}
protected:
private:
};
|
cfc52db693526049493edf98944b631da9a0f099 | 82e6375dedb79df18d5ccacd048083dae2bba383 | /src/alchemy/tests/test-balance.cpp | dbadc8fd8ef859c3e5bc09c93f0c54b47b07ff22 | [] | no_license | ybouret/upsylon | 0c97ac6451143323b17ed923276f3daa9a229e42 | f640ae8eaf3dc3abd19b28976526fafc6a0338f4 | refs/heads/master | 2023-02-16T21:18:01.404133 | 2023-01-27T10:41:55 | 2023-01-27T10:41:55 | 138,697,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | cpp | test-balance.cpp |
#include "y/alchemy/reactor.hpp"
#include "y/utest/run.hpp"
#include "y/yap.hpp"
#include "y/sequence/vector.hpp"
#include "support.hpp"
#include "y/alchemy/weak-acid.hpp"
#include "y/mkl/kernel/apk.hpp"
#include "y/lua++/state.hpp"
using namespace upsylon;
using namespace Alchemy;
Y_UTEST(balance)
{
Library lib;
Equilibria eqs;
Lua::VM vm = new Lua::State();
for(int i=1;i<argc;++i)
{
const string rx = argv[i];
eqs(rx,lib,vm);
}
if(false)
{
eqs.parse("dummy:-2A:-B:C:3D:@1",lib,vm);
}
if(false)
{
eqs.parse("combine:-X:-Y:@10.2",lib,vm);
}
// lib << "Na+" << "Cl-";
std::cerr << "<System>" << std::endl;
std::cerr << lib << std::endl;
std::cerr << eqs;
std::cerr << "<System/>" << std::endl << std::endl;
//Verbosity = false;
Reactor cs(lib,eqs, Equilibrium::Minimal);
Vector C(cs.M,0);
lib.draw(alea,C);
for(size_t j=cs.M;j>0;--j)
{
switch( lib(j).rating )
{
case 0: C[j] = 0; break;
case 1:
if(alea.to<double>()>0.7) C[j] = -C[j];
break;
default: C[j] = -C[j]; break;
}
}
cs.balance(C);
std::cerr << "C=" << C << std::endl;
}
Y_UTEST_DONE()
|
ffbf912ccfdfc8eabf40a89489e92db5128c9628 | c19fbae37e0361d44cbc4ef93df055b336467709 | /C++/FtpFileUpload/ftplib/ftp-ls.cpp | 7417405347f4f5d6fd88a53535b5d09f89d9cc4c | [] | no_license | cuidx/codememo | 6894bd4668b63c8981ee7a35bd98496b404add13 | 3bad4d3039a60c1369d74c77962d3b33a14cdbe1 | refs/heads/master | 2021-09-04T03:00:18.695532 | 2021-08-13T01:04:35 | 2021-08-13T01:04:35 | 104,612,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,292 | cpp | ftp-ls.cpp | /* Parsing FTP `ls' output.
Copyright (C) 1995, 1996, 1997, 2000, 2001
Free Software Foundation, Inc.
This file is part of GNU Wget.
GNU Wget is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GNU Wget is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
In addition, as a special exception, the Free Software Foundation
gives permission to link the code of its release of Wget with the
OpenSSL project's "OpenSSL" library (or with modified versions of it
that use the same license as the "OpenSSL" library), and distribute
the linked executables. You must obey the GNU General Public License
in all respects for all of the code used other than "OpenSSL". If you
modify this file, you may extend this exception to your version of the
file, but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. */
#include "stdafx.h"
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_STRING_H
# include <string.h>
#else
# include <strings.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <sys/types.h>
#include <errno.h>
#include "wget.h"
#include "utils.h"
#include "ftp.h"
#include "url.h"
/* 2004-12-09 SMS.
* Added some conditionality to allow easier use within Wput.
*/
#ifndef WPUT
/* Converts symbolic permissions to number-style ones, e.g. string
rwxr-xr-x to 755. For now, it knows nothing of
setuid/setgid/sticky. ACLs are ignored. */
static int
symperms (const char *s)
{
int perms = 0, i;
if (strlen (s) < 9)
return 0;
for (i = 0; i < 3; i++, s += 3)
{
perms <<= 3;
perms += (((s[0] == 'r') << 2) + ((s[1] == 'w') << 1) +
(s[2] == 'x' || s[2] == 's'));
}
return perms;
}
#endif /* ndef WPUT */
/* Cleans a line of text so that it can be consistently parsed. Destroys
<CR> and <LF> in case that thay occur at the end of the line and
replaces all <TAB> character with <SPACE>. Returns the length of the
modified line. */
static int
clean_line(char *line)
{
int len = strlen (line);
if (!len) return 0;
if (line[len - 1] == '\n')
line[--len] = '\0';
if (line[len - 1] == '\r')
line[--len] = '\0';
for ( ; *line ; line++ ) if (*line == '\t') *line = ' ';
return len;
}
/* Convert the Un*x-ish style directory listing stored in FILE to a
linked list of fileinfo (system-independent) entries. The contents
of FILE are considered to be produced by the standard Unix `ls -la'
output (whatever that might be). BSD (no group) and SYSV (with
group) listings are handled.
The time stamps are stored in a separate variable, time_t
compatible (I hope). The timezones are ignored. */
static struct fileinfo *
ftp_parse_unix_ls (const char *file, int ignore_perms)
{
FILE *fp;
static const char *months[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
int next, len, i, error, ignore;
int year, month, day; /* for time analysis */
int hour, min, sec;
struct tm timestruct, *tnow;
time_t timenow;
char *line, *tok; /* tokenizer */
struct fileinfo *dir, *l, cur; /* list creation */
fp = fopen (file, "r");
if (!fp)
{
logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
return NULL;
}
dir = l = NULL;
/* Line loop to end of file: */
while ((line = read_whole_line (fp)))
{
len = clean_line (line);
/* Skip if total... */
if (!strncasecmp (line, "total", 5))
{
xfree (line);
continue;
}
/* Get the first token (permissions). */
tok = strtok (line, " ");
if (!tok)
{
xfree (line);
continue;
}
cur.name = NULL;
cur.linkto = NULL;
/* Decide whether we deal with a file or a directory. */
switch (*tok)
{
case '-':
cur.type = FT_PLAINFILE;
DEBUGP (("PLAINFILE; "));
break;
case 'd':
cur.type = FT_DIRECTORY;
DEBUGP (("DIRECTORY; "));
break;
case 'l':
cur.type = FT_SYMLINK;
DEBUGP (("SYMLINK; "));
break;
default:
cur.type = FT_UNKNOWN;
DEBUGP (("UNKNOWN; "));
break;
}
#ifndef WPUT
if (ignore_perms)
{
switch (cur.type)
{
case FT_PLAINFILE:
cur.perms = 0644;
break;
case FT_DIRECTORY:
cur.perms = 0755;
break;
default:
/*cur.perms = 1023;*/ /* #### What is this? --hniksic */
cur.perms = 0644;
}
DEBUGP (("implicit perms %0o; ", cur.perms));
}
else
{
cur.perms = symperms (tok + 1);
DEBUGP (("perms %0o; ", cur.perms));
}
#endif /* ndef WPUT */
error = ignore = 0; /* Erroneous and ignoring entries are
treated equally for now. */
year = hour = min = sec = 0; /* Silence the compiler. */
month = day = 0;
next = -1;
/* While there are tokens on the line, parse them. Next is the
number of tokens left until the filename.
Use the month-name token as the "anchor" (the place where the
position wrt the file name is "known"). When a month name is
encountered, `next' is set to 5. Also, the preceding
characters are parsed to get the file size.
This tactic is quite dubious when it comes to
internationalization issues (non-English month names), but it
works for now. */
while ((tok = strtok (NULL, " ")))
{
--next;
if (next < 0) /* a month name was not encountered */
{
for (i = 0; i < 12; i++)
if (!strcmp (tok, months[i]))
break;
/* If we got a month, it means the token before it is the
size, and the filename is three tokens away. */
if (i != 12)
{
char *t = tok - 2;
long mul = 1;
for (cur.size = 0; t > line && ISDIGIT (*t); mul *= 10, t--)
cur.size += mul * (*t - '0');
if (t == line)
{
/* Something is seriously wrong. */
error = 1;
break;
}
month = i;
next = 5;
DEBUGP (("month: %s; ", months[month]));
}
}
else if (next == 4) /* days */
{
if (tok[1]) /* two-digit... */
day = 10 * (*tok - '0') + tok[1] - '0';
else /* ...or one-digit */
day = *tok - '0';
DEBUGP (("day: %d; ", day));
}
else if (next == 3)
{
/* This ought to be either the time, or the year. Let's
be flexible!
If we have a number x, it's a year. If we have x:y,
it's hours and minutes. If we have x:y:z, z are
seconds. */
year = 0;
min = hour = sec = 0;
/* We must deal with digits. */
if (ISDIGIT (*tok))
{
/* Suppose it's year. */
for (; ISDIGIT (*tok); tok++)
year = (*tok - '0') + 10 * year;
if (*tok == ':')
{
/* This means these were hours! */
hour = year;
year = 0;
++tok;
/* Get the minutes... */
for (; ISDIGIT (*tok); tok++)
min = (*tok - '0') + 10 * min;
if (*tok == ':')
{
/* ...and the seconds. */
++tok;
for (; ISDIGIT (*tok); tok++)
sec = (*tok - '0') + 10 * sec;
}
}
}
if (year)
{
DEBUGP (("year: %d (no tm); ", year));
}
else
{
DEBUGP (("time: %02d:%02d:%02d (no yr); ", hour, min, sec));
}
}
else if (next == 2) /* The file name */
{
int fnlen;
char *p;
/* Since the file name may contain a SPC, it is possible
for strtok to handle it wrong. */
fnlen = strlen (tok);
if (fnlen < len - (tok - line))
{
/* So we have a SPC in the file name. Restore the
original. */
tok[fnlen] = ' ';
/* If the file is a symbolic link, it should have a
` -> ' somewhere. */
if (cur.type == FT_SYMLINK)
{
p = strstr (tok, " -> ");
if (!p)
{
error = 1;
break;
}
cur.linkto = xstrdup (p + 4);
DEBUGP (("link to: %s\n", cur.linkto));
/* And separate it from the file name. */
*p = '\0';
}
}
/* If we have the filename, add it to the list of files or
directories. */
/* "." and ".." are an exception! */
if (!strcmp (tok, ".") || !strcmp (tok, ".."))
{
DEBUGP (("\nIgnoring `.' and `..'; "));
ignore = 1;
break;
}
/* Some FTP sites choose to have ls -F as their default
LIST output, which marks the symlinks with a trailing
`@', directory names with a trailing `/' and
executables with a trailing `*'. This is no problem
unless encountering a symbolic link ending with `@',
or an executable ending with `*' on a server without
default -F output. I believe these cases are very
rare. */
fnlen = strlen (tok); /* re-calculate `fnlen' */
cur.name = (char *)xmalloc (fnlen + 1);
memcpy (cur.name, tok, fnlen + 1);
if (fnlen)
{
if (cur.type == FT_DIRECTORY && cur.name[fnlen - 1] == '/')
{
cur.name[fnlen - 1] = '\0';
DEBUGP (("trailing `/' on dir.\n"));
}
else if (cur.type == FT_SYMLINK && cur.name[fnlen - 1] == '@')
{
cur.name[fnlen - 1] = '\0';
DEBUGP (("trailing `@' on link.\n"));
}
else if (cur.type == FT_PLAINFILE
&& (cur.perms & 0111)
&& cur.name[fnlen - 1] == '*')
{
cur.name[fnlen - 1] = '\0';
DEBUGP (("trailing `*' on exec.\n"));
}
} /* if (fnlen) */
else
error = 1;
break;
}
else
abort ();
} /* while */
if (!cur.name || (cur.type == FT_SYMLINK && !cur.linkto))
error = 1;
DEBUGP (("\n"));
if (error || ignore)
{
DEBUGP (("Skipping.\n"));
FREE_MAYBE (cur.name);
FREE_MAYBE (cur.linkto);
xfree (line);
continue;
}
if (!dir)
{
l = dir = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
memcpy (l, &cur, sizeof (cur));
l->prev = l->next = NULL;
}
else
{
cur.prev = l;
l->next = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
l = l->next;
memcpy (l, &cur, sizeof (cur));
l->next = NULL;
}
/* Get the current time. */
timenow = time (NULL);
tnow = localtime (&timenow);
/* Build the time-stamp (the idea by zaga@fly.cc.fer.hr). */
timestruct.tm_sec = sec;
timestruct.tm_min = min;
timestruct.tm_hour = hour;
timestruct.tm_mday = day;
timestruct.tm_mon = month;
if (year == 0)
{
/* Some listings will not specify the year if it is "obvious"
that the file was from the previous year. E.g. if today
is 97-01-12, and you see a file of Dec 15th, its year is
1996, not 1997. Thanks to Vladimir Volovich for
mentioning this! */
if (month > tnow->tm_mon)
timestruct.tm_year = tnow->tm_year - 1;
else
timestruct.tm_year = tnow->tm_year;
}
else
timestruct.tm_year = year;
if (timestruct.tm_year >= 1900)
timestruct.tm_year -= 1900;
timestruct.tm_wday = 0;
timestruct.tm_yday = 0;
timestruct.tm_isdst = -1;
l->tstamp = mktime (×truct); /* store the time-stamp */
xfree (line);
}
fclose (fp);
return dir;
}
static struct fileinfo *
ftp_parse_winnt_ls (const char *file)
{
FILE *fp;
int len;
int year, month, day; /* for time analysis */
int hour, min;
struct tm timestruct;
char *line, *tok; /* tokenizer */
struct fileinfo *dir, *l, cur; /* list creation */
fp = fopen (file, "r");
if (!fp)
{
logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
return NULL;
}
dir = l = NULL;
/* Line loop to end of file: */
while ((line = read_whole_line (fp)))
{
len = clean_line (line);
/* Extracting name is a bit of black magic and we have to do it
before `strtok' inserted extra \0 characters in the line
string. For the moment let us just suppose that the name starts at
column 39 of the listing. This way we could also recognize
filenames that begin with a series of space characters (but who
really wants to use such filenames anyway?). */
if (len < 40) continue;
tok = line + 39;
cur.name = xstrdup(tok);
DEBUGP(("Name: '%s'\n", cur.name));
/* First column: mm-dd-yy. Should atoi() on the month fail, january
will be assumed. */
tok = strtok(line, "-");
month = atoi(tok) - 1;
if (month < 0) month = 0;
tok = strtok(NULL, "-");
day = atoi(tok);
tok = strtok(NULL, " ");
year = atoi(tok);
/* Assuming the epoch starting at 1.1.1970 */
if (year <= 70) year += 100;
/* Second column: hh:mm[AP]M, listing does not contain value for
seconds */
tok = strtok(NULL, ":");
hour = atoi(tok);
tok = strtok(NULL, "M");
min = atoi(tok);
/* Adjust hour from AM/PM. Just for the record, the sequence goes
11:00AM, 12:00PM, 01:00PM ... 11:00PM, 12:00AM, 01:00AM . */
tok+=2;
if (hour == 12) hour = 0;
if (*tok == 'P') hour += 12;
DEBUGP(("YYYY/MM/DD HH:MM - %d/%02d/%02d %02d:%02d\n",
year+1900, month, day, hour, min));
/* Build the time-stamp (copy & paste from above) */
timestruct.tm_sec = 0;
timestruct.tm_min = min;
timestruct.tm_hour = hour;
timestruct.tm_mday = day;
timestruct.tm_mon = month;
timestruct.tm_year = year;
timestruct.tm_wday = 0;
timestruct.tm_yday = 0;
timestruct.tm_isdst = -1;
cur.tstamp = mktime (×truct); /* store the time-stamp */
DEBUGP(("Timestamp: %ld\n", cur.tstamp));
/* Third column: Either file length, or <DIR>. We also set the
permissions (guessed as 0644 for plain files and 0755 for
directories as the listing does not give us a clue) and filetype
here. */
tok = strtok(NULL, " ");
while (*tok == '\0') tok = strtok(NULL, " ");
if (*tok == '<')
{
cur.type = FT_DIRECTORY;
cur.size = 0;
cur.perms = 0755;
DEBUGP(("Directory\n"));
}
else
{
cur.type = FT_PLAINFILE;
cur.size = atoi(tok);
cur.perms = 0644;
DEBUGP(("File, size %ld bytes\n", cur.size));
}
cur.linkto = NULL;
/* And put everything into the linked list */
if (!dir)
{
l = dir = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
memcpy (l, &cur, sizeof (cur));
l->prev = l->next = NULL;
}
else
{
cur.prev = l;
l->next = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
l = l->next;
memcpy (l, &cur, sizeof (cur));
l->next = NULL;
}
xfree(line);
}
fclose(fp);
return dir;
}
/* Convert the VMS-style directory listing stored in "file" to a
linked list of fileinfo (system-independent) entries. The contents
of FILE are considered to be produced by the standard VMS
"DIRECTORY [/SIZE [= ALL]] /DATE [/OWNER] [/PROTECTION]" command,
more or less. (Different VMS FTP servers may have different headers,
and may not supply the same data, but all should be subsets of this.)
VMS normally provides local (server) time and date information.
Define the logical name or environment variable
"WGET_TIMEZONE_DIFFERENTIAL" (seconds) to adjust the receiving local
times if different from the remote local times.
*/
#define VMS_DEFAULT_PROT_FILE 0644
#define VMS_DEFAULT_PROT_DIR 0755
static struct fileinfo *
ftp_parse_vms_ls (const char *file)
{
FILE *fp;
int dt, i, j, len;
int perms;
time_t timenow;
struct tm timestruct;
char date_str[ 32];
char *line, *tok; /* tokenizer */
struct fileinfo *dir, *l, cur; /* list creation */
fp = fopen (file, "r");
if (!fp)
{
logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
return NULL;
}
dir = l = NULL;
/* Skip blank lines, Directory heading, and more blank lines. */
j = 0; /* Expecting initial blank line(s). */
while (1)
{
line = read_whole_line (fp);
if (line == NULL)
{
break;
}
else
{
i = clean_line (line);
if (i <= 0)
{
xfree (line); /* Free useless line storage. */
continue; /* Blank line. Keep looking. */
}
else
{
if ((j == 0) && (line[ i- 1] == ']'))
{
/* Found Directory heading line. Next non-blank line
is significant.
*/
j = 1;
}
else if (!strncmp (line, "Total of ", 9))
{
/* Found "Total of ..." footing line. No valid data
will follow (empty directory).
*/
xfree (line); /* Free useless line storage. */
line = NULL; /* Arrange for early exit. */
break;
}
else
{
break; /* Must be significant data. */
}
}
xfree (line); /* Free useless line storage. */
}
}
/* Read remainder of file until the next blank line or EOF. */
while (line != NULL)
{
char *p;
/* The first token is the file name. After a long name, other
data may be on the following line. A valid directory name ends
in ".DIR;1" (any case), although some VMS FTP servers may omit
the version number (";1").
*/
tok = strtok(line, " ");
if (tok == NULL) tok = line;
DEBUGP(("file name: '%s'\n", tok));
/* Stripping the version number on a VMS system would be wrong.
It may be foolish on a non-VMS system, too, but that's someone
else's problem. (Define PRESERVE_VMS_VERSIONS for proper
operation on other operating systems.)
*/
#if (!defined( __VMS) && !defined( PRESERVE_VMS_VERSIONS))
for (p = tok ; *p && *p != ';' ; p++);
if (*p == ';') *p = '\0';
#endif /* (!defined( __VMS) && !defined( PRESERVE_VMS_VERSIONS)) */
/* Differentiate between a directory and any other file. A VMS
listing may not include file protections (permissions). Set a
default permissions value (according to the file type), which
may be overwritten later. Store directory names without the
".DIR;1" file type and version number, as the plain name is
what will work in a CWD command.
*/
len = strlen( tok);
if (!strncasecmp( (tok+ (len- 4)), ".DIR", 4))
{
*(tok+ (len -= 4)) = '\0'; /* Discard ".DIR". */
cur.type = FT_DIRECTORY;
cur.perms = VMS_DEFAULT_PROT_DIR;
DEBUGP(("Directory (nv)\n"));
}
else if (!strncasecmp( (tok+ (len- 6)), ".DIR;1", 6))
{
*(tok+ (len -= 6)) = '\0'; /* Discard ".DIR;1". */
cur.type = FT_DIRECTORY;
cur.perms = VMS_DEFAULT_PROT_DIR;
DEBUGP(("Directory (v)\n"));
}
else
{
cur.type = FT_PLAINFILE;
cur.perms = VMS_DEFAULT_PROT_FILE;
DEBUGP(("File\n"));
}
cur.name = xstrdup(tok);
DEBUGP(("Name: '%s'\n", cur.name));
/* Null the date and time string. */
*date_str = '\0';
/* VMS lacks symbolic links. */
cur.linkto = NULL;
/* VMS reports file sizes in (512-byte) disk blocks, not bytes,
hence useless for an integrity check based on byte-count.
Set size to unknown.
*/
cur.size = 0;
/* Get token 2, if any. A long name may force all other data onto
a second line. If needed, read the second line.
*/
tok = strtok(NULL, " ");
if (tok == NULL)
{
DEBUGP(("Getting additional line.\n"));
xfree (line);
line = read_whole_line (fp);
if (!line)
{
DEBUGP(("EOF. Leaving listing parser.\n"));
break;
}
/* Second line must begin with " ". Otherwise, it's a first
line (and we may be confused).
*/
if (i <= 0)
{
/* Blank line. End of significant file listing. */
DEBUGP(("Blank line. Leaving listing parser.\n"));
xfree (line); /* Free useless line storage. */
break;
}
else if (line[ 0] != ' ')
{
DEBUGP(("Non-blank in column 1. Must be a new file name?\n"));
continue;
}
else
{
tok = strtok (line, " ");
if (tok == NULL)
{
/* Unexpected non-empty but apparently blank line. */
DEBUGP(("Null token. Leaving listing parser.\n"));
xfree (line); /* Free useless line storage. */
break;
}
}
}
/* Analyze tokens. (Order is not significant, except date must
precede time.)
Size: ddd or ddd/ddd (where "ddd" is a decimal number)
Date: DD-MMM-YYYY
Time: HH:MM or HH:MM:SS or HH:MM:SS.CC
Owner: [user] or [user,group]
Protection: (ppp,ppp,ppp,ppp) (where "ppp" is "RWED" or some
subset thereof, for System, Owner, Group, World.
If permission is lacking, info may be replaced by the string:
"No privilege for attempted operation".
*/
while (tok != NULL)
{
DEBUGP (("Token: >%s<: ", tok));
if ((strlen( tok) < 12) && (strchr( tok, '-') != NULL))
{
/* Date. */
DEBUGP (("Date.\n"));
strcpy( date_str, tok);
strcat( date_str, " ");
}
else if ((strlen( tok) < 12) && (strchr( tok, ':') != NULL))
{
/* Time. */
DEBUGP (("Time. "));
strncat( date_str,
tok,
(sizeof( date_str)- strlen( date_str)- 1));
DEBUGP (("Date time: >%s<\n", date_str));
}
else if (strchr( tok, '[') != NULL)
{
/* Owner. (Ignore.) */
DEBUGP (("Owner.\n"));
}
else if (strchr( tok, '(') != NULL)
{
/* Protections (permissions). */
perms = 0;
j = 0;
for (i = 0; i < strlen( tok); i++)
{
switch (tok[ i])
{
case '(':
break;
case ')':
break;
case ',':
if (j == 0)
{
perms = 0;
j = 1;
}
else
{
perms <<= 3;
}
break;
case 'R':
perms |= 4;
break;
case 'W':
perms |= 2;
break;
case 'E':
perms |= 1;
break;
case 'D':
perms |= 2;
break;
}
}
cur.perms = perms;
DEBUGP (("Prot. perms = %0o.\n", cur.perms));
}
else
{
/* Nondescript. Probably size(s), probably in blocks.
Could be "No privilege ..." message. (Ignore.)
*/
DEBUGP (("Ignored (size?).\n"));
}
tok = strtok (NULL, " ");
}
/* Tokens exhausted. Interpret the data, and fill in the
structure.
*/
/* Fill tm timestruct according to date-time string. Fractional
seconds are ignored. Default to current time, if conversion
fails.
*/
timenow = time( NULL);
localtime_r( &timenow, ×truct);
//strptime( date_str, "%d-%b-%Y %H:%M:%S", ×truct);
sprintf(date_str,"%d-%d-%d %d:%d:%d",timestruct.tm_mday,timestruct.tm_mon + 1,
timestruct.tm_year + 1900,timestruct.tm_hour,timestruct.tm_min,timestruct.tm_sec);
/* Convert struct tm local time to time_t local time. */
timenow = mktime (×truct);
/* Offset local time according to environment variable (seconds). */
if ((tok = getenv( "WGET_TIMEZONE_DIFFERENTIAL")) != NULL)
{
dt = atoi( tok);
DEBUGP (("Time differential = %d.\n", dt));
}
else
{
dt = 0;
}
if (dt >= 0)
{
timenow += dt;
}
else
{
timenow -= (-dt);
}
cur.tstamp = timenow; /* Store the time-stamp. */
DEBUGP(("Timestamp: %ld\n", cur.tstamp));
/* Add the data for this item to the linked list, */
if (!dir)
{
l = dir = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
memcpy (l, &cur, sizeof (cur));
l->prev = l->next = NULL;
}
else
{
cur.prev = l;
l->next = (struct fileinfo *)xmalloc (sizeof (struct fileinfo));
l = l->next;
memcpy (l, &cur, sizeof (cur));
l->next = NULL;
}
/* Free old line storage. Read a new line. */
xfree (line);
line = read_whole_line (fp);
if (line != NULL)
{
i = clean_line (line);
if (i <= 0)
{
/* Blank line. End of significant file listing. */
xfree (line); /* Free useless line storage. */
break;
}
}
}
fclose (fp);
return dir;
}
/* This function switches between the correct parsing routine depending on
the SYSTEM_TYPE. The system type should be based on the result of the
"SYST" response of the FTP server. According to this repsonse we will
use on of the three different listing parsers that cover the most of FTP
servers used nowadays.
Note that some VMS servers may respond with unexpected SYST strings.
It would be more reliable to determine the listing type by examining
the listing itself, because it is, after all, the listing itself
which will determine the success of the parsing attempted, not the
SYST response.
*/
struct fileinfo *
ftp_parse_ls (const char *file, const enum stype system_type)
{
switch (system_type)
{
case ST_UNIX:
return ftp_parse_unix_ls (file, FALSE);
case ST_WINNT:
{
/* Detect whether the listing is simulating the UNIX format */
FILE *fp;
int c;
fp = fopen (file, "r");
if (!fp)
{
logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
return NULL;
}
c = fgetc(fp);
fclose(fp);
/* If the first character of the file is '0'-'9', it's WINNT
format. */
if (c >= '0' && c <='9')
return ftp_parse_winnt_ls (file);
else
return ftp_parse_unix_ls (file, TRUE);
}
case ST_VMS:
return ftp_parse_vms_ls (file);
case ST_MACOS:
return ftp_parse_unix_ls (file, TRUE);
default:
logprintf (LOG_NOTQUIET, _("\
Unsupported listing type, trying Unix listing parser.\n"));
return ftp_parse_unix_ls (file, FALSE);
}
}
#ifndef WPUT
/* Stuff for creating FTP index. */
/* The function creates an HTML index containing references to given
directories and files on the appropriate host. The references are
FTP. */
uerr_t
ftp_index (const char *file, struct url *u, struct fileinfo *f)
{
FILE *fp;
char *upwd;
char *htclfile; /* HTML-clean file name */
if (!opt.dfp)
{
fp = fopen (file, "w");
if (!fp)
{
logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
return FOPENERR;
}
}
else
fp = opt.dfp;
if (u->user)
{
char *tmpu, *tmpp; /* temporary, clean user and passwd */
tmpu = url_escape (u->user);
tmpp = u->passwd ? url_escape (u->passwd) : NULL;
upwd = (char *)xmalloc (strlen (tmpu)
+ (tmpp ? (1 + strlen (tmpp)) : 0) + 2);
sprintf (upwd, "%s%s%s@", tmpu, tmpp ? ":" : "", tmpp ? tmpp : "");
xfree (tmpu);
FREE_MAYBE (tmpp);
}
else
upwd = xstrdup ("");
fprintf (fp, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n");
fprintf (fp, "<html>\n<head>\n<title>");
fprintf (fp, _("Index of /%s on %s:%d"), u->dir, u->host, u->port);
fprintf (fp, "</title>\n</head>\n<body>\n<h1>");
fprintf (fp, _("Index of /%s on %s:%d"), u->dir, u->host, u->port);
fprintf (fp, "</h1>\n<hr>\n<pre>\n");
while (f)
{
fprintf (fp, " ");
if (f->tstamp != -1)
{
/* #### Should we translate the months? Or, even better, use
ISO 8601 dates? */
static char *months[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
struct tm *ptm = localtime ((time_t *)&f->tstamp);
fprintf (fp, "%d %s %02d ", ptm->tm_year + 1900, months[ptm->tm_mon],
ptm->tm_mday);
if (ptm->tm_hour)
fprintf (fp, "%02d:%02d ", ptm->tm_hour, ptm->tm_min);
else
fprintf (fp, " ");
}
else
fprintf (fp, _("time unknown "));
switch (f->type)
{
case FT_PLAINFILE:
fprintf (fp, _("File "));
break;
case FT_DIRECTORY:
fprintf (fp, _("Directory "));
break;
case FT_SYMLINK:
fprintf (fp, _("Link "));
break;
default:
fprintf (fp, _("Not sure "));
break;
}
htclfile = html_quote_string (f->name);
fprintf (fp, "<a href=\"ftp://%s%s:%d", upwd, u->host, u->port);
if (*u->dir != '/')
putc ('/', fp);
fprintf (fp, "%s", u->dir);
if (*u->dir)
putc ('/', fp);
fprintf (fp, "%s", htclfile);
if (f->type == FT_DIRECTORY)
putc ('/', fp);
fprintf (fp, "\">%s", htclfile);
if (f->type == FT_DIRECTORY)
putc ('/', fp);
fprintf (fp, "</a> ");
if (f->type == FT_PLAINFILE)
fprintf (fp, _(" (%s bytes)"), legible (f->size));
else if (f->type == FT_SYMLINK)
fprintf (fp, "-> %s", f->linkto ? f->linkto : "(nil)");
putc ('\n', fp);
xfree (htclfile);
f = f->next;
}
fprintf (fp, "</pre>\n</body>\n</html>\n");
xfree (upwd);
if (!opt.dfp)
fclose (fp);
else
fflush (fp);
return FTPOK;
}
#endif /* ndef WPUT */
|
9237ddc5f17150c74124670c8949f064c9cba04d | 220c48a1ef7cf32a039c2d2ca69b9bd1541f294b | /glsdk/freeglut/progs/demos/Lorenz/lorenz.c | 6a816b2f16bab15fa387bceab3ad29cd7f3c7882 | [
"LicenseRef-scancode-unknown-license-reference",
"X11",
"Zlib",
"MIT",
"LicenseRef-scancode-public-domain",
"CC-BY-3.0"
] | permissive | paroj/gltut | 9b46265787530a512e7bbdf15b0985589d6a1543 | 849521f162f4b4f04f8f959c6759b93c524eba55 | refs/heads/master | 2023-08-22T17:08:22.414353 | 2022-08-20T10:23:35 | 2022-08-20T10:23:35 | 48,700,835 | 1,406 | 389 | MIT | 2022-08-20T10:05:17 | 2015-12-28T16:12:54 | C++ | UTF-8 | C++ | false | false | 11,152 | c | lorenz.c | /*
* Lorenz Strange Attractor
*
* Written by John F. Fay in honor of the "freeglut" 2.0.0 release in July 2003
*
* What it does:
* This program starts with two particles right next to each other. The particles
* move through a three-dimensional phase space governed by the following equations:
* dx/dt = sigma * ( y - x )
* dy/dt = r * x - y + x * z
* dz/dt = x * y + b * z
* These are the Lorenz equations and define the "Lorenz Attractor." Any two particles
* arbitrarily close together will move apart as time increases, but their tracks are
* confined within a region of the space.
*
* Commands:
* Arrow keys: Rotate the view
* PgUp, PgDn: Zoom in and out
* Mouse click: Center on the nearest point on a particle trajectory
*
* 'r'/'R': Reset the simulation
* 'm'/'M': Modify the Lorenz parameters (in the text window)
* 's'/'S': Stop (the advancement in time)
* 'g'/'G': Go
* <spacebar>: Single-step
* <Escape>: Quit
*/
/* Include Files */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <GL/freeglut.h>
#ifdef _MSC_VER
/* DUMP MEMORY LEAKS */
#include <crtdbg.h>
#endif
/************************************** Defined Constants ***************************************/
/* Number of points to draw in the curves */
#define NUM_POINTS 512
/* Angle to rotate when the user presses an arrow key */
#define ROTATION_ANGLE 5.0
/* Amount to scale bu when the user presses PgUp or PgDn */
#define SCALE_FACTOR 0.8
/*************************************** Global Variables ***************************************/
/* Lorenz Attractor variables */
double s0 = 10.0, r0 = 28.0, b0 = 8.0/3.0 ; /* Default Lorenz attactor parameters */
double time_step = 0.03 ; /* Time step in the simulation */
double sigma = 10.0, r = 28.0, b = 8.0/3.0 ; /* Lorenz attactor parameters */
double red_position[NUM_POINTS][3] ; /* Path of the red point */
double grn_position[NUM_POINTS][3] ; /* Path of the green point */
int array_index ; /* Position in *_position arrays of most recent point */
double distance = 0.0 ; /* Distance between the two points */
/* GLUT variables */
double yaw = 0.0, pit = 0.0 ; /* Euler angles of the viewing rotation */
double scale = 1.0 ; /* Scale factor */
double xcen = 0.0, ycen = 0.0, zcen = 0.0 ; /* Coordinates of the point looked at */
int animate = 1 ; /* 0 - stop, 1 = go, 2 = single-step */
/******************************************* Functions ******************************************/
/* The Lorenz Attractor */
void calc_deriv ( double position[3], double deriv[3] )
{
/* Calculate the Lorenz attractor derivatives */
deriv[0] = sigma * ( position[1] - position[0] ) ;
deriv[1] = ( r + position[2] ) * position[0] - position[1] ;
deriv[2] = -position[0] * position[1] - b * position[2] ;
}
void advance_in_time ( double time_step, double position[3], double new_position[3] )
{
/* Move a point along the Lorenz attractor */
double deriv0[3], deriv1[3], deriv2[3], deriv3[3] ;
int i ;
memcpy ( new_position, position, 3 * sizeof(double) ) ; /* Save the present values */
/* First pass in a Fourth-Order Runge-Kutta integration method */
calc_deriv ( position, deriv0 ) ;
for ( i = 0; i < 3; i++ )
new_position[i] = position[i] + 0.5 * time_step * deriv0[i] ;
/* Second pass */
calc_deriv ( new_position, deriv1 ) ;
for ( i = 0; i < 3; i++ )
new_position[i] = position[i] + 0.5 * time_step * deriv1[i] ;
/* Third pass */
calc_deriv ( position, deriv2 ) ;
for ( i = 0; i < 3; i++ )
new_position[i] = position[i] + time_step * deriv2[i] ;
/* Second pass */
calc_deriv ( new_position, deriv3 ) ;
for ( i = 0; i < 3; i++ )
new_position[i] = position[i] + 0.1666666666666666667 * time_step *
( deriv0[i] + 2.0 * ( deriv1[i] + deriv2[i] ) + deriv3[i] ) ;
}
static void
checkedFGets ( char *s, int size, FILE *stream )
{
if ( fgets ( s, size, stream ) == NULL ) {
fprintf ( stderr, "fgets failed\n");
exit ( EXIT_FAILURE );
}
}
/* GLUT callbacks */
#define INPUT_LINE_LENGTH 80
void key_cb ( unsigned char key, int x, int y )
{
int i ;
char inputline [ INPUT_LINE_LENGTH ] ;
switch ( key )
{
case 'r' : case 'R' : /* Reset the simulation */
/* Reset the Lorenz parameters */
sigma = s0 ;
b = b0 ;
r = r0 ;
/* Set an initial position */
red_position[0][0] = (double)rand() / (double)RAND_MAX ;
red_position[0][1] = (double)rand() / (double)RAND_MAX ;
red_position[0][2] = (double)rand() / (double)RAND_MAX ;
grn_position[0][0] = (double)rand() / (double)RAND_MAX ;
grn_position[0][1] = (double)rand() / (double)RAND_MAX ;
grn_position[0][2] = (double)rand() / (double)RAND_MAX ;
array_index = 0 ;
/* Initialize the arrays */
for ( i = 1; i < NUM_POINTS; i++ )
{
memcpy ( red_position[i], red_position[0], 3 * sizeof(double) ) ;
memcpy ( grn_position[i], grn_position[0], 3 * sizeof(double) ) ;
}
break ;
case 'm' : case 'M' : /* Modify the Lorenz parameters */
printf ( "Please enter new value for <sigma> (default %f, currently %f): ", s0, sigma ) ;
checkedFGets ( inputline, sizeof ( inputline ), stdin ) ;
sscanf ( inputline, "%lf", &sigma ) ;
printf ( "Please enter new value for <b> (default %f, currently %f): ", b0, b ) ;
checkedFGets ( inputline, sizeof ( inputline ), stdin ) ;
sscanf ( inputline, "%lf", &b ) ;
printf ( "Please enter new value for <r> (default %f, currently %f): ", r0, r ) ;
checkedFGets ( inputline, sizeof ( inputline ), stdin ) ;
sscanf ( inputline, "%lf", &r ) ;
break ;
case 's' : case 'S' : /* Stop the animation */
animate = 0 ;
break ;
case 'g' : case 'G' : /* Start the animation */
animate = 1 ;
break ;
case ' ' : /* Spacebar: Single step */
animate = 2 ;
break ;
case 27 : /* Escape key */
glutLeaveMainLoop () ;
break ;
}
}
void special_cb ( int key, int x, int y )
{
switch ( key )
{
case GLUT_KEY_UP : /* Rotate up a little */
glRotated ( ROTATION_ANGLE, 0.0, 1.0, 0.0 ) ;
break ;
case GLUT_KEY_DOWN : /* Rotate down a little */
glRotated ( -ROTATION_ANGLE, 0.0, 1.0, 0.0 ) ;
break ;
case GLUT_KEY_LEFT : /* Rotate left a little */
glRotated ( ROTATION_ANGLE, 0.0, 0.0, 1.0 ) ;
break ;
case GLUT_KEY_RIGHT : /* Rotate right a little */
glRotated ( -ROTATION_ANGLE, 0.0, 0.0, 1.0 ) ;
break ;
case GLUT_KEY_PAGE_UP : /* Zoom in a little */
glScaled ( 1.0 / SCALE_FACTOR, 1.0 / SCALE_FACTOR, 1.0 / SCALE_FACTOR ) ;
break ;
case GLUT_KEY_PAGE_DOWN : /* Zoom out a little */
glScaled ( SCALE_FACTOR, SCALE_FACTOR, SCALE_FACTOR ) ;
break ;
}
glutPostRedisplay () ;
}
void mouse_cb ( int button, int updown, int x, int y )
{
if ( updown == GLUT_DOWN )
{
double dist = 1.0e20 ; /* A very large number */
dist = 0.0 ; /* so we don't get "unused variable" compiler warning */
/* The idea here is that we go into "pick" mode and pick the nearest point
to the mouse click position. Unfortunately I don't have the time to implement
it at the moment. */
}
}
void draw_curve ( int index, double position [ NUM_POINTS ][3] )
{
int i = index ;
glBegin ( GL_LINE_STRIP ) ;
do
{
i = ( i == NUM_POINTS-1 ) ? 0 : i + 1 ;
glVertex3dv ( position[i] ) ;
}
while ( i != index ) ;
glEnd () ;
}
void bitmapPrintf (const char *fmt, ...)
{
static char buf[256];
va_list args;
va_start(args, fmt);
#if defined(WIN32) && !defined(__CYGWIN__)
(void) _vsnprintf (buf, sizeof(buf), fmt, args);
#else
(void) vsnprintf (buf, sizeof(buf), fmt, args);
#endif
va_end(args);
glutBitmapString ( GLUT_BITMAP_HELVETICA_12, (unsigned char*)buf ) ;
}
void display_cb ( void )
{
glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ;
glColor3d ( 1.0, 1.0, 1.0 ) ; /* White */
/* Draw some axes */
glBegin ( GL_LINES ) ;
glVertex3d ( 0.0, 0.0, 0.0 ) ;
glVertex3d ( 2.0, 0.0, 0.0 ) ;
glVertex3d ( 0.0, 0.0, 0.0 ) ;
glVertex3d ( 0.0, 1.0, 0.0 ) ;
glVertex3d ( 0.0, 0.0, 0.0 ) ;
glVertex3d ( 0.0, 0.0, 1.0 ) ;
glEnd () ;
glColor3d ( 1.0, 0.0, 0.0 ) ; /* Red */
draw_curve ( array_index, red_position ) ;
glColor3d ( 0.0, 1.0, 0.0 ) ; /* Green */
draw_curve ( array_index, grn_position ) ;
/* Print the distance between the two points */
glColor3d ( 1.0, 1.0, 1.0 ) ; /* White */
glRasterPos2i ( 1, 1 ) ;
bitmapPrintf ( "Distance: %10.6f", distance ) ;
glutSwapBuffers();
}
void reshape_cb ( int width, int height )
{
float ar;
glViewport ( 0, 0, width, height ) ;
glMatrixMode ( GL_PROJECTION ) ;
glLoadIdentity () ;
ar = (float) width / (float) height ;
glFrustum ( -ar, ar, -1.0, 1.0, 10.0, 100.0 ) ;
glMatrixMode ( GL_MODELVIEW ) ;
glLoadIdentity () ;
xcen = 0.0 ;
ycen = 0.0 ;
zcen = 0.0 ;
glTranslated ( xcen, ycen, zcen - 50.0 ) ;
}
void timer_cb ( int value )
{
/* Function called at regular intervals to update the positions of the points */
double deltax, deltay, deltaz ;
int new_index = array_index + 1 ;
/* Set the next timed callback */
glutTimerFunc ( 30, timer_cb, 0 ) ;
if ( animate > 0 )
{
if ( new_index == NUM_POINTS ) new_index = 0 ;
advance_in_time ( time_step, red_position[array_index], red_position[new_index] ) ;
advance_in_time ( time_step, grn_position[array_index], grn_position[new_index] ) ;
array_index = new_index ;
deltax = red_position[array_index][0] - grn_position[array_index][0] ;
deltay = red_position[array_index][1] - grn_position[array_index][1] ;
deltaz = red_position[array_index][2] - grn_position[array_index][2] ;
distance = sqrt ( deltax * deltax + deltay * deltay + deltaz * deltaz ) ;
if ( animate == 2 ) animate = 0 ;
}
glutPostRedisplay () ;
}
/* The Main Program */
int main ( int argc, char *argv[] )
{
int pargc = argc ;
/* Initialize the random number generator */
srand ( 1023 ) ;
/* Set up the OpenGL parameters */
glEnable ( GL_DEPTH_TEST ) ;
glClearColor ( 0.0, 0.0, 0.0, 0.0 ) ;
glClearDepth ( 1.0 ) ;
/* Initialize GLUT */
glutInitWindowSize ( 600, 600 ) ;
glutInit ( &pargc, argv ) ;
glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ) ;
/* Create the window */
glutCreateWindow ( "Lorenz Attractor" ) ;
glutKeyboardFunc ( key_cb ) ;
glutMouseFunc ( mouse_cb ) ;
glutSpecialFunc ( special_cb ) ;
glutDisplayFunc ( display_cb ) ;
glutReshapeFunc ( reshape_cb ) ;
glutTimerFunc ( 30, timer_cb, 0 ) ;
/* Initialize the attractor: The easiest way is to call the keyboard callback with an
* argument of 'r' for Reset.
*/
key_cb ( 'r', 0, 0 ) ;
/* Enter the GLUT main loop */
glutMainLoop () ;
#ifdef _MSC_VER
/* DUMP MEMORY LEAK INFORMATION */
_CrtDumpMemoryLeaks () ;
#endif
return 0 ;
}
|
3e81b943c8c2c4107b9c4add6e6f18dbec500e3a | 8dff49c4dc92983cbd0934725f97224fd9754d1d | /ZeroJudge/b836.cpp | 1f0222b6ca2f79dad79db00b6ed2b0e16ea6c3c4 | [] | no_license | cherry900606/OJ_Solutions | 1c7360ca35252aec459ef01d8e6a485778d32653 | b70f8baed30f446421fd39f311f1d5071a441734 | refs/heads/main | 2023-05-14T13:38:44.475393 | 2021-06-19T07:29:35 | 2021-06-19T07:29:35 | 378,026,385 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | b836.cpp | #include <iostream>
using namespace std;
int main()
{
long long int n,m;
while(cin>>n>>m)
{
if(m==0) cout<<"Go Kevin!!"<<endl;
else if((n-1)%m==0) cout<<"Go Kevin!!"<<endl;
else cout<<"No Stop!!"<<endl;
}
return 0;
}
|
322b7f9630ec1be08bdb158d36c67c618b24bf27 | a89131609d513678bef864616ec282ec3470862d | /src/Android/TraceAction.hpp | 2be7f6dfe80342184b37b3bc6fe9523e44042e68 | [] | no_license | hlhtddx/AndroidTrace | 05228131e7b6952193c839e0e4d389d81ba6a9fe | d34c6f1aa0fef79e754cc60543c527265e4b87a1 | refs/heads/master | 2020-04-06T06:16:13.601947 | 2018-01-29T09:40:39 | 2018-01-29T09:40:39 | 41,125,284 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | hpp | TraceAction.hpp |
#pragma once
#include "Call.hpp"
namespace Android {
#ifdef CLOCK_SOURCE_THREAD_CPU
typedef enum ActionType {
ACTION_ENTER = 0,
ACTION_EXIT = 1,
ACTION_INCOMPLETE = 2,
} ActionType;
class TraceAction final
{
public:
int mAction;
int mCall;
public:
TraceAction(ActionType action, int call)
{
mAction = action;
mCall = call;
}
};
#endif
};
|
6842711d28ba7b29eac7c170d92c5cc79876cd84 | eecb64a0eb8b6d28e22eb12926a7590d9a43b4d4 | /internal/libmdict/adler32_test.cc | 6c0ba7449b4118b0fc3e64b0a699b3152f248a8e | [] | no_license | terasum/medict | d960f4da14e68943c1513a0584c4af3cc734da97 | dac8ccab4e6a8cebaed947475463864baa2d7606 | refs/heads/v3-dev | 2023-03-17T11:46:45.929964 | 2022-09-03T06:45:21 | 2022-09-03T06:45:21 | 121,977,288 | 241 | 30 | null | 2023-09-11T11:46:13 | 2018-02-18T18:15:37 | C | UTF-8 | C++ | false | false | 357 | cc | adler32_test.cc | // adler32.cpp - originally written and placed in the public domain by Wei Dai
#include "adler32.h"
int main() {
// Adler32 adler32hasher;
char *str = const_cast<char *>("helloworld");
uint32_t hash = adler32checksum((unsigned char *)str, 10);
if (hash != 0x1736043D) {
printf("adler32 test failed, PANIC\n");
return -1;
}
return 0;
}
|
514005022ac87667e2abef43d42489431920c8dc | 33a2a48e8774a7ab52c3c20f11b646a676188028 | /DP/ChainOfPair.cpp | d72b4bf4126aa8c10d1a4dc25e7f66fa32932dd7 | [] | no_license | Avi7997/Algo_DS-codes-in-Btech | 12123f574b88a8613aa78c0b6bd74e818f759d6d | 2b1e3e0c06230cf7ae728e809476c92c29c366a1 | refs/heads/master | 2021-09-06T17:52:06.543603 | 2018-02-09T09:27:38 | 2018-02-09T09:27:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 884 | cpp | ChainOfPair.cpp | #include<bits/stdc++.h>
using namespace std;
struct hey{
int a;
int b;
};
void chain(struct hey ar[], int n){
int dp[n], mac[n]={0};
dp[n-1] = 1;
mac[n-1] = 1;
for( int i = n-2; i >= 0; i--){
int j = i+1;
mac[i] = mac[i+1];
//cout<<"mac "<<mac[i]<<endl;
while(ar[i].b > ar[j].a){
j++;
if(j >= n)
break;
}
if(j == n){
dp[i] = 1;
continue;
}
//cout<<"J is here "<<j<<endl;
dp[i] = mac[j] + 1;
if(mac[i]<dp[i])
mac[i] = dp[i];
}
/*for(int i = 0; i< n; i++)
cout<<mac[i]<<" ";
cout<<endl;*/
cout<<dp[0];
}
int main(){
int n;
cin >> n;
struct hey ar[n];
for( int i = 0; i < n; i++){
cin >> ar[i].a;
cin >> ar[i].b;
}
chain(ar,n);
}
|
f80b56815576c62e555d90cd161f5ded676d2030 | e1967a72410844f8a3368ab8cc488b1a7362334f | /src/quickMovementDemo.cpp | f7cd1eca95779eca7ae74a545c269a3df903647a | [] | no_license | sarossilli/lim-demo | e63b4086156d26673db56986453dc08ef2cf3bfd | b38436a0a1bcac826e0f97db26da272e69bb637b | refs/heads/master | 2022-12-24T16:51:59.464309 | 2020-10-06T22:30:40 | 2020-10-06T22:30:40 | 284,764,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,693 | cpp | quickMovementDemo.cpp | // Demonstrator Pod Fast Movements Code
// Use the uncommented version for actual arduino upload!
// This version makes the cart move back and forth along the track
// 11-11-19
//########################################## BACKGROUND INFO ####################################################################
// This code sends a current through each coil
// If the pin is set to a higher value, we can change the ammount of magnetic field from the coils (aka stronger magnetic force)
// Each coil's current can be changed (decreased/increased) by moivng up/down elements of a sine array so that the cart gets pushed along
// Each coils have a "phase" that is an ofset of a sine wave to push the cart along (PHASE1 is element 1 of sine, PHASE2 is shifted 24 ammount of elements, etc...)
// Use shift(); function to shift the current array down as the cart moves along the track and to get the new value to align the coils with the magnets.
// The drive(); function is used to write that calulated new current value to each coil. (includes error calculation from the rotary encoder and correction for the current to be correct)
// The Rotary Encoder is used as a PID system.
// A PID system automatically applies accurate and responsive correction to the control (drive();) function
// It is used to scale current values so the coils/magnets move at the correct speed based on the location
// We can put in a desired location (Setpoint value), an input value (actual measured position from rotary encoder) and an outputed value will be used to drive the motor correctly to that position
//#################################################################################################################################################
// Must Include this PID library (incuded in sharepoint)
// It has PID tools that is used to calculate an error/correction values
#include <PID_v1.h>
// Defines our arduino pin numbers. (Based on circuit layout)
const int encoder0PinA = 2 ;
const int encoder0PinB = 3 ;
const int EN1 = 5;
const int EN2 = 6;
const int EN3 = 7;
const int IN1 = 9;
const int IN2 = 10;
const int IN3 = 11;
int directionPin = 4;
int stepPin = 12;
volatile int encoder0Pos = 0; //This is the value of the position of the coils
// Setting up encoder object (myPID)
// - Setpoint is a desired value (a location on the track)
// - Input is the measured position
// - Output is the calculated value (scalar multiplier to increase/decrease pwm frequency)
double Setpoint, Input, Output;
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
// SPWM (Sine Wave) This is a pwm value for the pins. (255 is 32khz or max frequency)
int pwmSin[72] = {127, 138, 149, 160, 170, 181, 191, 200, 209, 217, 224, 231, 237, 242, 246, 250, 252, 254, 254, 254, 252, 250, 246, 242, 237, 231, 224, 217, 209, 200, 191, 181, 170, 160, 149, 138, 127, 116, 105, 94, 84, 73, 64, 54, 45, 37, 30, 23, 17, 12, 8, 4, 2, 0, 0, 0, 2, 4, 8, 12, 17, 23, 30, 37, 45, 54, 64, 73, 84, 94, 105, 116 };
// These are the 3 possible phases
// count[] is helpfull for shifiting pwnSin[] by one phase
enum phase {PHASE1, PHASE2, PHASE3};
int count[] = {0,24,48};
int sDistance; // This is a shift distance, the ammount of elements to shift by to get to the correct pwm
// These are our 3 magnet orientations and the correct pwm for each position
int *pos_U = pwmSin;
int *pos_V = pwmSin + 24;
int *pos_W = pwmSin + 48;
// length of track (how much to travel)
const double distance = 27;
double step_position = 0;
int test;
// Converted to mm value of position on track
double position_in_mm = (encoder0Pos) / 40.00;
// This sets up our pins and initializes the position of the coils to be aligned with the magnets
void setup() {
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
// These interupts catch each pulse from the rotary encoder.
// Each pulse will call doEncoderA/B function
// encoder pin on interrupt 0 (pin 2)
attachInterrupt(0, doEncoderA, CHANGE);
// encoder pin on interrupt 1 (pin 3)
attachInterrupt(1, doEncoderB, CHANGE);
// Increase PWM frequency to 32 kHz
setPwmFrequency(IN1);
setPwmFrequency(IN2);
setPwmFrequency(IN3);
// Set Pin Modes
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(EN1, OUTPUT);
pinMode(EN2, OUTPUT);
pinMode(EN3, OUTPUT);
digitalWrite(EN1, HIGH);
digitalWrite(EN2, HIGH);
digitalWrite(EN3, HIGH);
// Align our coils to the magnets by setting correct pwm values to each coil
analogWrite(IN1,*pos_U);
analogWrite(IN2,*pos_V);
analogWrite(IN3,*pos_W);
delay(2000);
analogWrite(IN1,0);
analogWrite(IN2,0);
analogWrite(IN3,0);
//Initailize position/step_position to 0
encoder0Pos = 0 ;
step_position = 0;
// Our input (actual location) and expected (setpoint) should be zero
Input = encoder0Pos / 40.00 ;
Setpoint = step_position;
//Setup our PID object
myPID.SetOutputLimits(-1000, 1000);
myPID.SetMode(AUTOMATIC);
myPID.SetSampleTime(1);
myPID.SetTunings(15,0,0.4); //val_1,0,val_
unsigned long previousMillis = 0;
}
//Used for timing intervals
unsigned long previousMillis = 0;
const long interval = 500;
int i = 0;
// Fucntion completed each clock cycle
void loop() {
int positions[2] = { -100.0 , 0};
// This section calculates how much to drive the motor based on the PID error calulation
// Input (actual location) is calcuated from encoderPosition
Input = encoder0Pos / 40.00;
// Calculated error value is stored in Output
myPID.Compute();
// Drive our motor based on the output of the calculation
drive(Output);
// The new setpoint (wanted value) is either end of the track (100 or -100)
Setpoint = positions[i];
// Update current timing
unsigned long currentMillis = millis();
// Each interval cycle switches i from 0 to 1 or 1 to 0
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (i < 1) {
i++;
} else {
i = 0;
}
}
}
// This function actually drives the motor.
// scale_factor is a value to multply our pwm by in order to decrease our pwm based on how much we need to move
void drive(double scale_factor){
// It devides scale_factor by 1000 since our limits of output are -1000 to 1000, and we need to decrease our pwm value (multiply by a value less than one)
scale_factor = scale_factor/1000;
if(scale_factor > 0.00){
// shiftDistance is used to shift the array the correct ammount of elements
// count[0] should always equal calculate()'s return value
// otherwise change (encoder0position) in setup();
sDistance = (-count[0] + calculate() + 24);
scale_factor = (scale_factor - 0.00) * (1.0 - 0.1) / (1.00 - 0.00) + 0.1;
//Shifts the pwmSin pointer by to the correct element
shift(&pos_U, sDistance , 72, PHASE1);
shift(&pos_V, sDistance, 72, PHASE2);
shift(&pos_W, sDistance, 72, PHASE3);
//Write the pwm frequency to the pins multiplied by the scale_factor from the encoder
analogWrite(IN1,*pos_U * scale_factor );
analogWrite(IN2,*pos_V * scale_factor );
analogWrite(IN3,*pos_W * scale_factor);
return;
}
// This section handles a negative scale factor
// It does the same thing as the statement before, just handles negatives
if(scale_factor < 0.00){
double temp = -scale_factor;
temp = (temp - 0.00) * (1.0 - 0.1) / (1.00 - 0.00) + 0.1;
sDistance =- ( count[0] - calculate() + 24) ; // +24
shift(&pos_U, sDistance , 72, PHASE1);
shift(&pos_V, sDistance, 72, PHASE2);
shift(&pos_W, sDistance, 72, PHASE3);
analogWrite(IN1,*pos_U * temp );
analogWrite(IN2,*pos_V * temp );
analogWrite(IN3,*pos_W * temp);
return;
}
if(scale_factor == 0.00)
return;
}
// A function that calculates the three phaseshift values (how many elements to shift our sine wave array by)
// it returns the 3rd phaseshift (should be equal to count[0])
int calculate(){
//re-find the position in mm
double position_in_mm = (encoder0Pos) / 40.00;
int multiple = position_in_mm / distance;
double phaseshift2 = position_in_mm-(multiple*distance);
// Serial.println(phaseshift2);
double phaseshift3 = (phaseshift2) * (72) / (distance - 0) + 0;
//Serial.println(phaseshift3);
return phaseshift3;
}
// Function that shifts the pwm sin wave by a number of elements
void shift(int **pwm_sin , int shift_distance , int array_size, phase phase_number){
//If we are shifting by one whole sin cycle, we will not change values (sin(0) is the same as sin(360) etc)
if(shift_distance == array_size)
return;
if(shift_distance > 0){
if(count[phase_number] + shift_distance < array_size){
//shift the pwm array and the count array by shift distance
*pwm_sin = *pwm_sin + shift_distance;
count[phase_number] += shift_distance ;
}
else //Handles if shift is beyond the end of array
{
int temp =count[phase_number] + shift_distance - array_size;
*pwm_sin = *pwm_sin - count[phase_number];
*pwm_sin = *pwm_sin + temp;
count[phase_number] = temp;
}
return;
}
//Handles negative shift values.
// Recursively calls shift(); with a correct value
if(shift_distance < 0){
int temp_distance = array_size + shift_distance;
shift(pwm_sin, temp_distance , array_size, phase_number);
}
if(shift_distance = 0 );
return;
}
// ENCODER-INTERRUPT
// This function is called when a pulse from the encoder is measured
// The encoder pulses 400 times per full rotaion, so this is used to measure the location of the motor
void doEncoderA() {
// look for a low-to-high on channel A
if (digitalRead(encoder0PinA) == HIGH) {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
else // must be a high-to-low edge on channel A
{
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
//Serial.println (encoder0Pos, DEC);
// use for debugging - remember to comment out
}
void doEncoderB() {
// look for a low-to-high on channel B
if (digitalRead(encoder0PinB) == HIGH) {
// check channel A to see which way encoder is turning
if (digitalRead(encoder0PinA) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
// Look for a high-to-low on channel B
else {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinA) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
}
// This fucntion sets the pmw frequency of the board.
// PWM frequency is the rate which the pin switches off/on
// This function sets the frequency to 32 kHz to make it high enough to not effect the load (our coils).
void setPwmFrequency(int pin) {
if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
if(pin == 5 || pin == 6) {
TCCR0B = TCCR0B & 0b11111000 | 0x01;
} else {
TCCR1B = TCCR1B & 0b11111000 | 0x01;
}
}
else if(pin == 3 || pin == 11) {
TCCR2B = TCCR2B & 0b11111000 | 0x01;
}
}
|
c8ccff7a4608f8021ee708649eaf8a1f29d42329 | 4d4822b29e666cea6b2d99d5b9d9c41916b455a9 | /Example/Pods/Headers/Private/GeoFeatures/boost/fusion/container/list/list_fwd.hpp | 32832a9e9c3556d151491aa5228058ed9a0ef5a6 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | eswiss/geofeatures | 7346210128358cca5001a04b0e380afc9d19663b | 1ffd5fdc49d859b829bdb8a9147ba6543d8d46c4 | refs/heads/master | 2020-04-05T19:45:33.653377 | 2016-01-28T20:11:44 | 2016-01-28T20:11:44 | 50,859,811 | 0 | 0 | null | 2016-02-01T18:12:28 | 2016-02-01T18:12:28 | null | UTF-8 | C++ | false | false | 79 | hpp | list_fwd.hpp | ../../../../../../../../../GeoFeatures/boost/fusion/container/list/list_fwd.hpp |
689b13c1bbeda7de04814ec39fff1031fc7d0174 | 48fff87acdaeafdf024d57dce70b68b0e85e6498 | /J1939Reader/J1939Reader.ino | 1277903b485913786135c97797627bb9ca80eb21 | [] | no_license | Fusickb/TheoreticalVibrations | 8cdd34a11995bf946f858f7aeab29330d9a3e6c7 | 2368a37ce63fdd8e4c5b7cbc0e2accabf0d9f837 | refs/heads/master | 2021-01-18T05:53:35.621598 | 2016-09-27T17:17:55 | 2016-09-27T17:17:55 | 68,475,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,254 | ino | J1939Reader.ino | #include <FlexCAN.h> // Includes Arduino's FlexCAN library. For reference this is available at https://github.com/teachop/FlexCAN_Library
#define ledPin 13 // Defines the pin 13 as the ledPin
FlexCAN J1939bus(250000); // Defines the J1939 CANBus to operate at a baudrate of 250,000.
static CAN_message_t rxmsg; // Defines the received CAN message as rxmsg
elapsedMillis ledTimer; // Sets a variable that counts up in milliseconds to blink the Led
boolean ledState = false; // Sets a boolean variable to false (light is off)
void setup() {
// put your setup code here, to run once:
J1939bus.begin(); // Initializes the J1939bus.
Serial.begin(115200); // Intializes the serial output at a baud rate of 115200.
pinMode(ledPin, OUTPUT); // Sets the ledPin to output mode.
}
void loop() {
// put your main code here, to run repeatedly:
while ( J1939bus.read(rxmsg) ) { // While the Bus is receiving a message, read the message and
uint32_t ID = rxmsg.id; // Create an ID that is unsigned and 32 bits long and makes this known as rxmsg.id which is a property of the rxmsg.
byte DLC = rxmsg.len; // Sets DLC to the rxmsg.len (the length of the transmitted message in bytes)
// This led flash proves that the Teensy is getting CAN traffic.
if (ledTimer >= 1000){ // When the timer reaches 1 second
ledTimer = 0; // Reset the timer to 0
ledState = !ledState; // Switch the variable for the ledState to the opposite value
digitalWrite(ledPin,ledState); // Write that change to the pin
}
if ( ID > 0x700 && ID < 0x724 ){ // if the ID of the message is 701 to 723
Serial.print(ID,HEX); // print the ID in HEX,
Serial.print(" "); // print a space,
Serial.print(DLC,HEX); // print the length of the message in HEX,
for (int i = 0; i<DLC; i++){ // For each byte of the message,
Serial.print(" "); // Print a space,
Serial.print(rxmsg.buf[i],HEX); // then print that portion of the message in HEX and repeat for all portions of the message
} //end for
Serial.println(); // Print a new line.
}// end if
} //end while
}//end loop
|
dadb008427a148b1231f690b4f1bb29ccca38711 | ff0cc7e931d038a9bd9a56665b20cd8dab071959 | /src/Apps/Plugins/NeuroToolsPlugin/widgets/ImageContrastWidget/coreImageContrastWidgetUI.cpp | d11f2ae36e92420747e832b4e6c90136def65614 | [] | no_license | jakubsadura/Swiezy | 6ebf1637057c4dbb8fda5bfd3f57ef7eec92279b | bd32b7815b5c0206582916b62935ff49008ee371 | refs/heads/master | 2016-09-11T00:39:59.005668 | 2011-05-22T19:38:33 | 2011-05-22T19:38:33 | 1,784,754 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,123 | cpp | coreImageContrastWidgetUI.cpp | // -*- C++ -*- generated by wxGlade 0.6.3 on Thu Jul 01 11:35:34 2010
#include "coreImageContrastWidgetUI.h"
// begin wxGlade: ::extracode
// end wxGlade
coreImageContrastWidgetUI::coreImageContrastWidgetUI(wxWindow* parent, int id, const wxPoint& pos, const wxSize& size, long style):
wxScrolledWindow(parent, id, pos, size, wxTAB_TRAVERSAL)
{
// begin wxGlade: coreImageContrastWidgetUI::coreImageContrastWidgetUI
m_checkEnable = new wxCheckBox(this, wxID_EnableSliders, wxT("Enable Sliders"));
m_bmpAdd = new wxStaticBitmap(this, wxID_ANY, wxNullBitmap);
negativeSlider = new wxSlider(this, wxID_NegativeSlider, 0, 0, 100, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE);
m_bmpSubstract = new wxStaticBitmap(this, wxID_ANY, wxNullBitmap);
positiveSlider = new wxSlider(this, wxID_PositiveSlider, 0, 0, 100, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE);
set_properties();
do_layout();
// end wxGlade
}
BEGIN_EVENT_TABLE(coreImageContrastWidgetUI, wxScrolledWindow)
// begin wxGlade: coreImageContrastWidgetUI::event_table
EVT_CHECKBOX(wxID_EnableSliders, coreImageContrastWidgetUI::OnChkBoxEnable)
EVT_COMMAND_SCROLL(wxID_NegativeSlider, coreImageContrastWidgetUI::OnSliderNegativeContrast)
EVT_COMMAND_SCROLL(wxID_PositiveSlider, coreImageContrastWidgetUI::OnSliderPositiveContrast)
// end wxGlade
END_EVENT_TABLE();
void coreImageContrastWidgetUI::OnChkBoxEnable(wxCommandEvent &event)
{
event.Skip();
wxLogDebug(wxT("Event handler (coreImageContrastWidgetUI::OnChkBoxEnable) not implemented yet")); //notify the user that he hasn't implemented the event handler yet
}
void coreImageContrastWidgetUI::OnSliderNegativeContrast(wxScrollEvent &event)
{
event.Skip();
wxLogDebug(wxT("Event handler (coreImageContrastWidgetUI::OnSliderNegativeContrast) not implemented yet")); //notify the user that he hasn't implemented the event handler yet
}
void coreImageContrastWidgetUI::OnSliderPositiveContrast(wxScrollEvent &event)
{
event.Skip();
wxLogDebug(wxT("Event handler (coreImageContrastWidgetUI::OnSliderPositiveContrast) not implemented yet")); //notify the user that he hasn't implemented the event handler yet
}
// wxGlade: add coreImageContrastWidgetUI event handlers
void coreImageContrastWidgetUI::set_properties()
{
// begin wxGlade: coreImageContrastWidgetUI::set_properties
SetSize(wxSize(368, 134));
SetScrollRate(10, 10);
// end wxGlade
}
void coreImageContrastWidgetUI::do_layout()
{
// begin wxGlade: coreImageContrastWidgetUI::do_layout
wxBoxSizer* sizer_3 = new wxBoxSizer(wxVERTICAL);
wxBoxSizer* sizer_6 = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* sizer_5 = new wxBoxSizer(wxHORIZONTAL);
sizer_3->Add(m_checkEnable, 0, 0, 0);
sizer_5->Add(m_bmpAdd, 0, wxALIGN_RIGHT, 0);
sizer_5->Add(negativeSlider, 1, wxEXPAND, 0);
sizer_3->Add(sizer_5, 0, wxEXPAND, 0);
sizer_6->Add(m_bmpSubstract, 0, wxALIGN_RIGHT, 0);
sizer_6->Add(positiveSlider, 1, wxEXPAND, 0);
sizer_3->Add(sizer_6, 0, wxEXPAND, 0);
SetSizer(sizer_3);
// end wxGlade
}
|
fce876c0ab28f6d51567e16a16bf0c00246ef406 | 99a0c9b3c6dfaea7e60288fe3bf0a99e0c250d98 | /2D-Portfolio/Client/LogoStatic.cpp | 6c34d60a37c1c46926af35631ec14180c0406c6f | [] | no_license | Ryujaehyeon/Portfolio | d6232cb0350a89d2be26526fe94feedc61d9271f | 4be010721d03340560edbc0514252bf58402954e | refs/heads/master | 2020-05-29T15:08:14.275370 | 2016-09-23T01:52:09 | 2016-09-23T01:52:09 | 65,179,835 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | cpp | LogoStatic.cpp | #include "StdAfx.h"
#include "LogoStatic.h"
CLogoStatic::CLogoStatic(void)
{
}
CLogoStatic::CLogoStatic(const OBJINFO& Info, const OBJ_TYPE _ObjType)
:CObj(Info, _ObjType)
{
}
CLogoStatic::~CLogoStatic(void)
{
}
|
ffc4ed6ce7b6f6d4da789b29fcd6d98dafb8ff1c | 319bba205ce1659bdae52f12e8352ffeffdebab5 | /src/sdl-modules/impl/sdl_ttf.cc | e8f4f6c468cb99acc34154f2c09a44d5eca94341 | [] | no_license | woguls/GE | e43e4f79ec4ec19438b850dab8564551a2545c32 | 984247555ab3af633e01b4f18d54f7f77e7ea036 | refs/heads/master | 2020-05-04T23:50:22.451590 | 2019-04-07T04:57:40 | 2019-04-07T04:57:40 | 179,556,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | cc | sdl_ttf.cc | #include <sdl-modules/sdl_ttf.h>
#include <v8pp/module.hpp>
#include <v8pp/class.hpp>
#include <common-util.h>
SdlTTF::SdlTTF
( resource_reference_t& ref, int ptsize )
{
ResourceReference* ref_ptr = ref.Get();
if (ref_ptr == nullptr) {
LOG("Attempted to create ttf from empty reference");
return;
}
resource_type rt = ref_ptr->GetType();
if ( rt == resource_ttf ) {
if(!TTF_WasInit() && TTF_Init()==-1) {
LOG(TTF_GetError());
return;
}
TTF_Font *font;
std::string path{ref_ptr->GetPath()};
font = TTF_OpenFont(path.c_str(), ptsize);
if (font == nullptr) {
LOG("SdlTTF:");
LOG(SDL_GetError());
return;
}
else sdl_ttf_font_t::Set(font);
return;
}
else {
std::string message = "Reference of type " + std::to_string(rt) + std::string(" is not ttf");
LOG(message.c_str());
}
}
void SdlTTF::Init(v8pp::module& m) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8pp::class_<SdlTTF> SdlTTF_class(isolate);
SdlTTF_class
.inherit<sdl_ttf_font_t>()
.ctor<resource_reference_t&, int>()
;
LOG("Initialized SDL.TTF()");
m.set("TTF", SdlTTF_class);
}
|
d4e1c82548295d7c835b6b911d006392eacd3ef5 | f8cf477528a74720409dd454308e1a38dd84ffbd | /src/ActiveBSP/include/actormsg/ReleaseResultPartMessage.h | 65cbf3a91acd599bb8a56b8e6f0df7181fb7a386 | [
"BSD-3-Clause"
] | permissive | fbaude/activebsp | c949f7f776585c5d7edcdc9607da9139e87480e0 | d867d74e58bde38cc0f816bcb23c6c41a5bb4f81 | refs/heads/main | 2023-05-07T23:45:25.169736 | 2021-05-28T13:57:45 | 2021-05-28T13:57:45 | 371,710,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | h | ReleaseResultPartMessage.h | #ifndef __RELEASE_RESULT_PART_MESSAGE_H__
#define __RELEASE_RESULT_PART_MESSAGE_H__
#include "ActorMessage.h"
namespace activebsp
{
class ReleaseResultPartMessage : public activebsp::ActorMessage
{
public:
ReleaseResultPartMessage(int src, char * buf, int buf_size);
ReleaseResultPartMessage(int resid);
virtual ~ReleaseResultPartMessage();
int getResId();
};
} // namespace activebsp
#endif // __RELEASE_RESULT_PART_MESSAGE_H__
|
d4d14e9f157e3eb7f0f1993a4bacb77f3e1842d1 | 07263bc11131f3a1cc9bb56fa88d0d2db4c00eae | /src/backend/executor/exchange_hash_join_executor.h | a1991093a8f0817452724e7cc5e091993cc4e3e7 | [
"Apache-2.0"
] | permissive | TailofJune/peloton | a89cc8f5b91fe333efa688996fdd8e1c93df1138 | 092c5625fd1011f98e61553f183eb7193a0583c4 | refs/heads/master | 2020-12-26T03:11:42.522692 | 2016-05-10T02:35:14 | 2016-05-10T02:35:14 | 56,364,070 | 1 | 0 | null | 2016-04-16T03:42:16 | 2016-04-16T03:42:15 | null | UTF-8 | C++ | false | false | 4,398 | h | exchange_hash_join_executor.h | #pragma once
#include <deque>
#include <vector>
#include "backend/executor/abstract_join_executor.h"
#include "backend/executor/exchange_hash_executor.h"
#include "backend/executor/hash_executor.h"
#include "backend/planner/hash_join_plan.h"
#include <atomic>
#include "backend/common/barrier.h"
#include "backend/common/thread_manager.h"
#include "boost/lockfree/queue.hpp"
namespace peloton {
namespace executor {
class ConcurrentOidSet {
public:
ConcurrentOidSet() {}
ConcurrentOidSet(ConcurrentOidSet &&that)
: container_(std::move(that.container_)) {}
ConcurrentOidSet(const ConcurrentOidSet &that) = delete;
ConcurrentOidSet &operator=(const ConcurrentOidSet &that) = delete;
ConcurrentOidSet &operator=(ConcurrentOidSet &&that) = delete;
size_t MUTEX_CNT = 16;
std::array<std::mutex, 16> mtx_list_;
std::unordered_set<oid_t> container_;
void Erase(oid_t key) {
int mutex_id = key % MUTEX_CNT;
mtx_list_[mutex_id].lock();
container_.erase(key);
mtx_list_[mutex_id].unlock();
}
bool Empty() { return container_.empty(); }
};
typedef std::uint_least32_t thread_no;
class PesudoBarrier {
public:
void Release() {
std::lock_guard<std::mutex> lock(mutex_);
++count_;
assert(count_ <= total_);
if (count_ == total_) {
done = true;
}
}
PesudoBarrier() : total_(0) {}
void SetTotal(thread_no new_total) { total_ = new_total; }
bool IsDone() { return done; }
bool IsNoNeedToDo() { return no_need_to_do_; }
void SetNeedToDo(bool value) { no_need_to_do_ = value; }
private:
thread_no total_;
bool done = false;
std::mutex mutex_;
size_t count_ = 0;
bool no_need_to_do_ = false;
};
typedef std::vector<ConcurrentOidSet> ExHashJoinRowSets;
class ExchangeHashJoinExecutor : public AbstractJoinExecutor {
ExchangeHashJoinExecutor(const ExchangeHashJoinExecutor &) = delete;
ExchangeHashJoinExecutor &operator=(const ExchangeHashJoinExecutor &) =
delete;
public:
explicit ExchangeHashJoinExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context);
std::vector<LogicalTile *> GetOutputs();
~ExchangeHashJoinExecutor() = default;
void GetRightHashTable(Barrier *barrier);
void GetLeftScanResult(Barrier *barrier);
void Probe(std::atomic<thread_no> *no, PesudoBarrier *barrier);
void UpdateLeftJoinRowSets();
void UpdateRightJoinRowSets();
// helper function to launch number worker threads, each of which will do
// function
static void LaunchWorkerThreads(size_t number,
std::function<void()> function) {
LOG_TRACE("LaunchWorkerThreads(%lu)", number);
ThreadManager &tm = ThreadManager::GetInstance();
for (size_t i = 0; i < number; ++i) tm.AddTask(function);
}
inline void RecordMatchedLeftRow(size_t tile_idx, oid_t row_idx) {
switch (join_type_) {
case JOIN_TYPE_LEFT:
case JOIN_TYPE_OUTER:
no_matching_left_row_sets_[tile_idx].erase(row_idx);
break;
default:
break;
}
}
/**
* Record a matched right row, which should not be constructed
* when building join outputs
*/
inline void RecordMatchedRightRow(size_t tile_idx, oid_t row_idx) {
switch (join_type_) {
case JOIN_TYPE_RIGHT:
case JOIN_TYPE_OUTER:
exhj_no_matching_right_row_sets_[tile_idx].Erase(row_idx);
break;
default:
break;
}
}
void SetTaskNumPerThread(size_t num) { SIZE_PER_PARTITION = num; }
std::chrono::time_point<std::chrono::system_clock> main_start;
std::chrono::time_point<std::chrono::system_clock> main_end;
PesudoBarrier probe_barrier_;
protected:
bool DInit();
bool DExecute();
private:
ExchangeHashExecutor *hash_executor_ = nullptr;
bool hashed_ = false;
bool prepare_children_ = false;
bool exec_outer_join_ = false;
boost::lockfree::queue<LogicalTile *, boost::lockfree::capacity<1000>>
lockfree_buffered_output_tiles;
std::atomic<size_t> atomic_left_matching_idx;
std::atomic<size_t> atomic_right_matching_idx;
std::vector<std::unique_ptr<LogicalTile>> right_tiles_;
bool no_need_to_probe_ = false;
size_t SIZE_PER_PARTITION = 75;
ExHashJoinRowSets exhj_no_matching_right_row_sets_;
bool BuildRightJoinOutput();
bool BuildLeftJoinOutput();
};
} // namespace executor
} // namespace peloton
|
dc086dc18d7c4d684f14339ac196958c1086403c | d8571a050518855e11f14688fb30efba304d8850 | /Snake/src/Snake/Window.h | 8414d79dc6115b372faf0bad59c46615761ee37c | [] | no_license | PatrickJessen/Snake | f5a006d90c77fe34c8fefa52d3d269758db9d9c8 | a5a188431649383bb0c7cab88f2d68ae576090ed | refs/heads/master | 2023-07-10T16:46:14.104401 | 2021-08-11T16:50:43 | 2021-08-11T16:50:43 | 395,057,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | h | Window.h | #pragma once
#define SDL_MAIN_HANDLED
#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
class Window
{
public:
Window(const char* title, int xpos, int ypos, int width, int height, bool fullscreen);
~Window();
//void Init(const char* title, int xpos, int ypos, int width, int height, bool fullscreen);
void HandleEvents();
void Update();
void Clear();
void Render();
void Clean();
SDL_Renderer* GetRender();
bool Running();
public:
int GetWidth();
int GetHeight();
SDL_Renderer* renderer;
private:
bool isRunning;
SDL_Window* window;
private:
int width;
int height;
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.