blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6050614394a1b89f884e9e36a25c9ea21c1ea2e0 | 9895bc169c7585e6fd6888916096f90c16135a5a | /Rainbow Pinball/ModuleRender.cpp | 46bd670d41d8ad448a8a6fbbed161f8d922f8d86 | [
"MIT"
] | permissive | RustikTie/Pinball | 60d3821d9c99e1d54109acef453013dc80ab9bc2 | e416dac239c883c5eed6713722beaffea82d2873 | refs/heads/master | 2021-07-23T11:43:09.994904 | 2017-11-02T22:58:33 | 2017-11-02T22:58:33 | 108,077,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,617 | cpp | #include "Globals.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "ModuleRender.h"
#include <math.h>
ModuleRender::ModuleRender(Application* app, bool start_enabled) : Module(app, start_enabled)
{
renderer = NULL;
camera.x = camera.y = 0;
camera.w = SCREEN_WIDTH;
camera.h = SCREEN_HEIGHT;
}
// Destructor
ModuleRender::~ModuleRender()
{}
// Called before render is available
bool ModuleRender::Init()
{
LOG("Creating Renderer context");
bool ret = true;
Uint32 flags = 0;
if(VSYNC == true)
{
flags |= SDL_RENDERER_PRESENTVSYNC;
}
renderer = SDL_CreateRenderer(App->window->window, -1, flags);
if(renderer == NULL)
{
LOG("Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
return ret;
}
// PreUpdate: clear buffer
update_status ModuleRender::PreUpdate()
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
return UPDATE_CONTINUE;
}
// Update: debug camera
update_status ModuleRender::Update()
{
/*
int speed = 3;
if(App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT)
App->renderer->camera.y += speed;
if(App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT)
App->renderer->camera.y -= speed;
if(App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT)
App->renderer->camera.x += speed;
if(App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT)
App->renderer->camera.x -= speed;
*/
return UPDATE_CONTINUE;
}
// PostUpdate present buffer to screen
update_status ModuleRender::PostUpdate()
{
SDL_RenderPresent(renderer);
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleRender::CleanUp()
{
LOG("Destroying renderer");
//Destroy window
if(renderer != NULL)
{
SDL_DestroyRenderer(renderer);
}
return true;
}
// Blit to screen
bool ModuleRender::Blit(SDL_Texture* texture, int x, int y, SDL_Rect* section, float speed, double angle, int pivot_x, int pivot_y )
{
bool ret = true;
SDL_Rect rect;
rect.x = (int) (camera.x * speed) + x * SCREEN_SIZE;
rect.y = (int) (camera.y * speed) + y * SCREEN_SIZE;
if(section != NULL)
{
rect.w = section->w;
rect.h = section->h;
}
else
{
SDL_QueryTexture(texture, NULL, NULL, &rect.w, &rect.h);
}
rect.w *= SCREEN_SIZE;
rect.h *= SCREEN_SIZE;
SDL_Point* p = NULL;
SDL_Point pivot;
if(pivot_x != INT_MAX && pivot_y != INT_MAX)
{
pivot.x = pivot_x;
pivot.y = pivot_y;
p = &pivot;
}
if(SDL_RenderCopyEx(renderer, texture, section, &rect, angle, p, SDL_FLIP_NONE) != 0)
{
LOG("Cannot blit to screen. SDL_RenderCopy error: %s", SDL_GetError());
ret = false;
}
return ret;
}
bool ModuleRender::DrawQuad(const SDL_Rect& rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool filled, bool use_camera)
{
bool ret = true;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_Rect rec(rect);
if(use_camera)
{
rec.x = (int)(camera.x + rect.x * SCREEN_SIZE);
rec.y = (int)(camera.y + rect.y * SCREEN_SIZE);
rec.w *= SCREEN_SIZE;
rec.h *= SCREEN_SIZE;
}
int result = (filled) ? SDL_RenderFillRect(renderer, &rec) : SDL_RenderDrawRect(renderer, &rec);
if(result != 0)
{
LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
ret = false;
}
return ret;
}
bool ModuleRender::DrawLine(int x1, int y1, int x2, int y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool use_camera)
{
bool ret = true;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
int result = -1;
if(use_camera)
result = SDL_RenderDrawLine(renderer, camera.x + x1 * SCREEN_SIZE, camera.y + y1 * SCREEN_SIZE, camera.x + x2 * SCREEN_SIZE, camera.y + y2 * SCREEN_SIZE);
else
result = SDL_RenderDrawLine(renderer, x1 * SCREEN_SIZE, y1 * SCREEN_SIZE, x2 * SCREEN_SIZE, y2 * SCREEN_SIZE);
if(result != 0)
{
LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
ret = false;
}
return ret;
}
bool ModuleRender::DrawCircle(int x, int y, int radius, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool use_camera)
{
bool ret = true;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
int result = -1;
SDL_Point points[360];
float factor = (float) M_PI / 180.0f;
for(uint i = 0; i < 360; ++i)
{
points[i].x = (int) (x + radius * cos( i * factor));
points[i].y = (int) (y + radius * sin( i * factor));
}
result = SDL_RenderDrawPoints(renderer, points, 1200);
if(result != 0)
{
LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
ret = false;
}
return ret;
} | [
"[email protected]"
] | |
095b9ef490dd909b0a4114b91b15e07ad19e775b | 22b8a4e1683b185718479c244cb390cdbed9abd9 | /PA4_Qin_Yifeng/proj4.cpp | 5de0de7ce74447bdde900110059e26ee46542d8e | [] | no_license | YifengQ/CS-202 | 18eb4454aef9bc5d761ec2bf085e534bcf9f8ae2 | 5d6ffb18e65b2dee02514749d470b6cd0d01a5a5 | refs/heads/master | 2021-06-24T21:55:17.851888 | 2021-04-10T21:47:08 | 2021-04-10T21:47:08 | 216,172,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,300 | cpp | //Yifeng Qin
//CS202
//10/3/17
//Project 4
/*
Layout
------------------
Declared classes / Prototypes
Menu Functions Prototype
Main
Menu Functions
Menu Functions
Class Sensor Functions
Class Car Functions
Class Agency Functions
*/
#include <iostream>
#include <fstream>
using namespace std;
const int maxsize = 255;
void myStringCopy (char *destination, const char *source);
void intStringCopy (int *destination, const int *source);
class sensor{
public:
//defaul and paramaterized constructors
sensor();
sensor(char* temp_type, float extracost);
void setType (char* t_type);
char* getType();
void setExtracost(float t_extracost);
float getExtracost();
// overload operator
sensor operator[](int sensor);
//reset functions for static int
void reset_gps();
void reset_camera();
void reset_lidar();
void reset_radar();
private:
char m_type [maxsize];
float m_extracost;
static int gps_cnt;
static int camera_cnt;
static int lidar_cnt;
static int radar_cnt;
};
//sensor::sensor(char *m_type){
// myStringCopy(this.m_type, m_type);
//}
//set all my static variables to zero
int sensor::gps_cnt = 0;
int sensor::camera_cnt = 0;
int sensor::lidar_cnt = 0;
int sensor::radar_cnt = 0;
class car{
public:
//defaul and paramaterized constructors
car();
car(char* temp_make, char* temp_model, char* temp_owner, int tempyear, float b_price, float f_price, bool t_avail);
void setMake (char* t_make);
char* getMake();
void setModel (char* t_model);
char* getModel();
void setOwner (char* t_owner);
char* getOwner();
void setYear(int t_year);
int getYear();
void setBaseprice(float t_baseprice);
float getBaseprice();
void setFinalprice(float t_finalprice);
float getFinalprice();
void setAvailable(bool t_avaliable);
bool getAvailable();
void printData();
void setSensor(int j, char* tempSensor);
void getSensor(int j);
// overload operator
car operator[](int cars);
private:
char m_make [maxsize];
char m_model [maxsize];
int m_year;
sensor m_sensors [3];
float m_baseprice;
float m_finalprice;
bool m_available;
char m_owner [maxsize];
};
class agency{
public:
//defaul and paramaterized constructors
agency();
agency(char* tempname, int* tempzipcode);
void setName(char* t_name);
char* getName();
void setInv(int i, int tempYear, char *tempMake, char* tempModel, float baseprice, float finalprice, bool avail, char* tempOwner);
void getInv(int j);
void getInv2(int j);
void getAgency();
void printExp();
void setZip(int t_zip);
int* getZip();
void EstPrice(int i);
void ResetAvail(char *temp_name);
// overload operator
agency operator[](int agency);
private:
char m_name[maxsize];
int m_zipcode[5];
car m_inventory [5];
};
//prototypes for my case functions
void case_1(agency* agency1, car* carz, int &cg, int &cl, int &cr, int &cc);
void case_2(agency* agency1, car* carz);
void case_3(int cg, int cl, int cr, int cc);
void case_4(agency* agency1);
void myStringCopy (char *destination, const char *source);
int main()
{
int menu;
bool if_file = false;
int i;
agency agency1[1];
car carz[5];
int z= 0;
int cg = 0, cl = 0, cr = 0, cc =0;
cout << "=====================================" << endl;
cout << " Menu"<< endl;
cout << "=====================================" << endl;
cout << "1) Input File Name" << endl;
cout << "2) Print Data" << endl;
cout << "3) TOTAL Number of Sensors" << endl;
cout << "4) Most Expensive Car" << endl;
cout << "5) Exit Program" << endl;
cout << "Enter Option: ";
cin >> menu;
while(menu != 5)
{
switch(menu)
{
case(1):
{
case_1(agency1, carz, cg, cl, cr, cc);
if_file = true;
break;
}
case(2):
{
if(if_file == false)
{
cout << "No File Was Entered. Please Enter a File (Menu 1) " << endl;
}
else
{
case_2(agency1, carz);
}
break;
}
case(3):
{
if(if_file == false)
{
cout << "No File Was Entered. Please Enter a File (Menu 1) " << endl;
}
else
{
case_3(cg, cl, cr, cc);
}
break;
}
case(4):
{
if(if_file == false)
{
cout << "No File Was Entered. Please Enter a File (Menu 1) " << endl;
}
else
{
case_4(agency1);
}
break;
}
}
cout << endl;
cout << "Enter Menu Option: ";
cin >> menu;
}
return 0;
}
//Input File Function
void case_1(agency* agency1, car* carz, int &cg, int &cl, int &cr, int &cc)
{
// all my temporary variables to pass to functions
char name[20];
char filename[20];
int zipcode;
int tyear;
float bprice;
float fprice = 100;
char tmake[30];
char tmodel[30];
bool tavail = 0;
int j= 0;
int i = 0;
int a = 0;
int z = 0;
char c , x, y;
int c_gps = 0;
int c_radar = 0;
int c_lidar = 0;
int c_camera = 0;
int c_none = 0;
int p_gps = 5;
int p_radar = 20;
int p_lidar = 15;
int p_camera = 10;
int p_none = 0;
/////////////////////////// count gps, count lidar, cound radar, count camera
cg = 0, cl = 0, cr = 0, cc = 0;
char t_owner = '\0';
char c_owner [maxsize];
char* owner_ptr = c_owner;
char* owner_ptrz = &c_owner[0];
char t_sensor[maxsize];
char* sensor_ptr = t_sensor;
char* sensor_ptrz = &t_sensor[0];
// opens file
cout << endl;
cout << "Enter the input file name: ";
cin >> filename;
cout << endl;
agency* agency_ptr = agency1;
car* car_ptr = carz;
ifstream file;
file.open(filename);
//pointer to agency to set agency name and zipcode
file >> name;
agency_ptr -> setName(name);
file >> zipcode;
agency_ptr -> setZip(zipcode);
//agency_ptr -> getAgency();
for(a = 0; a < 5 ; a++, j++, z++)
{
//takes in all the values for the car up to the sensor;
file >> tyear >> tmake >> tmodel >> bprice;
file >> c;
if( c == '{')
{
while( c != '}')
{
x=c;
file >> c;
//checks if the char value is equal to letters that correspond to the sensors
// then if it finds on it will increment it and set a temp char array with the snensor name
if(x == '{' & c == '}')
{
c_none++;
*sensor_ptr = 'n';
sensor_ptr++;
*sensor_ptr = 'o';
sensor_ptr++;
*sensor_ptr = 'n';
sensor_ptr++;
*sensor_ptr = 'e';
sensor_ptr++;
}
//checks if the char value is equal to letters that correspond to the sensors
// then if it finds on it will increment it and set a temp char array with the snensor name
if(x== 'g' & c == 'p'){
c_gps++;
cg++;
*sensor_ptr = 'g';
sensor_ptr++;
*sensor_ptr = 'p';
sensor_ptr++;
*sensor_ptr = 's';
sensor_ptr++;
*sensor_ptr = ' ';
sensor_ptr++;
}
//checks if the char value is equal to letters that correspond to the sensors
// then if it finds on it will increment it and set a temp char array with the snensor name
if(x== 'a' & c == 'd'){
c_radar++;
cr++;
*sensor_ptr = 'r';
sensor_ptr++;
*sensor_ptr = 'a';
sensor_ptr++;
*sensor_ptr = 'd';
sensor_ptr++;
*sensor_ptr = 'a';
sensor_ptr++;
*sensor_ptr = 'r';
sensor_ptr++;
*sensor_ptr = ' ';
sensor_ptr++;
}
//checks if the char value is equal to letters that correspond to the sensors
// then if it finds on it will increment it and set a temp char array with the snensor name
if(x== 'l' & c == 'i'){
c_lidar++;
cl++;
*sensor_ptr = 'l';
sensor_ptr++;
*sensor_ptr = 'i';
sensor_ptr++;
*sensor_ptr = 'd';
sensor_ptr++;
*sensor_ptr = 'a';
sensor_ptr++;
*sensor_ptr = 'r';
sensor_ptr++;
*sensor_ptr = ' ';
sensor_ptr++;
}
//checks if the char value is equal to letters that correspond to the sensors
// then if it finds on it will increment it and set a temp char array with the snensor name
if(x== 'c' & c == 'a'){
c_camera++;
cc++;
*sensor_ptr = 'c';
sensor_ptr++;
*sensor_ptr = 'a';
sensor_ptr++;
*sensor_ptr = 'm';
sensor_ptr++;
*sensor_ptr = 'e';
sensor_ptr++;
*sensor_ptr = 'r';
sensor_ptr++;
*sensor_ptr = 'a';
sensor_ptr++;
*sensor_ptr = ' ';
sensor_ptr++;
}
}
}
// totals the price by adding the base price with the total amount of that sensors and its repsected price
fprice = bprice + (p_gps*c_gps + p_radar*c_radar + p_lidar * c_lidar + p_camera * c_camera);
file >> tavail;
t_owner = file.get();
//checks it there is a owner by using the get function to check if there is a new line or a charcter
if( t_owner == '\n')
{
*c_owner = '\0';
}
while(t_owner != '\n')
{
//if there is a character it will copy over the contents and end it with a null
t_owner = file.get();
if(t_owner == '\n')
{
break;
}
*owner_ptr = t_owner;
owner_ptr++;
}
*owner_ptr = '\0';
*sensor_ptr = '\0';
owner_ptr = owner_ptrz;
sensor_ptr = sensor_ptrz;
agency_ptr -> setInv(j, tyear, tmake, tmodel, bprice, fprice, tavail, c_owner);
car_ptr -> setSensor(j, t_sensor);
c_none = 0, c_gps = 0, c_lidar = 0, c_radar = 0, c_camera = 0;
}
file.close();
}
//Print to terminal All data for the Gency and all its correspinding Cars
void case_2(agency* agency1, car* carz)
{
int z;
// calls all the print funtioncs that i have decalred
agency* agency_ptr = agency1;
cout << endl;
agency_ptr -> getAgency();
agency_ptr -> getZip();
car* car_ptr = carz;
for( z = 0; z < 5; z++)
{
agency_ptr -> getInv(z);
car_ptr -> getSensor(z);
agency_ptr -> getInv2(z);
}
}
//Print to terminal the Total number of sensors
void case_3(int cg, int cl, int cr, int cc)
{
//prints out all the sensors that there are
int t_sensors =0;
t_sensors = cg + cl + cr + cc;
cout << endl;
cout << "Total Sensors: " << t_sensors << endl;
cout << "Gps: " << cg << endl;
cout << "Lidar: " << cl << endl;
cout << "Radar: " << cr << endl;
cout << "Camera: " << cc << endl;
}
//Find the most expensive available car
void case_4(agency* agency1)
{
//calls the functions to set the prices and change the bool values and owner
int answer;
int days;
char name[10];
agency* agency_ptr = agency1;
agency_ptr -> printExp();
cout << "Would You Like To Rent it? Yes(1)/No(2): " ;
cin >> answer;
if(answer == 1)
{
cout << "How Many Days Would You Like to Rent It? : ";
cin >> days;
agency_ptr -> EstPrice(days);
cout << "Enter Your Name :";
cin >> name;
agency_ptr -> ResetAvail(name);
cout << "Successful" << endl;
}
}
void myStringCopy (char *destination, const char *source)
{
while( *source!= '\0')
{
*destination = *source;
source++;
destination++;
}
*destination = '\0';
}
void intStringCopy (int *destination, const int *source)
{
while( *source!= '\0')
{
*destination = *source;
source++;
destination++;
}
*destination = '\0';
}
/////////////////////SENSOR+++++++++++++++++++++++++++++++++++++++_+___+_+_+++_++_+__+
//default constructor and paramater constructor
sensor::sensor()
{
char tempType[10] = "none";
myStringCopy(m_type, tempType);
m_extracost = 0;
}
//default constructor and paramater constructor
sensor::sensor(char* temp_type, float extracost)
{
myStringCopy(m_type, temp_type);
m_extracost = extracost;
}
void sensor::setType(char* t_type)
{
myStringCopy(m_type, t_type);
}
char* sensor::getType()
{
return m_type;
}
void sensor::setExtracost(float t_extracost)
{
m_extracost = t_extracost;
}
float sensor::getExtracost()
{
return m_extracost;
}
void sensor::reset_gps(){
gps_cnt = 0;
}
void sensor::reset_camera(){
camera_cnt = 0;
}
void sensor::reset_lidar(){
lidar_cnt = 0;
}
void sensor::reset_radar(){
radar_cnt = 0;
}
/////////////////////// CAR ++++++++++++++++++++++++++++++++++++++++++++++++++++++
//default constructor and paramater constructor//default constructor and paramater constructor
car::car()
{
char tempval[5]= "\0";
myStringCopy(m_make, tempval);
myStringCopy(m_owner, tempval);
myStringCopy(m_model, tempval);
m_year = 0;
m_baseprice = 0;
m_finalprice = 0;
m_available = 0;
}
//default constructor and paramater constructor
car::car(char* temp_make, char* temp_model, char* temp_owner, int tempyear, float b_price, float f_price, bool t_avail)
{
myStringCopy(m_make, temp_make);
myStringCopy(m_owner, temp_model);
myStringCopy(m_model, temp_model);
m_year = tempyear;
m_baseprice = b_price;
m_finalprice = f_price;
m_available = t_avail;
}
void car::setMake(char* t_make)
{
myStringCopy(m_make, t_make);
}
char* car::getMake()
{
return m_make;
}
void car::setModel(char* t_model)
{
myStringCopy(m_model, t_model);
}
char* car::getModel()
{
return m_model;
}
void car::setOwner(char* t_owner)
{
myStringCopy(m_owner, t_owner);
}
char* car::getOwner()
{
return m_owner;
}
void car::setYear(int t_year)
{
m_year = t_year;
}
int car::getYear()
{
return m_year;
}
void car::setBaseprice(float t_baseprice)
{
m_baseprice = t_baseprice;
}
float car::getBaseprice()
{
return m_baseprice;
}
void car::setFinalprice(float t_finalprice)
{
m_finalprice = t_finalprice;
}
float car::getFinalprice()
{
return m_finalprice;
}
void car::setAvailable(bool t_available)
{
m_available = t_available;
}
bool car::getAvailable()
{
return m_available;
}
void car::setSensor(int j, char* tempSensor)
{
int i;
sensor* sensor_ptr = m_sensors;
sensor_ptr += j;
sensor_ptr -> setType(tempSensor);
}
void car::getSensor(int j)
{
int i;
sensor* sensor_ptr = m_sensors;
sensor_ptr += j;
cout << endl;
cout << "Sensors:" <<sensor_ptr -> getType() << ", ";
}
////////////////////Agency ++++++++++++++++++++++++
//default constructor and paramater constructor
agency::agency()
{
char tempval[5]= "\0";
myStringCopy(m_name, tempval);
int tempzip[5] = {0};
intStringCopy(m_zipcode, tempzip);
}
//default constructor and paramater constructor
agency::agency(char* tempname, int* tempzipcode)
{
myStringCopy(m_name, tempname);
intStringCopy(m_zipcode, tempzipcode);
}
void agency::setName(char* t_name)
{
myStringCopy(m_name, t_name);
}
char* agency::getName()
{
return m_name;
}
void agency::getAgency()
{
cout << m_name << " ";
}
void agency::printExp()
{
float temp_price;
int k = 0;
int j = 0;
car* car_ptr = m_inventory;
car* car_ptr2 = m_inventory;
car* car_ptr3 = m_inventory;
// i want to run through all the price values to find the most expensive car.
for (j = 0; j < 5; ++j)
{
car_ptr++;
// if one car price is bigger it will enter this for loop.
if(car_ptr -> getFinalprice() < car_ptr2 -> getFinalprice())
{
// then if the get price is larger than the current temp_price, it will replace it.
if(temp_price < car_ptr2 -> getFinalprice())
{
temp_price = car_ptr2 -> getFinalprice();
car_ptr++;
k++;
}
}
car_ptr2++;
}
car_ptr+= k;
cout << "Most Expensive Car: " << car_ptr3 -> getYear() << " " << car_ptr3 -> getMake() << " " << car_ptr3 -> getModel() << " $" << temp_price << endl;
}
//uses the same method to find the amount needed to increment the pointer to change the values and make an estmated price.
void agency::EstPrice(int i)
{
float temp_price;
int k = 0;
int j = 0;
float full_price;
car* car_ptr = m_inventory;
car* car_ptr2 = m_inventory;
// i want to run through all the price values to find the most expensive car.
for (j = 0; j < 5; ++j)
{
car_ptr++;
// if one car price is bigger it will enter this for loop.
if(car_ptr -> getFinalprice() < car_ptr2 -> getFinalprice())
{
// then if the get price is larger than the current temp_price, it will replace it.
if(temp_price < car_ptr2 -> getFinalprice())
{
temp_price = car_ptr2 -> getFinalprice();
car_ptr++;
k++;
}
}
car_ptr2++;
}
// the full price is multiplied by the number that is passed in
full_price = temp_price * i;
cout <<"Total Cost: $" <<full_price << endl;
}
void agency::ResetAvail(char *temp_name)
{
float temp_price;
int k = 0;
int j = 0;
float full_price;
car* car_ptr = m_inventory;
car* car_ptr2 = m_inventory;
car* car_ptr3 = m_inventory;
int avail = 1;
// i want to run through all the price values to find the most expensive car.
for (j = 0; j < 5; ++j)
{
car_ptr++;
// if one car price is bigger it will enter this for loop.
if(car_ptr -> getFinalprice() < car_ptr2 -> getFinalprice())
{
// then if the get price is larger than the current temp_price, it will replace it.
if(temp_price < car_ptr2 -> getFinalprice())
{
temp_price = car_ptr2 -> getFinalprice();
car_ptr++;
k++;
}
}
car_ptr2++;
}
car_ptr += k;
car_ptr3 -> setAvailable(avail);
car_ptr3 -> setOwner(temp_name);
}
void agency::setInv(int i, int tempYear, char *tempMake, char* tempModel, float baseprice, float finalprice, bool avail, char* tempOwner)
{
//function in the agency so it has access to the private members of the class
//pass in a value to increment the pointer to the car i want.
int j;
car* car_ptr = m_inventory;
car_ptr += i;
car_ptr -> setYear(tempYear);
car_ptr ->setMake(tempMake);
car_ptr ->setModel(tempModel);
car_ptr ->setBaseprice(baseprice);
car_ptr ->setFinalprice(finalprice);
car_ptr ->setAvailable(avail);
car_ptr ->setOwner(tempOwner);
}
void agency::getInv(int j)
{
//function in the agency so it has access to the private members of the class
//pass in a value to increment the pointer to the car i want.
int z;
car* car_ptr = m_inventory;
car_ptr += j;
cout << car_ptr -> getYear() << " ";
cout << car_ptr -> getMake() << " ";
cout << car_ptr -> getModel() << ", Base Price: $";
cout << car_ptr -> getBaseprice() << ", Final Price: $";
cout << car_ptr -> getFinalprice();
}
void agency::getInv2(int j)
{
//function in the agency so it has access to the private members of the class
//pass in a value to increment the pointer to the car i want.
car* car_ptr = m_inventory;
car_ptr += j;
cout << "Available: " << car_ptr -> getAvailable() << boolalpha << ", ";
cout << "Owner:" << car_ptr -> getOwner();
cout << endl;
car_ptr++;
}
void agency::setZip(int t_zip)
{
int i = 0;
int* zip_ptr = m_zipcode;
int z;
zip_ptr += 4;
while(t_zip != 0)
{
// increment the zip pointer because i want to give a value into the memory allocation in the array. Because the module saves it backwords, i have to increment the pointer and then decrement it to have the zop code in the right direction.
z = t_zip % 10;
*zip_ptr = z;
t_zip /= 10;
--zip_ptr;
}
//intStringCopy(m_zipcode, t_zip);
}
int* agency::getZip()
{
//have to use a for loop to print out the zipcode array
int* zip_ptr = m_zipcode;
int i=0;
zip_ptr = m_zipcode;
for(i = 0; i< 5; i++)
{
cout << *zip_ptr;
zip_ptr++;
}
cout << endl;
}
| [
"[email protected]"
] | |
bacfbdf112bdb9b3e4b8c4d0a797ce6a811f4ab4 | b65acdd4e28bac5b0b0cc088bded08cc80437ad8 | /MVSProg/Task15/Project1/Project1/Source.cpp | bd5fc8c5a4e9f48ee35ebf210ca70debefacdac5 | [] | no_license | YulianStrus/Examples-of-academic-homeworks | 44794bb234626319810f444a3115557b4e59d54f | f2fb2b5e02f069ff8f0cbc1a95c472ad2becad4c | refs/heads/master | 2023-05-27T16:09:41.220326 | 2021-06-02T10:04:07 | 2021-06-02T10:04:07 | 313,245,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,735 | cpp | #include "iostream"
using namespace std;
void main()
{
int n, l, j, i, h, k=1;
char s;
cout << "Choose the type of rectangular triangle: " << endl;
cout << "1 +\t " << "2 +\t " << "3 +++\t " << "4 +++\t " << endl;
cout << " ++\t " << " ++\t " << " ++\t " << " ++\t " << endl;
cout << " +++\t " << " +++\t " << " + \t " << " +\t " << endl;
cin >> n;
switch (n)
{
case 1: cout << "Enter the length of the catheter " << endl; cin >> l;
cout << "Enter symbol " << endl; cin >> s;
h = l;
for (i = 1; i <= h; i++)
{
for (j = 1; j <= l; j++)
if (j >= k)
{
cout << " ";
}
else cout << s;
cout << endl; k++;
}
break;
case 2: cout << "Enter the length of the catheter " << endl; cin >> l;
cout << "Enter symbol " << endl; cin >> s;
h = l;
k = l;
for (i = 1; i <= h; i++)
{
for (j = 1; j <= l; j++)
if (j < k)
{
cout << " ";
}
else cout << s;
cout << endl; k--;
}
break;
case 3: cout << "Enter the length of the catheter " << endl; cin >> l;
cout << "Enter symbol " << endl; cin >> s;
h = l;
for (i = 1; i <= h; i++)
{
for (j = 1; j <= l; j++)
cout << s; l--;
cout << endl;
}
break;
case 4: cout << "Enter the length of the catheter " << endl; cin >> l;
cout << "Enter symbol " << endl; cin >> s;
h = l;
for (i = 1; i <= h; i++)
{
for (j = 1; j <= l; j++)
if (j >= k)
{
cout << s;
}
else cout << " ";
cout << endl; k++;
}
break;
default: cout << "Incorrect choice!!!"; break;
}
system("pause");
}
| [
"[email protected]"
] | |
d6ff8447ec3690ed844db4b27aa9d4cbe83249c0 | 8d0947f1dac5aebef957f7fda9a4b3f8e2355235 | /2015/main1/main1/work2.cpp | 51939f289658182f993a2bbd75cc2b542ba00299 | [] | no_license | LuckLittleBoy/Freshman | f6fb8b30415782cc18a3357b813422532759987e | 7ab486f6b49333f3b6f9bc739606f38ac00f3cc5 | refs/heads/master | 2021-05-05T16:03:21.904338 | 2017-09-12T02:09:09 | 2017-09-12T02:09:09 | 103,209,919 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 521 | cpp | #include<iostream>
using namespace std;
struct complex
{
double real,image;
};
complex input()
{
complex x;
cout<<"请输入一个复数的实部和虚部:";
cin>>x.real>>x.image;
return x;
}
complex mul(complex x,complex y)
{
complex z;
z.real=x.real*y.real-x.image*y.image;
z.image=x.image*y.real+x.real*y.image;
return z;
}
void output(complex x)
{
cout<<x.real<<"+";
cout<<x.image<<"i"<<endl;
}
void main()
{
complex a,b;
a=input();
b=input();
cout<<"两复数相乘得:";
output(mul(a,b));
} | [
"[email protected]"
] | |
3efecf199269cc689a08f9ce8f8677823005ffad | 428989cb9837b6fedeb95e4fcc0a89f705542b24 | /erle/ros2_ws/install/include/std_msgs/msg/dds_opensplice/u_int64__type_support.hpp | 96c8663405cafd0acc7ecbba774bd77b8c5ef22a | [] | no_license | swift-nav/ros_rover | 70406572cfcf413ce13cf6e6b47a43d5298d64fc | 308f10114b35c70b933ee2a47be342e6c2f2887a | refs/heads/master | 2020-04-14T22:51:38.911378 | 2016-07-08T21:44:22 | 2016-07-08T21:44:22 | 60,873,336 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 121 | hpp | /home/erle/ros2_ws/build/std_msgs/rosidl_typesupport_opensplice_cpp/std_msgs/msg/dds_opensplice/u_int64__type_support.hpp | [
"[email protected]"
] | |
8ae1f6178628d0d99671b75d8306ffd33e938ffe | 07e85c2ce56c3969cfb2ee164d929961e4697e5c | /WuwaFantasy/WuwaFantasy/cFrustum.cpp | 47db3fa9ce5ccb4769e9b914b8945bcc0e239e09 | [] | no_license | serment7/WuwaFantasy | 85ad82e3431e30c4e6086cde3755a755514ce20b | 10b5d30e1c19ff3909a56b801df91185029ff106 | refs/heads/master | 2020-12-24T07:48:48.610156 | 2019-12-24T13:30:35 | 2019-12-24T13:30:35 | 59,941,071 | 0 | 1 | null | 2016-06-05T05:01:25 | 2016-05-29T12:05:10 | C++ | SHIFT_JIS | C++ | false | false | 4,550 | cpp | #include "stdafx.h"
#include "cFrustum.h"
cFrustum::cFrustum()
{
}
cFrustum::~cFrustum()
{
Release();
}
void cFrustum::SetFrustum(const D3DXMATRIXA16 & matV, const D3DXMATRIXA16 & matP)
{
ST_PC_VERTEX v;
v.c = D3DXCOLOR(1, 0, 0, 1);
//0,0,0,基?で絶面体を?く
m_vecVertex.clear();
v.p = D3DXVECTOR3(-1.0f, -1.0f, 0.0f); m_vecVertex.push_back(v);
v.p = D3DXVECTOR3(1.0f, -1.0f, 0.0f); m_vecVertex.push_back(v);
v.p = D3DXVECTOR3(1.0f, -1.0f, 1.0f); m_vecVertex.push_back(v);
v.p = D3DXVECTOR3(-1.0f, -1.0f, 1.0f); m_vecVertex.push_back(v);
v.p = D3DXVECTOR3(-1.0f, 1.0f, 0.0f); m_vecVertex.push_back(v);
v.p = D3DXVECTOR3(1.0f, 1.0f, 0.0f); m_vecVertex.push_back(v);
v.p = D3DXVECTOR3(1.0f, 1.0f, 1.0f); m_vecVertex.push_back(v);
v.p = D3DXVECTOR3(-1.0f, 1.0f, 1.0f); m_vecVertex.push_back(v);
D3DXMATRIXA16 matVP, matInv;
matVP = matV * matP;
D3DXMatrixInverse(&matInv, NULL, &matVP);
for (size_t i = 0; i < m_vecVertex.size(); ++i)
D3DXVec3TransformCoord(&m_vecVertex[i].p, &m_vecVertex[i].p, &matInv);
m_vPos = (m_vecVertex[0].p + m_vecVertex[5].p) / 2.0f;
/*
g_pD3DDevice->CreateVertexBuffer(
m_vecVertex.size() * sizeof(ST_PC_VERTEX)
, D3DUSAGE_WRITEONLY
, ST_PC_VERTEX::FVF
, D3DPOOL_MANAGED
, &m_pVB
, 0
);
ST_PC_VERTEX* vertices;
m_pVB->Lock(0, 0, (LPVOID*)&vertices, 0);
for (size_t j = 0; j < m_vecVertex.size(); ++j)
vertices[j] = m_vecVertex[j];
m_pVB->Unlock();
*/
m_vecPlane.clear();
D3DXPLANE p;
D3DXPlaneFromPoints(&p, &m_vecVertex[4].p, &m_vecVertex[7].p, &m_vecVertex[6].p);
m_vecPlane.push_back(p);//top
D3DXPlaneFromPoints(&p, &m_vecVertex[0].p, &m_vecVertex[1].p, &m_vecVertex[2].p);
m_vecPlane.push_back(p);//bottom
D3DXPlaneFromPoints(&p, &m_vecVertex[0].p, &m_vecVertex[4].p, &m_vecVertex[5].p);
m_vecPlane.push_back(p);//near
D3DXPlaneFromPoints(&p, &m_vecVertex[2].p, &m_vecVertex[6].p, &m_vecVertex[7].p);
m_vecPlane.push_back(p);//far
D3DXPlaneFromPoints(&p, &m_vecVertex[0].p, &m_vecVertex[3].p, &m_vecVertex[7].p);
m_vecPlane.push_back(p);//left
D3DXPlaneFromPoints(&p, &m_vecVertex[1].p, &m_vecVertex[5].p, &m_vecVertex[6].p);
m_vecPlane.push_back(p);//right
}
bool cFrustum::IsIn(D3DXVECTOR3 * pV)
{
float fDist = 0.0f;
fDist = D3DXPlaneDotCoord(&m_vecPlane[3], pV);
if (fDist > 0) return false;
fDist = D3DXPlaneDotCoord(&m_vecPlane[4], pV);
if (fDist > 0) return false;
fDist = D3DXPlaneDotCoord(&m_vecPlane[5], pV);
if (fDist > 0) return false;
return true;
}
bool cFrustum::IsInSphere(BoundingSphere * sphere)
{
float fDist = 0.0f;
fDist = D3DXPlaneDotCoord(&m_vecPlane[3], &sphere->vCenter);
if (fDist > sphere->fRadius) return false;
fDist = D3DXPlaneDotCoord(&m_vecPlane[4], &sphere->vCenter);
if (fDist > sphere->fRadius) return false;
fDist = D3DXPlaneDotCoord(&m_vecPlane[5], &sphere->vCenter);
if (fDist > sphere->fRadius) return false;
return true;
}
void cFrustum::Release()
{
SAFE_RELEASE(m_pVB);
SAFE_RELEASE(m_pIB);
}
void cFrustum::Draw()
{
/*
g_pD3DDevice->CreateIndexBuffer(
36 * sizeof(DWORD)
, D3DUSAGE_WRITEONLY
, D3DFMT_INDEX16
, D3DPOOL_MANAGED
, &m_pIB
, 0
);
DWORD* indices = 0;
m_pIB->Lock(0, 0, (LPVOID*)&indices, 0);
indices[0] = 0; indices[1] = 1; indices[2] = 2;
indices[3] = 0; indices[4] = 2; indices[5] = 3;
indices[6] = 4; indices[7] = 7; indices[8] = 6;
indices[9] = 4; indices[10] = 6; indices[11] = 5;
indices[12] = 1; indices[13] = 5; indices[14] = 6;
indices[15] = 1; indices[16] = 6; indices[17] = 2;
indices[18] = 0; indices[19] = 3; indices[20] = 7;
indices[21] = 0; indices[22] = 7; indices[23] = 4;
indices[24] = 0; indices[25] = 4; indices[26] = 5;
indices[27] = 0; indices[28] = 5; indices[29] = 1;
indices[30] = 3; indices[31] = 7; indices[32] = 6;
indices[33] = 3; indices[34] = 6; indices[35] = 2;
m_pIB->Unlock();
g_pD3DDevice->SetStreamSource(0, m_pVB, 0, sizeof(ST_PC_VERTEX));
g_pD3DDevice->SetIndices(m_pIB);
g_pD3DDevice->SetFVF(ST_PC_VERTEX::FVF);
g_pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_vecVertex.size(), 0, (m_vecVertex.size() * 3) / 2);
*/
}
void cFrustum::SetCamPos(const D3DXVECTOR3 & camPos)
{
m_vPos = camPos;
D3DXMATRIXA16 mat;
//カメラの?ジション値をトレンスレ?ションしカメラのワ?ルド値を生成する
D3DXMatrixTranslation(&mat, m_vPos.x, m_vPos.y, m_vPos.z);
m_matWorld = mat;
}
| [
"[email protected]"
] | |
16ad5fe2bcc934c0c807966a81d6708b26100631 | 47075e364b86f553a56cc2b0d04c476d282908f8 | /AClass/LiteHTMLAttributes.cpp | b33959e53c5fb9cd742b701eba86a9d2edf1b8ff | [
"MIT"
] | permissive | quantxyz/approval_list | b5d6af8b4adff176ea515020f8ca12f1b0cc5bf3 | 7e37164f1c93374f22a27ae84948890d90143c45 | refs/heads/master | 2022-05-01T06:00:07.692672 | 2016-01-24T17:00:57 | 2016-01-24T17:00:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,638 | cpp | /**
* PROJECT - HTML Reader Class Library
*
* LiteHTMLAttributes.cpp
*
* Written By Gurmeet S. Kochar <[email protected]>
* Copyright (c) 2004. All rights reserved.
*
* This code may be used in compiled form in any way you desire
* (including commercial use). The code may be redistributed
* unmodified by any means PROVIDING it is not sold for profit
* without the authors written consent, and providing that this
* notice and the authors name and all copyright notices remains
* intact. However, this file and the accompanying source code may
* not be hosted on a website or bulletin board without the authors
* written permission.
*
* This file is provided "AS IS" with no expressed or implied warranty.
* The author accepts no liability for any damage/loss of business that
* this product may cause.
*
* Although it is not necessary, but if you use this code in any of
* your application (commercial or non-commercial), please INFORM me
* so that I may know how useful this library is. This will encourage
* me to keep updating it.
*/
#include "stdafx.h"
#include "LiteHTMLAttributes.h"
#ifdef _DEBUG
# define new DEBUG_NEW
# undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif // _DEBUG
#pragma warning(push, 4)
const COLORREF CLiteHTMLElemAttr::_clrInvalid = (COLORREF)0xFFFFFFFF;
const unsigned short CLiteHTMLElemAttr::_percentMax = USHRT_MAX;
// the reason behind setting the block size of our collection
// to 166 is that we have a total of 166 known named colors
CLiteHTMLElemAttr::CNamedColors CLiteHTMLElemAttr::_namedColors(166 /* block size */);
#pragma warning(pop)
| [
"[email protected]"
] | |
70c05c9e38ea6081ee2ab30298c019817df2a08e | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/sanic/src/solve_LU.cpp | 22e459c091b60cd0733f3ce6a382d0cadebaedb1 | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 501 | cpp |
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::export]]
Eigen::MatrixXd solve_PPLU(
Eigen::Map<Eigen::MatrixXd> a,
Eigen::Map<Eigen::MatrixXd> b) {
Eigen::PartialPivLU<Eigen::MatrixXd> lu(a);
Eigen::MatrixXd x = lu.solve(b);
return x;
}
// [[Rcpp::export]]
Eigen::MatrixXd solve_SLU(
Eigen::MappedSparseMatrix<double> a,
Eigen::Map<Eigen::MatrixXd> b) {
Eigen::SparseLU<Eigen::SparseMatrix<double> > lu(a);
Eigen::MatrixXd x = lu.solve(b);
return x;
}
| [
"[email protected]"
] | |
e8319536d72c8e3e2993a8d05c9eb10806da4128 | b9643226fed06909dc1e2daf417e78cfb3a42ec3 | /real_estate_database_manager/Property.h | df439bfbead9b08a92eea4c0a3ba3e72a23ab6f1 | [] | no_license | karimrhoualem/realEstateManager | d7f1117df929c2283009589aa7c5f6b5eafc1d9d | c3a04c9da4b8626119d0a12acce4977779a688b5 | refs/heads/master | 2020-12-05T20:50:17.376874 | 2020-01-07T04:52:04 | 2020-01-07T04:52:04 | 232,243,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,137 | h | /*
Karim Rhoualem - Student #26603157
Dilara Omeroglu - Student #40030357
*/
#pragma once
#include <iostream>
using namespace std;
#include <string>
#include "Client.h"
#include "RealEstateAgent.h"
#include "Date.h"
class Property
{
private:
string m_streetAddress;
string m_cityName;
Client* m_seller; // Initialized to the Client parameter of the constructor function.
Client* m_buyer; // Initialized to a null pointer.
RealEstateAgent* m_agent;
Date m_listingDate;
public:
Property();
Property(string streetAddress, string cityName, Client* seller, RealEstateAgent* agent, Date listingDate);
Property(const Property& anotherProperty); //Copy constructor
~Property();
void setStreetAddress(string streetAddress);
string getStreetAddress() const;
void setCityName(string cityName);
string getCityName() const;
void setSeller(Client* seller);
Client* getSeller() const;
void setBuyer(Client* buyer);
Client* getBuyer() const;
void setAgent(RealEstateAgent* agent);
RealEstateAgent* getAgent() const;
void setListingDate(Date listingDate);
Date getListingDate() const;
virtual void print() const;
};
| [
"[email protected]"
] | |
8c6e2b07b4e01cfd1122e0f88755d44d2d91be4e | 627446942aa275ffc1323e467140c37566cd94ad | /LabProject08-0-1/Scene.cpp | 11c373b44fe69992acecad8e586dd1acdbbc4703 | [] | no_license | yeongjo/SchoolDx12_2 | ec6f45114f4a74842d23d4fe70cfdf5ae0aea2e4 | de947fe3955560a77ae82b62f8cc34a343ca0a15 | refs/heads/master | 2023-06-01T17:41:08.512774 | 2020-12-19T02:51:48 | 2020-12-19T02:51:48 | 376,394,420 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 18,270 | cpp | //-----------------------------------------------------------------------------
// File: CScene.cpp
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "Scene.h"
CScene::CScene()
{
}
CScene::~CScene()
{
}
void CScene::BuildDefaultLightsAndMaterials()
{
m_nLights = 4;
m_pLights = new LIGHT[m_nLights];
::ZeroMemory(m_pLights, sizeof(LIGHT) * m_nLights);
m_xmf4GlobalAmbient = XMFLOAT4(0.15f, 0.15f, 0.15f, 1.0f);
m_pLights[0].m_bEnable = true;
m_pLights[0].m_nType = POINT_LIGHT;
m_pLights[0].m_fRange = 1000.0f;
m_pLights[0].m_xmf4Ambient = XMFLOAT4(0.1f, 0.0f, 0.0f, 1.0f);
m_pLights[0].m_xmf4Diffuse = XMFLOAT4(0.8f, 0.0f, 0.0f, 1.0f);
m_pLights[0].m_xmf4Specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 0.0f);
m_pLights[0].m_xmf3Position = XMFLOAT3(30.0f, 30.0f, 30.0f);
m_pLights[0].m_xmf3Direction = XMFLOAT3(0.0f, 0.0f, 0.0f);
m_pLights[0].m_xmf3Attenuation = XMFLOAT3(1.0f, 0.001f, 0.0001f);
m_pLights[1].m_bEnable = true;
m_pLights[1].m_nType = SPOT_LIGHT;
m_pLights[1].m_fRange = 500.0f;
m_pLights[1].m_xmf4Ambient = XMFLOAT4(0.1f, 0.1f, 0.1f, 1.0f);
m_pLights[1].m_xmf4Diffuse = XMFLOAT4(0.4f, 0.4f, 0.4f, 1.0f);
m_pLights[1].m_xmf4Specular = XMFLOAT4(0.3f, 0.3f, 0.3f, 0.0f);
m_pLights[1].m_xmf3Position = XMFLOAT3(-50.0f, 20.0f, -5.0f);
m_pLights[1].m_xmf3Direction = XMFLOAT3(0.0f, 0.0f, 1.0f);
m_pLights[1].m_xmf3Attenuation = XMFLOAT3(1.0f, 0.01f, 0.0001f);
m_pLights[1].m_fFalloff = 8.0f;
m_pLights[1].m_fPhi = (float)cos(XMConvertToRadians(40.0f));
m_pLights[1].m_fTheta = (float)cos(XMConvertToRadians(20.0f));
m_pLights[2].m_bEnable = true;
m_pLights[2].m_nType = DIRECTIONAL_LIGHT;
m_pLights[2].m_xmf4Ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f);
m_pLights[2].m_xmf4Diffuse = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f);
m_pLights[2].m_xmf4Specular = XMFLOAT4(0.4f, 0.4f, 0.4f, 0.0f);
m_pLights[2].m_xmf3Direction = XMFLOAT3(1.0f, 0.0f, 0.0f);
m_pLights[3].m_bEnable = true;
m_pLights[3].m_nType = SPOT_LIGHT;
m_pLights[3].m_fRange = 600.0f;
m_pLights[3].m_xmf4Ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f);
m_pLights[3].m_xmf4Diffuse = XMFLOAT4(0.3f, 0.7f, 0.0f, 1.0f);
m_pLights[3].m_xmf4Specular = XMFLOAT4(0.3f, 0.3f, 0.3f, 0.0f);
m_pLights[3].m_xmf3Position = XMFLOAT3(50.0f, 30.0f, 30.0f);
m_pLights[3].m_xmf3Direction = XMFLOAT3(0.0f, 1.0f, 1.0f);
m_pLights[3].m_xmf3Attenuation = XMFLOAT3(1.0f, 0.01f, 0.0001f);
m_pLights[3].m_fFalloff = 8.0f;
m_pLights[3].m_fPhi = (float)cos(XMConvertToRadians(90.0f));
m_pLights[3].m_fTheta = (float)cos(XMConvertToRadians(30.0f));
}
void CScene::BuildObjects(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList)
{
m_pd3dGraphicsRootSignature = CreateGraphicsRootSignature(pd3dDevice);
BuildDefaultLightsAndMaterials();
m_pSkyBox = new CSkyBox(pd3dDevice, pd3dCommandList, m_pd3dGraphicsRootSignature);
m_nShaders = 1;
m_ppShaders = new CShader*[m_nShaders];
CObjectsShader *pObjectsShader = new CObjectsShader();
pObjectsShader->CreateShader(pd3dDevice, pd3dCommandList, m_pd3dGraphicsRootSignature);
pObjectsShader->BuildObjects(pd3dDevice, pd3dCommandList, m_pd3dGraphicsRootSignature, NULL);
m_ppShaders[0] = pObjectsShader;
CreateShaderVariables(pd3dDevice, pd3dCommandList);
}
void CScene::ReleaseObjects()
{
if (m_pd3dGraphicsRootSignature) m_pd3dGraphicsRootSignature->Release();
if (m_ppShaders)
{
for (int i = 0; i < m_nShaders; i++)
{
m_ppShaders[i]->ReleaseShaderVariables();
m_ppShaders[i]->ReleaseObjects();
m_ppShaders[i]->Release();
}
delete[] m_ppShaders;
}
if (m_pSkyBox) delete m_pSkyBox;
if (m_ppGameObjects)
{
for (int i = 0; i < m_nGameObjects; i++) if (m_ppGameObjects[i]) m_ppGameObjects[i]->Release();
delete[] m_ppGameObjects;
}
ReleaseShaderVariables();
if (m_pLights) delete[] m_pLights;
}
ID3D12RootSignature *CScene::CreateGraphicsRootSignature(ID3D12Device *pd3dDevice)
{
ID3D12RootSignature *pd3dGraphicsRootSignature = NULL;
#ifdef _WITH_STANDARD_TEXTURE_MULTIPLE_DESCRIPTORS
D3D12_DESCRIPTOR_RANGE pd3dDescriptorRanges[8];
pd3dDescriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[0].NumDescriptors = 1;
pd3dDescriptorRanges[0].BaseShaderRegister = 6; //t6: gtxtAlbedoTexture
pd3dDescriptorRanges[0].RegisterSpace = 0;
pd3dDescriptorRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[1].NumDescriptors = 1;
pd3dDescriptorRanges[1].BaseShaderRegister = 7; //t7: gtxtSpecularTexture
pd3dDescriptorRanges[1].RegisterSpace = 0;
pd3dDescriptorRanges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[2].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[2].NumDescriptors = 1;
pd3dDescriptorRanges[2].BaseShaderRegister = 8; //t8: gtxtNormalTexture
pd3dDescriptorRanges[2].RegisterSpace = 0;
pd3dDescriptorRanges[2].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[3].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[3].NumDescriptors = 1;
pd3dDescriptorRanges[3].BaseShaderRegister = 9; //t9: gtxtMetallicTexture
pd3dDescriptorRanges[3].RegisterSpace = 0;
pd3dDescriptorRanges[3].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[4].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[4].NumDescriptors = 1;
pd3dDescriptorRanges[4].BaseShaderRegister = 10; //t10: gtxtEmissionTexture
pd3dDescriptorRanges[4].RegisterSpace = 0;
pd3dDescriptorRanges[4].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[5].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[5].NumDescriptors = 1;
pd3dDescriptorRanges[5].BaseShaderRegister = 11; //t11: gtxtDetailAlbedoTexture
pd3dDescriptorRanges[5].RegisterSpace = 0;
pd3dDescriptorRanges[5].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[6].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[6].NumDescriptors = 1;
pd3dDescriptorRanges[6].BaseShaderRegister = 12; //t12: gtxtDetailNormalTexture
pd3dDescriptorRanges[6].RegisterSpace = 0;
pd3dDescriptorRanges[6].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[7].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[7].NumDescriptors = 1;
pd3dDescriptorRanges[7].BaseShaderRegister = 13; //t13: gtxtSkyBoxTexture
pd3dDescriptorRanges[7].RegisterSpace = 0;
pd3dDescriptorRanges[7].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
D3D12_ROOT_PARAMETER pd3dRootParameters[11];
pd3dRootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
pd3dRootParameters[0].Descriptor.ShaderRegister = 1; //Camera
pd3dRootParameters[0].Descriptor.RegisterSpace = 0;
pd3dRootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
pd3dRootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
pd3dRootParameters[1].Constants.Num32BitValues = 33;
pd3dRootParameters[1].Constants.ShaderRegister = 2; //GameObject
pd3dRootParameters[1].Constants.RegisterSpace = 0;
pd3dRootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
pd3dRootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
pd3dRootParameters[2].Descriptor.ShaderRegister = 4; //Lights
pd3dRootParameters[2].Descriptor.RegisterSpace = 0;
pd3dRootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
pd3dRootParameters[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[3].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[3].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[0]);
pd3dRootParameters[3].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[4].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[4].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[4].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[1]);
pd3dRootParameters[4].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[5].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[5].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[5].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[2]);
pd3dRootParameters[5].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[6].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[6].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[6].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[3]);
pd3dRootParameters[6].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[7].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[7].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[7].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[4]);
pd3dRootParameters[7].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[8].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[8].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[8].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[5]);
pd3dRootParameters[8].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[9].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[9].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[9].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[6]);
pd3dRootParameters[9].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[10].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[10].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[10].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[7]);
pd3dRootParameters[10].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
#else
D3D12_DESCRIPTOR_RANGE pd3dDescriptorRanges[2];
pd3dDescriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[0].NumDescriptors = 7;
pd3dDescriptorRanges[0].BaseShaderRegister = 6; //t6: gtxtStandardTextures[7] //0:Albedo, 1:Specular, 2:Metallic, 3:Normal, 4:Emission, 5:DetailAlbedo, 6:DetailNormal
pd3dDescriptorRanges[0].RegisterSpace = 0;
pd3dDescriptorRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
pd3dDescriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
pd3dDescriptorRanges[1].NumDescriptors = 1;
pd3dDescriptorRanges[1].BaseShaderRegister = 13; //t13: gtxtSkyBoxTexture
pd3dDescriptorRanges[1].RegisterSpace = 0;
pd3dDescriptorRanges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
D3D12_ROOT_PARAMETER pd3dRootParameters[5];
pd3dRootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
pd3dRootParameters[0].Descriptor.ShaderRegister = 1; //Camera
pd3dRootParameters[0].Descriptor.RegisterSpace = 0;
pd3dRootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
pd3dRootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
pd3dRootParameters[1].Constants.Num32BitValues = 33;
pd3dRootParameters[1].Constants.ShaderRegister = 2; //GameObject
pd3dRootParameters[1].Constants.RegisterSpace = 0;
pd3dRootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
pd3dRootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
pd3dRootParameters[2].Descriptor.ShaderRegister = 4; //Lights
pd3dRootParameters[2].Descriptor.RegisterSpace = 0;
pd3dRootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
pd3dRootParameters[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[3].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[3].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[0]);
pd3dRootParameters[3].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dRootParameters[4].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pd3dRootParameters[4].DescriptorTable.NumDescriptorRanges = 1;
pd3dRootParameters[4].DescriptorTable.pDescriptorRanges = &(pd3dDescriptorRanges[1]);
pd3dRootParameters[4].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
#endif
D3D12_STATIC_SAMPLER_DESC pd3dSamplerDescs[2];
pd3dSamplerDescs[0].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
pd3dSamplerDescs[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
pd3dSamplerDescs[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
pd3dSamplerDescs[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
pd3dSamplerDescs[0].MipLODBias = 0;
pd3dSamplerDescs[0].MaxAnisotropy = 1;
pd3dSamplerDescs[0].ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
pd3dSamplerDescs[0].MinLOD = 0;
pd3dSamplerDescs[0].MaxLOD = D3D12_FLOAT32_MAX;
pd3dSamplerDescs[0].ShaderRegister = 0;
pd3dSamplerDescs[0].RegisterSpace = 0;
pd3dSamplerDescs[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
pd3dSamplerDescs[1].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
pd3dSamplerDescs[1].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
pd3dSamplerDescs[1].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
pd3dSamplerDescs[1].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
pd3dSamplerDescs[1].MipLODBias = 0;
pd3dSamplerDescs[1].MaxAnisotropy = 1;
pd3dSamplerDescs[1].ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
pd3dSamplerDescs[1].MinLOD = 0;
pd3dSamplerDescs[1].MaxLOD = D3D12_FLOAT32_MAX;
pd3dSamplerDescs[1].ShaderRegister = 1;
pd3dSamplerDescs[1].RegisterSpace = 0;
pd3dSamplerDescs[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
D3D12_ROOT_SIGNATURE_FLAGS d3dRootSignatureFlags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
D3D12_ROOT_SIGNATURE_DESC d3dRootSignatureDesc;
::ZeroMemory(&d3dRootSignatureDesc, sizeof(D3D12_ROOT_SIGNATURE_DESC));
d3dRootSignatureDesc.NumParameters = _countof(pd3dRootParameters);
d3dRootSignatureDesc.pParameters = pd3dRootParameters;
d3dRootSignatureDesc.NumStaticSamplers = _countof(pd3dSamplerDescs);
d3dRootSignatureDesc.pStaticSamplers = pd3dSamplerDescs;
d3dRootSignatureDesc.Flags = d3dRootSignatureFlags;
ID3DBlob *pd3dSignatureBlob = NULL;
ID3DBlob *pd3dErrorBlob = NULL;
D3D12SerializeRootSignature(&d3dRootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &pd3dSignatureBlob, &pd3dErrorBlob);
pd3dDevice->CreateRootSignature(0, pd3dSignatureBlob->GetBufferPointer(), pd3dSignatureBlob->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&pd3dGraphicsRootSignature);
if (pd3dSignatureBlob) pd3dSignatureBlob->Release();
if (pd3dErrorBlob) pd3dErrorBlob->Release();
return(pd3dGraphicsRootSignature);
}
void CScene::CreateShaderVariables(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList)
{
UINT ncbElementBytes = ((sizeof(LIGHTS) + 255) & ~255); //256의 배수
m_pd3dcbLights = ::CreateBufferResource(pd3dDevice, pd3dCommandList, NULL, ncbElementBytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, NULL);
m_pd3dcbLights->Map(0, NULL, (void **)&m_pcbMappedLights);
}
void CScene::UpdateShaderVariables(ID3D12GraphicsCommandList *pd3dCommandList)
{
::memcpy(m_pcbMappedLights->m_pLights, m_pLights, sizeof(LIGHT) * m_nLights);
::memcpy(&m_pcbMappedLights->m_xmf4GlobalAmbient, &m_xmf4GlobalAmbient, sizeof(XMFLOAT4));
::memcpy(&m_pcbMappedLights->m_nLights, &m_nLights, sizeof(int));
}
void CScene::ReleaseShaderVariables()
{
if (m_pd3dcbLights)
{
m_pd3dcbLights->Unmap(0, NULL);
m_pd3dcbLights->Release();
}
}
void CScene::ReleaseUploadBuffers()
{
if (m_pSkyBox) m_pSkyBox->ReleaseUploadBuffers();
for (int i = 0; i < m_nShaders; i++) m_ppShaders[i]->ReleaseUploadBuffers();
for (int i = 0; i < m_nGameObjects; i++) m_ppGameObjects[i]->ReleaseUploadBuffers();
}
bool CScene::OnProcessingMouseMessage(HWND hWnd, UINT nMessageID, WPARAM wParam, LPARAM lParam)
{
return(false);
}
bool CScene::OnProcessingKeyboardMessage(HWND hWnd, UINT nMessageID, WPARAM wParam, LPARAM lParam)
{
switch (nMessageID)
{
case WM_KEYDOWN:
switch (wParam)
{
case 'W': m_ppGameObjects[0]->MoveForward(+1.0f); break;
case 'S': m_ppGameObjects[0]->MoveForward(-1.0f); break;
case 'A': m_ppGameObjects[0]->MoveStrafe(-1.0f); break;
case 'D': m_ppGameObjects[0]->MoveStrafe(+1.0f); break;
case 'Q': m_ppGameObjects[0]->MoveUp(+1.0f); break;
case 'R': m_ppGameObjects[0]->MoveUp(-1.0f); break;
default:
break;
}
break;
default:
break;
}
return(false);
}
bool CScene::ProcessInput(UCHAR *pKeysBuffer)
{
return(false);
}
void CScene::AnimateObjects(float fTimeElapsed)
{
for (int i = 0; i < m_nGameObjects; i++) if (m_ppGameObjects[i]) m_ppGameObjects[i]->Animate(fTimeElapsed, NULL);
for (int i = 0; i < m_nGameObjects; i++) if (m_ppGameObjects[i]) m_ppGameObjects[i]->UpdateTransform(NULL);
for (int i = 0; i < m_nShaders; i++) if (m_ppShaders[i]) m_ppShaders[i]->AnimateObjects(fTimeElapsed);
if (m_pLights)
{
m_pLights[1].m_xmf3Position = m_pPlayer->GetPosition();
m_pLights[1].m_xmf3Direction = m_pPlayer->GetLookVector();
}
}
void CScene::Render(ID3D12GraphicsCommandList *pd3dCommandList, CCamera *pCamera)
{
if (m_pd3dGraphicsRootSignature) pd3dCommandList->SetGraphicsRootSignature(m_pd3dGraphicsRootSignature);
pCamera->SetViewportsAndScissorRects(pd3dCommandList);
pCamera->UpdateShaderVariables(pd3dCommandList);
UpdateShaderVariables(pd3dCommandList);
D3D12_GPU_VIRTUAL_ADDRESS d3dcbLightsGpuVirtualAddress = m_pd3dcbLights->GetGPUVirtualAddress();
pd3dCommandList->SetGraphicsRootConstantBufferView(2, d3dcbLightsGpuVirtualAddress); //Lights
// 970에선 안된다
if (m_pSkyBox) m_pSkyBox->Render(pd3dCommandList, pCamera);
for (int i = 0; i < m_nGameObjects; i++) if (m_ppGameObjects[i]) m_ppGameObjects[i]->Render(pd3dCommandList, pCamera);
for (int i = 0; i < m_nShaders; i++) if (m_ppShaders[i]) m_ppShaders[i]->Render(pd3dCommandList, pCamera);
}
| [
"[email protected]"
] | |
51869a48fa230d08a6bd090d693775dbb1ce8ce3 | 8d83c56718f0845423ec1eff847df9f590b0a116 | /Mods/CrysisWarsMod/Code/GameCVars.cpp | e5436fed335cf2de3607110314fa91097a6e66a5 | [] | no_license | CyberSys/Crysis-Wars-Source-Code | 534e7936a9856b529fce327ae4d2388828066498 | 9cfe9fa887f6583b72f3bf1dc3c5609077e44fc6 | refs/heads/master | 2021-09-02T12:54:05.307572 | 2018-01-02T20:29:59 | 2018-01-02T20:29:59 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 89,769 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2004.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 11:8:2004 10:50 : Created by Márcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "GameCVars.h"
#include "GameRules.h"
#include "ItemSharedParams.h"
#include <INetwork.h>
#include <IGameObject.h>
#include <IActorSystem.h>
#include <IItemSystem.h>
#include "WeaponSystem.h"
#include "ServerSynchedStorage.h"
#include "ItemString.h"
#include "HUD/HUD.h"
#include "Menus/QuickGame.h"
#include "Environment/BattleDust.h"
#include "NetInputChainDebug.h"
#include "Menus/FlashMenuObject.h"
#include "Menus/MPHub.h"
#include "INetworkService.h"
static void BroadcastChangeSafeMode( ICVar * )
{
SGameObjectEvent event(eCGE_ResetMovementController, eGOEF_ToExtensions);
IEntitySystem * pES = gEnv->pEntitySystem;
IEntityItPtr pIt = pES->GetEntityIterator();
while (!pIt->IsEnd())
{
if (IEntity * pEnt = pIt->Next())
if (IActor * pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pEnt->GetId()))
pActor->HandleEvent( event );
}
}
void CmdBulletTimeMode( IConsoleCmdArgs* cmdArgs)
{
g_pGameCVars->goc_enable = 0;
g_pGameCVars->goc_tpcrosshair = 0;
g_pGameCVars->bt_ironsight = 1;
g_pGameCVars->bt_speed = 0;
g_pGameCVars->bt_energy_decay = 2.5;
g_pGameCVars->bt_end_reload = 1;
g_pGameCVars->bt_end_select = 1;
g_pGameCVars->bt_end_melee = 0;
}
void CmdGOCMode( IConsoleCmdArgs* cmdArgs)
{
g_pGameCVars->goc_enable = 1;
g_pGameCVars->goc_tpcrosshair = 1;
g_pGameCVars->bt_ironsight = 1;
g_pGameCVars->bt_speed = 0;
g_pGameCVars->bt_energy_decay = 0;
g_pGameCVars->bt_end_reload = 1;
g_pGameCVars->bt_end_select = 1;
g_pGameCVars->bt_end_melee = 0;
//
CPlayer *pPlayer = static_cast<CPlayer *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
if(pPlayer && !pPlayer->IsThirdPerson())
{
pPlayer->ToggleThirdPerson();
}
}
void CmdListInvisiblePlayers(IConsoleCmdArgs* cmdArgs)
{
IActorIteratorPtr it = g_pGame->GetIGameFramework()->GetIActorSystem()->CreateActorIterator();
while (IActor* pActor = it->Next())
{
if(pActor->IsPlayer() && !pActor->IsClient())
{
IEntityRenderProxy* pProxy = static_cast<IEntityRenderProxy*>(pActor->GetEntity()->GetProxy(ENTITY_PROXY_RENDER));
if(pProxy )
{
CryLogAlways("Player %s is %s", pActor->GetEntity()->GetName(), pProxy->IsRenderProxyVisAreaVisible() ? "visible" : "invisible");
}
}
}
}
// game related cvars must start with an g_
// game server related cvars must start with sv_
// game client related cvars must start with cl_
// no other types of cvars are allowed to be defined here!
void SCVars::InitCVars(IConsole *pConsole)
{
//client cvars
pConsole->Register("cl_hud",&cl_hud,1,0,"Show/Hide the HUD", CHUDCommon::HUD);
pConsole->Register("cl_fov", &cl_fov, 60.0f, 0, "field of view.");
pConsole->Register("cl_bob", &cl_bob, 1.0f, 0, "view/weapon bobbing multiplier");
pConsole->Register("cl_headBob", &cl_headBob, 1.0f, 0, "head bobbing multiplier");
pConsole->Register("cl_headBobLimit", &cl_headBobLimit, 0.06f, 0, "head bobbing distance limit");
pConsole->Register("cl_tpvDist", &cl_tpvDist, 3.5f, 0, "camera distance in 3rd person view");
pConsole->Register("cl_tpvYaw", &cl_tpvYaw, 0, 0, "camera angle offset in 3rd person view");
pConsole->Register("cl_nearPlane", &cl_nearPlane, 0, 0, "overrides the near clipping plane if != 0, just for testing.");
pConsole->Register("cl_sprintShake", &cl_sprintShake, 0.0f, 0, "sprint shake");
pConsole->Register("cl_sensitivityZeroG", &cl_sensitivityZeroG, 70.0f, VF_DUMPTODISK, "Set mouse sensitivity in ZeroG!");
pConsole->Register("cl_sensitivity", &cl_sensitivity, 45.0f, VF_DUMPTODISK, "Set mouse sensitivity!");
pConsole->Register("cl_controllersensitivity", &cl_controllersensitivity, 45.0f, VF_DUMPTODISK, "Set controller sensitivity!");
pConsole->Register("cl_invertMouse", &cl_invertMouse, 0, VF_DUMPTODISK, "mouse invert?");
pConsole->Register("cl_invertController", &cl_invertController, 0, VF_DUMPTODISK, "Controller Look Up-Down invert");
pConsole->Register("cl_crouchToggle", &cl_crouchToggle, 0, VF_DUMPTODISK, "To make the crouch key work as a toggle");
pConsole->Register("cl_fpBody", &cl_fpBody, 2, 0, "first person body");
//FIXME:just for testing
pConsole->Register("cl_strengthscale", &cl_strengthscale, 1.0f, 0, "nanosuit strength scale");
/*
// GOC
pConsole->Register("goc_enable", &goc_enable, 0, VF_CHEAT, "gears of crysis");
pConsole->Register("goc_tpcrosshair", &goc_tpcrosshair, 0, VF_CHEAT, "keep crosshair in third person");
pConsole->Register("goc_targetx", &goc_targetx, 0.5f, VF_CHEAT, "target position of camera");
pConsole->Register("goc_targety", &goc_targety, -2.5f, VF_CHEAT, "target position of camera");
pConsole->Register("goc_targetz", &goc_targetz, 0.2f, VF_CHEAT, "target position of camera");
pConsole->AddCommand("GOCMode", CmdGOCMode, VF_CHEAT, "Enable GOC mode");
// BulletTime
pConsole->Register("bt_speed", &bt_speed, 0, VF_CHEAT, "bullet-time when in speed mode");
pConsole->Register("bt_ironsight", &bt_ironsight, 0, VF_CHEAT, "bullet-time when in ironsight");
pConsole->Register("bt_end_reload", &bt_end_reload, 0, VF_CHEAT, "end bullet-time when reloading");
pConsole->Register("bt_end_select", &bt_end_select, 0, VF_CHEAT, "end bullet-time when selecting a new weapon");
pConsole->Register("bt_end_melee", &bt_end_melee, 0, VF_CHEAT, "end bullet-time when melee");
pConsole->Register("bt_time_scale", &bt_time_scale, 0.2f, VF_CHEAT, "bullet-time time scale to apply");
pConsole->Register("bt_pitch", &bt_pitch, -0.4f, VF_CHEAT, "sound pitch shift for bullet-time");
pConsole->Register("bt_energy_max", &bt_energy_max, 1.0f, VF_CHEAT, "maximum bullet-time energy");
pConsole->Register("bt_energy_decay", &bt_energy_decay, 2.5f, VF_CHEAT, "bullet time energy decay rate");
pConsole->Register("bt_energy_regen", &bt_energy_regen, 0.5f, VF_CHEAT, "bullet time energy regeneration rate");
pConsole->AddCommand("bulletTimeMode", CmdBulletTimeMode, VF_CHEAT, "Enable bullet time mode");
*/
pConsole->Register("dt_enable", &dt_enable, 0, 0, "suit actions activated by double-tapping");
pConsole->Register("dt_time", &dt_time, 0.25f, 0, "time in seconds between double taps");
pConsole->Register("dt_meleeTime", &dt_meleeTime, 0.3f, 0, "time in seconds between double taps for melee");
pConsole->Register("i_staticfiresounds", &i_staticfiresounds, 1, VF_DUMPTODISK, "Enable/Disable static fire sounds. Static sounds are not unloaded when idle.");
pConsole->Register("i_soundeffects", &i_soundeffects, 1, VF_DUMPTODISK, "Enable/Disable playing item sound effects.");
pConsole->Register("i_lighteffects", &i_lighteffects, 1, VF_DUMPTODISK, "Enable/Disable lights spawned during item effects.");
pConsole->Register("i_particleeffects", &i_particleeffects, 1, VF_DUMPTODISK, "Enable/Disable particles spawned during item effects.");
pConsole->Register("i_rejecteffects", &i_rejecteffects, 1, VF_DUMPTODISK, "Enable/Disable ammo reject effects during weapon firing.");
pConsole->Register("i_offset_front", &i_offset_front, 0.0f, 0, "Item position front offset");
pConsole->Register("i_offset_up", &i_offset_up, 0.0f, 0, "Item position up offset");
pConsole->Register("i_offset_right", &i_offset_right, 0.0f, 0, "Item position right offset");
pConsole->Register("i_unlimitedammo", &i_unlimitedammo, 0, VF_CHEAT, "unlimited ammo");
pConsole->Register("i_iceeffects", &i_iceeffects, 0, VF_CHEAT, "Enable/Disable specific weapon effects for ice environments");
pConsole->Register("i_lighteffectShadows", &i_lighteffectsShadows, 0, VF_DUMPTODISK, "Enable/Disable shadow casting on weapon lights. 1 - Player only, 2 - Other players/AI, 3 - All (require i_lighteffects enabled).");
// marcok TODO: seem to be only used on script side ...
pConsole->RegisterFloat("cl_motionBlur", 2, 0, "motion blur type (0=off, 1=accumulation-based, 2=velocity-based)");
pConsole->RegisterFloat("cl_sprintBlur", 0.6f, 0, "sprint blur");
pConsole->RegisterFloat("cl_hitShake", 1.25f, 0, "hit shake");
pConsole->RegisterFloat("cl_hitBlur", 0.25f, 0, "blur on hit");
pConsole->RegisterInt("cl_righthand", 1, 0, "Select right-handed weapon!");
pConsole->RegisterInt("cl_screeneffects", 1, 0, "Enable player screen effects (depth-of-field, motion blur, ...).");
pConsole->Register("cl_debugSwimming", &cl_debugSwimming, 0, VF_CHEAT, "enable swimming debugging");
pConsole->Register("cl_g15lcdEnable", &cl_g15lcdEnable, 1, VF_DUMPTODISK, "enable support for Logitech G15 LCD");
pConsole->Register("cl_g15lcdTick", &cl_g15lcdTick, 250, VF_DUMPTODISK, "milliseconds between lcd updates");
ca_GameControlledStrafingPtr = pConsole->GetCVar("ca_GameControlledStrafing");
pConsole->Register("pl_curvingSlowdownSpeedScale", &pl_curvingSlowdownSpeedScale, 0.5f, VF_CHEAT, "Player only slowdown speedscale when curving/leaning extremely.");
pConsole->Register("ac_enableProceduralLeaning", &ac_enableProceduralLeaning, 1.0f, VF_CHEAT, "Enable procedural leaning (disabled asset leaning and curving slowdown).");
pConsole->Register("cl_shallowWaterSpeedMulPlayer", &cl_shallowWaterSpeedMulPlayer, 0.6f, VF_CHEAT, "shallow water speed multiplier (Players only)");
pConsole->Register("cl_shallowWaterSpeedMulAI", &cl_shallowWaterSpeedMulAI, 0.8f, VF_CHEAT, "Shallow water speed multiplier (AI only)");
pConsole->Register("cl_shallowWaterDepthLo", &cl_shallowWaterDepthLo, 0.3f, VF_CHEAT, "Shallow water depth low (below has zero slowdown)");
pConsole->Register("cl_shallowWaterDepthHi", &cl_shallowWaterDepthHi, 1.0f, VF_CHEAT, "Shallow water depth high (above has full slowdown)");
pConsole->RegisterInt("g_grabLog", 0, 0, "verbosity for grab logging (0-2)");
pConsole->Register("pl_inputAccel", &pl_inputAccel, 30.0f, 0, "Movement input acceleration");
pConsole->RegisterInt("cl_actorsafemode", 0, VF_CHEAT, "Enable/disable actor safe mode", BroadcastChangeSafeMode);
pConsole->Register("h_useIK", &h_useIK, 1, 0, "Hunter uses always IK");
pConsole->Register("h_drawSlippers", &h_drawSlippers, 0, 0, "Red ball when tentacle is lifted, green when on ground");
pConsole->Register("g_tentacle_joint_limit", &g_tentacle_joint_limit, -1.0f, 0, "forces specific tentacle limits; used for tweaking");
pConsole->Register("g_enableSpeedLean", &g_enableSpeedLean, 0, 0, "Enables player-controlled curve leaning in speed mode.");
//
pConsole->Register("int_zoomAmount", &int_zoomAmount, 0.75f, VF_CHEAT, "Maximum zoom, between 0.0 and 1.0. Default = .75");
pConsole->Register("int_zoomInTime", &int_zoomInTime, 5.0f, VF_CHEAT, "Number of seconds it takes to zoom in. Default = 5.0");
pConsole->Register("int_moveZoomTime", &int_moveZoomTime, 0.1f, VF_CHEAT, "Number of seconds it takes to zoom out when moving. Default = 0.2");
pConsole->Register("int_zoomOutTime", &int_zoomOutTime, 0.1f, VF_CHEAT, "Number of seconds it takes to zoom out when you stop firing. Default = 0.5");
pConsole->RegisterFloat("aa_maxDist", 10.0f, VF_CHEAT, "max lock distance");
pConsole->Register("hr_rotateFactor", &hr_rotateFactor, -.1f, VF_CHEAT, "rotate factor");
pConsole->Register("hr_rotateTime", &hr_rotateTime, .07f, VF_CHEAT, "rotate time");
pConsole->Register("hr_dotAngle", &hr_dotAngle, .75f, VF_CHEAT, "max angle for FOV change");
pConsole->Register("hr_fovAmt", &hr_fovAmt, .03f, VF_CHEAT, "goal FOV when hit");
pConsole->Register("hr_fovTime", &hr_fovTime, .05f, VF_CHEAT, "fov time");
// frozen shake vars (for tweaking only)
pConsole->Register("cl_debugFreezeShake", &cl_debugFreezeShake, 0, VF_CHEAT|VF_DUMPTODISK, "Toggle freeze shake debug draw");
pConsole->Register("cl_frozenSteps", &cl_frozenSteps, 3, VF_CHEAT, "Number of steps for unfreeze shaking");
pConsole->Register("cl_frozenSensMin", &cl_frozenSensMin, 1.0f, VF_CHEAT, "Frozen sensitivity min"); // was 0.2
pConsole->Register("cl_frozenSensMax", &cl_frozenSensMax, 1.0f, VF_CHEAT, "Frozen sensitivity max"); // was 0.4
pConsole->Register("cl_frozenAngleMin", &cl_frozenAngleMin, 1.f, VF_CHEAT, "Frozen clamp angle min");
pConsole->Register("cl_frozenAngleMax", &cl_frozenAngleMax, 10.f, VF_CHEAT, "Frozen clamp angle max");
pConsole->Register("cl_frozenMouseMult", &cl_frozenMouseMult, 0.00015f, VF_CHEAT, "Frozen mouseshake multiplier");
pConsole->Register("cl_frozenKeyMult", &cl_frozenKeyMult, 0.02f, VF_CHEAT, "Frozen movement keys multiplier");
pConsole->Register("cl_frozenSoundDelta", &cl_frozenSoundDelta, 0.004f, VF_CHEAT, "Threshold for unfreeze shake to trigger a crack sound");
pConsole->Register("g_frostDecay", &g_frostDecay, 0.25f, VF_CHEAT, "Frost decay speed when freezing actors");
pConsole->Register("g_stanceTransitionSpeed", &g_stanceTransitionSpeed, 15.0f, VF_CHEAT, "Set speed of camera transition from stance to stance");
pConsole->Register("g_stanceTransitionSpeedSecondary", &g_stanceTransitionSpeedSecondary, 6.0f, VF_CHEAT, "Set speed of camera transition from stance to stance");
pConsole->Register("g_playerHealthValue", &g_playerHealthValue, 200, VF_CHEAT, "Maximum player health.");
pConsole->Register("g_walkMultiplier", &g_walkMultiplier, 1, VF_SAVEGAME, "Modify movement speed");
pConsole->Register("g_suitRecoilEnergyCost", &g_suitRecoilEnergyCost, 3.0f, VF_CHEAT, "Subtracted energy when weapon is fired in strength mode.");
pConsole->Register("g_suitSpeedMult", &g_suitSpeedMult, 1.85f, 0, "Modify speed mode effect.");
pConsole->Register("g_suitSpeedMultMultiplayer", &g_suitSpeedMultMultiplayer, 0.35f, 0, "Modify speed mode effect for Multiplayer.");
pConsole->Register("g_suitArmorHealthValue", &g_suitArmorHealthValue, 200.0f, 0, "This defines how much damage is reduced by 100% energy, not considering recharge. The value should be between 1 and <SuitMaxEnergy>.");
pConsole->Register("g_suitSpeedEnergyConsumption", &g_suitSpeedEnergyConsumption, 110.0f, 0, "Energy reduction in speed mode per second.");
pConsole->Register("g_suitSpeedEnergyConsumptionMultiplayer", &g_suitSpeedEnergyConsumptionMultiplayer, 50.0f, 0, "Energy reduction in speed mode per second in multiplayer.");
pConsole->Register("g_suitCloakEnergyDrainAdjuster", &g_suitCloakEnergyDrainAdjuster, 1.0f, 0, "Multiplier for energy reduction in cloak mode.");
pConsole->Register("g_mpSpeedRechargeDelay", &g_mpSpeedRechargeDelay, 1, VF_CHEAT, "Toggles delay when sprinting below 20% energy.");
pConsole->Register("g_AiSuitEnergyRechargeTime", &g_AiSuitEnergyRechargeTime, 10.0f, VF_CHEAT, "Modify suit energy recharge for AI.");
pConsole->Register("g_AiSuitStrengthMeleeMult", &g_AiSuitStrengthMeleeMult, 0.4f, VF_CHEAT, "Modify AI strength mode melee damage relative to player damage.");
pConsole->Register("g_AiSuitHealthRegenTime", &g_AiSuitHealthRegenTime, 33.3f, VF_CHEAT, "Modify suit health recharge for AI.");
pConsole->Register("g_AiSuitArmorModeHealthRegenTime", &g_AiSuitArmorModeHealthRegenTime, 20.0f, VF_CHEAT, "Modify suit health recharge for AI in armor mode.");
pConsole->Register("g_playerSuitEnergyRechargeTime", &g_playerSuitEnergyRechargeTime, 8.0f, VF_CHEAT, "Modify suit energy recharge for Player.");
pConsole->Register("g_playerSuitEnergyRechargeTimeArmor", &g_playerSuitEnergyRechargeTimeArmor, 6.0f, VF_CHEAT, "Modify suit energy recharge for Player in singleplayer in armor mode.");
pConsole->Register("g_playerSuitEnergyRechargeTimeArmorMoving", &g_playerSuitEnergyRechargeTimeArmorMoving, 7.0f, VF_CHEAT, "Modify suit energy recharge for Player in singleplayer in armor mode while moving.");
pConsole->Register("g_playerSuitEnergyRechargeTimeMultiplayer", &g_playerSuitEnergyRechargeTimeMultiplayer, 10.0f, VF_CHEAT, "Modify suit energy recharge for Player in multiplayer.");
pConsole->Register("g_playerSuitEnergyRechargeDelay", &g_playerSuitEnergyRechargeDelay, 1.0f, VF_CHEAT, "Delay of energy recharge after the player has been hit.");
pConsole->Register("g_playerSuitHealthRegenTime", &g_playerSuitHealthRegenTime, 20.0f, VF_CHEAT, "Modify suit health recharge for Player.");
pConsole->Register("g_playerSuitHealthRegenTimeMoving", &g_playerSuitHealthRegenTimeMoving, 27.0f, VF_CHEAT, "Modify suit health recharge for moving Player.");
pConsole->Register("g_playerSuitArmorModeHealthRegenTime", &g_playerSuitArmorModeHealthRegenTime, 10.0f, VF_CHEAT, "Modify suit health recharge for Player in armor mode.");
pConsole->Register("g_playerSuitArmorModeHealthRegenTimeMoving", &g_playerSuitArmorModeHealthRegenTimeMoving, 15.0f, VF_CHEAT, "Modify suit health recharge for Player moving in armor mode.");
pConsole->Register("g_playerSuitHealthRegenDelay", &g_playerSuitHealthRegenDelay, 2.5f, VF_CHEAT, "Delay of health regeneration after the player has been hit.");
pConsole->Register("g_difficultyLevel", &g_difficultyLevel, 2, VF_CHEAT|VF_READONLY, "Difficulty level");
pConsole->Register("g_difficultyHintSystem", &g_difficultyHintSystem, 2, VF_CHEAT|VF_READONLY, "Lower difficulty hint system (0 is off, 1 is radius based, 2 is save-game based)");
pConsole->Register("g_difficultyRadius", &g_difficultyRadius, 300, VF_CHEAT|VF_READONLY, "Radius in which player needs to die to display lower difficulty level hint.");
pConsole->Register("g_difficultyRadiusThreshold", &g_difficultyRadiusThreshold, 5, VF_CHEAT|VF_READONLY, "Number of times player has to die within radius to trigger difficulty hint.");
pConsole->Register("g_difficultySaveThreshold", &g_difficultySaveThreshold, 5, VF_CHEAT|VF_READONLY, "Number of times player has to die with same savegame active to trigger difficulty hint.");
pConsole->Register("g_pp_scale_income", &g_pp_scale_income, 1, 0, "Scales incoming PP.");
pConsole->Register("g_pp_scale_price", &g_pp_scale_price, 1, 0, "Scales PP prices.");
pConsole->Register("g_energy_scale_price", &g_energy_scale_price, 0, 0, "Scales energy prices.");
pConsole->Register("g_energy_scale_income", &g_energy_scale_income, 1, 0, "Scales incoming energy.");
pConsole->Register("g_enableFriendlyFallAndPlay", &g_enableFriendlyFallAndPlay, 0, 0, "Enables fall&play feedback for friendly actors.");
pConsole->Register("g_playerRespawns", &g_playerRespawns, 0, VF_SAVEGAME, "Sets the player lives.");
pConsole->Register("g_playerLowHealthThreshold", &g_playerLowHealthThreshold, 40.0f, VF_CHEAT, "The player health threshold when the low health effect kicks in.");
pConsole->Register("g_playerLowHealthThreshold2", &g_playerLowHealthThreshold2, 60.0f, VF_CHEAT, "The player health threshold when the low health effect reaches maximum.");
pConsole->Register("g_playerLowHealthThresholdMultiplayer", &g_playerLowHealthThresholdMultiplayer, 20.0f, VF_CHEAT, "The player health threshold when the low health effect kicks in.");
pConsole->Register("g_playerLowHealthThreshold2Multiplayer", &g_playerLowHealthThreshold2Multiplayer, 30.0f, VF_CHEAT, "The player health threshold when the low health effect reaches maximum.");
pConsole->Register("g_punishFriendlyDeaths", &g_punishFriendlyDeaths, 1, VF_CHEAT, "The player gets punished by death when killing a friendly unit.");
pConsole->Register("g_enableMPStealthOMeter", &g_enableMPStealthOMeter, 0, VF_CHEAT, "Enables the stealth-o-meter to detect enemies in MP matches.");
pConsole->Register("g_meleeWhileSprinting", &g_meleeWhileSprinting, 0, 0, "Enables option to melee while sprinting, using left mouse button.");
pConsole->Register("g_fallAndPlayThreshold", &g_fallAndPlayThreshold, 50, VF_CHEAT, "Minimum damage for fall and play.");
// Depth of Field control
pConsole->Register("g_dofset_minScale", &g_dofset_minScale, 1.0f, VF_CHEAT, "Scale Dof_FocusMin param when it gets set Default = 1");
pConsole->Register("g_dofset_maxScale", &g_dofset_maxScale, 3.0f, VF_CHEAT, "Scale Dof_FocusMax param when it gets set Default = 3");
pConsole->Register("g_dofset_limitScale", &g_dofset_limitScale, 9.0f, VF_CHEAT, "Scale Dof_FocusLimit param when it gets set Default = 9");
pConsole->Register("g_dof_minHitScale", &g_dof_minHitScale, 0.25f, VF_CHEAT, "Scale of ray hit distance which Min tries to approach. Default = 0.25");
pConsole->Register("g_dof_maxHitScale", &g_dof_maxHitScale, 2.0f, VF_CHEAT, "Scale of ray hit distance which Max tries to approach. Default = 2.0f");
pConsole->Register("g_dof_sampleAngle", &g_dof_sampleAngle, 5.0f, VF_CHEAT, "Sample angle in degrees. Default = 5");
pConsole->Register("g_dof_minAdjustSpeed", &g_dof_minAdjustSpeed, 100.0f, VF_CHEAT, "Speed that DoF can adjust the min value with. Default = 100");
pConsole->Register("g_dof_maxAdjustSpeed", &g_dof_maxAdjustSpeed, 200.0f, VF_CHEAT, "Speed that DoF can adjust the max value with. Default = 200");
pConsole->Register("g_dof_averageAdjustSpeed", &g_dof_averageAdjustSpeed, 20.0f, VF_CHEAT, "Speed that the average between min and max can be approached. Default = 20");
pConsole->Register("g_dof_distAppart", &g_dof_distAppart, 10.0f, VF_CHEAT, "Minimum distance that max and min can be apart. Default = 10");
pConsole->Register("g_dof_ironsight", &g_dof_ironsight, 1, VF_CHEAT, "Enable ironsight dof. Default = 1");
// explosion culling
pConsole->Register("g_ec_enable", &g_ec_enable, 1, VF_CHEAT, "Enable/Disable explosion culling of small objects. Default = 1");
pConsole->Register("g_ec_radiusScale", &g_ec_radiusScale, 2.0f, VF_CHEAT, "Explosion culling scale to apply to explosion radius for object query.");
pConsole->Register("g_ec_volume", &g_ec_volume, 0.75f, VF_CHEAT, "Explosion culling volume which needs to be exceed for objects to not be culled.");
pConsole->Register("g_ec_extent", &g_ec_extent, 2.0f, VF_CHEAT, "Explosion culling length of an AABB side which needs to be exceed for objects to not be culled.");
pConsole->Register("g_ec_removeThreshold", &g_ec_removeThreshold, 20, VF_CHEAT, "At how many items in exploding area will it start removing items.");
pConsole->Register("g_radialBlur", &g_radialBlur, 1.0f, VF_CHEAT, "Radial blur on explosions. Default = 1, 0 to disable");
pConsole->Register("g_playerFallAndPlay", &g_playerFallAndPlay, 0, 0, "When enabled, the player doesn't die from direct damage, but goes to fall and play.");
pConsole->Register("g_enableTracers", &g_enableTracers, 1, 0, "Enable/Disable tracers.");
pConsole->Register("g_enableAlternateIronSight", &g_enableAlternateIronSight, 0, 0, "Enable/Disable alternate ironsight mode");
pConsole->Register("g_ragdollMinTime", &g_ragdollMinTime, 10.0f, 0, "minimum time in seconds that a ragdoll will be visible");
pConsole->Register("g_ragdollUnseenTime", &g_ragdollUnseenTime, 2.0f, 0, "time in seconds that the player has to look away from the ragdoll before it disappears");
pConsole->Register("g_ragdollPollTime", &g_ragdollPollTime, 0.5f, 0, "time in seconds where 'unseen' polling is done");
pConsole->Register("g_ragdollDistance", &g_ragdollDistance, 10.0f, 0, "distance in meters that the player has to be away from the ragdoll before it can disappear");
pConsole->Register("g_debugaimlook", &g_debugaimlook, 0, VF_CHEAT, "Debug aim/look direction");
pConsole->Register("g_enableIdleCheck", &g_enableIdleCheck, 1, 0);
// Crysis supported gamemode CVars
pConsole->Register("g_timelimit", &g_timelimit, 60.0f, 0, "Duration of a time-limited game (in minutes). Default is 0, 0 means no time-limit.");
pConsole->Register("g_roundtime", &g_roundtime, 2.0f, 0, "Duration of a round (in minutes). Default is 0, 0 means no time-limit.");
pConsole->Register("g_preroundtime", &g_preroundtime, 8, 0, "Frozen time before round starts. Default is 8, 0 Disables freeze time.");
pConsole->Register("g_suddendeathtime", &g_suddendeathtime, 30, 0, "Number of seconds before round end to start sudden death. Default if 30. 0 Disables sudden death.");
pConsole->Register("g_roundlimit", &g_roundlimit, 30, 0, "Maximum numbers of rounds to be played. Default is 0, 0 means no limit.");
pConsole->Register("g_fraglimit", &g_fraglimit, 0, 0, "Number of frags before a round restarts. Default is 0, 0 means no frag-limit.");
pConsole->Register("g_fraglead", &g_fraglead, 1, 0, "Number of frags a player has to be ahead of other players once g_fraglimit is reached. Default is 1.");
pConsole->Register("g_scorelimit", &g_scorelimit, 300, 0, "Score before a round restarts. Default is 300, 0 means no score-limit.");
pConsole->Register("g_scorelead", &g_scorelead, 1, 0, "Score a team has to be ahead of other team once g_scorelimit is reached. Default is 1.");
pConsole->Register("g_spawnteamdist", &g_spawnteamdist, 20, 0, "TIA; tend to choose spawnpoints with max teammates withing the dist.");
pConsole->Register("g_spawnenemydist", &g_spawnenemydist, 15, 0, "TIA; reject spawn-points closer than this to enemy.");
pConsole->Register("g_spawndeathdist", &g_spawndeathdist, 20, 0, "TIA; reject spawn-points closer than this to death position.");
pConsole->Register("g_spawndebug", &g_spawnDebug, 0, VF_CHEAT, "enables debugging spawn for TIA");
pConsole->Register("g_friendlyfireratio", &g_friendlyfireratio, 0.5f, 0, "Sets friendly damage ratio.");
pConsole->Register("g_friendlyVehicleCollisionRatio", &g_friendlyVehicleCollisionRatio, 0.5f, 0, "Sets ratio of damage applied by friendly vehicles");
pConsole->Register("g_revivetime", &g_revivetime, 15, 0, "Revive wave timer.");
pConsole->Register("g_autoteambalance", &g_autoteambalance, 1, 0, "Enables auto team balance.");
pConsole->Register("g_autoteambalance_threshold", &g_autoteambalance_threshold, 3, 0, "Sets the auto team balance player threshold.");
pConsole->Register("g_minplayerlimit", &g_minplayerlimit, 2, 0, "Minimum number of players to start a match.");
pConsole->Register("g_minteamlimit", &g_minteamlimit, 1, 0, "Minimum number of players in each team to start a match.");
pConsole->Register("g_tk_punish", &g_tk_punish, 1, 0, "Turns on punishment for team kills");
pConsole->Register("g_tk_punish_limit", &g_tk_punish_limit, 5, 0, "Number of team kills user will be banned for");
pConsole->Register("g_teamlock", &g_teamlock, 2, 0, "Number of players one team needs to have over the other, for the game to deny joining it. 0 disables.");
pConsole->Register("g_useHitSoundFeedback", &g_useHitSoundFeedback, 1, 0, "Switches hit readability feedback sounds on/off.");
pConsole->Register("g_debugNetPlayerInput", &g_debugNetPlayerInput, 0, VF_CHEAT, "Show some debug for player input");
pConsole->Register("g_debug_fscommand", &g_debug_fscommand, 0, 0, "Print incoming fscommands to console");
pConsole->Register("g_debugDirectMPMenu", &g_debugDirectMPMenu, 0, 0, "Jump directly to MP menu on application start.");
pConsole->Register("g_skipIntro", &g_skipIntro, 0, VF_CHEAT, "Skip all the intro videos.");
pConsole->Register("g_resetActionmapOnStart", &g_resetActionmapOnStart, 0, 0, "Resets Keyboard mapping on application start.");
pConsole->Register("g_useProfile", &g_useProfile, 1, 0, "Don't save anything to or load anything from profile.");
pConsole->Register("g_startFirstTime", &g_startFirstTime, 1, VF_DUMPTODISK, "1 before the game was started first time ever.");
pConsole->Register("g_cutsceneSkipDelay", &g_cutsceneSkipDelay, 0.0f, 0, "Skip Delay for Cutscenes.");
pConsole->Register("g_enableAutoSave", &g_enableAutoSave, 1, 0, "Switches all savegames created by Flowgraph (checkpoints). Does not affect user generated saves or levelstart savegames.");
//
pConsole->Register("g_godMode", &g_godMode, 0, VF_CHEAT, "God Mode");
pConsole->Register("g_detachCamera", &g_detachCamera, 0, VF_CHEAT, "Detach camera");
pConsole->Register("g_suicideDelay", &g_suicideDelay, 2, VF_CHEAT, "delay in sec before executing kill command");
pConsole->Register("g_debugCollisionDamage", &g_debugCollisionDamage, 0, VF_DUMPTODISK, "Log collision damage");
pConsole->Register("g_debugHits", &g_debugHits, 0, VF_DUMPTODISK, "Log hits");
pConsole->Register("g_trooperProneMinDistance", &g_trooperProneMinDistance, 10, VF_DUMPTODISK, "Distance to move for trooper to switch to prone stance");
// pConsole->Register("g_trooperMaxPhysicsAnimBlend", &g_trooperMaxPhysicAnimBlend, 0, VF_DUMPTODISK, "Max value for trooper tentacle dynamic physics/anim blending");
// pConsole->Register("g_trooperPhysicsAnimBlendSpeed", &g_trooperPhysicAnimBlendSpeed, 100.f, VF_DUMPTODISK, "Trooper tentacle dynamic physics/anim blending speed");
pConsole->Register("g_trooperTentacleAnimBlend", &g_trooperTentacleAnimBlend, 0, VF_DUMPTODISK, "Trooper tentacle physic_anim blend (0..1) - overrides the physic_blend AG parameter when it's not 0");
pConsole->Register("g_trooperBankingMultiplier", &g_trooperBankingMultiplier, 1, VF_DUMPTODISK, "Trooper banking multiplier coeff (0..x)");
pConsole->Register("g_alienPhysicsAnimRatio", &g_alienPhysicsAnimRatio, 0.0f, VF_CHEAT );
pConsole->Register("g_spRecordGameplay", &g_spRecordGameplay, 0, 0, "Write sp gameplay information to harddrive.");
pConsole->Register("g_spGameplayRecorderUpdateRate", &g_spGameplayRecorderUpdateRate, 1.0f, 0, "Update-delta of gameplay recorder in seconds.");
pConsole->Register("pl_debug_ladders", &pl_debug_ladders, 0, VF_CHEAT);
pConsole->Register("pl_debug_movement", &pl_debug_movement, 0, VF_CHEAT);
pConsole->Register("pl_debug_jumping", &pl_debug_jumping, 0, VF_CHEAT);
pl_debug_filter = pConsole->RegisterString("pl_debug_filter","",VF_CHEAT);
pConsole->Register("aln_debug_movement", &aln_debug_movement, 0, VF_CHEAT);
aln_debug_filter = pConsole->RegisterString("aln_debug_filter","",VF_CHEAT);
// emp grenade
pConsole->Register("g_emp_style", &g_empStyle, 0, VF_CHEAT, "");
pConsole->Register("g_emp_nanosuit_downtime", &g_empNanosuitDowntime, 10.0f, VF_CHEAT, "Time that the nanosuit is deactivated after leaving the EMP field.");
// hud cvars
pConsole->Register("hud_mpNamesDuration", &hud_mpNamesDuration, 2, 0, "MP names will fade after this duration.");
pConsole->Register("hud_mpNamesNearDistance", &hud_mpNamesNearDistance, 1, 0, "MP names will be fully visible when nearer than this.");
pConsole->Register("hud_mpNamesFarDistance", &hud_mpNamesFarDistance, 100, 0, "MP names will be fully invisible when farther than this.");
pConsole->Register("hud_onScreenNearDistance", &hud_onScreenNearDistance, 10, 0, "On screen icons won't scale anymore, when nearer than this.");
pConsole->Register("hud_onScreenFarDistance", &hud_onScreenFarDistance, 500, 0, "On screen icons won't scale anymore, when farther than this.");
pConsole->Register("hud_onScreenNearSize", &hud_onScreenNearSize, 1.4f, 0, "On screen icon size when nearest.");
pConsole->Register("hud_onScreenFarSize", &hud_onScreenFarSize, 0.7f, 0, "On screen icon size when farthest.");
pConsole->Register("hud_colorLine", &hud_colorLine, 4481854, 0, "HUD line color.");
pConsole->Register("hud_colorOver", &hud_colorOver, 14125840, 0, "HUD hovered color.");
pConsole->Register("hud_colorText", &hud_colorText, 12386209, 0, "HUD text color.");
pConsole->Register("hud_voicemode", &hud_voicemode, 1, 0, "Usage of the voice when switching of Nanosuit mode.");
pConsole->Register("hud_enableAlienInterference", &hud_enableAlienInterference, 1, VF_SAVEGAME, "Switched the alien interference effect.");
pConsole->Register("hud_alienInterferenceStrength", &hud_alienInterferenceStrength, 0.8f, VF_SAVEGAME, "Scales alien interference effect strength.");
pConsole->Register("hud_godFadeTime", &hud_godFadeTime, 3, VF_CHEAT, "sets the fade time of the god mode message");
pConsole->Register("hud_crosshair_enable", &hud_crosshair_enable, 1,0, "Toggles singleplayer crosshair visibility.", CHUD::OnCrosshairCVarChanged);
pConsole->Register("hud_crosshair", &hud_crosshair, 1,0, "Select the crosshair (1-8)", CHUD::OnCrosshairCVarChanged);
pConsole->Register("hud_alternateCrosshairSpread",&hud_iAlternateCrosshairSpread,0, 0, "Switch new crosshair spread code on/off.");
pConsole->Register("hud_alternateCrosshairSpreadCrouch",&hud_fAlternateCrosshairSpreadCrouch,12.0f, VF_CHEAT);
pConsole->Register("hud_alternateCrosshairSpreadNeutral",&hud_fAlternateCrosshairSpreadNeutral,6.0f, VF_CHEAT);
pConsole->Register("hud_chDamageIndicator", &hud_chDamageIndicator, 1,0,"Switch crosshair-damage indicator... (1 on, 0 off)");
pConsole->Register("hud_showAllObjectives", &hud_showAllObjectives, 0, 0, "Show all on screen objectives, not only the active one.");
pConsole->Register("hud_showObjectiveMessages", &hud_showObjectiveMessages, 0, 0, "Show objective messages for Powerstruggle player.");
pConsole->Register("hud_panoramicHeight", &hud_panoramicHeight, 10,0,"Set screen border for 'cinematic view' in percent.", CHUD::OnSubtitlePanoramicHeightCVarChanged);
pConsole->Register("hud_subtitles", &hud_subtitles, 0,0,"Subtitle mode. 0==Off, 1=All, 2=CutscenesOnly", CHUD::OnSubtitleCVarChanged);
pConsole->Register("hud_subtitlesDebug", &hud_subtitlesDebug, 0,0,"Debug subtitles");
pConsole->Register("hud_subtitlesRenderMode", &hud_subtitlesRenderMode, 0,0,"Subtitle RenderMode. 0==Flash, 1=3DEngine");
pConsole->Register("hud_subtitlesFontSize", &hud_subtitlesFontSize, 16, 0, "FontSize for Subtitles.");
pConsole->Register("hud_subtitlesHeight", &hud_subtitlesHeight, 10, 0,"Height of Subtitles in Percent. Normally same as hud_PanoramicHeight");
pConsole->Register("hud_subtitlesShowCharName", &hud_subtitlesShowCharName, 1, 0,"Show Character talking along with Subtitle");
pConsole->Register("hud_subtitlesQueueCount", &hud_subtitlesQueueCount, 1, 0,"Maximum amount of subtitles in Update Queue");
pConsole->Register("hud_subtitlesVisibleCount", &hud_subtitlesVisibleCount, 1, 0,"Maximum amount of subtitles in Visible Queue");
pConsole->Register("hud_attachBoughEquipment", &hud_attachBoughtEquipment, 0,VF_CHEAT,"Attach equipment in PS equipment packs to the last bought/selected weapon.");
pConsole->Register("hud_radarBackground", &hud_radarBackground, 1, 0, "Switches the miniMap-background for the radar.");
pConsole->Register("hud_radarJammingEffectScale", &hud_radarJammingEffectScale, 0.75f, 0, "Scales the intensity of the radar jamming effect.");
pConsole->Register("hud_radarJammingThreshold", &hud_radarJammingThreshold, 0.99f, 0, "Threshold to disable the radar (independent from effect).");
pConsole->Register("hud_startPaused", &hud_startPaused, 1, 0, "The game starts paused, waiting for user input.");
pConsole->Register("hud_faderDebug", &hud_faderDebug, 0, 0, "Show Debug Information for FullScreen Faders.");
pConsole->Register("hud_nightVisionConsumption", &hud_nightVisionConsumption, 0.5f, VF_CHEAT, "Scales the energy consumption of the night vision.");
pConsole->Register("hud_nightVisionRecharge", &hud_nightVisionRecharge, 2.0f, VF_CHEAT, "Scales the energy recharge of the night vision.");
pConsole->Register("hud_showBigVehicleReload", &hud_showBigVehicleReload, 0, 0, "Enables an additional reload bar around the crosshair in big vehicles.");
pConsole->Register("hud_radarScanningDelay", &hud_binocsScanningDelay, 0.55f, VF_CHEAT, "Defines the delay in seconds the binoculars take to scan an object.");
pConsole->Register("hud_binocsScanningWidth", &hud_binocsScanningWidth, 0.3f, VF_CHEAT, "Defines the width/height in which the binocular raycasts are offset from the center to scan objects.");
pConsole->Register("hud_creategame_pb_server", &hud_creategame_pb_server, 0, 0, "Contains the value of the Punkbuster checkbox in the create game screen.");
// Controller aim helper cvars
pConsole->Register("aim_assistSearchBox", &aim_assistSearchBox, 100.0f, 0, "The area autoaim looks for enemies within");
pConsole->Register("aim_assistMaxDistance", &aim_assistMaxDistance, 150.0f, 0, "The maximum range at which autoaim operates");
pConsole->Register("aim_assistSnapDistance", &aim_assistSnapDistance, 3.0f, 0, "The maximum deviation autoaim is willing to compensate for");
pConsole->Register("aim_assistVerticalScale", &aim_assistVerticalScale, 0.75f, 0, "The amount of emphasis on vertical correction (the less the number is the more vertical component is compensated)");
pConsole->Register("aim_assistSingleCoeff", &aim_assistSingleCoeff, 1.0f, 0, "The scale of single-shot weapons' aim assistance");
pConsole->Register("aim_assistAutoCoeff", &aim_assistAutoCoeff, 0.5f, 0, "The scale of auto weapons' aim assistance at continuous fire");
pConsole->Register("aim_assistRestrictionTimeout", &aim_assistRestrictionTimeout, 20.0f, 0, "The restriction timeout on aim assistance after user uses a mouse");
// Controller control
pConsole->Register("hud_aspectCorrection", &hud_aspectCorrection, 2, 0, "Aspect ratio corrections for controller rotation: 0-off, 1-direct, 2-inverse");
pConsole->Register("hud_ctrl_Curve_X", &hud_ctrl_Curve_X, 3.0f, 0, "Analog controller X rotation curve");
pConsole->Register("hud_ctrl_Curve_Z", &hud_ctrl_Curve_Z, 3.0f, 0, "Analog controller Z rotation curve");
pConsole->Register("hud_ctrl_Coeff_X", &hud_ctrl_Coeff_X, 3.5f*3.5f, 0, "Analog controller X rotation scale"); // was 3.5*3.5 but aspect ratio correction does the scaling now! adjust only if that gives no satisfactory results
pConsole->Register("hud_ctrl_Coeff_Z", &hud_ctrl_Coeff_Z, 5.0f*5.0f, 0, "Analog controller Z rotation scale");
pConsole->Register("hud_ctrlZoomMode", &hud_ctrlZoomMode, 0, 0, "Weapon aiming mode with controller. 0 is same as mouse zoom, 1 cancels at release");
pConsole->Register("g_combatFadeTime", &g_combatFadeTime, 17.0f, 0, "sets the battle fade time in seconds ");
pConsole->Register("g_combatFadeTimeDelay", &g_combatFadeTimeDelay, 7.0f, 0, "waiting time before the battle starts fading out, in seconds ");
pConsole->Register("g_battleRange", &g_battleRange, 50.0f, 0, "sets the battle range in meters ");
// Assistance switches
pConsole->Register("aim_assistAimEnabled", &aim_assistAimEnabled, 1, 0, "Enable/disable aim assitance on aim zooming");
pConsole->Register("aim_assistTriggerEnabled", &aim_assistTriggerEnabled, 1, 0, "Enable/disable aim assistance on firing the weapon");
pConsole->Register("hit_assistSingleplayerEnabled", &hit_assistSingleplayerEnabled, 1, 0, "Enable/disable minimum damage hit assistance");
pConsole->Register("hit_assistMultiplayerEnabled", &hit_assistMultiplayerEnabled, 1, 0, "Enable/disable minimum damage hit assistance in multiplayer games");
//movement cvars
pConsole->Register("v_profileMovement", &v_profileMovement, 0, 0, "Used to enable profiling of the current vehicle movement (1 to enable)");
pConsole->Register("v_pa_surface", &v_pa_surface, 1, VF_CHEAT, "Enables/disables vehicle surface particles");
pConsole->Register("v_wind_minspeed", &v_wind_minspeed, 0.f, VF_CHEAT, "If non-zero, vehicle wind areas always set wind >= specified value");
pConsole->Register("v_draw_suspension", &v_draw_suspension, 0, VF_DUMPTODISK, "Enables/disables display of wheel suspension, for the vehicle that has v_profileMovement enabled");
pConsole->Register("v_draw_slip", &v_draw_slip, 0, VF_DUMPTODISK, "Draw wheel slip status");
pConsole->Register("v_invertPitchControl", &v_invertPitchControl, 0, VF_DUMPTODISK, "Invert the pitch control for driving some vehicles, including the helicopter and the vtol");
pConsole->Register("v_sprintSpeed", &v_sprintSpeed, 0.f, 0, "Set speed for acceleration measuring");
pConsole->Register("v_rockBoats", &v_rockBoats, 1, 0, "Enable/disable boats idle rocking");
pConsole->Register("v_dumpFriction", &v_dumpFriction, 0, 0, "Dump vehicle friction status");
pConsole->Register("v_debugSounds", &v_debugSounds, 0, 0, "Enable/disable vehicle sound debug drawing");
pConsole->Register("v_debugMountedWeapon", &v_debugMountedWeapon, 0, 0, "Enable/disable vehicle mounted weapon camera debug draw");
pConsole->Register("v_newBrakingFriction", &v_newBrakingFriction, 1, VF_CHEAT, "Change rear wheel friction under handbraking (true/false)");
pConsole->Register("v_newBoost", &v_newBoost, 0, VF_CHEAT, "Apply new boost scheme (true/false)");
pAltitudeLimitCVar = pConsole->Register("v_altitudeLimit", &v_altitudeLimit, v_altitudeLimitDefault(), VF_CHEAT, "Used to restrict the helicopter and VTOL movement from going higher than a set altitude. If set to zero, the altitude limit is disabled.");
pAltitudeLimitLowerOffsetCVar = pConsole->Register("v_altitudeLimitLowerOffset", &v_altitudeLimitLowerOffset, 0.1f, VF_CHEAT, "Used in conjunction with v_altitudeLimit to set the zone when gaining altitude start to be more difficult.");
pConsole->Register("v_help_tank_steering", &v_help_tank_steering, 0, 0, "Enable tank steering help for AI");
pConsole->Register("v_stabilizeVTOL", &v_stabilizeVTOL, 0.35f, VF_DUMPTODISK, "Specifies if the air movements should automatically stabilize");
pConsole->Register("pl_swimBaseSpeed", &pl_swimBaseSpeed, 4.0f, VF_CHEAT, "Swimming base speed.");
pConsole->Register("pl_swimBackSpeedMul", &pl_swimBackSpeedMul, 0.8f, VF_CHEAT, "Swimming backwards speed mul.");
pConsole->Register("pl_swimSideSpeedMul", &pl_swimSideSpeedMul, 0.9f, VF_CHEAT, "Swimming sideways speed mul.");
pConsole->Register("pl_swimVertSpeedMul", &pl_swimVertSpeedMul, 0.5f, VF_CHEAT, "Swimming vertical speed mul.");
pConsole->Register("pl_swimNormalSprintSpeedMul", &pl_swimNormalSprintSpeedMul, 1.5f, VF_CHEAT, "Swimming Non-Speed sprint speed mul.");
pConsole->Register("pl_swimSpeedSprintSpeedMul", &pl_swimSpeedSprintSpeedMul, 2.5f, VF_CHEAT, "Swimming Speed sprint speed mul.");
pConsole->Register("pl_swimUpSprintSpeedMul", &pl_swimUpSprintSpeedMul, 2.0f, VF_CHEAT, "Swimming sprint while looking up (dolphin rocket).");
pConsole->Register("pl_swimJumpStrengthCost", &pl_swimJumpStrengthCost, 50.0f, VF_CHEAT, "Swimming strength shift+jump energy cost (dolphin rocket).");
pConsole->Register("pl_swimJumpStrengthSprintMul", &pl_swimJumpStrengthSprintMul, 2.5f, VF_CHEAT, "Swimming strength shift+jump velocity mul (dolphin rocket).");
pConsole->Register("pl_swimJumpStrengthBaseMul", &pl_swimJumpStrengthBaseMul, 1.0f, VF_CHEAT, "Swimming strength normal jump velocity mul (dolphin rocket).");
pConsole->Register("pl_swimJumpSpeedCost", &pl_swimJumpSpeedCost, 50.0f, VF_CHEAT, "Swimming speed shift+jump energy cost (dolphin rocket).");
pConsole->Register("pl_swimJumpSpeedSprintMul", &pl_swimJumpSpeedSprintMul, 2.5f, VF_CHEAT, "Swimming speed shift+jump velocity mul (dolphin rocket).");
pConsole->Register("pl_swimJumpSpeedBaseMul", &pl_swimJumpSpeedBaseMul, 1.0f, VF_CHEAT, "Swimming speed normal jump velocity mul (dolphin rocket).");
pConsole->Register("pl_fallDamage_SpeedSafe", &pl_fallDamage_Normal_SpeedSafe, 8.0f, VF_CHEAT, "Safe fall speed (in all modes, including strength jump on flat ground).");
pConsole->Register("pl_fallDamage_SpeedFatal", &pl_fallDamage_Normal_SpeedFatal, 13.7f, VF_CHEAT, "Fatal fall speed in armor mode (13.5 m/s after falling freely for ca 20m).");
pConsole->Register("pl_fallDamage_SpeedBias", &pl_fallDamage_SpeedBias, 1.5f, VF_CHEAT, "Damage bias for medium fall speed: =1 linear, <1 more damage, >1 less damage.");
pConsole->Register("pl_debugFallDamage", &pl_debugFallDamage, 0, VF_CHEAT, "Enables console output of fall damage information.");
pConsole->Register("pl_zeroGSpeedMultNormal", &pl_zeroGSpeedMultNormal, 1.2f, VF_CHEAT, "Modify movement speed in zeroG, in normal mode.");
pConsole->Register("pl_zeroGSpeedMultNormalSprint", &pl_zeroGSpeedMultNormalSprint, 1.7f, VF_CHEAT, "Modify movement speed in zeroG, in normal sprint.");
pConsole->Register("pl_zeroGSpeedMultSpeed", &pl_zeroGSpeedMultSpeed, 1.7f, VF_CHEAT, "Modify movement speed in zeroG, in speed mode.");
pConsole->Register("pl_zeroGSpeedMultSpeedSprint", &pl_zeroGSpeedMultSpeedSprint, 5.0f, VF_CHEAT, "Modify movement speed in zeroG, in speed sprint.");
pConsole->Register("pl_zeroGUpDown", &pl_zeroGUpDown, 1.0f, 0, "Scales the z-axis movement speed in zeroG.");
pConsole->Register("pl_zeroGBaseSpeed", &pl_zeroGBaseSpeed, 3.0f, 0, "Maximum player speed request limit for zeroG.");
pConsole->Register("pl_zeroGSpeedMaxSpeed", &pl_zeroGSpeedMaxSpeed, -1.0f, 0, "(DEPRECATED) Maximum player speed request limit for zeroG while in speed mode.");
pConsole->Register("pl_zeroGSpeedModeEnergyConsumption", &pl_zeroGSpeedModeEnergyConsumption, 0.5f, 0, "Percentage consumed per second while speed sprinting in ZeroG.");
pConsole->Register("pl_zeroGDashEnergyConsumption", &pl_zeroGDashEnergyConsumption, 0.25f, 0, "Percentage consumed when doing a dash in ZeroG.");
pConsole->Register("pl_zeroGSwitchableGyro", &pl_zeroGSwitchableGyro, 0, 0, "MERGE/REVERT");
pConsole->Register("pl_zeroGEnableGBoots", &pl_zeroGEnableGBoots, 0, 0, "Switch G-Boots action on/off (if button assigned).");
pConsole->Register("pl_zeroGThrusterResponsiveness", &pl_zeroGThrusterResponsiveness, 0.3f, VF_CHEAT, "Thrusting responsiveness.");
pConsole->Register("pl_zeroGFloatDuration", &pl_zeroGFloatDuration, 1.25f, VF_CHEAT, "Floating duration until full stop (after stopped thrusting).");
pConsole->Register("pl_zeroGParticleTrail", &pl_zeroGParticleTrail, 0, 0, "Enable particle trail when in zerog.");
pConsole->Register("pl_zeroGEnableGyroFade", &pl_zeroGEnableGyroFade, 2, VF_CHEAT, "Enable fadeout of gyro-stabilizer for vertical view angles (2=disable speed fade as well).");
pConsole->Register("pl_zeroGGyroFadeAngleInner", &pl_zeroGGyroFadeAngleInner, 20.0f, VF_CHEAT, "ZeroG gyro inner angle (default is 20).");
pConsole->Register("pl_zeroGGyroFadeAngleOuter", &pl_zeroGGyroFadeAngleOuter, 60.0f, VF_CHEAT, "ZeroG gyro outer angle (default is 60).");
pConsole->Register("pl_zeroGGyroFadeExp", &pl_zeroGGyroFadeExp, 2.0f, VF_CHEAT, "ZeroG gyro angle bias (default is 2.0).");
pConsole->Register("pl_zeroGGyroStrength", &pl_zeroGGyroStrength, 1.0f, VF_CHEAT, "ZeroG gyro strength (default is 1.0).");
pConsole->Register("pl_zeroGAimResponsiveness", &pl_zeroGAimResponsiveness, 8.0f, VF_CHEAT, "ZeroG aim responsiveness vs. inertia (default is 8.0).");
// weapon system
i_debuggun_1 = pConsole->RegisterString("i_debuggun_1", "ai_statsTarget", VF_DUMPTODISK, "Command to execute on primary DebugGun fire");
i_debuggun_2 = pConsole->RegisterString("i_debuggun_2", "ag_debug", VF_DUMPTODISK, "Command to execute on secondary DebugGun fire");
pConsole->Register("tracer_min_distance", &tracer_min_distance, 4.0f, 0, "Distance at which to start scaling/lengthening tracers.");
pConsole->Register("tracer_max_distance", &tracer_max_distance, 50.0f, 0, "Distance at which to stop scaling/lengthening tracers.");
pConsole->Register("tracer_min_scale", &tracer_min_scale, 0.5f, 0, "Scale at min distance.");
pConsole->Register("tracer_max_scale", &tracer_max_scale, 5.0f, 0, "Scale at max distance.");
pConsole->Register("tracer_max_count", &tracer_max_count, 32, 0, "Max number of active tracers.");
pConsole->Register("tracer_player_radiusSqr", &tracer_player_radiusSqr, 400.0f, 0, "Sqr Distance around player at which to start decelerate/acelerate tracer speed.");
pConsole->Register("i_debug_projectiles", &i_debug_projectiles, 0, VF_CHEAT, "Displays info about projectile status, where available.");
pConsole->Register("i_auto_turret_target", &i_auto_turret_target, 1, VF_CHEAT, "Enables/Disables auto turrets aquiring targets.");
pConsole->Register("i_auto_turret_target_tacshells", &i_auto_turret_target_tacshells, 0, 0, "Enables/Disables auto turrets aquiring TAC shells as targets");
pConsole->Register("i_debug_zoom_mods", &i_debug_zoom_mods, 0, VF_CHEAT, "Use zoom mode spread/recoil mods");
pConsole->Register("i_debug_sounds", &i_debug_sounds, 0, VF_CHEAT, "Enable item sound debugging");
pConsole->Register("i_debug_turrets", &i_debug_turrets, 0, VF_CHEAT,
"Enable GunTurret debugging.\n"
"Values:\n"
"0: off"
"1: basics\n"
"2: prediction\n"
"3: sweeping\n"
"4: searching\n"
"5: deviation\n"
);
pConsole->Register("i_debug_mp_flowgraph", &i_debug_mp_flowgraph, 0, VF_CHEAT, "Displays info on the MP flowgraph node");
pConsole->Register("h_turnSpeed", &h_turnSpeed, 1.3f, 0);
// quick game
g_quickGame_map = pConsole->RegisterString("g_quickGame_map","",VF_DUMPTODISK, "QuickGame option");
g_quickGame_mode = pConsole->RegisterString("g_quickGame_mode","PowerStruggle", VF_DUMPTODISK, "QuickGame option");
pConsole->Register("g_quickGame_min_players",&g_quickGame_min_players,0,VF_DUMPTODISK,"QuickGame option");
pConsole->Register("g_quickGame_prefer_lan",&g_quickGame_prefer_lan,0,VF_DUMPTODISK,"QuickGame option");
pConsole->Register("g_quickGame_prefer_favorites",&g_quickGame_prefer_favorites,0,VF_DUMPTODISK,"QuickGame option");
pConsole->Register("g_quickGame_prefer_mycountry",&g_quickGame_prefer_my_country,0,VF_DUMPTODISK,"QuickGame option");
pConsole->Register("g_quickGame_ping1_level",&g_quickGame_ping1_level,80,VF_DUMPTODISK,"QuickGame option");
pConsole->Register("g_quickGame_ping2_level",&g_quickGame_ping2_level,170,VF_DUMPTODISK,"QuickGame option");
pConsole->Register("g_quickGame_debug",&g_quickGame_debug,0,VF_CHEAT,"QuickGame option");
pConsole->Register("g_displayIgnoreList",&g_displayIgnoreList,1,VF_DUMPTODISK,"Display ignore list in chat tab.");
pConsole->Register("g_buddyMessagesIngame",&g_buddyMessagesIngame,1,VF_DUMPTODISK,"Output incoming buddy messages in chat while playing game.");
pConsole->RegisterInt("g_showIdleStats", 0, 0);
// battledust
pConsole->Register("g_battleDust_enable", &g_battleDust_enable, 1, 0, "Enable/Disable battledust");
pConsole->Register("g_battleDust_debug", &g_battleDust_debug, 0, 0, "0: off, 1: text, 2: text+gfx");
g_battleDust_effect = pConsole->RegisterString("g_battleDust_effect", "misc.battledust.light", 0, "Sets the effect to use for battledust");
pConsole->Register("g_PSTutorial_Enabled", &g_PSTutorial_Enabled, 1, 0, "Enable/disable powerstruggle tutorial");
pConsole->Register("g_proneNotUsableWeapon_FixType", &g_proneNotUsableWeapon_FixType, 1, 0, "Test various fixes for not selecting hurricane while prone");
pConsole->Register("g_proneAimAngleRestrict_Enable", &g_proneAimAngleRestrict_Enable, 1, 0, "Test fix for matching aim restrictions between 1st and 3rd person");
pConsole->Register("sv_voting_timeout", &sv_votingTimeout, 60, 0, "Voting timeout");
pConsole->Register("sv_voting_cooldown", &sv_votingCooldown, 180, 0, "Voting cooldown");
pConsole->Register("sv_voting_ratio",&sv_votingRatio, 0.51f, 0, "Part of player's votes needed for successful vote.");
pConsole->Register("sv_voting_team_ratio",&sv_votingTeamRatio, 0.67f, 0, "Part of team member's votes needed for successful vote.");
pConsole->Register("sv_input_timeout",&sv_input_timeout, 0, 0, "Experimental timeout in ms to stop interpolating client inputs since last update.");
pConsole->Register("g_spectate_TeamOnly", &g_spectate_TeamOnly, 1, 0, "If true, you can only spectate players on your team");
pConsole->Register("g_spectate_FixedOrientation", &g_spectate_FixedOrientation, 0, 0, "If true, spectator camera is fixed behind player. Otherwise spectator controls orientation");
pConsole->Register("g_claymore_limit", &g_explosiveLimits[eET_Claymore], 2, 0, "Max claymores a player can place (recycled above this value)");
pConsole->Register("g_avmine_limit", &g_explosiveLimits[eET_AVMine], 3, 0, "Max avmines a player can place (recycled above this value)");
pConsole->Register("g_c4_limit", &g_explosiveLimits[eET_C4], 1, 0, "Max C4 a player can place (recycled above this value)");
pConsole->Register("g_fgl_limit", &g_explosiveLimits[eET_LaunchedGrenade], 2, 0, "Max FGL remote grenades a player can launch (recycled above this value)");
pConsole->Register("g_debugMines", &g_debugMines, 0, 0, "Enable debug output for mines and claymores");
pConsole->Register("aim_assistCrosshairSize", &aim_assistCrosshairSize, 25, VF_CHEAT, "screen size used for crosshair aim assistance");
pConsole->Register("aim_assistCrosshairDebug", &aim_assistCrosshairDebug, 0, VF_CHEAT, "debug crosshair aim assistance");
pConsole->Register("g_MPDeathCam", &g_deathCam, 1, 0, "Enables / disables the MP death camera (shows the killer's location)");
pConsole->Register("g_MPDeathCamMaxZoomFOV", &g_deathCamMaxZoomFOV, 0.1f, 0, "FOV at maximum zoom of the death camera");
pConsole->Register("g_MPDeathCamMinZoom", &g_deathCamMinZoomDistance, 2, 0, "Distance at which the death camera begins to zoom on the killer");
pConsole->Register("g_MPDeathCamMaxZoom", &g_deathCamMaxZoomDistance, 50, 0, "Distance to the killer at which the death camera is fully zoomed in");
pConsole->Register("g_MPDeathEffects", &g_deathEffects, 0, 0, "Enables / disables the MP death screen-effects");
pConsole->Register("sv_pacifist", &sv_pacifist, 0, 0, "Pacifist mode (only works on dedicated server)");
pVehicleQuality = pConsole->GetCVar("v_vehicle_quality"); assert(pVehicleQuality);
i_restrictItems = pConsole->RegisterString("i_restrictItems", "", 0, "List of items to restrict for this MP round", RestrictedItemsChanged );
pConsole->Register("g_spawnProtectionTime", &g_spawnProtectionTime, 2, 0, "Number of seconds of invulnerability after a respawn in MP");
pConsole->Register("g_roundRestartTime", &g_roundRestartTime, 30, 0, "Time until round start after minimum people join");
net_mapDownloadURL = pConsole->RegisterString("net_mapDownloadURL", "", 0, "URL for clients to download the current map");
pConsole->Register("g_debugShotValidator", &g_debugShotValidator, 0, 0, "Debug the shot validator");
pConsole->AddCommand("g_listVisiblePlayers", CmdListInvisiblePlayers, 0, "List all players and their visible status");
pConsole->Register("g_painSoundGap", &g_painSoundGap, 0.1f, 0, "Minimum time gap between local player pain sounds");
pConsole->Register("g_explosionScreenShakeMultiplier", &g_explosionScreenShakeMultiplier, 0.25f, 0, "Multiplier for explosion screenshake");
NetInputChainInitCVars();
}
//------------------------------------------------------------------------
void SCVars::ReleaseCVars()
{
IConsole* pConsole = gEnv->pConsole;
pConsole->UnregisterVariable("cl_fov", true);
pConsole->UnregisterVariable("cl_bob", true);
pConsole->UnregisterVariable("cl_tpvDist", true);
pConsole->UnregisterVariable("cl_tpvYaw", true);
pConsole->UnregisterVariable("cl_nearPlane", true);
pConsole->UnregisterVariable("cl_sprintShake", true);
pConsole->UnregisterVariable("cl_sensitivityZeroG", true);
pConsole->UnregisterVariable("cl_sensitivity", true);
pConsole->UnregisterVariable("cl_controllersensitivity", true);
pConsole->UnregisterVariable("cl_invertMouse", true);
pConsole->UnregisterVariable("cl_invertController", true);
pConsole->UnregisterVariable("cl_crouchToggle", true);
pConsole->UnregisterVariable("cl_fpBody", true);
pConsole->UnregisterVariable("cl_hud", true);
pConsole->UnregisterVariable("i_staticfiresounds", true);
pConsole->UnregisterVariable("i_soundeffects", true);
pConsole->UnregisterVariable("i_lighteffects", true);
pConsole->UnregisterVariable("i_lighteffectShadows", true);
pConsole->UnregisterVariable("i_particleeffects", true);
pConsole->UnregisterVariable("i_offset_front", true);
pConsole->UnregisterVariable("i_offset_up", true);
pConsole->UnregisterVariable("i_offset_right", true);
pConsole->UnregisterVariable("i_unlimitedammo", true);
pConsole->UnregisterVariable("i_iceeffects", true);
pConsole->UnregisterVariable("cl_strengthscale", true);
pConsole->UnregisterVariable("cl_motionBlur", true);
pConsole->UnregisterVariable("cl_sprintBlur", true);
pConsole->UnregisterVariable("cl_hitShake", true);
pConsole->UnregisterVariable("cl_hitBlur", true);
pConsole->UnregisterVariable("cl_righthand", true);
pConsole->UnregisterVariable("cl_screeneffects", true);
pConsole->UnregisterVariable("pl_inputAccel", true);
pConsole->UnregisterVariable("cl_actorsafemode", true);
pConsole->UnregisterVariable("g_hunterIK", true);
pConsole->UnregisterVariable("g_tentacle_joint_limit", true);
pConsole->UnregisterVariable("g_enableSpeedLean", true);
pConsole->UnregisterVariable("int_zoomAmount", true);
pConsole->UnregisterVariable("int_zoomInTime", true);
pConsole->UnregisterVariable("int_moveZoomTime", true);
pConsole->UnregisterVariable("int_zoomOutTime", true);
pConsole->UnregisterVariable("aa_maxDist", true);
pConsole->UnregisterVariable("hr_rotateFactor", true);
pConsole->UnregisterVariable("hr_rotateTime", true);
pConsole->UnregisterVariable("hr_dotAngle", true);
pConsole->UnregisterVariable("hr_fovAmt", true);
pConsole->UnregisterVariable("hr_fovTime", true);
pConsole->UnregisterVariable("cl_debugFreezeShake", true);
pConsole->UnregisterVariable("cl_frozenSteps", true);
pConsole->UnregisterVariable("cl_frozenSensMin", true);
pConsole->UnregisterVariable("cl_frozenSensMax", true);
pConsole->UnregisterVariable("cl_frozenAngleMin", true);
pConsole->UnregisterVariable("cl_frozenAngleMax", true);
pConsole->UnregisterVariable("cl_frozenMouseMult", true);
pConsole->UnregisterVariable("cl_frozenKeyMult", true);
pConsole->UnregisterVariable("cl_frozenSoundDelta", true);
pConsole->UnregisterVariable("g_frostDecay", true);
pConsole->UnregisterVariable("g_stanceTransitionSpeed", true);
pConsole->UnregisterVariable("g_stanceTransitionSpeedSecondary", true);
pConsole->UnregisterVariable("g_playerHealthValue", true);
pConsole->UnregisterVariable("g_walkMultiplier", true);
pConsole->UnregisterVariable("g_suitSpeedMult", true);
pConsole->UnregisterVariable("g_suitRecoilEnergyCost", true);
pConsole->UnregisterVariable("g_suitSpeedMultMultiplayer", true);
pConsole->UnregisterVariable("g_suitArmorHealthValue", true);
pConsole->UnregisterVariable("g_suitSpeedEnergyConsumption", true);
pConsole->UnregisterVariable("g_suitSpeedEnergyConsumptionMultiplayer", true);
pConsole->UnregisterVariable("g_AiSuitEnergyRechargeTime", true);
pConsole->UnregisterVariable("g_AiSuitHealthRechargeTime", true);
pConsole->UnregisterVariable("g_AiSuitArmorModeHealthRegenTime", true);
pConsole->UnregisterVariable("g_AiSuitStrengthMeleeMult", true);
pConsole->UnregisterVariable("g_playerSuitEnergyRechargeTime", true);
pConsole->UnregisterVariable("g_playerSuitEnergyRechargeTimeArmor", true);
pConsole->UnregisterVariable("g_playerSuitEnergyRechargeTimeArmorMoving", true);
pConsole->UnregisterVariable("g_playerSuitEnergyRechargeTimeMultiplayer", true);
pConsole->UnregisterVariable("g_playerSuitHealthRechargeTime", true);
pConsole->UnregisterVariable("g_playerSuitArmorModeHealthRegenTime", true);
pConsole->UnregisterVariable("g_playerSuitHealthRechargeTimeMoving", true);
pConsole->UnregisterVariable("g_playerSuitArmorModeHealthRegenTimeMoving", true);
pConsole->UnregisterVariable("g_useHitSoundFeedback", true);
pConsole->UnregisterVariable("g_playerLowHealthThreshold", true);
pConsole->UnregisterVariable("g_playerLowHealthThreshold2", true);
pConsole->UnregisterVariable("g_playerLowHealthThresholdMultiplayer", true);
pConsole->UnregisterVariable("g_playerLowHealthThreshold2Multiplayer", true);
pConsole->UnregisterVariable("g_pp_scale_income", true);
pConsole->UnregisterVariable("g_pp_scale_price", true);
pConsole->UnregisterVariable("g_radialBlur", true);
pConsole->UnregisterVariable("g_PlayerFallAndPlay", true);
pConsole->UnregisterVariable("g_fallAndPlayThreshold", true);
pConsole->UnregisterVariable("g_enableAlternateIronSight",true);
pConsole->UnregisterVariable("g_enableTracers", true);
pConsole->UnregisterVariable("g_meleeWhileSprinting", true);
pConsole->UnregisterVariable("g_spawndebug", true);
pConsole->UnregisterVariable("g_spawnteamdist", true);
pConsole->UnregisterVariable("g_spawnenemydist", true);
pConsole->UnregisterVariable("g_spawndeathdist", true);
pConsole->UnregisterVariable("g_timelimit", true);
pConsole->UnregisterVariable("g_teamlock", true);
pConsole->UnregisterVariable("g_roundlimit", true);
pConsole->UnregisterVariable("g_preroundtime", true);
pConsole->UnregisterVariable("g_suddendeathtime", true);
pConsole->UnregisterVariable("g_roundtime", true);
pConsole->UnregisterVariable("g_fraglimit", true);
pConsole->UnregisterVariable("g_fraglead", true);
pConsole->UnregisterVariable("g_debugNetPlayerInput", true);
pConsole->UnregisterVariable("g_debug_fscommand", true);
pConsole->UnregisterVariable("g_debugDirectMPMenu", true);
pConsole->UnregisterVariable("g_skipIntro", true);
pConsole->UnregisterVariable("g_resetActionmapOnStart", true);
pConsole->UnregisterVariable("g_useProfile", true);
pConsole->UnregisterVariable("g_startFirstTime", true);
pConsole->UnregisterVariable("g_tk_punish", true);
pConsole->UnregisterVariable("g_tk_punish_limit", true);
pConsole->UnregisterVariable("g_godMode", true);
pConsole->UnregisterVariable("g_detachCamera", true);
pConsole->UnregisterVariable("g_suicideDelay", true);
pConsole->UnregisterVariable("g_debugCollisionDamage", true);
pConsole->UnregisterVariable("g_debugHits", true);
pConsole->UnregisterVariable("g_trooperProneMinDistance", true);
pConsole->UnregisterVariable("g_trooperTentacleAnimBlend", true);
pConsole->UnregisterVariable("g_trooperBankingMultiplier", true);
pConsole->UnregisterVariable("v_profileMovement", true);
pConsole->UnregisterVariable("v_pa_surface", true);
pConsole->UnregisterVariable("v_wind_minspeed", true);
pConsole->UnregisterVariable("v_draw_suspension", true);
pConsole->UnregisterVariable("v_draw_slip", true);
pConsole->UnregisterVariable("v_invertPitchControl", true);
pConsole->UnregisterVariable("v_sprintSpeed", true);
pConsole->UnregisterVariable("v_rockBoats", true);
pConsole->UnregisterVariable("v_debugMountedWeapon", true);
pConsole->UnregisterVariable("v_zeroGSpeedMultSpeed", true);
pConsole->UnregisterVariable("v_zeroGSpeedMultSpeedSprint", true);
pConsole->UnregisterVariable("v_zeroGSpeedMultNormal", true);
pConsole->UnregisterVariable("v_zeroGSpeedMultNormalSprint", true);
pConsole->UnregisterVariable("v_zeroGUpDown", true);
pConsole->UnregisterVariable("v_zeroGMaxSpeed", true);
pConsole->UnregisterVariable("v_zeroGSpeedMaxSpeed", true);
pConsole->UnregisterVariable("v_zeroGSpeedModeEnergyConsumption", true);
pConsole->UnregisterVariable("v_zeroGSwitchableGyro", true);
pConsole->UnregisterVariable("v_zeroGEnableGBoots", true);
pConsole->UnregisterVariable("v_dumpFriction", true);
pConsole->UnregisterVariable("v_debugSounds", true);
pConsole->UnregisterVariable("v_altitudeLimit", true);
pConsole->UnregisterVariable("v_altitudeLimitLowerOffset", true);
pConsole->UnregisterVariable("v_airControlSensivity", true);
// variables from CPlayer
pConsole->UnregisterVariable("player_DrawIK", true);
pConsole->UnregisterVariable("player_NoIK", true);
pConsole->UnregisterVariable("g_enableIdleCheck", true);
pConsole->UnregisterVariable("pl_debug_ladders", true);
pConsole->UnregisterVariable("pl_debug_movement", true);
pConsole->UnregisterVariable("pl_debug_filter", true);
// alien debugging
pConsole->UnregisterVariable("aln_debug_movement", true);
pConsole->UnregisterVariable("aln_debug_filter", true);
// variables from CPlayerMovementController
pConsole->UnregisterVariable("g_showIdleStats", true);
pConsole->UnregisterVariable("g_debugaimlook", true);
// variables from CHUD
pConsole->UnregisterVariable("hud_mpNamesNearDistance", true);
pConsole->UnregisterVariable("hud_mpNamesFarDistance", true);
pConsole->UnregisterVariable("hud_onScreenNearDistance", true);
pConsole->UnregisterVariable("hud_onScreenFarDistance", true);
pConsole->UnregisterVariable("hud_onScreenNearSize", true);
pConsole->UnregisterVariable("hud_onScreenFarSize", true);
pConsole->UnregisterVariable("hud_colorLine", true);
pConsole->UnregisterVariable("hud_colorOver", true);
pConsole->UnregisterVariable("hud_colorText", true);
pConsole->UnregisterVariable("hud_showAllObjectives", true);
pConsole->UnregisterVariable("hud_showObjectiveMessages", true);
pConsole->UnregisterVariable("hud_godfadetime", true);
pConsole->UnregisterVariable("g_combatfadetime", true);
pConsole->UnregisterVariable("g_combatfadetimedelay", true);
pConsole->UnregisterVariable("g_battlerange", true);
pConsole->UnregisterVariable("hud_centernames", true);
pConsole->UnregisterVariable("hud_crosshair", true);
pConsole->UnregisterVariable("hud_chdamageindicator", true);
pConsole->UnregisterVariable("hud_panoramic", true);
pConsole->UnregisterVariable("hud_voicemode", true);
pConsole->UnregisterVariable("hud_enableAlienInterference", true);
pConsole->UnregisterVariable("hud_alienInterferenceStrength", true);
pConsole->UnregisterVariable("hud_crosshair_enable", true);
pConsole->UnregisterVariable("hud_attachBoughEquipment", true);
pConsole->UnregisterVariable("hud_subtitlesRenderMode", true);
pConsole->UnregisterVariable("hud_panoramicHeight", true);
pConsole->UnregisterVariable("hud_subtitles", true);
pConsole->UnregisterVariable("hud_subtitlesFontSize", true);
pConsole->UnregisterVariable("hud_subtitlesHeight", true);
pConsole->UnregisterVariable("hud_startPaused", true);
pConsole->UnregisterVariable("hud_nightVisionRecharge", true);
pConsole->UnregisterVariable("hud_nightVisionConsumption", true);
pConsole->UnregisterVariable("hud_showBigVehicleReload", true);
pConsole->UnregisterVariable("hud_binocsScanningDelay", true);
pConsole->UnregisterVariable("hud_binocsScanningWidth", true);
pConsole->UnregisterVariable("hud_creategame_pb_server", true);
pConsole->UnregisterVariable("hud_alternateCrosshairSpread", true);
pConsole->UnregisterVariable("hud_alternateCrosshairSpreadCrouch", true);
pConsole->UnregisterVariable("hud_alternateCrosshairSpreadNeutral", true);
// variables from CHUDRadar
pConsole->UnregisterVariable("hud_radarBackground", true);
pConsole->UnregisterVariable("hud_radarJammingThreshold", true);
pConsole->UnregisterVariable("hud_radarJammingEffectScale", true);
// Controller aim helper cvars
pConsole->UnregisterVariable("aim_assistSearchBox", true);
pConsole->UnregisterVariable("aim_assistMaxDistance", true);
pConsole->UnregisterVariable("aim_assistSnapDistance", true);
pConsole->UnregisterVariable("aim_assistVerticalScale", true);
pConsole->UnregisterVariable("aim_assistSingleCoeff", true);
pConsole->UnregisterVariable("aim_assistAutoCoeff", true);
pConsole->UnregisterVariable("aim_assistRestrictionTimeout", true);
pConsole->UnregisterVariable("hud_aspectCorrection", true);
pConsole->UnregisterVariable("hud_ctrl_Curve_X", true);
pConsole->UnregisterVariable("hud_ctrl_Curve_Z", true);
pConsole->UnregisterVariable("hud_ctrl_Coeff_X", true);
pConsole->UnregisterVariable("hud_ctrl_Coeff_Z", true);
pConsole->UnregisterVariable("hud_ctrlZoomMode", true);
// Aim assitance switches
pConsole->UnregisterVariable("aim_assistAimEnabled", true);
pConsole->UnregisterVariable("aim_assistTriggerEnabled", true);
pConsole->UnregisterVariable("hit_assistSingleplayerEnabled", true);
pConsole->UnregisterVariable("hit_assistMultiplayerEnabled", true);
// weapon system
pConsole->UnregisterVariable("i_debuggun_1", true);
pConsole->UnregisterVariable("i_debuggun_2", true);
pConsole->UnregisterVariable("tracer_min_distance", true);
pConsole->UnregisterVariable("tracer_max_distance", true);
pConsole->UnregisterVariable("tracer_min_scale", true);
pConsole->UnregisterVariable("tracer_max_scale", true);
pConsole->UnregisterVariable("tracer_max_count", true);
pConsole->UnregisterVariable("tracer_player_radiusSqr", true);
pConsole->UnregisterVariable("i_debug_projectiles", true);
pConsole->UnregisterVariable("i_auto_turret_target", true);
pConsole->UnregisterVariable("i_auto_turret_target_tacshells", true);
pConsole->UnregisterVariable("i_debug_zoom_mods", true);
pConsole->UnregisterVariable("i_debug_mp_flowgraph", true);
pConsole->UnregisterVariable("g_quickGame_map",true);
pConsole->UnregisterVariable("g_quickGame_mode",true);
pConsole->UnregisterVariable("g_quickGame_min_players",true);
pConsole->UnregisterVariable("g_quickGame_prefer_lan",true);
pConsole->UnregisterVariable("g_quickGame_prefer_favorites",true);
pConsole->UnregisterVariable("g_quickGame_prefer_mycountry",true);
pConsole->UnregisterVariable("g_quickGame_ping1_level",true);
pConsole->UnregisterVariable("g_quickGame_ping2_level",true);
pConsole->UnregisterVariable("g_quickGame_debug",true);
pConsole->UnregisterVariable("g_skip_tutorial",true);
pConsole->UnregisterVariable("g_displayIgnoreList",true);
pConsole->UnregisterVariable("g_buddyMessagesIngame",true);
pConsole->UnregisterVariable("g_battleDust_enable", true);
pConsole->UnregisterVariable("g_battleDust_debug", true);
pConsole->UnregisterVariable("g_battleDust_effect", true);
pConsole->UnregisterVariable("g_PSTutorial_Enabled", true);
pConsole->UnregisterVariable("g_proneNotUsableWeapon_FixType", true);
pConsole->UnregisterVariable("g_proneAimAngleRestrict_Enable", true);
pConsole->UnregisterVariable("sv_voting_timeout",true);
pConsole->UnregisterVariable("sv_voting_cooldown",true);
pConsole->UnregisterVariable("sv_voting_ratio",true);
pConsole->UnregisterVariable("sv_voting_team_ratio",true);
pConsole->UnregisterVariable("g_spectate_TeamOnly", true);
pConsole->UnregisterVariable("g_claymore_limit", true);
pConsole->UnregisterVariable("g_avmine_limit", true);
pConsole->UnregisterVariable("g_debugMines", true);
pConsole->UnregisterVariable("aim_assistCrosshairSize", true);
pConsole->UnregisterVariable("aim_assistCrosshairDebug", true);
pConsole->UnregisterVariable("i_restrictItems", true);
pConsole->UnregisterVariable("g_spawnProtectionTime", true);
pConsole->UnregisterVariable("g_roundRestartTime", true);
pConsole->UnregisterVariable("net_mapDownloadURL", true);
pConsole->UnregisterVariable("g_debugShotValidator", true);
pConsole->UnregisterVariable("g_painSoundFrequency", true);
pConsole->UnregisterVariable("g_explosionScreenShakeMultiplier", true);
}
//------------------------------------------------------------------------
void CGame::CmdDumpSS(IConsoleCmdArgs *pArgs)
{
g_pGame->GetSynchedStorage()->Dump();
}
//------------------------------------------------------------------------
void CGame::RegisterConsoleVars()
{
assert(m_pConsole);
if (m_pCVars)
{
m_pCVars->InitCVars(m_pConsole);
}
}
//------------------------------------------------------------------------
void CmdDumpItemNameTable(IConsoleCmdArgs *pArgs)
{
SharedString::CSharedString::DumpNameTable();
}
//------------------------------------------------------------------------
void CmdHelp(IConsoleCmdArgs* pArgs)
{
if(pArgs && pArgs->GetArgCount() == 1)
{
if(gEnv->pSystem->IsDedicated())
{
// dedicated server help here. Load it from text file
FILE * f = gEnv->pCryPak->FOpen( "Game/Scripts/Network/Help.txt", "rt" );
if (!f)
return;
static const int BUFSZ = 4096;
char buf[BUFSZ];
size_t nRead;
do
{
nRead = gEnv->pCryPak->FRead( buf, BUFSZ, f );
// scan for newlines
int i=0;
for(size_t c = 0; c < nRead; ++c)
{
if(buf[c] == '\n')
{
string output(&buf[i], c-i);
gEnv->pConsole->PrintLine(output);
i = c+1;
}
}
}
while (nRead == BUFSZ);
gEnv->pCryPak->FClose( f );
}
else
{
gEnv->pConsole->ExecuteString("help ?");
}
}
else if(pArgs && pArgs->GetArgCount() == 2)
{
string cmd = pArgs->GetArg(1);
cmd += " ?";
gEnv->pConsole->ExecuteString(cmd.c_str());
}
}
//------------------------------------------------------------------------
void CGame::RegisterConsoleCommands()
{
assert(m_pConsole);
m_pConsole->AddCommand("quit", "System.Quit()", VF_RESTRICTEDMODE, "Quits the game");
m_pConsole->AddCommand("goto", "g_localActor:SetWorldPos({x=%1, y=%2, z=%3})", VF_CHEAT, "Sets current player position.");
m_pConsole->AddCommand("gotoe", "local e=System.GetEntityByName(%1); if (e) then g_localActor:SetWorldPos(e:GetWorldPos()); end", VF_CHEAT, "Sets current player position.");
m_pConsole->AddCommand("freeze", "g_gameRules:SetFrozenAmount(g_localActor,1)", 0, "Freezes player");
m_pConsole->AddCommand("loadactionmap", CmdLoadActionmap, 0, "Loads a key configuration file");
m_pConsole->AddCommand("restartgame", CmdRestartGame, 0, "Restarts Crysis Wars completely.");
m_pConsole->AddCommand("lastinv", CmdLastInv, 0, "Selects last inventory item used.");
m_pConsole->AddCommand("team", CmdTeam, VF_RESTRICTEDMODE, "Sets player team.");
m_pConsole->AddCommand("loadLastSave", CmdLoadLastSave, 0, "Loads the last savegame if available.");
m_pConsole->AddCommand("spectator", CmdSpectator, 0, "Sets the player as a spectator.");
m_pConsole->AddCommand("join_game", CmdJoinGame, VF_RESTRICTEDMODE, "Enter the current ongoing game.");
m_pConsole->AddCommand("kill", CmdKill, VF_RESTRICTEDMODE, "Kills the player.");
m_pConsole->AddCommand("v_kill", CmdVehicleKill, VF_CHEAT, "Kills the players vehicle.");
m_pConsole->AddCommand("sv_restart", CmdRestart, 0, "Restarts the round.");
m_pConsole->AddCommand("sv_say", CmdSay, 0, "Broadcasts a message to all clients.");
m_pConsole->AddCommand("i_reload", CmdReloadItems, 0, "Reloads item scripts.");
m_pConsole->AddCommand("dumpss", CmdDumpSS, 0, "test synched storage.");
m_pConsole->AddCommand("dumpnt", CmdDumpItemNameTable, 0, "Dump ItemString table.");
m_pConsole->AddCommand("g_reloadGameRules", CmdReloadGameRules, 0, "Reload GameRules script");
m_pConsole->AddCommand("g_quickGame", CmdQuickGame, 0, "Quick connect to good server.");
m_pConsole->AddCommand("g_quickGameStop", CmdQuickGameStop, 0, "Cancel quick game search.");
m_pConsole->AddCommand("g_nextlevel", CmdNextLevel,0,"Switch to next level in rotation or restart current one.");
m_pConsole->AddCommand("vote", CmdVote, VF_RESTRICTEDMODE, "Vote on current topic.");
m_pConsole->AddCommand("startKickVoting",CmdStartKickVoting, VF_RESTRICTEDMODE, "Initiate voting.");
m_pConsole->AddCommand("listplayers",CmdListPlayers, VF_RESTRICTEDMODE, "Initiate voting.");
m_pConsole->AddCommand("startNextMapVoting",CmdStartNextMapVoting, VF_RESTRICTEDMODE, "Initiate voting.");
m_pConsole->AddCommand("g_battleDust_reload", CmdBattleDustReload, 0, "Reload the battle dust parameters xml");
m_pConsole->AddCommand("login",CmdLogin, 0, "Log in to GameSpy using nickname and password as arguments");
m_pConsole->AddCommand("login_profile", CmdLoginProfile, 0, "Log in to GameSpy using email, profile and password as arguments");
m_pConsole->AddCommand("register", CmdRegisterNick, VF_CHEAT, "Register nickname with email, nickname and password");
m_pConsole->AddCommand("connect_crynet",CmdCryNetConnect,0,"Connect to online game server");
m_pConsole->AddCommand("preloadforstats","PreloadForStats()",VF_CHEAT,"Preload multiplayer assets for memory statistics.");
m_pConsole->AddCommand("help", CmdHelp, VF_RESTRICTEDMODE, "Information on console commands");
}
//------------------------------------------------------------------------
void CGame::UnregisterConsoleCommands()
{
assert(m_pConsole);
m_pConsole->RemoveCommand("quit");
m_pConsole->RemoveCommand("goto");
m_pConsole->RemoveCommand("freeze");
m_pConsole->RemoveCommand("loadactionmap");
m_pConsole->RemoveCommand("restartgame");
m_pConsole->RemoveCommand("team");
m_pConsole->RemoveCommand("kill");
m_pConsole->RemoveCommand("v_kill");
m_pConsole->RemoveCommand("sv_restart");
m_pConsole->RemoveCommand("sv_say");
m_pConsole->RemoveCommand("i_reload");
m_pConsole->RemoveCommand("dumpss");
m_pConsole->RemoveCommand("g_reloadGameRules");
m_pConsole->RemoveCommand("g_quickGame");
m_pConsole->RemoveCommand("g_quickGameStop");
m_pConsole->RemoveCommand("g_nextlevel");
m_pConsole->RemoveCommand("vote");
m_pConsole->RemoveCommand("startKickVoting");
m_pConsole->RemoveCommand("startNextMapVoting");
m_pConsole->RemoveCommand("listplayers");
m_pConsole->RemoveCommand("g_battleDust_reload");
m_pConsole->RemoveCommand("bulletTimeMode");
m_pConsole->RemoveCommand("GOCMode");
m_pConsole->RemoveCommand("help");
// variables from CHUDCommon
m_pConsole->RemoveCommand("ShowGODMode");
}
//------------------------------------------------------------------------
void CGame::CmdLastInv(IConsoleCmdArgs *pArgs)
{
if (!gEnv->bClient)
return;
if (CActor *pClientActor=static_cast<CActor *>(g_pGame->GetIGameFramework()->GetClientActor()))
pClientActor->SelectLastItem(true);
}
//------------------------------------------------------------------------
void CGame::CmdTeam(IConsoleCmdArgs *pArgs)
{
if (!gEnv->bClient)
return;
IActor *pClientActor=g_pGame->GetIGameFramework()->GetClientActor();
if (!pClientActor)
return;
CGameRules *pGameRules = g_pGame->GetGameRules();
if (pGameRules)
pGameRules->ChangeTeam(pGameRules->GetActorByEntityId(pClientActor->GetEntityId()), pArgs->GetArg(1));
}
//------------------------------------------------------------------------
void CGame::CmdLoadLastSave(IConsoleCmdArgs *pArgs)
{
if (!gEnv->bClient || gEnv->bMultiplayer)
return;
if(g_pGame->GetMenu() && g_pGame->GetMenu()->IsActive())
return;
string* lastSave = NULL;
if(g_pGame->GetMenu())
lastSave = g_pGame->GetMenu()->GetLastInGameSave();
if(lastSave && lastSave->size())
{
if(!g_pGame->GetIGameFramework()->LoadGame(lastSave->c_str(), true))
g_pGame->GetIGameFramework()->LoadGame(g_pGame->GetLastSaveGame().c_str(), false);
}
else
{
const string& file = g_pGame->GetLastSaveGame().c_str();
if(!g_pGame->GetIGameFramework()->LoadGame(file.c_str(), true))
g_pGame->GetIGameFramework()->LoadGame(file.c_str(), false);
}
}
//------------------------------------------------------------------------
void CGame::CmdSpectator(IConsoleCmdArgs *pArgs)
{
if (!gEnv->bClient)
return;
IActor *pClientActor=g_pGame->GetIGameFramework()->GetClientActor();
if (!pClientActor)
return;
CGameRules *pGameRules = g_pGame->GetGameRules();
if (pGameRules)
{
int mode=2;
if (pArgs->GetArgCount()==2)
mode=atoi(pArgs->GetArg(1));
pGameRules->ChangeSpectatorMode(pGameRules->GetActorByEntityId(pClientActor->GetEntityId()), mode, 0, true);
}
}
//------------------------------------------------------------------------
void CGame::CmdJoinGame(IConsoleCmdArgs *pArgs)
{
if (!gEnv->bClient)
return;
IActor *pClientActor=g_pGame->GetIGameFramework()->GetClientActor();
if (!pClientActor)
return;
if (g_pGame->GetGameRules()->GetTeamCount()>0)
return;
CGameRules *pGameRules = g_pGame->GetGameRules();
if (pGameRules)
pGameRules->ChangeSpectatorMode(pGameRules->GetActorByEntityId(pClientActor->GetEntityId()), 0, 0, true);
}
//------------------------------------------------------------------------
void CGame::CmdKill(IConsoleCmdArgs *pArgs)
{
if (!gEnv->bClient)
return;
CActor *pClientActor=static_cast<CActor*>(g_pGame->GetIGameFramework()->GetClientActor());
if (!pClientActor)
return;
pClientActor->Suicide(g_pGameCVars->g_suicideDelay);
}
//------------------------------------------------------------------------
void CGame::CmdVehicleKill(IConsoleCmdArgs *pArgs)
{
if (!gEnv->bClient)
return;
IActor *pClientActor=g_pGame->GetIGameFramework()->GetClientActor();
if (!pClientActor)
return;
IVehicle* pVehicle = pClientActor->GetLinkedVehicle();
if (!pVehicle)
return;
CGameRules *pGameRules = g_pGame->GetGameRules();
if (pGameRules)
{
HitInfo suicideInfo(pVehicle->GetEntityId(), pVehicle->GetEntityId(), pVehicle->GetEntityId(),
-1, 0, 0, -1, 0, pVehicle->GetEntity()->GetWorldPos(), ZERO, ZERO);
suicideInfo.SetDamage(10000);
pGameRules->ClientHit(suicideInfo);
}
}
//------------------------------------------------------------------------
void CGame::CmdRestart(IConsoleCmdArgs *pArgs)
{
if(g_pGame && g_pGame->GetGameRules())
g_pGame->GetGameRules()->Restart();
}
//------------------------------------------------------------------------
void CGame::CmdSay(IConsoleCmdArgs *pArgs)
{
if (pArgs->GetArgCount()>1 && gEnv->bServer && g_pGame->GetGameRules())
{
const char *msg=pArgs->GetCommandLine()+strlen(pArgs->GetArg(0))+1;
g_pGame->GetGameRules()->SendTextMessage(eTextMessageServer, msg, eRMI_ToAllClients);
if (!gEnv->bClient)
CryLogAlways("** Server: %s **", msg);
}
}
//------------------------------------------------------------------------
void CGame::CmdLoadActionmap(IConsoleCmdArgs *pArgs)
{
if(pArgs->GetArg(1))
g_pGame->LoadActionMaps(pArgs->GetArg(1));
}
//------------------------------------------------------------------------
void CGame::CmdRestartGame(IConsoleCmdArgs *pArgs)
{
GetISystem()->Relaunch(true);
GetISystem()->Quit();
}
//------------------------------------------------------------------------
void CGame::CmdReloadItems(IConsoleCmdArgs *pArgs)
{
g_pGame->GetItemSharedParamsList()->Reset();
g_pGame->GetIGameFramework()->GetIItemSystem()->Reload();
g_pGame->GetWeaponSystem()->Reload();
}
//------------------------------------------------------------------------
void CGame::CmdReloadGameRules(IConsoleCmdArgs *pArgs)
{
if (gEnv->bMultiplayer)
return;
IGameRulesSystem* pGameRulesSystem = g_pGame->GetIGameFramework()->GetIGameRulesSystem();
IGameRules* pGameRules = pGameRulesSystem->GetCurrentGameRules();
const char* name = "SinglePlayer";
IEntityClass* pEntityClass = 0;
if (pGameRules)
{
pEntityClass = pGameRules->GetEntity()->GetClass();
name = pEntityClass->GetName();
}
else
pEntityClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
if (pEntityClass)
{
pEntityClass->LoadScript(true);
if (pGameRulesSystem->CreateGameRules(name))
CryLog("reloaded GameRules <%s>", name);
else
GameWarning("reloading GameRules <%s> failed!", name);
}
}
void CGame::CmdNextLevel(IConsoleCmdArgs* pArgs)
{
ILevelRotation *pLevelRotation = g_pGame->GetIGameFramework()->GetILevelSystem()->GetLevelRotation();
if (pLevelRotation->GetLength())
pLevelRotation->ChangeLevel(pArgs);
}
void CGame::CmdStartKickVoting(IConsoleCmdArgs* pArgs)
{
if (!gEnv->bClient)
return;
if (pArgs->GetArgCount() < 2)
{
CryLogAlways("Usage: startKickVoting player_id");
CryLogAlways("Use listplayers to get a list of player ids.");
return;
}
IActor *pClientActor=g_pGame->GetIGameFramework()->GetClientActor();
if (!pClientActor)
return;
if (CGameRules *pGameRules = g_pGame->GetGameRules())
{
if (CActor *pActor=pGameRules->GetActorByChannelId(atoi(pArgs->GetArg(1))))
pGameRules->StartVoting(static_cast<CActor *>(pClientActor), eVS_kick, pActor->GetEntityId(), pActor->GetEntity()->GetName());
}
}
void CGame::CmdStartNextMapVoting(IConsoleCmdArgs* pArgs)
{
IActor *pClientActor=NULL;
if (gEnv->bClient)
pClientActor=g_pGame->GetIGameFramework()->GetClientActor();
if (CGameRules *pGameRules = g_pGame->GetGameRules())
pGameRules->StartVoting(static_cast<CActor *>(pClientActor), eVS_nextMap, 0, "");
}
void CGame::CmdVote(IConsoleCmdArgs* pArgs)
{
if (!gEnv->bClient)
return;
IActor *pClientActor=g_pGame->GetIGameFramework()->GetClientActor();
if (!pClientActor)
return;
if (CGameRules *pGameRules = g_pGame->GetGameRules())
pGameRules->Vote(pGameRules->GetActorByEntityId(pClientActor->GetEntityId()), true);
}
void CGame::CmdListPlayers(IConsoleCmdArgs* pArgs)
{
if (CGameRules *pGameRules = g_pGame->GetGameRules())
{
CGameRules::TPlayers players;
pGameRules->GetPlayers(players);
if (!players.empty())
{
CryLogAlways(" [id] [name]");
for (CGameRules::TPlayers::iterator it=players.begin(); it!=players.end(); ++it)
{
if (CActor *pActor=pGameRules->GetActorByEntityId(*it))
CryLogAlways(" %5d %s", pActor->GetChannelId(), pActor->GetEntity()->GetName());
}
}
}
}
void CGame::CmdQuickGame(IConsoleCmdArgs* pArgs)
{
g_pGame->GetMenu()->GetMPHub()->OnQuickGame();
}
void CGame::CmdQuickGameStop(IConsoleCmdArgs* pArgs)
{
}
void CGame::CmdBattleDustReload(IConsoleCmdArgs* pArgs)
{
if(CBattleDust* pBD = g_pGame->GetGameRules()->GetBattleDust())
{
pBD->ReloadXml();
}
}
static bool GSCheckComplete()
{
INetworkService* serv = gEnv->pNetwork->GetService("GameSpy");
if(!serv)
return true;
return serv->GetState() != eNSS_Initializing;
}
static bool GSLoggingIn()
{
return !g_pGame->GetMenu()->GetMPHub()->IsLoggingIn();
}
void CGame::CmdLogin(IConsoleCmdArgs* pArgs)
{
if(pArgs->GetArgCount()>2)
{
g_pGame->BlockingProcess(&GSCheckComplete);
INetworkService* serv = gEnv->pNetwork->GetService("GameSpy");
if(!serv || serv->GetState() != eNSS_Ok)
return;
if(gEnv->pSystem->IsDedicated())
{
if(INetworkProfile* profile = serv->GetNetworkProfile())
{
profile->Login(pArgs->GetArg(1),pArgs->GetArg(2));
}
}
else
{
if(g_pGame->GetMenu() && g_pGame->GetMenu()->GetMPHub())
{
g_pGame->GetMenu()->GetMPHub()->DoLogin(pArgs->GetArg(1),pArgs->GetArg(2));
g_pGame->BlockingProcess(&GSLoggingIn);
}
}
}
else
GameWarning("Invalid parameters.");
}
static bool GSRegisterNick()
{
INetworkService* serv = gEnv->pNetwork->GetService("GameSpy");
if(!serv)
return true;
INetworkProfile* profile = serv->GetNetworkProfile();
if(!profile)
return true;
return !profile->IsLoggingIn() || profile->IsLoggedIn();
}
void CGame::CmdRegisterNick(IConsoleCmdArgs* pArgs)
{
if(!gEnv->pSystem->IsDedicated())
{
GameWarning("This can be used only on dedicated server.");
return;
}
if(pArgs->GetArgCount()>3)
{
g_pGame->BlockingProcess(&GSCheckComplete);
INetworkService* serv = gEnv->pNetwork->GetService("GameSpy");
if(!serv || serv->GetState() != eNSS_Ok)
return;
if(INetworkProfile* profile = serv->GetNetworkProfile())
{
profile->Register(pArgs->GetArg(1), pArgs->GetArg(2), pArgs->GetArg(3), "", SRegisterDayOfBirth(ZERO));
}
g_pGame->BlockingProcess(&GSRegisterNick);
if(INetworkProfile* profile = serv->GetNetworkProfile())
{
profile->Logoff();
}
}
else
GameWarning("Invalid parameters.");
}
void CGame::CmdLoginProfile(IConsoleCmdArgs* pArgs)
{
if(pArgs->GetArgCount()>3)
{
g_pGame->BlockingProcess(&GSCheckComplete);
INetworkService* serv = gEnv->pNetwork->GetService("GameSpy");
if(!serv || serv->GetState() != eNSS_Ok)
return;
g_pGame->GetMenu()->GetMPHub()->DoLoginProfile(pArgs->GetArg(1),pArgs->GetArg(2),pArgs->GetArg(3));
g_pGame->BlockingProcess(&GSLoggingIn);
}
else
GameWarning("Invalid parameters.");
}
static bool gGSConnecting = false;
struct SCryNetConnectListener : public IServerListener
{
virtual void RemoveServer(const int id){}
virtual void UpdatePing(const int id,const int ping){}
virtual void UpdateValue(const int id,const char* name,const char* value){}
virtual void UpdatePlayerValue(const int id,const int playerNum,const char* name,const char* value){}
virtual void UpdateTeamValue(const int id,const int teamNum,const char *name,const char* value){}
virtual void UpdateComplete(bool cancelled){}
//we only need this thing to connect to server
virtual void OnError(const EServerBrowserError)
{
End(false);
}
virtual void NewServer(const int id,const SBasicServerInfo* info)
{
UpdateServer(id, info);
}
virtual void UpdateServer(const int id,const SBasicServerInfo* info)
{
m_port = info->m_hostPort;
}
virtual void ServerUpdateFailed(const int id)
{
End(false);
}
virtual void ServerUpdateComplete(const int id)
{
m_browser->CheckDirectConnect(id,m_port);
}
virtual void ServerDirectConnect(bool neednat, uint ip, ushort port)
{
string connect;
if(neednat)
{
int cookie = rand() + (rand()<<16);
connect.Format("connect <nat>%d|%d.%d.%d.%d:%d",cookie,ip&0xFF,(ip>>8)&0xFF,(ip>>16)&0xFF,(ip>>24)&0xFF,port);
m_browser->SendNatCookie(ip,port,cookie);
}
else
{
connect.Format("connect %d.%d.%d.%d:%d",ip&0xFF,(ip>>8)&0xFF,(ip>>16)&0xFF,(ip>>24)&0xFF,port);
}
m_browser->Stop();
End(true);
g_pGame->GetIGameFramework()->ExecuteCommandNextFrame(connect.c_str());
}
void End(bool success)
{
if(!success)
CryLog("Server is not responding.");
gGSConnecting = false;
m_browser->Stop();
m_browser->SetListener(0);
delete this;
}
IServerBrowser* m_browser;
ushort m_port;
};
static bool GSConnect()
{
return !gGSConnecting;
}
void CGame::CmdCryNetConnect(IConsoleCmdArgs* pArgs)
{
ushort port = SERVER_DEFAULT_PORT;
if(pArgs->GetArgCount()>2)
port = atoi(pArgs->GetArg(2));
else
{
ICVar* pv = GetISystem()->GetIConsole()->GetCVar("cl_serverport");
if(pv)
port = pv->GetIVal();
}
if(pArgs->GetArgCount()>1)
{
g_pGame->BlockingProcess(&GSCheckComplete);
INetworkService* serv = gEnv->pNetwork->GetService("GameSpy");
if(!serv || serv->GetState() != eNSS_Ok)
return;
IServerBrowser* sb = serv->GetServerBrowser();
SCryNetConnectListener* lst = new SCryNetConnectListener();
lst->m_browser = sb;
sb->SetListener(lst);
sb->Start(false);
sb->BrowseForServer(pArgs->GetArg(1),port);
gGSConnecting = true;
g_pGame->BlockingProcess(&GSConnect);
}
else
GameWarning("Invalid parameters.");
}
void SCVars::RestrictedItemsChanged(ICVar* var)
{
// pass new restricted item string to game rules
CGameRules* pGameRules = g_pGame->GetGameRules();
if(pGameRules && var && gEnv->bMultiplayer)
{
pGameRules->CreateRestrictedItemList(var->GetString());
}
} | [
"[email protected]"
] | |
bd262f603f877477dea99b1d46db3d4cdc2f8ed6 | 33b6d591ffa7e066f2e361ef4cba94731bcfcec3 | /nocode/design_pattern/LuaForVisualCPlusPlus/lua515/lua_tinker/lua_tinker.h | 0d347476cc9ade55a9a72e4f57a95dd4eece958a | [
"LicenseRef-scancode-other-permissive"
] | permissive | projectDaemon/nocode | c0a8f7d6b5f15127fcc7ffcd25e7883d70b0be85 | 972bf19f57ae034a6dba2e432e409484ecc665a8 | refs/heads/master | 2021-01-24T12:12:01.522986 | 2018-02-26T17:37:32 | 2018-02-26T17:37:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,732 | h | // lua_tinker.h
//
// LuaTinker - Simple and light C++ wrapper for Lua.
//
// Copyright (c) 2005-2007 Kwon-il Lee ([email protected])
//
// please check Licence.txt file for licence and legal issues.
#if !defined(_LUA_TINKER_H_)
#define _LUA_TINKER_H_
#include <new>
extern "C"
{
#include "../lua515/src/lua.h"
#include "../lua515/src/lualib.h"
#include "../lua515/src/lauxlib.h"
};
namespace lua_tinker
{
// init LuaTinker
void init(lua_State *L);
void init_s64(lua_State *L);
void init_u64(lua_State *L);
// excution
void dofile(lua_State *L, const char *filename);
void dostring(lua_State *L, const char* buff);
void dobuffer(lua_State *L, const char* buff, size_t sz);
// debug helpers
void enum_stack(lua_State *L);
int on_error(lua_State *L);
void print_error(lua_State *L, const char* fmt, ...);
// dynamic type extention
struct lua_value
{
virtual void to_lua(lua_State *L) = 0;
};
// type trait
template<typename T> struct class_name;
struct table;
template<bool C, typename A, typename B> struct if_ {};
template<typename A, typename B> struct if_<true, A, B> { typedef A type; };
template<typename A, typename B> struct if_<false, A, B> { typedef B type; };
template<typename A>
struct is_ptr { static const bool value = false; };
template<typename A>
struct is_ptr<A*> { static const bool value = true; };
template<typename A>
struct is_ref { static const bool value = false; };
template<typename A>
struct is_ref<A&> { static const bool value = true; };
template<typename A>
struct remove_const { typedef A type; };
template<typename A>
struct remove_const<const A> { typedef A type; };
template<typename A>
struct base_type { typedef A type; };
template<typename A>
struct base_type<A*> { typedef A type; };
template<typename A>
struct base_type<A&> { typedef A type; };
template<typename A>
struct class_type { typedef typename remove_const<typename base_type<A>::type>::type type; };
/////////////////////////////////
enum { no = 1, yes = 2 };
typedef char (& no_type )[no];
typedef char (& yes_type)[yes];
struct int_conv_type { int_conv_type(int); };
no_type int_conv_tester (...);
yes_type int_conv_tester (int_conv_type);
no_type vfnd_ptr_tester (const volatile char *);
no_type vfnd_ptr_tester (const volatile short *);
no_type vfnd_ptr_tester (const volatile int *);
no_type vfnd_ptr_tester (const volatile long *);
no_type vfnd_ptr_tester (const volatile double *);
no_type vfnd_ptr_tester (const volatile float *);
no_type vfnd_ptr_tester (const volatile bool *);
yes_type vfnd_ptr_tester (const volatile void *);
template <typename T> T* add_ptr(T&);
template <bool C> struct bool_to_yesno { typedef no_type type; };
template <> struct bool_to_yesno<true> { typedef yes_type type; };
template <typename T>
struct is_enum
{
static T arg;
static const bool value = ( (sizeof(int_conv_tester(arg)) == sizeof(yes_type)) && (sizeof(vfnd_ptr_tester(add_ptr(arg))) == sizeof(yes_type)) );
};
/////////////////////////////////
// from lua
template<typename T>
struct void2val { static T invoke(void* input){ return *(T*)input; } };
template<typename T>
struct void2ptr { static T* invoke(void* input){ return (T*)input; } };
template<typename T>
struct void2ref { static T& invoke(void* input){ return *(T*)input; } };
template<typename T>
struct void2type
{
static T invoke(void* ptr)
{
return if_<is_ptr<T>::value
,void2ptr<base_type<T>::type>
,if_<is_ref<T>::value
,void2ref<base_type<T>::type>
,void2val<base_type<T>::type>
>::type
>::type::invoke(ptr);
}
};
template<typename T>
struct user2type { static T invoke(lua_State *L, int index) { return void2type<T>::invoke(lua_touserdata(L, index)); } };
template<typename T>
struct lua2enum { static T invoke(lua_State *L, int index) { return (T)(int)lua_tonumber(L, index); } };
template<typename T>
struct lua2object
{
static T invoke(lua_State *L, int index)
{
if(!lua_isuserdata(L,index))
{
lua_pushstring(L, "no class at first argument. (forgot ':' expression ?)");
lua_error(L);
}
return void2type<T>::invoke(user2type<user*>::invoke(L,index)->m_p);
}
};
template<typename T>
T lua2type(lua_State *L, int index)
{
return if_<is_enum<T>::value
,lua2enum<T>
,lua2object<T>
>::type::invoke(L, index);
}
struct user
{
user(void* p) : m_p(p) {}
virtual ~user() {}
void* m_p;
};
template<typename T>
struct val2user : user
{
val2user() : user(new T) {}
template<typename T1>
val2user(T1 t1) : user(new T(t1)) {}
template<typename T1, typename T2>
val2user(T1 t1, T2 t2) : user(new T(t1, t2)) {}
template<typename T1, typename T2, typename T3>
val2user(T1 t1, T2 t2, T3 t3) : user(new T(t1, t2, t3)) {}
~val2user() { delete ((T*)m_p); }
};
template<typename T>
struct ptr2user : user
{
ptr2user(T* t) : user((void*)t) {}
};
template<typename T>
struct ref2user : user
{
ref2user(T& t) : user(&t) {}
};
// to lua
template<typename T>
struct val2lua { static void invoke(lua_State *L, T& input){ new(lua_newuserdata(L, sizeof(val2user<T>))) val2user<T>(input); } };
template<typename T>
struct ptr2lua { static void invoke(lua_State *L, T* input){ if(input) new(lua_newuserdata(L, sizeof(ptr2user<T>))) ptr2user<T>(input); else lua_pushnil(L); } };
template<typename T>
struct ref2lua { static void invoke(lua_State *L, T& input){ new(lua_newuserdata(L, sizeof(ref2user<T>))) ref2user<T>(input); } };
template<typename T>
struct enum2lua { static void invoke(lua_State *L, T val) { lua_pushnumber(L, (int)val); } };
template<typename T>
struct object2lua
{
static void invoke(lua_State *L, T val)
{
if_<is_ptr<T>::value
,ptr2lua<base_type<T>::type>
,if_<is_ref<T>::value
,ref2lua<base_type<T>::type>
,val2lua<base_type<T>::type>
>::type
>::type::invoke(L, val);
meta_push(L, class_name<class_type<T>::type>::name());
lua_setmetatable(L, -2);
}
};
template<typename T>
void type2lua(lua_State *L, T val)
{
if_<is_enum<T>::value
,enum2lua<T>
,object2lua<T>
>::type::invoke(L, val);
}
// get value from cclosure
template<typename T>
T upvalue_(lua_State *L)
{
return user2type<T>::invoke(L, lua_upvalueindex(1));
}
// read a value from lua stack
template<typename T>
T read(lua_State *L, int index) { return lua2type<T>(L, index); }
template<> char* read(lua_State *L, int index);
template<> const char* read(lua_State *L, int index);
template<> char read(lua_State *L, int index);
template<> unsigned char read(lua_State *L, int index);
template<> short read(lua_State *L, int index);
template<> unsigned short read(lua_State *L, int index);
template<> long read(lua_State *L, int index);
template<> unsigned long read(lua_State *L, int index);
template<> int read(lua_State *L, int index);
template<> unsigned int read(lua_State *L, int index);
template<> float read(lua_State *L, int index);
template<> double read(lua_State *L, int index);
template<> bool read(lua_State *L, int index);
template<> void read(lua_State *L, int index);
template<> __int64 read(lua_State *L, int index);
template<> unsigned __int64 read(lua_State *L, int index);
template<> table read(lua_State *L, int index);
// push a value to lua stack
template<typename T>
void push(lua_State *L, T ret) { type2lua<T>(L, ret); }
template<> void push(lua_State *L, char ret);
template<> void push(lua_State *L, unsigned char ret);
template<> void push(lua_State *L, short ret);
template<> void push(lua_State *L, unsigned short ret);
template<> void push(lua_State *L, long ret);
template<> void push(lua_State *L, unsigned long ret);
template<> void push(lua_State *L, int ret);
template<> void push(lua_State *L, unsigned int ret);
template<> void push(lua_State *L, float ret);
template<> void push(lua_State *L, double ret);
template<> void push(lua_State *L, char* ret);
template<> void push(lua_State *L, const char* ret);
template<> void push(lua_State *L, bool ret);
template<> void push(lua_State *L, lua_value* ret);
template<> void push(lua_State *L, __int64 ret);
template<> void push(lua_State *L, unsigned __int64 ret);
template<> void push(lua_State *L, table ret);
// pop a value from lua stack
template<typename T>
T pop(lua_State *L) { T t = read<T>(L, -1); lua_pop(L, 1); return t; }
template<> void pop(lua_State *L);
template<> table pop(lua_State *L);
// functor
template<typename T1=void, typename T2=void, typename T3=void, typename T4=void, typename T5=void>
struct functor
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,upvalue_<RVal(*)(T1,T2,T3,T4,T5)>(L)(read<T1>(L,1),read<T2>(L,2),read<T3>(L,3),read<T4>(L,4),read<T5>(L,5))); return 1; }
template<>
static int invoke<void>(lua_State *L) { upvalue_<void(*)(T1,T2,T3,T4,T5)>(L)(read<T1>(L,1),read<T2>(L,2),read<T3>(L,3),read<T4>(L,4),read<T5>(L,5)); return 0; }
};
template<typename T1, typename T2, typename T3, typename T4>
struct functor<T1,T2,T3,T4>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,upvalue_<RVal(*)(T1,T2,T3,T4)>(L)(read<T1>(L,1),read<T2>(L,2),read<T3>(L,3),read<T4>(L,4))); return 1; }
template<>
static int invoke<void>(lua_State *L) { upvalue_<void(*)(T1,T2,T3,T4)>(L)(read<T1>(L,1),read<T2>(L,2),read<T3>(L,3),read<T4>(L,4)); return 0; }
};
template<typename T1, typename T2, typename T3>
struct functor<T1,T2,T3>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,upvalue_<RVal(*)(T1,T2,T3)>(L)(read<T1>(L,1),read<T2>(L,2),read<T3>(L,3))); return 1; }
template<>
static int invoke<void>(lua_State *L) { upvalue_<void(*)(T1,T2,T3)>(L)(read<T1>(L,1),read<T2>(L,2),read<T3>(L,3)); return 0; }
};
template<typename T1, typename T2>
struct functor<T1,T2>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,upvalue_<RVal(*)(T1,T2)>(L)(read<T1>(L,1),read<T2>(L,2))); return 1; }
template<>
static int invoke<void>(lua_State *L) { upvalue_<void(*)(T1,T2)>(L)(read<T1>(L,1),read<T2>(L,2)); return 0; }
};
template<typename T1>
struct functor<T1>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,upvalue_<RVal(*)(T1)>(L)(read<T1>(L,1))); return 1; }
template<>
static int invoke<void>(lua_State *L) { upvalue_<void(*)(T1)>(L)(read<T1>(L,1)); return 0; }
};
template<>
struct functor<>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,upvalue_<RVal(*)()>(L)()); return 1; }
template<>
static int invoke<void>(lua_State *L) { upvalue_<void(*)()>(L)(); return 0; }
};
// push_functor
template<typename RVal>
void push_functor(lua_State *L, RVal (*func)())
{
lua_pushcclosure(L, functor<>::invoke<RVal>, 1);
}
template<typename RVal, typename T1>
void push_functor(lua_State *L, RVal (*func)(T1))
{
lua_pushcclosure(L, functor<T1>::invoke<RVal>, 1);
}
template<typename RVal, typename T1, typename T2>
void push_functor(lua_State *L, RVal (*func)(T1,T2))
{
lua_pushcclosure(L, functor<T1,T2>::invoke<RVal>, 1);
}
template<typename RVal, typename T1, typename T2, typename T3>
void push_functor(lua_State *L, RVal (*func)(T1,T2,T3))
{
lua_pushcclosure(L, functor<T1,T2,T3>::invoke<RVal>, 1);
}
template<typename RVal, typename T1, typename T2, typename T3, typename T4>
void push_functor(lua_State *L, RVal (*func)(T1,T2,T3,T4))
{
lua_pushcclosure(L, functor<T1,T2,T3,T4>::invoke<RVal>, 1);
}
template<typename RVal, typename T1, typename T2, typename T3, typename T4, typename T5>
void push_functor(lua_State *L, RVal (*func)(T1,T2,T3,T4,T5))
{
lua_pushcclosure(L, functor<T1,T2,T3,T4,T5>::invoke<RVal>, 1);
}
// member variable
struct var_base
{
virtual void get(lua_State *L) = 0;
virtual void set(lua_State *L) = 0;
};
template<typename T, typename V>
struct mem_var : var_base
{
V T::*_var;
mem_var(V T::*val) : _var(val) {}
void get(lua_State *L) { push(L, read<T*>(L,1)->*(_var)); }
void set(lua_State *L) { read<T*>(L,1)->*(_var) = read<V>(L, 3); }
};
// member function
template<typename T, typename T1=void, typename T2=void, typename T3=void, typename T4=void, typename T5=void>
struct mem_functor
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,(read<T*>(L,1)->*upvalue_<RVal(T::*)(T1,T2,T3,T4,T5)>(L))(read<T1>(L,2),read<T2>(L,3),read<T3>(L,4),read<T4>(L,5),read<T5>(L,6)));; return 1; }
template<>
static int invoke<void>(lua_State *L) { (read<T*>(L,1)->*upvalue_<void(T::*)(T1,T2,T3,T4,T5)>(L))(read<T1>(L,2),read<T2>(L,3),read<T3>(L,4),read<T4>(L,5),read<T5>(L,6)); return 0; }
};
template<typename T, typename T1, typename T2, typename T3, typename T4>
struct mem_functor<T,T1,T2,T3,T4>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,(read<T*>(L,1)->*upvalue_<RVal(T::*)(T1,T2,T3,T4)>(L))(read<T1>(L,2),read<T2>(L,3),read<T3>(L,4),read<T4>(L,5))); return 1; }
template<>
static int invoke<void>(lua_State *L) { (read<T*>(L,1)->*upvalue_<void(T::*)(T1,T2,T3,T4)>(L))(read<T1>(L,2),read<T2>(L,3),read<T3>(L,4),read<T4>(L,5)); return 0; }
};
template<typename T, typename T1, typename T2, typename T3>
struct mem_functor<T,T1,T2,T3>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,(read<T*>(L,1)->*upvalue_<RVal(T::*)(T1,T2,T3)>(L))(read<T1>(L,2),read<T2>(L,3),read<T3>(L,4))); return 1; }
template<>
static int invoke<void>(lua_State *L) { (read<T*>(L,1)->*upvalue_<void(T::*)(T1,T2,T3)>(L))(read<T1>(L,2),read<T2>(L,3),read<T3>(L,4)); return 0; }
};
template<typename T, typename T1, typename T2>
struct mem_functor<T,T1, T2>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,(read<T*>(L,1)->*upvalue_<RVal(T::*)(T1,T2)>(L))(read<T1>(L,2),read<T2>(L,3))); return 1; }
template<>
static int invoke<void>(lua_State *L) { (read<T*>(L,1)->*upvalue_<void(T::*)(T1,T2)>(L))(read<T1>(L,2),read<T2>(L,3)); return 0; }
};
template<typename T, typename T1>
struct mem_functor<T,T1>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,(read<T*>(L,1)->*upvalue_<RVal(T::*)(T1)>(L))(read<T1>(L,2))); return 1; }
template<>
static int invoke<void>(lua_State *L) { (read<T*>(L,1)->*upvalue_<void(T::*)(T1)>(L))(read<T1>(L,2)); return 0; }
};
template<typename T>
struct mem_functor<T>
{
template<typename RVal>
static int invoke(lua_State *L) { push(L,(read<T*>(L,1)->*upvalue_<RVal(T::*)()>(L))()); return 1; }
template<>
static int invoke<void>(lua_State *L) { (read<T*>(L,1)->*upvalue_<void(T::*)()>(L))(); return 0; }
};
// push_functor
template<typename RVal, typename T>
void push_functor(lua_State *L, RVal (T::*func)())
{
lua_pushcclosure(L, mem_functor<T>::invoke<RVal>, 1);
}
template<typename RVal, typename T>
void push_functor(lua_State *L, RVal (T::*func)() const)
{
lua_pushcclosure(L, mem_functor<T>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1>
void push_functor(lua_State *L, RVal (T::*func)(T1))
{
lua_pushcclosure(L, mem_functor<T,T1>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1>
void push_functor(lua_State *L, RVal (T::*func)(T1) const)
{
lua_pushcclosure(L, mem_functor<T,T1>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2))
{
lua_pushcclosure(L, mem_functor<T,T1,T2>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2) const)
{
lua_pushcclosure(L, mem_functor<T,T1,T2>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2, typename T3>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2,T3))
{
lua_pushcclosure(L, mem_functor<T,T1,T2,T3>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2, typename T3>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2,T3) const)
{
lua_pushcclosure(L, mem_functor<T,T1,T2,T3>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2, typename T3, typename T4>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2,T3,T4))
{
lua_pushcclosure(L, mem_functor<T,T1,T2,T3,T4>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2, typename T3, typename T4>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2,T3,T4) const)
{
lua_pushcclosure(L, mem_functor<T,T1,T2,T3,T4>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2, typename T3, typename T4, typename T5>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2,T3,T4,T5))
{
lua_pushcclosure(L, mem_functor<T,T1,T2,T3,T4,T5>::invoke<RVal>, 1);
}
template<typename RVal, typename T, typename T1, typename T2, typename T3, typename T4, typename T5>
void push_functor(lua_State *L, RVal (T::*func)(T1,T2,T3,T4,T5) const)
{
lua_pushcclosure(L, mem_functor<T,T1,T2,T3,T4,T5>::invoke<RVal>, 1);
}
// constructor
template<typename T1=void, typename T2=void, typename T3=void, typename T4=void>
struct constructor {};
template<typename T1, typename T2, typename T3>
struct constructor<T1,T2,T3>
{
template<typename T>
static void invoke(lua_State *L)
{
new(lua_newuserdata(L, sizeof(val2user<T>))) val2user<T>(read<T1>(L,2),read<T2>(L,3),read<T3>(L,4));
}
};
template<typename T1, typename T2>
struct constructor<T1,T2>
{
template<typename T>
static void invoke(lua_State *L)
{
new(lua_newuserdata(L, sizeof(val2user<T>))) val2user<T>(read<T1>(L,2),read<T2>(L,3));
}
};
template<typename T1>
struct constructor<T1>
{
template<typename T>
static void invoke(lua_State *L)
{
new(lua_newuserdata(L, sizeof(val2user<T>))) val2user<T>(read<T1>(L,2));
}
};
template<>
struct constructor<void>
{
template<typename T>
static void invoke(lua_State *L)
{
new(lua_newuserdata(L, sizeof(val2user<T>))) val2user<T>();
}
};
template<typename T>
struct creator
{
template<typename CONSTRUCTOR>
static int invoke(lua_State *L)
{
CONSTRUCTOR::invoke<T>(L);
meta_push(L, class_name<class_type<T>::type>::name());
lua_setmetatable(L, -2);
return 1;
}
};
// destroyer
template<typename T>
int destroyer(lua_State *L)
{
((user*)lua_touserdata(L, 1))->~user();
return 0;
}
// global function
template<typename F>
void def(lua_State* L, const char* name, F func)
{
lua_pushstring(L, name);
lua_pushlightuserdata(L, func);
push_functor(L, func);
lua_settable(L, LUA_GLOBALSINDEX);
}
// global variable
template<typename T>
void set(lua_State* L, const char* name, T object)
{
lua_pushstring(L, name);
push(L, object);
lua_settable(L, LUA_GLOBALSINDEX);
}
template<typename T>
T get(lua_State* L, const char* name)
{
lua_pushstring(L, name);
lua_gettable(L, LUA_GLOBALSINDEX);
return pop<T>(L);
}
template<typename T>
void decl(lua_State* L, const char* name, T object)
{
set(L, name, object);
}
// call
template<typename RVal>
RVal call(lua_State* L, const char* name)
{
lua_pushcclosure(L, on_error, 0);
int errfunc = lua_gettop(L);
lua_pushstring(L, name);
lua_gettable(L, LUA_GLOBALSINDEX);
if(lua_isfunction(L,-1))
{
if(lua_pcall(L, 0, 1, errfunc) != 0)
{
lua_pop(L, 1);
}
}
else
{
print_error(L, "lua_tinker::call() attempt to call global `%s' (not a function)", name);
}
lua_remove(L, -2);
return pop<RVal>(L);
}
template<typename RVal, typename T1>
RVal call(lua_State* L, const char* name, T1 arg)
{
lua_pushcclosure(L, on_error, 0);
int errfunc = lua_gettop(L);
lua_pushstring(L, name);
lua_gettable(L, LUA_GLOBALSINDEX);
if(lua_isfunction(L,-1))
{
push(L, arg);
if(lua_pcall(L, 1, 1, errfunc) != 0)
{
lua_pop(L, 1);
}
}
else
{
print_error(L, "lua_tinker::call() attempt to call global `%s' (not a function)", name);
}
lua_remove(L, -2);
return pop<RVal>(L);
}
template<typename RVal, typename T1, typename T2>
RVal call(lua_State* L, const char* name, T1 arg1, T2 arg2)
{
lua_pushcclosure(L, on_error, 0);
int errfunc = lua_gettop(L);
lua_pushstring(L, name);
lua_gettable(L, LUA_GLOBALSINDEX);
if(lua_isfunction(L,-1))
{
push(L, arg1);
push(L, arg2);
if(lua_pcall(L, 2, 1, errfunc) != 0)
{
lua_pop(L, 1);
}
}
else
{
print_error(L, "lua_tinker::call() attempt to call global `%s' (not a function)", name);
}
lua_remove(L, -2);
return pop<RVal>(L);
}
template<typename RVal, typename T1, typename T2, typename T3>
RVal call(lua_State* L, const char* name, T1 arg1, T2 arg2, T3 arg3)
{
lua_pushcclosure(L, on_error, 0);
int errfunc = lua_gettop(L);
lua_pushstring(L, name);
lua_gettable(L, LUA_GLOBALSINDEX);
if(lua_isfunction(L,-1))
{
push(L, arg1);
push(L, arg2);
push(L, arg3);
if(lua_pcall(L, 3, 1, errfunc) != 0)
{
lua_pop(L, 1);
}
}
else
{
print_error(L, "lua_tinker::call() attempt to call global `%s' (not a function)", name);
}
lua_remove(L, -2);
return pop<RVal>(L);
}
// class helper
int meta_get(lua_State *L);
int meta_set(lua_State *L);
void meta_push(lua_State *L, const char* name);
// class init
template<typename T>
void class_add(lua_State* L, const char* name)
{
class_name<T>::name(name);
lua_pushstring(L, name);
lua_newtable(L);
lua_pushstring(L, "__name");
lua_pushstring(L, name);
lua_rawset(L, -3);
lua_pushstring(L, "__index");
lua_pushcclosure(L, meta_get, 0);
lua_rawset(L, -3);
lua_pushstring(L, "__newindex");
lua_pushcclosure(L, meta_set, 0);
lua_rawset(L, -3);
lua_pushstring(L, "__gc");
lua_pushcclosure(L, destroyer<T>, 0);
lua_rawset(L, -3);
lua_settable(L, LUA_GLOBALSINDEX);
}
// Tinker Class Inheritence
template<typename T, typename P>
void class_inh(lua_State* L)
{
meta_push(L, class_name<T>::name());
if(lua_istable(L, -1))
{
lua_pushstring(L, "__parent");
meta_push(L, class_name<P>::name());
lua_rawset(L, -3);
}
lua_pop(L, 1);
}
// Tinker Class Constructor
template<typename T, typename CONSTRUCTOR>
void class_con(lua_State* L, CONSTRUCTOR)
{
meta_push(L, class_name<T>::name());
if(lua_istable(L, -1))
{
lua_newtable(L);
lua_pushstring(L, "__call");
lua_pushcclosure(L, creator<T>::invoke<CONSTRUCTOR>, 0);
lua_rawset(L, -3);
lua_setmetatable(L, -2);
}
lua_pop(L, 1);
}
// Tinker Class Functions
template<typename T, typename F>
void class_def(lua_State* L, const char* name, F func)
{
meta_push(L, class_name<T>::name());
if(lua_istable(L, -1))
{
lua_pushstring(L, name);
new(lua_newuserdata(L,sizeof(F))) F(func);
push_functor(L, func);
lua_rawset(L, -3);
}
lua_pop(L, 1);
}
// Tinker Class Variables
template<typename T, typename BASE, typename VAR>
void class_mem(lua_State* L, const char* name, VAR BASE::*val)
{
meta_push(L, class_name<T>::name());
if(lua_istable(L, -1))
{
lua_pushstring(L, name);
new(lua_newuserdata(L,sizeof(mem_var<BASE,VAR>))) mem_var<BASE,VAR>(val);
lua_rawset(L, -3);
}
lua_pop(L, 1);
}
template<typename T>
struct class_name
{
// global name
static const char* name(const char* name = NULL)
{
static char temp[256] = "";
if(name) strcpy(temp, name);
return temp;
}
};
// Table Object on Stack
struct table_obj
{
table_obj(lua_State* L, int index);
~table_obj();
void inc_ref();
void dec_ref();
bool validate();
template<typename T>
void set(const char* name, T object)
{
if(validate())
{
lua_pushstring(m_L, name);
push(m_L, object);
lua_settable(m_L, m_index);
}
}
template<typename T>
T get(const char* name)
{
if(validate())
{
lua_pushstring(m_L, name);
lua_gettable(m_L, m_index);
}
else
{
lua_pushnil(m_L);
}
return pop<T>(m_L);
}
lua_State* m_L;
int m_index;
const void* m_pointer;
int m_ref;
};
// Table Object Holder
struct table
{
table(lua_State* L);
table(lua_State* L, int index);
table(lua_State* L, const char* name);
table(const table& input);
~table();
template<typename T>
void set(const char* name, T object)
{
m_obj->set(name, object);
}
template<typename T>
T get(const char* name)
{
return m_obj->get<T>(name);
}
table_obj* m_obj;
};
} // namespace lua_tinker
#endif //_LUA_TINKER_H_ | [
"[email protected]"
] | |
b1b219e8a8596060c714b819cf3b3732778d62f3 | 027ad99a3fa9231dd96dd610fdbebd26f9fd02db | /Projects/manager_CameraLinkVis/camera_linkvis_manager.cxx | 4621a98cd857c45640b685ce471120679b9081ac | [
"BSD-3-Clause"
] | permissive | droidoid/MoPlugs | ee5b6162a3a504d43d8a62ab221cfe72317afe25 | fce52e6469408e32e94af8ac8a303840bc956e53 | refs/heads/master | 2020-12-19T04:26:07.530778 | 2019-08-07T22:05:07 | 2019-08-07T22:05:07 | 235,619,955 | 1 | 0 | BSD-3-Clause | 2020-01-22T16:54:13 | 2020-01-22T16:54:12 | null | UTF-8 | C++ | false | false | 6,904 | cxx |
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// file: camera_linkvis_manager.cpp
//
// Author Sergey Solokhin (Neill3d)
//
//
// GitHub page - https://github.com/Neill3d/MoPlugs
// Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//--- Class declaration
#include "camera_linkvis_manager.h"
//--- Registration defines
#define CAMERA_LINKVIS__CLASS CAMERA_LINKVIS__CLASSNAME
#define CAMERA_LINKVIS__NAME CAMERA_LINKVIS__CLASSSTR
//--- FiLMBOX implementation and registration
FBCustomManagerImplementation( CAMERA_LINKVIS__CLASS ); // Manager class name.
FBRegisterCustomManager( CAMERA_LINKVIS__CLASS ); // Manager class name.
/************************************************
* FiLMBOX Creation
************************************************/
bool Manager_CameraLinkVis::FBCreate()
{
mLastCamera = nullptr;
return true;
}
/************************************************
* FiLMBOX Destruction.
************************************************/
void Manager_CameraLinkVis::FBDestroy()
{
// Free any user memory here.
}
/************************************************
* Execution callback.
************************************************/
bool Manager_CameraLinkVis::Init()
{
return true;
}
bool Manager_CameraLinkVis::Open()
{
//mSystem.OnConnectionNotify.Add(this, (FBCallback)&Manager_CameraLinkVis::EventConnDataNotify);
//mSystem.OnConnectionDataNotify.Add(this, (FBCallback)&Manager_CameraLinkVis::EventConnDataNotify);
//mSystem.OnUIIdle.Add(this, (FBCallback)&Manager_CameraLinkVis::EventUIIdle);
//mSystem.OnVideoFrameRendering.Add(this, (FBCallback) &Manager_CameraLinkVis::EventUIIdle);
mSystem.Scene->OnChange.Add(this, (FBCallback) &Manager_CameraLinkVis::EventSceneChange);
FBEvaluateManager::TheOne().OnRenderingPipelineEvent.Add(this, (FBCallback) &Manager_CameraLinkVis::EventRender);
//FBEvaluateManager::TheOne().OnEvaluationPipelineEvent.Add(this, (FBCallback) &Manager_CameraLinkVis::EventRender);
return true;
}
bool Manager_CameraLinkVis::Clear()
{
return true;
}
bool Manager_CameraLinkVis::Close()
{
//mSystem.OnConnectionNotify.Remove(this, (FBCallback)&Manager_CameraLinkVis::EventConnDataNotify);
//mSystem.OnConnectionDataNotify.Remove(this, (FBCallback)&Manager_CameraLinkVis::EventConnDataNotify);
//mSystem.OnUIIdle.Remove(this, (FBCallback)&Manager_CameraLinkVis::EventUIIdle);
//mSystem.OnVideoFrameRendering.Remove(this, (FBCallback) &Manager_CameraLinkVis::EventUIIdle);
mSystem.Scene->OnChange.Remove(this, (FBCallback) &Manager_CameraLinkVis::EventSceneChange);
FBEvaluateManager::TheOne().OnRenderingPipelineEvent.Remove(this, (FBCallback) &Manager_CameraLinkVis::EventRender);
//FBEvaluateManager::TheOne().OnEvaluationPipelineEvent.Remove(this, (FBCallback) &Manager_CameraLinkVis::EventRender);
return true;
}
void Manager_CameraLinkVis::EventConnDataNotify(HISender pSender, HKEvent pEvent)
{
FBEventConnectionDataNotify lEvent(pEvent);
FBPlug* lPlug;
if( lEvent.Plug )
{
if ( FBIS(lEvent.Plug, FBCamera) )
{
lPlug = lEvent.Plug;
FBCamera *pCamera = (FBCamera*) lPlug;
FBString cameraName ( pCamera->Name );
printf( "camera name - %s\n", cameraName );
}
}
}
void Manager_CameraLinkVis::EventConnNotify(HISender pSender, HKEvent pEvent)
{
FBEventConnectionNotify lEvent(pEvent);
FBPlug* lPlug;
if( lEvent.SrcPlug )
{
if ( FBIS(lEvent.SrcPlug, FBCamera) )
{
FBString cameraName( ( (FBCamera*)(FBPlug*)lEvent.SrcPlug )->Name );
printf( "camera name - %s\n", cameraName );
}
}
}
void Manager_CameraLinkVis::EventRender(HISender pSender, HKEvent pEvent)
{
FBEventEvalGlobalCallback levent(pEvent);
if (levent.GetTiming() == kFBGlobalEvalCallbackBeforeRender) // kFBGlobalEvalCallbackBeforeDAG
{
EventUIIdle(nullptr, nullptr);
}
}
void Manager_CameraLinkVis::EventUIIdle(HISender pSender, HKEvent pEvent)
{
FBCamera *pCamera = mSystem.Scene->Renderer->CurrentCamera;
if (FBIS(pCamera, FBCameraSwitcher))
pCamera = ( (FBCameraSwitcher*) pCamera)->CurrentCamera;
if (pCamera != mLastCamera)
{
// DONE: change camera
//printf( "change\n" );
// leave all cameras groups
FBScene *pScene = mSystem.Scene;
for (int i=0; i<pScene->Cameras.GetCount(); ++i)
{
FBCamera *iCam = (FBCamera*) pScene->Cameras[i];
if (iCam->SystemCamera == false)
LeaveCamera(iCam);
}
// enter one current
EnterCamera(pCamera);
}
mLastCamera = pCamera;
}
bool GroupVis(const char *groupName, const bool show)
{
FBScene *pScene = FBSystem::TheOne().Scene;
for (int i=0; i<pScene->Groups.GetCount(); ++i)
{
if ( strcmp( pScene->Groups[i]->Name, groupName ) == 0 )
{
pScene->Groups[i]->Show = show;
FBGroup *pGroup = pScene->Groups[i];
for (int j=0, count=pGroup->Items.GetCount(); j<count; ++j)
{
FBComponent *pcomp = pGroup->Items[j];
if (FBIS(pcomp, FBModel))
{
( (FBModel*) pcomp)->Show = show;
}
}
return true;
}
}
return false;
}
void Manager_CameraLinkVis::LeaveCamera(FBCamera *pCamera)
{
if (pCamera == nullptr) return;
FBProperty *pProp = pCamera->PropertyList.Find( "LinkedGroup" );
if (pProp)
{
const char *groupName = pProp->AsString();
GroupVis( groupName, false );
}
}
void Manager_CameraLinkVis::EnterCamera(FBCamera *pCamera)
{
if (pCamera == nullptr) return;
FBProperty *pProp = pCamera->PropertyList.Find( "LinkedGroup" );
if (pProp)
{
const char *groupName = pProp->AsString();
GroupVis( groupName, true );
}
}
static FBGroup *gGroup = nullptr;
static FBCamera *gCamera = nullptr;
FBCamera *FindCameraByGroup(const char *groupName)
{
FBScene *pScene = FBSystem::TheOne().Scene;
for (int i=0; i<pScene->Cameras.GetCount(); ++i)
{
FBCamera *pCamera = (FBCamera*) pScene->Cameras[i];
if (pCamera->SystemCamera == false)
{
FBProperty *lProp = pCamera->PropertyList.Find( "LinkedGroup" );
if (lProp)
{
const char *lname = lProp->AsString();
if ( strcmp( lname, groupName ) == 0 )
{
return pCamera;
}
}
}
}
return nullptr;
}
void Manager_CameraLinkVis::EventSceneChange(HISender pSender, HKEvent pEvent)
{
FBEventSceneChange sceneEvent(pEvent);
if (sceneEvent.Type == kFBSceneChangeRename)
{
if ( FBIS(sceneEvent.Component, FBGroup) )
{
gGroup = (FBGroup*) (FBComponent*) sceneEvent.Component;
gCamera = FindCameraByGroup(gGroup->Name);
}
}
else if (sceneEvent.Type == kFBSceneChangeRenamed)
{
if (gGroup != nullptr && gCamera != nullptr)
{
FBProperty *lProp = gCamera->PropertyList.Find("LinkedGroup");
if (lProp)
{
lProp->SetString( gGroup->Name );
}
}
}
} | [
"[email protected]"
] | |
9c79ee7216fed9040416e9641dd258d8c59feb77 | 59c47e1f8b2738fc2b824462e31c1c713b0bdcd7 | /006-All_Test_Demo/000-vital/000-sodimas_notice/000-code/TFT_4.0_4.3_switch/splashform.h | 850744411cfef25580327e9f544ccfb04b21a1ae | [] | no_license | casterbn/Qt_project | 8efcc46e75e2bbe03dc4aeaafeb9e175fb7b04ab | 03115674eb3612e9dc65d4fd7bcbca9ba27f691c | refs/heads/master | 2021-10-19T07:27:24.550519 | 2019-02-19T05:26:22 | 2019-02-19T05:26:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | h | #ifndef SPLASHFORM_H
#define SPLASHFORM_H
#include <QWidget>
namespace Ui {
class SplashForm;
}
class SplashForm : public QWidget
{
Q_OBJECT
public:
explicit SplashForm(QWidget *parent = 0);
~SplashForm();
private:
Ui::SplashForm *ui;
};
#endif // SPLASHFORM_H
| [
"[email protected]"
] | |
63133b638a389f5ab7fb65ff1ad0a70069efbfaf | 6c77cf237697f252d48b287ae60ccf61b3220044 | /aws-cpp-sdk-dynamodb/include/aws/dynamodb/model/AutoScalingTargetTrackingScalingPolicyConfigurationUpdate.h | 852ff1df5d03e400f6d798dab33be37d180f5e36 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | Gohan/aws-sdk-cpp | 9a9672de05a96b89d82180a217ccb280537b9e8e | 51aa785289d9a76ac27f026d169ddf71ec2d0686 | refs/heads/master | 2020-03-26T18:48:43.043121 | 2018-11-09T08:44:41 | 2018-11-09T08:44:41 | 145,232,234 | 1 | 0 | Apache-2.0 | 2018-08-30T13:42:27 | 2018-08-18T15:42:39 | C++ | UTF-8 | C++ | false | false | 7,646 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/dynamodb/DynamoDB_EXPORTS.h>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace DynamoDB
{
namespace Model
{
/**
* <p>Represents the settings of a target tracking scaling policy that will be
* modified.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/AutoScalingTargetTrackingScalingPolicyConfigurationUpdate">AWS
* API Reference</a></p>
*/
class AWS_DYNAMODB_API AutoScalingTargetTrackingScalingPolicyConfigurationUpdate
{
public:
AutoScalingTargetTrackingScalingPolicyConfigurationUpdate();
AutoScalingTargetTrackingScalingPolicyConfigurationUpdate(Aws::Utils::Json::JsonView jsonValue);
AutoScalingTargetTrackingScalingPolicyConfigurationUpdate& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Indicates whether scale in by the target tracking policy is disabled. If the
* value is true, scale in is disabled and the target tracking policy won't remove
* capacity from the scalable resource. Otherwise, scale in is enabled and the
* target tracking policy can remove capacity from the scalable resource. The
* default value is false.</p>
*/
inline bool GetDisableScaleIn() const{ return m_disableScaleIn; }
/**
* <p>Indicates whether scale in by the target tracking policy is disabled. If the
* value is true, scale in is disabled and the target tracking policy won't remove
* capacity from the scalable resource. Otherwise, scale in is enabled and the
* target tracking policy can remove capacity from the scalable resource. The
* default value is false.</p>
*/
inline void SetDisableScaleIn(bool value) { m_disableScaleInHasBeenSet = true; m_disableScaleIn = value; }
/**
* <p>Indicates whether scale in by the target tracking policy is disabled. If the
* value is true, scale in is disabled and the target tracking policy won't remove
* capacity from the scalable resource. Otherwise, scale in is enabled and the
* target tracking policy can remove capacity from the scalable resource. The
* default value is false.</p>
*/
inline AutoScalingTargetTrackingScalingPolicyConfigurationUpdate& WithDisableScaleIn(bool value) { SetDisableScaleIn(value); return *this;}
/**
* <p>The amount of time, in seconds, after a scale in activity completes before
* another scale in activity can start. The cooldown period is used to block
* subsequent scale in requests until it has expired. You should scale in
* conservatively to protect your application's availability. However, if another
* alarm triggers a scale out policy during the cooldown period after a scale-in,
* application autoscaling scales out your scalable target immediately. </p>
*/
inline int GetScaleInCooldown() const{ return m_scaleInCooldown; }
/**
* <p>The amount of time, in seconds, after a scale in activity completes before
* another scale in activity can start. The cooldown period is used to block
* subsequent scale in requests until it has expired. You should scale in
* conservatively to protect your application's availability. However, if another
* alarm triggers a scale out policy during the cooldown period after a scale-in,
* application autoscaling scales out your scalable target immediately. </p>
*/
inline void SetScaleInCooldown(int value) { m_scaleInCooldownHasBeenSet = true; m_scaleInCooldown = value; }
/**
* <p>The amount of time, in seconds, after a scale in activity completes before
* another scale in activity can start. The cooldown period is used to block
* subsequent scale in requests until it has expired. You should scale in
* conservatively to protect your application's availability. However, if another
* alarm triggers a scale out policy during the cooldown period after a scale-in,
* application autoscaling scales out your scalable target immediately. </p>
*/
inline AutoScalingTargetTrackingScalingPolicyConfigurationUpdate& WithScaleInCooldown(int value) { SetScaleInCooldown(value); return *this;}
/**
* <p>The amount of time, in seconds, after a scale out activity completes before
* another scale out activity can start. While the cooldown period is in effect,
* the capacity that has been added by the previous scale out event that initiated
* the cooldown is calculated as part of the desired capacity for the next scale
* out. You should continuously (but not excessively) scale out.</p>
*/
inline int GetScaleOutCooldown() const{ return m_scaleOutCooldown; }
/**
* <p>The amount of time, in seconds, after a scale out activity completes before
* another scale out activity can start. While the cooldown period is in effect,
* the capacity that has been added by the previous scale out event that initiated
* the cooldown is calculated as part of the desired capacity for the next scale
* out. You should continuously (but not excessively) scale out.</p>
*/
inline void SetScaleOutCooldown(int value) { m_scaleOutCooldownHasBeenSet = true; m_scaleOutCooldown = value; }
/**
* <p>The amount of time, in seconds, after a scale out activity completes before
* another scale out activity can start. While the cooldown period is in effect,
* the capacity that has been added by the previous scale out event that initiated
* the cooldown is calculated as part of the desired capacity for the next scale
* out. You should continuously (but not excessively) scale out.</p>
*/
inline AutoScalingTargetTrackingScalingPolicyConfigurationUpdate& WithScaleOutCooldown(int value) { SetScaleOutCooldown(value); return *this;}
/**
* <p>The target value for the metric. The range is 8.515920e-109 to 1.174271e+108
* (Base 10) or 2e-360 to 2e360 (Base 2).</p>
*/
inline double GetTargetValue() const{ return m_targetValue; }
/**
* <p>The target value for the metric. The range is 8.515920e-109 to 1.174271e+108
* (Base 10) or 2e-360 to 2e360 (Base 2).</p>
*/
inline void SetTargetValue(double value) { m_targetValueHasBeenSet = true; m_targetValue = value; }
/**
* <p>The target value for the metric. The range is 8.515920e-109 to 1.174271e+108
* (Base 10) or 2e-360 to 2e360 (Base 2).</p>
*/
inline AutoScalingTargetTrackingScalingPolicyConfigurationUpdate& WithTargetValue(double value) { SetTargetValue(value); return *this;}
private:
bool m_disableScaleIn;
bool m_disableScaleInHasBeenSet;
int m_scaleInCooldown;
bool m_scaleInCooldownHasBeenSet;
int m_scaleOutCooldown;
bool m_scaleOutCooldownHasBeenSet;
double m_targetValue;
bool m_targetValueHasBeenSet;
};
} // namespace Model
} // namespace DynamoDB
} // namespace Aws
| [
"[email protected]"
] | |
84e370147038858df7cad2347e4653ffdca337a2 | 21fd3fa22e2483acf2c078aede31ab4cdbf19a3d | /src/core/transformations/morph_openclose.cpp | 99292eb57650cfc0ae8a0b7021b3cd6935199852 | [] | no_license | andre-wojtowicz/image-processing-project-student | 449f751f3a05b994f88ba24addc0943ff5f7cf2c | 9258c9a0f14953bd6b048b93b6a9e1cb33db2722 | refs/heads/master | 2021-01-10T14:30:47.377958 | 2019-10-14T08:37:13 | 2019-10-14T08:37:13 | 52,097,014 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | cpp | #include "morph_openclose.h"
#include "morph_erode.h"
#include "morph_dilate.h"
MorphOpenClose::MorphOpenClose(PNM* img) :
MorphologicalOperator(img), m_type(Open)
{
}
MorphOpenClose::MorphOpenClose(PNM* img, ImageViewer* iv) :
MorphologicalOperator(img, iv), m_type(Open)
{
}
PNM* MorphOpenClose::transform()
{
int size = getParameter("size").toInt();;
SE shape = (SE) getParameter("shape").toInt();
m_type = (Type) getParameter("type").toInt();
qDebug() << Q_FUNC_INFO << "Not implemented yet!";
return 0;
}
PNM* MorphOpenClose::erode(PNM* image, int size, SE shape)
{
MorphErode e(image, getSupervisor());
e.setParameter("silent", true);
e.setParameter("shape", shape);
e.setParameter("size", size);
return e.transform();
}
PNM* MorphOpenClose::dilate(PNM* image, int size, SE shape)
{
MorphDilate e(image, getSupervisor());
e.setParameter("silent", true);
e.setParameter("shape", shape);
e.setParameter("size", size);
return e.transform();
}
| [
"[email protected]"
] | |
06cf7b2287e62e5e24842037e6d495f1bcc6908a | fa5038cdd23db2c58112963a58f98162eb2153f7 | /multisocket.h | a36f641b2c3eb1261ccd5004fe8544d877c9078c | [
"Apache-2.0"
] | permissive | Aharobot/iirlib | 7cf67ba9245ca027620b3d0d43c11de0c47caa58 | cf167d64e4a2157a31cefca2fe69dcbda1956525 | refs/heads/master | 2021-01-18T13:02:06.517628 | 2014-10-13T21:43:32 | 2014-10-13T21:43:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | h | // --*- C++ -*--
/*
* IIRLIB Multi Socket Connection Modules
*
* Last modified on 2008 Feb 13th by Tetsunari Inamura
*
* Copyright (c) Tetsunari Inamura 1998-2008.
* All Rights Reserved.
*/
#ifndef __MULTISOCKET_H__
#define __MULTISOCKET_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <time.h>
#ifdef WIN32
#include <io.h>
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#include "glib.h"
#include "connection.h"
#define MAX_MULTI_SOCKET 3
#define MULTI_SOCKET_NEW_CONNECTION (-1)
#define NAMESIZE 64
class MultiSocket
{
public:
MultiSocket (char *str, int port);
int Accept ();
int Close (int no );
int MaxFD (int max );
int FDSet (fd_set *readfds);
int FDISSET (fd_set *readfds, int *result);
int DebugPrintFD ();
Connection * GetConnection (int n);
private:
char name[NAMESIZE];
int socket_fd;
int port;
Connection *connection[MAX_MULTI_SOCKET]; // sequence of Connection instances
};
#endif
| [
"[email protected]"
] | |
121126532232ef703e2e64c8cc405ac5b4d067a3 | ac8c5a26e336f7a9ac88cd0dbf7aae6d9d7042fe | /src/core/plate_locate.cpp | f7e668b6895059417a0751df8761f18e7ec7cc64 | [
"Apache-2.0"
] | permissive | tomturing/MyEasyPR | 9911d6b4cb229d87126753f1ae17b95b1a8f29ab | 091d580d2aa2b68dfe9667754c73db1e755b10be | refs/heads/master | 2021-01-10T02:43:48.306822 | 2016-03-14T08:09:35 | 2016-03-14T08:09:35 | 53,832,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,831 | cpp | #include "easypr/plate_locate.h"
#include "easypr/util.h"
using namespace std;
/*! \namespace easypr
Namespace where all the C++ EasyPR functionality resides
*/
namespace easypr {
const float DEFAULT_ERROR = 0.9f; // 0.6
const float DEFAULT_ASPECT = 3.75f; // 3.75
CPlateLocate::CPlateLocate() {
// cout << "CPlateLocate" << endl;
m_GaussianBlurSize = DEFAULT_GAUSSIANBLUR_SIZE;
m_MorphSizeWidth = DEFAULT_MORPH_SIZE_WIDTH;
m_MorphSizeHeight = DEFAULT_MORPH_SIZE_HEIGHT;
m_error = DEFAULT_ERROR;
m_aspect = DEFAULT_ASPECT;
m_verifyMin = DEFAULT_VERIFY_MIN;
m_verifyMax = DEFAULT_VERIFY_MAX;
m_angle = DEFAULT_ANGLE;
m_debug = DEFAULT_DEBUG;
}
//! 生活模式与工业模式切换
//!
//如果为真,则设置各项参数为定位生活场景照片(如百度图片)的参数,否则恢复默认值。
void CPlateLocate::setLifemode(bool param) {
if (param == true) {
setGaussianBlurSize(5);
setMorphSizeWidth(10);
setMorphSizeHeight(3);
setVerifyError(0.75);
setVerifyAspect(4.0);
setVerifyMin(1);
setVerifyMax(200);
} else {
setGaussianBlurSize(DEFAULT_GAUSSIANBLUR_SIZE);
setMorphSizeWidth(DEFAULT_MORPH_SIZE_WIDTH);
setMorphSizeHeight(DEFAULT_MORPH_SIZE_HEIGHT);
setVerifyError(DEFAULT_ERROR);
setVerifyAspect(DEFAULT_ASPECT);
setVerifyMin(DEFAULT_VERIFY_MIN);
setVerifyMax(DEFAULT_VERIFY_MAX);
}
}
//! 对minAreaRect获得的最小外接矩形,用纵横比进行判断
bool CPlateLocate::verifySizes(RotatedRect mr) {
float error = m_error;
// Spain car plate size: 52x11 aspect 4,7272
// China car plate size: 440mm*140mm,aspect 3.142857
// Real car plate size: 136 * 32, aspect 4
float aspect = m_aspect;
// Set a min and max area. All other patchs are discarded
// int min= 1*aspect*1; // minimum area
// int max= 2000*aspect*2000; // maximum area
int min = 34 * 8 * m_verifyMin; // minimum area
int max = 34 * 8 * m_verifyMax; // maximum area
// Get only patchs that match to a respect ratio.
float rmin = aspect - aspect * error;
float rmax = aspect + aspect * error;
float area = mr.size.height * mr.size.width;
float r = (float)mr.size.width / (float)mr.size.height;
if (r < 1) r = (float)mr.size.height / (float)mr.size.width;
// cout << "area:" << area << endl;
// cout << "r:" << r << endl;
if ((area < min || area > max) || (r < rmin || r > rmax))
return false;
else
return true;
}
// !基于HSV空间的颜色搜索方法
int CPlateLocate::colorSearch(const Mat& src, const Color r, Mat& out,
vector<RotatedRect>& outRects, int index) {
Mat match_grey;
// width值对最终结果影响很大,可以考虑进行多次colorSerch,每次不同的值
// 另一种解决方案就是在结果输出到SVM之前,进行线与角的再纠正
const int color_morph_width = 10;
const int color_morph_height = 2;
// 进行颜色查找
colorMatch(src, match_grey, r, false);
if (m_debug) {
utils::imwrite("resources/image/tmp/match_grey.jpg", match_grey);
}
Mat src_threshold;
threshold(match_grey, src_threshold, 0, 255,
CV_THRESH_OTSU + CV_THRESH_BINARY);
Mat element = getStructuringElement(
MORPH_RECT, Size(color_morph_width, color_morph_height));
morphologyEx(src_threshold, src_threshold, MORPH_CLOSE, element);
if (m_debug) {
utils::imwrite("resources/image/tmp/color.jpg", src_threshold);
}
src_threshold.copyTo(out);
// 查找轮廓
vector<vector<Point>> contours;
// 注意,findContours会改变src_threshold
// 因此要输出src_threshold必须在这之前使用copyTo方法
findContours(src_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
// 需要进行大小尺寸判断
if (!verifySizes(mr))
itc = contours.erase(itc);
else {
++itc;
outRects.push_back(mr);
}
}
return 0;
}
//! Sobel第一次搜索
//! 不限制大小和形状,获取的BoundRect进入下一步
int CPlateLocate::sobelFrtSearch(const Mat& src,
vector<Rect_<float>>& outRects) {
Mat src_threshold;
// soble操作,得到二值图像
sobelOper(src, src_threshold, m_GaussianBlurSize, m_MorphSizeWidth,
m_MorphSizeHeight);
if (0) {
imshow("sobelFrtSearch", src_threshold);
waitKey(0);
destroyWindow("sobelFrtSearch");
}
vector<vector<Point>> contours;
findContours(src_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
vector<RotatedRect> first_rects;
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
// 需要进行大小尺寸判断
if (verifySizes(mr)) {
first_rects.push_back(mr);
float area = mr.size.height * mr.size.width;
float r = (float)mr.size.width / (float)mr.size.height;
if (r < 1) r = (float)mr.size.height / (float)mr.size.width;
/*cout << "area:" << area << endl;
cout << "r:" << r << endl;*/
}
++itc;
}
for (size_t i = 0; i < first_rects.size(); i++) {
RotatedRect roi_rect = first_rects[i];
Rect_<float> safeBoundRect;
if (!calcSafeRect(roi_rect, src, safeBoundRect)) continue;
outRects.push_back(safeBoundRect);
}
return 0;
}
//! Sobel第二次搜索,对断裂的部分进行再次的处理
//! 对大小和形状做限制,生成参考坐标
int CPlateLocate::sobelSecSearchPart(Mat& bound, Point2f refpoint,
vector<RotatedRect>& outRects) {
Mat bound_threshold;
////!
///第二次参数比一次精细,但针对的是得到的外接矩阵之后的图像,再sobel得到二值图像
sobelOperT(bound, bound_threshold, 3, 6, 2);
////二值化去掉两边的边界
// Mat mat_gray;
// cvtColor(bound,mat_gray,CV_BGR2GRAY);
// bound_threshold = mat_gray.clone();
////threshold(input_grey, img_threshold, 5, 255, CV_THRESH_OTSU +
/// CV_THRESH_BINARY);
// int w = mat_gray.cols;
// int h = mat_gray.rows;
// Mat tmp = mat_gray(Rect(w*0.15,h*0.2,w*0.6,h*0.6));
// int threadHoldV = ThresholdOtsu(tmp);
// threshold(mat_gray, bound_threshold,threadHoldV, 255, CV_THRESH_BINARY);
Mat tempBoundThread = bound_threshold.clone();
////
clearLiuDingOnly(tempBoundThread);
int posLeft = 0, posRight = 0;
if (bFindLeftRightBound(tempBoundThread, posLeft, posRight)) {
//找到两个边界后进行连接修补处理
if (posRight != 0 && posLeft != 0 && posLeft < posRight) {
int posY = int(bound_threshold.rows * 0.5);
for (int i = posLeft + (int)(bound_threshold.rows * 0.1);
i < posRight - 4; i++) {
bound_threshold.data[posY * bound_threshold.cols + i] = 255;
}
}
utils::imwrite("resources/image/tmp/repaireimg1.jpg", bound_threshold);
//两边的区域不要
for (int i = 0; i < bound_threshold.rows; i++) {
bound_threshold.data[i * bound_threshold.cols + posLeft] = 0;
bound_threshold.data[i * bound_threshold.cols + posRight] = 0;
}
utils::imwrite("resources/image/tmp/repaireimg2.jpg", bound_threshold);
}
vector<vector<Point>> contours;
findContours(bound_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
vector<RotatedRect> second_rects;
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
second_rects.push_back(mr);
++itc;
}
for (size_t i = 0; i < second_rects.size(); i++) {
RotatedRect roi = second_rects[i];
if (verifySizes(roi)) {
Point2f refcenter = roi.center + refpoint;
Size2f size = roi.size;
float angle = roi.angle;
RotatedRect refroi(refcenter, size, angle);
outRects.push_back(refroi);
}
}
return 0;
}
//! Sobel第二次搜索
//! 对大小和形状做限制,生成参考坐标
int CPlateLocate::sobelSecSearch(Mat& bound, Point2f refpoint,
vector<RotatedRect>& outRects) {
Mat bound_threshold;
//!
//第二次参数比一次精细,但针对的是得到的外接矩阵之后的图像,再sobel得到二值图像
sobelOper(bound, bound_threshold, 3, 10, 3);
// Mat tempBoundThread = bound_threshold.clone();
//////
// tempBoundThread = clearLiuDing(tempBoundThread);
// int posLeft = 0,posRight = 0;
// if (bFindLeftRightBound2(tempBoundThread,posLeft,posRight))
//{
// //找到两个边界后进行连接修补处理
// if (posRight !=0 && posLeft != 0 && posLeft < posRight)
// {
// int posY = bound_threshold.rows*0.5;
// for (int i=posLeft+bound_threshold.rows*0.1;i<posRight-4;i++)
// {
// bound_threshold.data[posY*bound_threshold.step[0]+i] =
// 255;
// }
// }
// imwrite("resources/image/tmp/repaireimg1.jpg",bound_threshold);
// //两边的区域不要
// for (int i=0;i<bound_threshold.rows;i++)
// {
// bound_threshold.data[i*bound_threshold.step[0]+posLeft] = 0;
// bound_threshold.data[i*bound_threshold.step[0]+posRight] = 0;
// }
// imwrite("resources/image/tmp/repaireimg2.jpg",bound_threshold);
//}
utils::imwrite("resources/image/tmp/sobelSecSearch.jpg", bound_threshold);
vector<vector<Point>> contours;
findContours(bound_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
vector<RotatedRect> second_rects;
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
second_rects.push_back(mr);
++itc;
}
for (size_t i = 0; i < second_rects.size(); i++) {
RotatedRect roi = second_rects[i];
if (verifySizes(roi)) {
Point2f refcenter = roi.center + refpoint;
Size2f size = roi.size;
float angle = roi.angle;
RotatedRect refroi(refcenter, size, angle);
outRects.push_back(refroi);
}
}
return 0;
}
//! Sobel运算//对图像分割,腐蚀和膨胀的操作
//! 输入彩色图像,输出二值化图像
int CPlateLocate::sobelOper(const Mat& in, Mat& out, int blurSize, int morphW,
int morphH) {
Mat mat_blur;
mat_blur = in.clone();
GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT);
Mat mat_gray;
if (mat_blur.channels() == 3)
cvtColor(mat_blur, mat_gray, CV_RGB2GRAY);
else
mat_gray = mat_blur;
// equalizeHist(mat_gray, mat_gray);
int scale = SOBEL_SCALE;
int delta = SOBEL_DELTA;
int ddepth = SOBEL_DDEPTH;
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
// 对X soble
Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
// 对Y soble
// Sobel(mat_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
// convertScaleAbs(grad_y, abs_grad_y);
// 在两个权值组合
// 因为Y方向的权重是0,因此在此就不再计算Y方向的sobel了
Mat grad;
addWeighted(abs_grad_x, SOBEL_X_WEIGHT, 0, 0, 0, grad);
// 分割
Mat mat_threshold;
double otsu_thresh_val =
threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
// 腐蚀和膨胀
Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH));
morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element);
out = mat_threshold;
if (0) {
imshow("sobelOper", out);
waitKey(0);
destroyWindow("sobelOper");
}
return 0;
}
void DeleteNotArea(Mat& inmat) {
Mat input_grey;
cvtColor(inmat, input_grey, CV_BGR2GRAY);
int w = inmat.cols;
int h = inmat.rows;
Mat tmpMat = inmat(Rect_<double>(w * 0.15, h * 0.1, w * 0.7, h * 0.7));
//判断车牌颜色以此确认threshold方法
Color plateType = getPlateType(tmpMat, true);
Mat img_threshold;
if (BLUE == plateType) {
img_threshold = input_grey.clone();
Mat tmp = input_grey(Rect_<double>(w * 0.15, h * 0.15, w * 0.7, h * 0.7));
int threadHoldV = ThresholdOtsu(tmp);
threshold(input_grey, img_threshold, threadHoldV, 255, CV_THRESH_BINARY);
// threshold(input_grey, img_threshold, 5, 255, CV_THRESH_OTSU +
// CV_THRESH_BINARY);
utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold);
} else if (YELLOW == plateType) {
img_threshold = input_grey.clone();
Mat tmp = input_grey(Rect_<double>(w * 0.1, h * 0.1, w * 0.8, h * 0.8));
int threadHoldV = ThresholdOtsu(tmp);
threshold(input_grey, img_threshold, threadHoldV, 255,
CV_THRESH_BINARY_INV);
utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold);
// threshold(input_grey, img_threshold, 10, 255, CV_THRESH_OTSU +
// CV_THRESH_BINARY_INV);
} else
threshold(input_grey, img_threshold, 10, 255,
CV_THRESH_OTSU + CV_THRESH_BINARY);
int posLeft = 0;
int posRight = 0;
int top = 0;
int bottom = img_threshold.rows - 1;
clearLiuDing(img_threshold, top, bottom);
if (bFindLeftRightBound1(img_threshold, posLeft, posRight)) {
inmat = inmat(Rect(posLeft, top, w - posLeft, bottom - top));
/*int posY = inmat.rows*0.5*inmat.cols;
for (int i=posLeft;i<posRight;i++)
{
inmat.data[posY+i] = 255;
}
*/
/*roiRect.x += posLeft;
roiRect.width -=posLeft;*/
}
}
//! 抗扭斜处理
int CPlateLocate::deskew(const Mat& src, const Mat& src_b,
vector<RotatedRect>& inRects,
vector<CPlate>& outPlates) {
Mat mat_debug;
src.copyTo(mat_debug);
for (size_t i = 0; i < inRects.size(); i++) {
RotatedRect roi_rect = inRects[i];
float r = (float)roi_rect.size.width / (float)roi_rect.size.height;
float roi_angle = roi_rect.angle;
Size roi_rect_size = roi_rect.size;
if (r < 1) {
roi_angle = 90 + roi_angle;
swap(roi_rect_size.width, roi_rect_size.height);
}
if (m_debug) {
Point2f rect_points[4];
roi_rect.points(rect_points);
for (int j = 0; j < 4; j++)
line(mat_debug, rect_points[j], rect_points[(j + 1) % 4],
Scalar(0, 255, 255), 1, 8);
}
// m_angle=60
if (roi_angle - m_angle < 0 && roi_angle + m_angle > 0) {
Rect_<float> safeBoundRect;
bool isFormRect = calcSafeRect(roi_rect, src, safeBoundRect);
if (!isFormRect) continue;
Mat bound_mat = src(safeBoundRect);
Mat bound_mat_b = src_b(safeBoundRect);
Point2f roi_ref_center = roi_rect.center - safeBoundRect.tl();
Mat deskew_mat;
if ((roi_angle - 3 < 0 && roi_angle + 3 > 0) || 90.0 == roi_angle ||
-90.0 == roi_angle) {
deskew_mat = bound_mat;
} else {
// 角度在5到60度之间的,首先需要旋转 rotation
Mat rotated_mat;
Mat rotated_mat_b;
if (!rotation(bound_mat, rotated_mat, roi_rect_size, roi_ref_center,
roi_angle))
continue;
if (!rotation(bound_mat_b, rotated_mat_b, roi_rect_size, roi_ref_center,
roi_angle))
continue;
// 如果图片偏斜,还需要视角转换 affine
double roi_slope = 0;
// imshow("1roated_mat",rotated_mat);
// imshow("rotated_mat_b",rotated_mat_b);
if (isdeflection(rotated_mat_b, roi_angle, roi_slope)) {
affine(rotated_mat, deskew_mat, roi_slope);
} else
deskew_mat = rotated_mat;
}
Mat plate_mat;
plate_mat.create(HEIGHT, WIDTH, TYPE);
// haitungaga添加,删除非区域,这个函数影响了25%的完整定位率
DeleteNotArea(deskew_mat);
// 这里对deskew_mat进行了一个筛选
// 使用了经验数值:2.3和6
if (0) {
imshow("deskew_mat", deskew_mat);
waitKey(0);
destroyWindow("deskew_mat");
}
//
if (deskew_mat.cols * 1.0 / deskew_mat.rows > 2.3 &&
deskew_mat.cols * 1.0 / deskew_mat.rows < 6) {
//如果图像大于我们所要求的图像,对图像进行一个大小变更
if (deskew_mat.cols >= WIDTH || deskew_mat.rows >= HEIGHT)
resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_AREA);
else
resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_CUBIC);
if (0) {
imshow("plate_mat", plate_mat);
waitKey(0);
destroyWindow("plate_mat");
}
CPlate plate;
plate.setPlatePos(roi_rect);
plate.setPlateMat(plate_mat);
outPlates.push_back(plate);
}
}
}
if (0) {
imshow("mat_debug", mat_debug);
waitKey(0);
destroyWindow("mat_debug");
}
return 0;
}
//! 旋转操作
bool CPlateLocate::rotation(Mat& in, Mat& out, const Size rect_size,
const Point2f center, const double angle) {
Mat in_large;
in_large.create(int(in.rows * 1.5), int(in.cols * 1.5), in.type());
float x = in_large.cols / 2 - center.x > 0 ? in_large.cols / 2 - center.x : 0;
float y = in_large.rows / 2 - center.y > 0 ? in_large.rows / 2 - center.y : 0;
float width = x + in.cols < in_large.cols ? in.cols : in_large.cols - x;
float height = y + in.rows < in_large.rows ? in.rows : in_large.rows - y;
/*assert(width == in.cols);
assert(height == in.rows);*/
if (width != in.cols || height != in.rows) return false;
Mat imageRoi = in_large(Rect_<float>(x, y, width, height));
addWeighted(imageRoi, 0, in, 1, 0, imageRoi);
Point2f center_diff(in.cols / 2.f, in.rows / 2.f);
Point2f new_center(in_large.cols / 2.f, in_large.rows / 2.f);
Mat rot_mat = getRotationMatrix2D(new_center, angle, 1);
/*imshow("in_copy", in_large);
waitKey(0);*/
Mat mat_rotated;
warpAffine(in_large, mat_rotated, rot_mat, Size(in_large.cols, in_large.rows),
CV_INTER_CUBIC);
/*imshow("mat_rotated", mat_rotated);
waitKey(0);*/
Mat img_crop;
getRectSubPix(mat_rotated, Size(rect_size.width, rect_size.height),
new_center, img_crop);
out = img_crop;
/*imshow("img_crop", img_crop);
waitKey(0);*/
return true;
}
//! 是否偏斜
//! 输入二值化图像,输出判断结果
bool CPlateLocate::isdeflection(const Mat& in, const double angle,
double& slope) { /*imshow("in",in);
waitKey(0);*/
int nRows = in.rows;
int nCols = in.cols;
assert(in.channels() == 1);
int comp_index[3];
int len[3];
comp_index[0] = nRows / 4;
comp_index[1] = nRows / 4 * 2;
comp_index[2] = nRows / 4 * 3;
const uchar* p;
for (int i = 0; i < 3; i++) {
int index = comp_index[i];
p = in.ptr<uchar>(index);
int j = 0;
int value = 0;
while (0 == value && j < nCols) value = int(p[j++]);
len[i] = j;
}
// cout << "len[0]:" << len[0] << endl;
// cout << "len[1]:" << len[1] << endl;
// cout << "len[2]:" << len[2] << endl;
// len[0]/len[1]/len[2]这三个应该是取车牌边线的值,来计算车牌边线的斜率
double maxlen = max(len[2], len[0]);
double minlen = min(len[2], len[0]);
double difflen = abs(len[2] - len[0]);
// cout << "nCols:" << nCols << endl;
double PI = 3.14159265;
// angle是根据水平那根直线的斜率转换过来的角度
double g = tan(angle * PI / 180.0);
if (maxlen - len[1] > nCols / 32 || len[1] - minlen > nCols / 32) {
// 如果斜率为正,则底部在下,反之在上
double slope_can_1 =
double(len[2] - len[0]) / double(comp_index[1]); //求直线的斜率
double slope_can_2 = double(len[1] - len[0]) / double(comp_index[0]);
double slope_can_3 = double(len[2] - len[1]) / double(comp_index[0]);
// cout<<"angle:"<<angle<<endl;
// cout<<"g:"<<g<<endl;
// cout << "slope_can_1:" << slope_can_1 << endl;
// cout << "slope_can_2:" << slope_can_2 << endl;
// cout << "slope_can_3:" << slope_can_3 << endl;
// if(g>=0)
slope = abs(slope_can_1 - g) <= abs(slope_can_2 - g) ? slope_can_1
: slope_can_2;
// cout << "slope:" << slope << endl;
return true;
} else {
slope = 0;
}
return false;
}
//! 扭变操作//通过opencv的仿射变换
void CPlateLocate::affine(const Mat& in, Mat& out, const double slope) {
// imshow("in", in);
// waitKey(0);
//这里的slope是通过判断是否倾斜得出来的倾斜率
Point2f dstTri[3];
Point2f plTri[3];
float height = (float)in.rows; //行
float width = (float)in.cols; //列
float xiff = (float)abs(slope) * height;
if (slope > 0) {
//右偏型,新起点坐标系在xiff/2位置
plTri[0] = Point2f(0, 0);
plTri[1] = Point2f(width - xiff - 1, 0);
plTri[2] = Point2f(0 + xiff, height - 1);
dstTri[0] = Point2f(xiff / 2, 0);
dstTri[1] = Point2f(width - 1 - xiff / 2, 0);
dstTri[2] = Point2f(xiff / 2, height - 1);
} else {
//左偏型,新起点坐标系在 -xiff/2位置
plTri[0] = Point2f(0 + xiff, 0);
plTri[1] = Point2f(width - 1, 0);
plTri[2] = Point2f(0, height - 1);
dstTri[0] = Point2f(xiff / 2, 0);
dstTri[1] = Point2f(width - 1 - xiff + xiff / 2, 0);
dstTri[2] = Point2f(xiff / 2, height - 1);
}
Mat warp_mat = getAffineTransform(plTri, dstTri);
Mat affine_mat;
affine_mat.create((int)height, (int)width, TYPE);
if (in.rows > HEIGHT || in.cols > WIDTH)
warpAffine(in, affine_mat, warp_mat, affine_mat.size(),
CV_INTER_AREA); //仿射变换
else
warpAffine(in, affine_mat, warp_mat, affine_mat.size(), CV_INTER_CUBIC);
out = affine_mat;
// imshow("out", out);
// waitKey(0);
}
//! 计算一个安全的Rect
//! 如果不存在,返回false
bool CPlateLocate::calcSafeRect(const RotatedRect& roi_rect, const Mat& src,
Rect_<float>& safeBoundRect) {
Rect_<float> boudRect = roi_rect.boundingRect();
// boudRect的左上的x和y有可能小于0
float tl_x = boudRect.x > 0 ? boudRect.x : 0;
float tl_y = boudRect.y > 0 ? boudRect.y : 0;
// boudRect的右下的x和y有可能大于src的范围
float br_x = boudRect.x + boudRect.width < src.cols
? boudRect.x + boudRect.width - 1
: src.cols - 1;
float br_y = boudRect.y + boudRect.height < src.rows
? boudRect.y + boudRect.height - 1
: src.rows - 1;
float roi_width = br_x - tl_x;
float roi_height = br_y - tl_y;
if (roi_width <= 0 || roi_height <= 0) return false;
// 新建一个mat,确保地址不越界,以防mat定位roi时抛异常
safeBoundRect = Rect_<float>(tl_x, tl_y, roi_width, roi_height);
return true;
}
// !基于颜色信息的车牌定位
int CPlateLocate::plateColorLocate(Mat src, vector<CPlate>& candPlates,
int index) {
vector<RotatedRect> rects_color_blue;
vector<RotatedRect> rects_color_yellow;
vector<CPlate> plates;
Mat src_b;
// 查找蓝色车牌
// 查找颜色匹配车牌
colorSearch(src, BLUE, src_b, rects_color_blue, index);
// 进行抗扭斜处理
deskew(src, src_b, rects_color_blue, plates);
// 查找黄色车牌
colorSearch(src, YELLOW, src_b, rects_color_yellow, index);
deskew(src, src_b, rects_color_yellow, plates);
for (size_t i = 0; i < plates.size(); i++) {
candPlates.push_back(plates[i]);
}
return 0;
}
//! Sobel运算
//! 输入彩色图像,输出二值化图像
int CPlateLocate::sobelOperT(const Mat& in, Mat& out, int blurSize, int morphW,
int morphH) {
Mat mat_blur;
mat_blur = in.clone();
GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT);
Mat mat_gray;
if (mat_blur.channels() == 3)
cvtColor(mat_blur, mat_gray, CV_BGR2GRAY);
else
mat_gray = mat_blur;
utils::imwrite("resources/image/tmp/grayblure.jpg", mat_gray);
// equalizeHist(mat_gray, mat_gray);
int scale = SOBEL_SCALE;
int delta = SOBEL_DELTA;
int ddepth = SOBEL_DDEPTH;
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
//因为Y方向的权重是0,因此在此就不再计算Y方向的sobel了
Mat grad;
addWeighted(abs_grad_x, 1, 0, 0, 0, grad);
utils::imwrite("resources/image/tmp/graygrad.jpg", grad);
Mat mat_threshold;
double otsu_thresh_val =
threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
utils::imwrite("resources/image/tmp/grayBINARY.jpg", mat_threshold);
Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH));
morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element);
utils::imwrite("resources/image/tmp/phologyEx.jpg", mat_threshold);
out = mat_threshold;
return 0;
}
// !基于垂直线条的车牌定位
int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate>& candPlates,
int index) {
vector<RotatedRect> rects_sobel;
vector<RotatedRect> rects_sobel_sel;
vector<CPlate> plates;
vector<Rect_<float>> bound_rects;
// Sobel第一次粗略搜索
sobelFrtSearch(src, bound_rects);
vector<Rect_<float>> bound_rects_part;
//对不符合要求的区域进行扩展
for (size_t i = 0; i < bound_rects.size(); i++) {
float fRatio = bound_rects[i].width * 1.0f / bound_rects[i].height;
if (fRatio < 3.0 && fRatio > 1.0 && bound_rects[i].height < 120) {
Rect_<float> itemRect = bound_rects[i];
//宽度过小,进行扩展
itemRect.x = itemRect.x - itemRect.height * (4 - fRatio);
if (itemRect.x < 0) {
itemRect.x = 0;
}
itemRect.width = itemRect.width + itemRect.height * 2 * (4 - fRatio);
if (itemRect.width + itemRect.x >= src.cols) {
itemRect.width = src.cols - itemRect.x;
}
itemRect.y = itemRect.y - itemRect.height * 0.08f;
itemRect.height = itemRect.height * 1.16f;
bound_rects_part.push_back(itemRect);
}
}
//对断裂的部分进行二次处理
for (size_t i = 0; i < bound_rects_part.size(); i++) {
Rect_<float> bound_rect = bound_rects_part[i];
Point2f refpoint(bound_rect.x, bound_rect.y);
float x = bound_rect.x > 0 ? bound_rect.x : 0;
float y = bound_rect.y > 0 ? bound_rect.y : 0;
float width =
x + bound_rect.width < src.cols ? bound_rect.width : src.cols - x;
float height =
y + bound_rect.height < src.rows ? bound_rect.height : src.rows - y;
Rect_<float> safe_bound_rect(x, y, width, height);
Mat bound_mat = src(safe_bound_rect);
// Sobel第二次精细搜索(部分)
sobelSecSearchPart(bound_mat, refpoint, rects_sobel);
}
for (size_t i = 0; i < bound_rects.size(); i++) {
Rect_<float> bound_rect = bound_rects[i];
Point2f refpoint(bound_rect.x, bound_rect.y);
float x = bound_rect.x > 0 ? bound_rect.x : 0;
float y = bound_rect.y > 0 ? bound_rect.y : 0;
float width =
x + bound_rect.width < src.cols ? bound_rect.width : src.cols - x;
float height =
y + bound_rect.height < src.rows ? bound_rect.height : src.rows - y;
Rect_<float> safe_bound_rect(x, y, width, height);
Mat bound_mat = src(safe_bound_rect);
// Sobel第二次精细搜索
sobelSecSearch(bound_mat, refpoint, rects_sobel);
// sobelSecSearchPart(bound_mat, refpoint, rects_sobel);
}
Mat src_b;
sobelOper(src, src_b, 3, 10, 3);
// 进行抗扭斜处理
deskew(src, src_b, rects_sobel, plates);
for (size_t i = 0; i < plates.size(); i++) candPlates.push_back(plates[i]);
return 0;
}
// !车牌定位
// !把颜色与Sobel定位的车牌全部输出
int CPlateLocate::plateLocate(Mat src, vector<Mat>& resultVec, int index) {
vector<CPlate> all_result_Plates;
plateColorLocate(src, all_result_Plates, index);
plateSobelLocate(src, all_result_Plates, index);
for (size_t i = 0; i < all_result_Plates.size(); i++) {
CPlate plate = all_result_Plates[i];
resultVec.push_back(plate.getPlateMat());
}
return 0;
}
} /*! \namespace easypr*/ | [
"[email protected]"
] | |
06f557c38a0dbbe3fdb342c8ef822c7962b14578 | 2d45bd1404bc1169bc847266071f2b4ce8871c78 | /tensorflow/compiler/xla/service/hlo_runner.h | 76d8b92bed484381a59d7f54e0a75bb7e75649ee | [
"Apache-2.0"
] | permissive | JuliaComputing/tensorflow | 77681ce4aa19cce683d195c18fb6312ed267897b | a2e3dcdb4f439f05592b3e4698cb25a28d85a3b7 | refs/heads/master | 2021-07-07T06:00:11.905241 | 2018-09-04T23:52:11 | 2018-09-04T23:57:41 | 147,434,640 | 2 | 0 | Apache-2.0 | 2018-09-05T00:01:43 | 2018-09-05T00:01:42 | null | UTF-8 | C++ | false | false | 7,654 | h | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_HLO_RUNNER_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_HLO_RUNNER_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "absl/types/span.h"
#include "tensorflow/compiler/xla/service/backend.h"
#include "tensorflow/compiler/xla/service/compiler.h"
#include "tensorflow/compiler/xla/service/computation_placer.h"
#include "tensorflow/compiler/xla/service/executable.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/stream_executor_no_cuda.h"
namespace xla {
// A base class for running an HloModule. This executes the given HloModule on a
// certain backend directly without using the client interface. HloModule can be
// explicitly built, or loaded from a serialization file (e.g., hlo proto
// file), or parsed from a hlo textual IR string.
class HloRunner {
public:
// The options used to configure a ExecuteReplicated() call.
struct ReplicatedExecuteOptions {
// The number of devices the HLO module should be replicated onto.
int64 num_replicas = 1;
// The arguments to be fed to each replica. Since this is used for a
// replicated execution, all the arguments are the same for all replicas.
std::vector<const Literal*> arguments;
// If the HLO module being run has an infeed instruction, this will be the
// data which will be fed to it, for as many as infeed_steps steps.
const Literal* infeed = nullptr;
// The number of times the infeed literal should be fed to the HLO module.
// For a clean exit, this should match the iterations-per-loop parameter
// used when generating the HLO module proto (that is usually the main
// while bounary counter). A value higher then iterations-per-loop would
// lead to infeed threads feeding to a gone computation, while a lower
// value would trigger a stuck ExecuteReplicated() call (the computation
// will be trying to infeed data which will never come).
int64 infeed_steps = -1;
// The shape of the outfeed operation. If empty, the HLO module does not
// generate any outfeed.
Shape outfeed_shape;
// A pointer to a vector where the outfeed values will be stored. If
// nullptr, the values will be read and discarded.
std::vector<std::unique_ptr<Literal>>* outfeed_values = nullptr;
// Whether the HLO passes should be run on the input module. Usually
// saved modules are coming from after the HLO pass pipeline, so triggering
// another run will likely cause errors.
bool run_hlo_passes = false;
};
explicit HloRunner(se::Platform* platform);
~HloRunner();
// Converts an HloModule from the given hlo textual IR string (in
// HloModule::ToString format).
static StatusOr<std::unique_ptr<HloModule>> CreateModuleFromString(
const absl::string_view hlo_string, const DebugOptions& debug_options);
// Reads the proto file in xla.HloProto format, creates and returns the
// HloModule.
static StatusOr<std::unique_ptr<HloModule>> ReadModuleFromBinaryProtoFile(
const std::string& filename, const DebugOptions& debug_options);
static StatusOr<std::unique_ptr<HloModule>> ReadModuleFromTextProtoFile(
const std::string& filename, const DebugOptions& debug_options);
// Reads the hlo text dump file in HloModule::ToString format, creates and
// returns the HloModule.
static StatusOr<std::unique_ptr<HloModule>> ReadModuleFromHloTextFile(
const std::string& filename, const DebugOptions& debug_options);
// Transfers data between the host and device.
StatusOr<ScopedShapedBuffer> TransferLiteralToDevice(const Literal& literal);
StatusOr<std::vector<ScopedShapedBuffer>> TransferLiteralsToDevice(
const absl::Span<const Literal* const> literals);
StatusOr<std::vector<ScopedShapedBuffer>> TransferLiteralsToDevice(
const absl::Span<const std::unique_ptr<Literal>> literals);
StatusOr<std::unique_ptr<Literal>> TransferLiteralFromDevice(
const ShapedBuffer& buffer);
// Executes the given module with given literals as input and returns the
// result as a Literal.
//
// If run_hlo_passes is false, the module will be executed without Hlo
// optimization.
StatusOr<std::unique_ptr<Literal>> Execute(
std::unique_ptr<HloModule> module,
const absl::Span<const Literal* const> arguments,
bool run_hlo_passes = true, ExecutionProfile* profile = nullptr);
StatusOr<std::unique_ptr<Literal>> Execute(
std::unique_ptr<HloModule> module,
const absl::Span<const std::unique_ptr<Literal>> arguments,
bool run_hlo_passes = true, ExecutionProfile* profile = nullptr);
// As Execute(), but accepts and returns device buffers instead of host
// buffers.
StatusOr<ScopedShapedBuffer> ExecuteWithDeviceBuffers(
std::unique_ptr<HloModule> module,
const absl::Span<const ShapedBuffer* const> arguments,
bool run_hlo_passes = true, ExecutionProfile* profile = nullptr);
StatusOr<ScopedShapedBuffer> ExecuteWithDeviceBuffers(
std::unique_ptr<HloModule> module,
const absl::Span<const ScopedShapedBuffer> arguments,
bool run_hlo_passes = true, ExecutionProfile* profile = nullptr);
// Executes a given HLO module into a set of replicas, and returns a map
// with the replica number as key, and the corresponding returned literal as
// value.
StatusOr<std::vector<std::unique_ptr<Literal>>> ExecuteReplicated(
std::unique_ptr<HloModule> module,
const ReplicatedExecuteOptions& options);
// If backend is not created in the constructor, creates and returns the
// default backend. If creation fails, crashes the program.
//
// This creates the backend lazily so it's possible to instantiate an
// HloRunner in a program without any backends linked in.
Backend& backend();
const Backend& backend() const;
private:
// Creates an executable object given an HLO module. If run_hlo_passes is
// true, the HLO passes will be run before.
StatusOr<std::unique_ptr<Executable>> CreateExecutable(
std::unique_ptr<HloModule> module, bool run_hlo_passes);
// Creates a ServiceExecutableRunOptions object to configure a run on device,
// using the provided stream object. If device_assignment is not nullptr, it
// will be used to configure the replication parameters. Replicated executions
// should pass the device_assignment parameter.
ServiceExecutableRunOptions GetServiceRunOptionsForDevice(
int64 device, se::Stream* stream, DeviceAssignment* device_assignment);
std::unique_ptr<Backend> backend_;
};
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_HLO_RUNNER_H_
| [
"[email protected]"
] | |
0558a436bf94f4d50863ca00755d42c18f1ac7ab | 2400d76a8041b1240b12e2beac9723d2047a47a6 | /library/include/model/typedefs.h | 920bcc60143bd340d7d6ad9db42959718b46a1ac | [] | no_license | michalsuminski/Rental-Logic | be1b8fd7b722f784628deb429f152dc749a3083a | b75cfcd83dfecfdac07de2fc92c66464201dd0ad | refs/heads/main | 2023-04-02T07:24:30.873604 | 2021-04-15T12:18:33 | 2021-04-15T12:18:33 | 355,577,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | h | #ifndef CARRENTALPROJECT_TYPEDEFS_H
#define CARRENTALPROJECT_TYPEDEFS_H
#include <memory>
#include <functional>
class Address;
class Client;
class Item;
class Rent;
typedef std::shared_ptr <Client> ClientPtr;
typedef std::shared_ptr <Rent> RentPtr;
typedef std::shared_ptr <Item> ItemPtr;
typedef std::shared_ptr <Address> AddressPtr;
typedef std::function<bool(ClientPtr)> ClientPredicate;
typedef std::function<bool(RentPtr)> RentPredicate; // obojetnie jak zdefiniuje funkcje byle by sie zgadzaly typy przyjmuje RentPtr zwraca bool
typedef std::function<bool(ItemPtr)> ItemPredicate;
#endif //CARRENTALPROJECT_TYPEDEFS_H
| [
"[email protected]"
] | |
0444074a4fa63e923f802774192118b6011883df | 1118208a7f68175ce3138af84bd81e959e731f67 | /cpp/ch7/7_3.cpp | eacbc270a4614221d817b0896f46a47b43d8868f | [] | no_license | yoonsch217/crackingthecodinginterview6th | ff18c4275be8862e4a0d0e9b22ef265aed20873a | 60a3f3457be72926e701d21552b5851273a21ad5 | refs/heads/master | 2022-01-08T01:16:16.347074 | 2022-01-02T17:56:46 | 2022-01-02T17:56:46 | 201,307,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp |
class Jukebox{
private:
CDPlayer cdPlayer;
User user;
set<CD> cdCollection;
SongSelector ts;
public:
Jukebox(CDPlayer cdPlayer, User user, set<CD> cdCollection, SongSelector ts){
}
Song getCurrentSong(){return ts.getCurrentSong();}
void setUser(User u){this.user = u;}
};
class CDPlayer{
private:
Playlist p;
CD c;
public:
CDPlayer(CD c, Playlist p){
}
void playSong(Song s){
}
Playlist getPlaylist(){return p;}
void setPlaylist(Playlist p){ this.p = p;}
CD getCD(){ return c;}
void setCD(CD c){this.c = c;}
};
class Playlist{
private:
Song song;
Queue<Song> queue;
public:
Playlist(Song song, Queue<Song> queue){
}
Song getNextSToPlay(){
return queue.peek();
}
void queueUpSong(Song s){queue.add(s);}
};
| [
"[email protected]"
] | |
75296b5c1ed5b2a5a9ee0d3c12725705a23213ec | 98317d55cb8053131e700f5ad20c2f91481db4cd | /src/amount.h | 3027e070bc58997debfbb656d62bf7f306addbad | [
"MIT"
] | permissive | fertcoin/fertcoin | 4816ad7c08a64698177f0cc7d1e581dc1b954c85 | 1d644a3a15baea52acd45e82531bb1a839787d80 | refs/heads/main | 2023-07-10T01:22:09.630763 | 2021-08-10T21:37:17 | 2021-08-10T21:37:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,995 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018 The fertcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_AMOUNT_H
#define BITCOIN_AMOUNT_H
#include "serialize.h"
#include <stdlib.h>
#include <string>
typedef int64_t CAmount;
static const CAmount COIN = 100000000;
static const CAmount CENT = 1000000;
/** Type-safe wrapper class to for fee rates
* (how much to pay based on transaction size)
*/
class CFeeRate
{
private:
CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes
public:
CFeeRate() : nSatoshisPerK(0) {}
explicit CFeeRate(const CAmount& _nSatoshisPerK) : nSatoshisPerK(_nSatoshisPerK) {}
CFeeRate(const CAmount& nFeePaid, size_t nSize);
CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; }
CAmount GetFee(size_t size) const; // unit returned is satoshis
CAmount GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes
friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; }
friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; }
friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; }
friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; }
friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; }
std::string ToString() const;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(nSatoshisPerK);
}
};
#endif // BITCOIN_AMOUNT_H
| [
"[email protected]"
] | |
caa947584389ec00a2169b6e3b6fb8519df5d95b | d14650b04365c11a5d43c33f2acd4bbfae6b25b2 | /app/src/AppMesh.cpp | 63cb87a3c45424465c1c99726fa0655268dac3ba | [
"Apache-2.0"
] | permissive | ChaseDream2015/Viry3D | 6a16458b588ba552ac1d2e5e1533bc627a06a123 | b10f7b1259d246f4bdb9e389a24820ef86d5660f | refs/heads/master | 2021-06-27T12:35:35.516019 | 2017-09-15T16:42:16 | 2017-09-15T16:42:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,915 | cpp | /*
* Viry3D
* Copyright 2014-2017 by Stack - [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Main.h"
#include "Application.h"
#include "GameObject.h"
#include "Resource.h"
#include "graphics/Camera.h"
#include "graphics/Mesh.h"
#include "graphics/Material.h"
#include "graphics/Texture2D.h"
#include "renderer/MeshRenderer.h"
#include "ui/UILabel.h"
#include "time/Time.h"
using namespace Viry3D;
class AppMesh : public Application
{
public:
AppMesh();
virtual void Start();
virtual void Update();
WeakRef<GameObject> m_cube;
float m_rotate_deg;
};
#if 0
VR_MAIN(AppMesh);
#endif
AppMesh::AppMesh()
{
this->SetName("Viry3D::AppMesh");
this->SetInitSize(800, 600);
}
void AppMesh::Start()
{
this->CreateFPSUI(20, 1, 1);
auto camera = GameObject::Create("camera")->AddComponent<Camera>();
camera->GetTransform()->SetPosition(Vector3(0, 6, -10));
camera->GetTransform()->SetRotation(Quaternion::Euler(30, 0, 0));
camera->SetCullingMask(1 << 0);
auto mesh = Mesh::Create();
mesh->vertices.Add(Vector3(-1, 1, -1));
mesh->vertices.Add(Vector3(-1, -1, -1));
mesh->vertices.Add(Vector3(1, -1, -1));
mesh->vertices.Add(Vector3(1, 1, -1));
mesh->vertices.Add(Vector3(-1, 1, 1));
mesh->vertices.Add(Vector3(-1, -1, 1));
mesh->vertices.Add(Vector3(1, -1, 1));
mesh->vertices.Add(Vector3(1, 1, 1));
mesh->uv.Add(Vector2(0, 0));
mesh->uv.Add(Vector2(0, 1));
mesh->uv.Add(Vector2(1, 1));
mesh->uv.Add(Vector2(1, 0));
mesh->uv.Add(Vector2(1, 0));
mesh->uv.Add(Vector2(1, 1));
mesh->uv.Add(Vector2(0, 1));
mesh->uv.Add(Vector2(0, 0));
unsigned short triangles[] = {
0, 1, 2, 0, 2, 3,
3, 2, 6, 3, 6, 7,
7, 6, 5, 7, 5, 4,
4, 5, 1, 4, 1, 0,
4, 0, 3, 4, 3, 7,
1, 5, 6, 1, 6, 2
};
mesh->triangles.AddRange(triangles, 36);
auto mat = Material::Create("Diffuse");
mesh->Update();
auto obj = GameObject::Create("mesh");
auto renderer = obj->AddComponent<MeshRenderer>();
renderer->SetSharedMesh(mesh);
renderer->SetSharedMaterial(mat);
Resource::LoadTextureAsync("Assets/AppMesh/wow.png.tex",
[=] (Ref<Object> obj)
{
auto tex = RefCast<Texture>(obj);
mat->SetMainTexture(tex);
});
m_cube = obj;
m_rotate_deg = 0;
Resource::LoadGameObjectAsync("Assets/AppMesh/plane.prefab");
}
void AppMesh::Update()
{
m_cube.lock()->GetTransform()->SetLocalRotation(Quaternion::Euler(0, m_rotate_deg, 0));
m_rotate_deg += 30 * Time::GetDeltaTime();
}
| [
"[email protected]"
] | |
e787f3a341b7c37c903414043ead2cc5e1684ad1 | 293b2fd1659b9af828392f42cb5ae2120700ad75 | /src/arraygenerator.cpp | 959518f0286490b2011d89297ca964413626d969 | [
"MIT"
] | permissive | mjakobczyk/minhash | bfb15451b5180f7edbe53846960636d7b580353c | 6295d6c439943d8ae4d587ad41ef429f1b82cd13 | refs/heads/master | 2020-03-22T16:24:50.467176 | 2019-01-31T21:13:46 | 2019-01-31T21:13:46 | 140,325,168 | 1 | 1 | MIT | 2019-01-31T21:13:47 | 2018-07-09T18:16:44 | C++ | UTF-8 | C++ | false | false | 609 | cpp | #include "arraygenerator.h"
ArrayGenerator::ArrayGenerator() : seed(time(0)), engine(seed), distribution(0, ULLONG_MAX)
{
}
uint64_t * ArrayGenerator::generateUint64Array(int size_)
{
uint64_t * array = new uint64_t[size_]();
return array;
}
uint64_t * ArrayGenerator::generateRandomUint64Array(int size_)
{
uint64_t * array = this->generateUint64Array(size_);
for (unsigned int i = 0; i < size_; ++i)
{
array[i] = this->generateRandomUint64();
}
return array;
}
uint64_t ArrayGenerator::generateRandomUint64()
{
return this->distribution(this->engine);
}
| [
"[email protected]"
] | |
38fad3e6f6bafefad6389fa3e89698cea730ca5a | 088ab92e4f8251fdceef9966149ea50f027f18c0 | /Assignment1/Q3.cpp | 2f1efb1c00be8e259f1c21d59fef47789dfe7de4 | [] | no_license | aashishbansal23/DataStructures-Algorithm-Practice | d221e9ececb360d781e33925e00222401fb501c8 | 53fcc0c881cbb720c0878c3dbaaa4330506f0f9b | refs/heads/master | 2023-05-03T23:43:20.453563 | 2021-05-24T16:32:09 | 2021-05-24T16:32:09 | 313,001,031 | 2 | 0 | null | 2021-03-17T15:42:48 | 2020-11-15T09:52:41 | C++ | UTF-8 | C++ | false | false | 124 | cpp | #include<stdio.h>
int main()
{
int i;
int arr[5] = {1};
for(i=0; i<5; i++){
printf("%d\n", arr[i]);
}
return 0;
}
| [
"[email protected]"
] | |
21157b7000f23a5f47c97b833f576be93b5ddb41 | cf86574f8dc83ac340b9f7816fb55c1583c3b5c8 | /ios/Pods/Flipper-Folly/folly/portability/Builtins.h | 109e620e5037564ec6587ee7b0e0a548ba0e9355 | [
"Apache-2.0",
"MIT"
] | permissive | juxtin/yarnu | 94b9f6068ebf3dd46b02173eb2cb9b394a06c969 | a3c3748a6738283644f252f87244880ca430c2f4 | refs/heads/master | 2022-12-30T07:17:56.708695 | 2020-09-28T19:29:02 | 2020-09-28T19:29:02 | 299,406,578 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,673 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#if defined(_WIN32) && !defined(__clang__)
#include <assert.h>
#include <folly/Portability.h>
#include <intrin.h>
#include <stdint.h>
namespace folly {
namespace portability {
namespace detail {
void call_flush_instruction_cache_self_pid(void* begin, size_t size);
}
} // namespace portability
} // namespace folly
FOLLY_ALWAYS_INLINE void __builtin___clear_cache(char* begin, char* end) {
if (folly::kIsArchAmd64) {
// x86_64 doesn't require the instruction cache to be flushed after
// modification.
} else {
// Default to flushing it for everything else, such as ARM.
folly::portability::detail::call_flush_instruction_cache_self_pid(
static_cast<void*>(begin), static_cast<size_t>(end - begin));
}
}
#if !defined(_MSC_VER) || (_MSC_VER < 1923)
FOLLY_ALWAYS_INLINE int __builtin_clz(unsigned int x) {
unsigned long index;
return int(_BitScanReverse(&index, (unsigned long)x) ? 31 - index : 32);
}
FOLLY_ALWAYS_INLINE int __builtin_clzl(unsigned long x) {
return __builtin_clz((unsigned int)x);
}
#if defined(_M_IX86) || defined(_M_ARM) || defined(_M_ARM64)
FOLLY_ALWAYS_INLINE int __builtin_clzll(unsigned long long x) {
if (x == 0) {
return 64;
}
unsigned int msb = (unsigned int)(x >> 32);
unsigned int lsb = (unsigned int)x;
return (msb != 0) ? __builtin_clz(msb) : 32 + __builtin_clz(lsb);
}
#else
FOLLY_ALWAYS_INLINE int __builtin_clzll(unsigned long long x) {
unsigned long index;
return int(_BitScanReverse64(&index, x) ? 63 - index : 64);
}
#endif
FOLLY_ALWAYS_INLINE int __builtin_ctz(unsigned int x) {
unsigned long index;
return int(_BitScanForward(&index, (unsigned long)x) ? index : 32);
}
FOLLY_ALWAYS_INLINE int __builtin_ctzl(unsigned long x) {
return __builtin_ctz((unsigned int)x);
}
#if defined(_M_IX86) || defined(_M_ARM) || defined(_M_ARM64)
FOLLY_ALWAYS_INLINE int __builtin_ctzll(unsigned long long x) {
unsigned long index;
unsigned int msb = (unsigned int)(x >> 32);
unsigned int lsb = (unsigned int)x;
if (lsb != 0) {
return (int)(_BitScanForward(&index, lsb) ? index : 64);
} else {
return (int)(_BitScanForward(&index, msb) ? index + 32 : 64);
}
}
#else
FOLLY_ALWAYS_INLINE int __builtin_ctzll(unsigned long long x) {
unsigned long index;
return int(_BitScanForward64(&index, x) ? index : 64);
}
#endif
#endif // !defined(_MSC_VER) || (_MSC_VER < 1923)
FOLLY_ALWAYS_INLINE int __builtin_ffs(int x) {
unsigned long index;
return int(_BitScanForward(&index, (unsigned long)x) ? index + 1 : 0);
}
FOLLY_ALWAYS_INLINE int __builtin_ffsl(long x) {
return __builtin_ffs(int(x));
}
#if defined(_M_IX86) || defined(_M_ARM) || defined(_M_ARM64)
FOLLY_ALWAYS_INLINE int __builtin_ffsll(long long x) {
int ctzll = __builtin_ctzll((unsigned long long)x);
return ctzll != 64 ? ctzll + 1 : 0;
}
#else
FOLLY_ALWAYS_INLINE int __builtin_ffsll(long long x) {
unsigned long index;
return int(_BitScanForward64(&index, (unsigned long long)x) ? index + 1 : 0);
}
FOLLY_ALWAYS_INLINE int __builtin_popcount(unsigned int x) {
return int(__popcnt(x));
}
#if !defined(_MSC_VER) || (_MSC_VER < 1923)
FOLLY_ALWAYS_INLINE int __builtin_popcountl(unsigned long x) {
static_assert(sizeof(x) == 4, "");
return int(__popcnt(x));
}
#endif // !defined(_MSC_VER) || (_MSC_VER < 1923)
#endif
#if !defined(_MSC_VER) || (_MSC_VER < 1923)
#if defined(_M_IX86)
FOLLY_ALWAYS_INLINE int __builtin_popcountll(unsigned long long x) {
return int(__popcnt((unsigned int)(x >> 32))) +
int(__popcnt((unsigned int)x));
}
#elif defined(_M_X64)
FOLLY_ALWAYS_INLINE int __builtin_popcountll(unsigned long long x) {
return int(__popcnt64(x));
}
#endif
#endif // !defined(_MSC_VER) || (_MSC_VER < 1923)
FOLLY_ALWAYS_INLINE void* __builtin_return_address(unsigned int frame) {
// I really hope frame is zero...
(void)frame;
assert(frame == 0);
return _ReturnAddress();
}
#endif
| [
"[email protected]"
] | |
bdf24097e097669b211c714772bc8df5805ee04e | 0b3d390032c56decc837dd8fe0f2ad676409e6e6 | /src/SerialPort.cpp | 64a479c0fd4a9d73c04b652d555507dbcfcf59c3 | [] | no_license | bielpiero/lucky_bea | fffc95cf3afde4487d321da57c67646b76be2e90 | f822020d1b85b4e2ab710269d79a071bfe33d1c7 | refs/heads/master | 2021-01-17T00:38:51.749145 | 2020-09-23T15:06:45 | 2020-09-23T15:06:45 | 28,190,460 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,844 | cpp | #include "SerialPort.h"
const uint16_t SerialPort::vendorId = 0x1ffb;
const size_t SerialPort::nProductIds = 4;
const uint16_t SerialPort::productIds[] = { 0x0089, 0x008a, 0x008b, 0x008c };
SerialPort::SerialPort(){
bool found = false;
libusb_init(&ctx);
libusb_device** list;
int count = libusb_get_device_list(ctx, &list);
for (int i = 0; i < count; i++) {
libusb_device* device = list[i];
struct libusb_device_descriptor desc;
libusb_get_device_descriptor(device, &desc);
if (isMaestroDevice(desc)) {
//printdev(device);
std::cout << "Pololu Maestro device detected..." << std::endl;
found = true;
libusb_device_handle* current_device;
int ret = libusb_open(device, ¤t_device);
device_handle.push_back(current_device);
}
}
libusb_free_device_list(list, 1);
if(!found){
std::cout << "No Pololu Maestro Device Detected..." << std::endl;
libusb_exit(ctx);
}
}
SerialPort::~SerialPort(){
for(int i = 0; i< device_handle.size(); i++){
libusb_close(device_handle[i]);
}
libusb_exit(ctx);
}
void SerialPort::printdev(libusb_device *dev) {
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0) {
cout<<"failed to get device descriptor"<<endl;
return;
}
cout<<"Number of possible configurations: "<<(int)desc.bNumConfigurations<< endl;
cout<<"Device Class: "<<(int)desc.bDeviceClass<< endl;
cout<<"VendorID: "<<desc.idVendor<< endl;
cout<<"ProductID: "<<desc.idProduct<<endl;
//cout<<"extra: " << desc.extra << endl;
libusb_config_descriptor *config;
libusb_get_config_descriptor(dev, 0, &config);
cout<<"Interfaces: "<<(int)config->bNumInterfaces<< endl;
const libusb_interface *inter;
const libusb_interface_descriptor *interdesc;
const libusb_endpoint_descriptor *epdesc;
for(int i=0; i<(int)config->bNumInterfaces; i++) {
inter = &config->interface[i];
cout<<"Number of alternate settings: "<<inter->num_altsetting<<endl;
for(int j=0; j<inter->num_altsetting; j++) {
interdesc = &inter->altsetting[j];
cout<<"Interface Number: "<<(int)interdesc->bInterfaceNumber<<" | ";
cout<<"Number of endpoints: "<<(int)interdesc->bNumEndpoints<<" | ";
for(int k=0; k<(int)interdesc->bNumEndpoints; k++) {
epdesc = &interdesc->endpoint[k];
cout<<"Descriptor Type: "<<(int)epdesc->bDescriptorType<<" | ";
cout<<"EP Address: "<<(int)epdesc->bEndpointAddress<< endl;
}
}
}
cout<<endl<<endl<<endl;
libusb_free_config_descriptor(config);
}
bool SerialPort::isMaestroDevice(libusb_device_descriptor& desc) {
if (desc.idVendor == vendorId) {
for (int i = 0; i < nProductIds; i++) {
if (desc.idProduct == productIds[i]) {
// vendor and product both matched
return true;
}
}
}
// no product id match
return false;
}
int SerialPort::controlTransfer(uint8_t cardId, uint8_t request, uint16_t value, uint16_t index) {
int ret = libusb_control_transfer(
device_handle[cardId], 0x40, request,
value, index,
(unsigned char*) 0, 0, 5000);
return 0;
}
void SerialPort::setTarget(uint8_t cardId, uint8_t servo, uint16_t value) {
controlTransfer(cardId, REQUEST_SET_TARGET, value, servo);
}
void SerialPort::setSpeed(uint8_t cardId, uint8_t servo, uint16_t value) {
controlTransfer(cardId, REQUEST_SET_SERVO_VARIABLE, value, servo);
}
void SerialPort::setAcceleration(uint8_t cardId, uint8_t servo, uint16_t value) {
// setting high bit on servo number indicates acceleration
controlTransfer(cardId, REQUEST_SET_SERVO_VARIABLE, value, servo | 0x80);
} | [
"[email protected]"
] | |
2c8a9fc6aaa48edace4bddb9c11bda61ebfa343b | 1815b64a60fa9d0ccd3270d53cd176536558153f | /chrome/browser/ui/webui/settings/chromeos/os_apps_page/app_notification_handler_unittest.cc | 366cb910f9c6119bd96f8923ef0403145650181e | [
"BSD-3-Clause"
] | permissive | violetForeden/chromium | ae8c65739de96dd141136e6523b4a2c5978491d9 | 43f3ea874caca29eead4dc4dfb1c8ce6f11fa5da | refs/heads/main | 2023-06-29T09:43:21.454580 | 2021-09-12T08:27:01 | 2021-09-12T08:27:01 | 405,598,541 | 1 | 0 | BSD-3-Clause | 2021-09-12T09:22:55 | 2021-09-12T09:22:55 | null | UTF-8 | C++ | false | false | 6,864 | cc | // Copyright 2021 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.
#include "chrome/browser/ui/webui/settings/chromeos/os_apps_page/app_notification_handler.h"
#include <memory>
#include <utility>
#include <vector>
#include "ash/public/cpp/message_center_ash.h"
#include "base/logging.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/ui/webui/app_management/app_management.mojom.h"
#include "chrome/test/base/testing_profile.h"
#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "components/services/app_service/public/mojom/types.mojom.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace settings {
namespace {
class FakeMessageCenterAsh : public ash::MessageCenterAsh {
public:
FakeMessageCenterAsh() = default;
~FakeMessageCenterAsh() override = default;
// MessageCenterAsh override:
void SetQuietMode(bool in_quiet_mode) override {
if (in_quiet_mode != in_quiet_mode_) {
in_quiet_mode_ = in_quiet_mode;
NotifyOnQuietModeChanged(in_quiet_mode);
}
}
bool IsQuietMode() const override { return in_quiet_mode_; }
private:
bool in_quiet_mode_ = false;
};
} // namespace
class AppNotificationHandlerTest : public testing::Test {
public:
AppNotificationHandlerTest()
: task_environment_(content::BrowserTaskEnvironment::REAL_IO_THREAD),
profile_(std::make_unique<TestingProfile>()) {}
~AppNotificationHandlerTest() override = default;
void SetUp() override {
ash::MessageCenterAsh::SetForTesting(&message_center_ash_);
app_service_proxy_ =
std::make_unique<apps::AppServiceProxyChromeOs>(profile_.get());
handler_ =
std::make_unique<AppNotificationHandler>(app_service_proxy_.get());
}
void TearDown() override {
handler_.reset();
app_service_proxy_.reset();
ash::MessageCenterAsh::SetForTesting(nullptr);
}
protected:
bool GetHandlerQuietModeState() { return handler_->in_quiet_mode_; }
void SetQuietModeState(bool quiet_mode_enabled) {
handler_->SetQuietMode(quiet_mode_enabled);
}
void CreateAndStoreFakeApp(
std::string fake_id,
apps::mojom::AppType app_type,
std::uint32_t permission_type,
apps::mojom::PermissionValueType permission_value_type) {
std::vector<apps::mojom::PermissionPtr> fake_permissions;
apps::mojom::PermissionPtr fake_permission = apps::mojom::Permission::New();
fake_permission->permission_id = permission_type;
fake_permission->value_type = permission_value_type;
fake_permission->value = /*True=*/1;
fake_permission->is_managed = false;
fake_permissions.push_back(fake_permission.Clone());
std::vector<apps::mojom::AppPtr> fake_apps;
apps::mojom::AppPtr fake_app = apps::mojom::App::New();
fake_app->app_type = app_type;
fake_app->app_id = fake_id;
fake_app->show_in_management = apps::mojom::OptionalBool::kTrue;
fake_app->readiness = apps::mojom::Readiness::kReady;
fake_app->permissions = std::move(fake_permissions);
fake_apps.push_back(fake_app.Clone());
UpdateAppRegistryCache(fake_apps, app_type);
}
void UpdateAppRegistryCache(std::vector<apps::mojom::AppPtr>& fake_apps,
apps::mojom::AppType app_type) {
app_service_proxy_->AppRegistryCache().OnApps(std::move(fake_apps),
app_type, false);
}
bool CheckIfFakeAppInList(std::string fake_id) {
bool app_found = false;
for (app_notification::mojom::AppPtr const& app : handler_->apps_) {
if (app->id.compare(fake_id) == 0) {
app_found = true;
break;
}
}
return app_found;
}
private:
std::unique_ptr<AppNotificationHandler> handler_;
content::BrowserTaskEnvironment task_environment_;
std::unique_ptr<TestingProfile> profile_;
std::unique_ptr<apps::AppServiceProxyChromeOs> app_service_proxy_;
FakeMessageCenterAsh message_center_ash_;
};
// Tests for update of in_quiet_mode_ variable by MessageCenterAsh observer
// OnQuietModeChange() after quiet mode state change between true and false.
TEST_F(AppNotificationHandlerTest, TestOnQuietModeChanged) {
ash::MessageCenterAsh::Get()->SetQuietMode(true);
EXPECT_TRUE(GetHandlerQuietModeState());
ash::MessageCenterAsh::Get()->SetQuietMode(false);
EXPECT_FALSE(GetHandlerQuietModeState());
}
// Tests for update of in_quiet_mode_ variable after setting state
// with MessageCenterAsh SetQuietMode() true and false.
TEST_F(AppNotificationHandlerTest, TestSetQuietMode) {
SetQuietModeState(true);
EXPECT_TRUE(GetHandlerQuietModeState());
SetQuietModeState(false);
EXPECT_FALSE(GetHandlerQuietModeState());
}
// Tests the filtering of the GetApps() function
// by creating multiple fake apps with different parameters
// and confirming that GetApps() only adds the correct ones.
// GetApps() should only add kArc and kWeb apps
// with the NOTIFICATIONS permission.
TEST_F(AppNotificationHandlerTest, TestGetAppsFiltering) {
CreateAndStoreFakeApp(
"arcAppWithNotifications", apps::mojom::AppType::kArc,
static_cast<std::uint32_t>(
app_management::mojom::ArcPermissionType::NOTIFICATIONS),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp(
"webAppWithNotifications", apps::mojom::AppType::kWeb,
static_cast<std::uint32_t>(
app_management::mojom::PwaPermissionType::NOTIFICATIONS),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp("arcAppWithCamera", apps::mojom::AppType::kArc,
static_cast<std::uint32_t>(
app_management::mojom::ArcPermissionType::CAMERA),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp(
"webAppWithGeolocation", apps::mojom::AppType::kWeb,
static_cast<std::uint32_t>(
app_management::mojom::PwaPermissionType::GEOLOCATION),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp(
"pluginVmAppWithPrinting", apps::mojom::AppType::kPluginVm,
static_cast<std::uint32_t>(
app_management::mojom::PluginVmPermissionType::PRINTING),
apps::mojom::PermissionValueType::kBool);
EXPECT_TRUE(CheckIfFakeAppInList("arcAppWithNotifications"));
EXPECT_TRUE(CheckIfFakeAppInList("webAppWithNotifications"));
EXPECT_FALSE(CheckIfFakeAppInList("arcAppWithCamera"));
EXPECT_FALSE(CheckIfFakeAppInList("webAppWithGeolocation"));
EXPECT_FALSE(CheckIfFakeAppInList("pluginVmAppWithPrinting"));
}
} // namespace settings
} // namespace chromeos
| [
"[email protected]"
] | |
c5650c03166bf06b32aa5935cda0ebcbe03e2621 | d0317ba18b027ad04d802cadaf2d69dc319d98cb | /lib/UnoCore/Backends/CPlusPlus/Uno/ObjectModel.h | b66b8570b72ea4c43ede05f37763c94b482e67bf | [
"MIT"
] | permissive | afrog33k/uno | aa1aebf2edd7c40ac9e37b95c8e02703f492c73f | adf8035c96c562ac6c50d7b08dbf8ee8457befb1 | refs/heads/master | 2020-04-09T01:55:57.759640 | 2018-11-01T18:10:01 | 2018-11-01T18:10:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,960 | h | // @(MSG_ORIGIN)
// @(MSG_EDIT_WARNING)
#pragma once
#include <atomic>
#include <cstdarg>
#include <cstdlib>
#include <exception>
#if @(REFLECTION:Defined)
#include <Uno/Reflection.h>
#else
#include <Uno/Memory.h>
#endif
@{Uno.Exception:ForwardDeclaration}
struct uObjectMonitor;
/**
\addtogroup ObjectModel
@{
*/
struct uObject
{
uType* __type;
uWeakObject* __weakptr;
uObjectMonitor* __monitor;
#ifdef DEBUG_ARC
size_t __size;
size_t __id;
#endif
std::atomic_int __retains;
uType* GetType() const;
int32_t GetHashCode();
bool Equals(uObject* object);
uString* ToString();
protected:
uObject() {}
private:
uObject& operator =(const uObject&);
uObject(const uObject&);
};
enum uTypeType
{
uTypeTypeVoid,
uTypeTypeEnum,
uTypeTypeStruct,
uTypeTypeGeneric,
uTypeTypeByRef,
uTypeTypeClass,
uTypeTypeDelegate,
uTypeTypeInterface,
uTypeTypeArray,
};
enum uTypeState
{
uTypeStateUninitialized,
uTypeStateBuilding,
uTypeStateBuilt,
uTypeStateInitializing,
uTypeStateInitialized
};
enum uTypeFlags
{
uTypeFlagsAbstract = 1 << 0,
uTypeFlagsRetainStruct = 1 << 1,
uTypeFlagsClosedKnown = 1 << 2,
uTypeFlagsClosed = 1 << 3,
};
enum uFieldFlags
{
uFieldFlagsConstrained = 1 << 0,
uFieldFlagsInherited = 1 << 1,
uFieldFlagsStatic = 1 << 2,
uFieldFlagsWeak = 1 << 3
};
struct uFieldInfo
{
union {
void* Address;
uintptr_t Offset;
};
uType* Type;
size_t Flags;
};
struct uInterfaceInfo
{
uType* Type;
size_t Offset;
};
struct uOperatorTable
{
void(*fp_StorePtr)(uType*, const void*, void*);
void(*fp_StoreValue)(uType*, const void*, void*);
void(*fp_StoreStrong)(uType*, const void*, void*);
void(*fp_StoreStrongValue)(uType*, const void*, void*);
};
struct uType : uObject
{
const char* FullName;
uint32_t Type;
uint16_t Flags;
uint16_t State;
size_t TypeSize;
size_t ValueSize;
size_t ObjectSize;
size_t Alignment;
#ifdef DEBUG_ARC
size_t ObjectCount;
#endif
// Initialization
void Build();
void Init();
size_t DependencyCount;
uType** DependencyTypes;
void SetDependencies(uType* first, ...);
// Inheritance
uType* Base;
void SetBase(uType* base);
// Interfaces
size_t InterfaceCount;
uInterfaceInfo* Interfaces;
void SetInterfaces(uType* type, size_t offset, ...);
const void* InterfacePtr(const uObject* object);
// Type checking
bool Is(const uType* type) const;
// Fields
size_t FieldCount;
uFieldInfo* Fields;
void SetFields(size_t inherited);
void SetFields(size_t inherited, uType* type, uintptr_t offset, int flags, ...);
uTField Field(uTRef object, size_t index);
uTField Field(size_t index);
// Generics
uType* Definition;
size_t GenericCount;
uType** Generics;
size_t MethodTypeCount;
uType** MethodTypes;
size_t PrecalcCount;
uType** PrecalcTypes;
void SetPrecalc(uType* first, ...);
bool IsClosed();
uType* NewMethodType(size_t genericCount, size_t precalcCount = 0, size_t dependencyCount = 0, bool isDefinition = true);
uType* NewMethodType(uType* definition);
uType* GetBase(uType* definition);
uType* GetVirtual(size_t index, uType* method);
uType* MakeGeneric(size_t count, uType** args);
uType* MakeMethod(size_t index, uType* first, ...);
uType* MakeType(uType* first, ...);
uType* Precalced(size_t index);
uType* T(size_t index);
uType* U(size_t index);
uObject* New();
// Arrays
uArrayType* _array;
uArrayType* Array();
// Pass-by-ref
uByRefType* _byRef;
uByRefType* ByRef();
// Operators
uOperatorTable* Operators;
// ARC
uObjectRefs Refs;
// Reflection
#if @(REFLECTION:Defined)
uReflection Reflection;
#endif
// V-table
void(*fp_build_)(uType*);
const void* fp_ctor_;
void(*fp_cctor_)(uType*);
void(*fp_Finalize)(uObject*);
void(*fp_GetHashCode)(uObject*, int32_t*);
void(*fp_Equals)(uObject*, uObject*, bool*);
void(*fp_ToString)(uObject*, uString**);
};
struct uTypeOptions
{
uType* BaseDefinition;
size_t FieldCount;
size_t GenericCount;
size_t MethodTypeCount;
size_t InterfaceCount;
size_t DependencyCount;
size_t PrecalcCount;
size_t ObjectSize;
size_t TypeSize;
size_t ValueSize;
size_t Alignment;
uTypeOptions() {
memset(this, 0, sizeof(uTypeOptions));
}
};
inline uType* uObject::GetType() const {
return __type;
}
inline int32_t uObject::GetHashCode() {
int32_t result;
return (*__type->fp_GetHashCode)(this, &result), result;
}
inline bool uObject::Equals(uObject* object) {
bool result;
return (*__type->fp_Equals)(this, object, &result), result;
}
inline uString* uObject::ToString() {
uString* result;
return (*__type->fp_ToString)(this, &result), result;
}
#define U_IS_VOID(type) ((type)->Type == uTypeTypeVoid)
#define U_IS_BY_REF(type) ((type)->Type >= uTypeTypeByRef)
#define U_IS_OBJECT(type) ((type)->Type >= uTypeTypeClass)
#define U_IS_VALUE(type) ((type)->Type < uTypeTypeByRef)
#define U_IS_ABSTRACT(type) ((type)->Flags & uTypeFlagsAbstract)
uType* uObject_typeof();
uType* uVoid_typeof();
/** @} */
/**
\addtogroup Exception
@{
*/
struct uThrowable : public std::exception
{
@{Uno.Exception} Exception;
const char* Function;
int Line;
uThrowable(@{Uno.Exception} exception, const char* func, int line);
uThrowable(const uThrowable& copy);
virtual ~uThrowable() throw();
virtual const char* what() const throw();
static U_NORETURN void ThrowIndexOutOfRange(const char* func, int line);
static U_NORETURN void ThrowInvalidCast(const char* func, int line);
static U_NORETURN void ThrowInvalidCast(const uType* from, const uType* to, const char* func, int line);
static U_NORETURN void ThrowInvalidOperation(const char* message, const char* func, int line);
static U_NORETURN void ThrowNullReference(const char* func, int line);
private:
uThrowable& operator =(const uThrowable&);
uThrowable();
};
#define U_THROW(exception) throw uThrowable((exception), U_FUNCTION, __LINE__)
#define U_THROW_ICE() uThrowable::ThrowInvalidCast(U_FUNCTION, __LINE__)
#define U_THROW_ICE2(from, to) uThrowable::ThrowInvalidCast(from, to, U_FUNCTION, __LINE__)
#define U_THROW_IOE(message) uThrowable::ThrowInvalidOperation(message, U_FUNCTION, __LINE__)
#define U_THROW_IOORE() uThrowable::ThrowIndexOutOfRange(U_FUNCTION, __LINE__)
#define U_THROW_NRE() uThrowable::ThrowNullReference(U_FUNCTION, __LINE__)
/** @} */
/**
\addtogroup Class
@{
*/
struct uClassType : uType
{
static uClassType* New(const char* name, uTypeOptions& options);
};
uObject* uNew(uType* type);
uObject* uNew(uType* type, size_t size);
inline bool uIs(const uObject* object, const uType* type) {
return object && object->__type->Is(type);
}
template<class T>
T uAs(uObject* object, const uType* type) {
U_ASSERT(sizeof(T) == type->ValueSize);
return object && object->__type->Is(type) ? (T)object : NULL;
}
template<class T>
T uCast(uObject* object, const uType* type) {
U_ASSERT(sizeof(T) == type->ValueSize);
if (object && !object->__type->Is(type))
U_THROW_ICE2(object->__type, type);
return (T)object;
}
template<class T>
T uPtr(const T& ptr) {
if (!ptr) U_THROW_NRE();
return ptr;
}
template<class T>
T uPtr(const uSStrong<T>& ref) {
return uPtr(ref._object);
}
template<class T>
T uPtr(const uStrong<T>& ref) {
return uPtr(ref._object);
}
template<class T>
T uPtr(const uSWeak<T>& ref) {
return uPtr((T)uLoadWeak(ref._object));
}
template<class T>
T uPtr(const uWeak<T>& ref) {
return uPtr((T)uLoadWeak(ref._object));
}
/** @} */
/**
\addtogroup Interface
@{
*/
struct uInterfaceType : uType
{
static uInterfaceType* New(const char* name, size_t genericCount = 0, size_t methodCount = 0);
};
struct uInterface
{
uObject* _object;
const void* _vtable;
uInterface(uObject* object, uType* interfaceType) {
U_ASSERT(interfaceType);
_object = object;
_vtable = interfaceType->InterfacePtr(object);
}
template<class T>
const T* VTable() const {
U_ASSERT(_object && _vtable);
return (const T*)_vtable;
}
uObject* operator ->() const {
return _object;
}
operator uObject*() const {
return _object;
}
};
/** @} */
/**
\addtogroup Delegate
@{
*/
struct uDelegateType : uType
{
uType* ReturnType;
size_t ParameterCount;
uType** ParameterTypes;
void SetSignature(uType* returnType, ...);
static uDelegateType* New(const char* name, size_t parameterCount = 0, size_t genericCount = 0);
};
struct uDelegate : uObject
{
void* _this;
const void* _func;
uType* _generic;
uStrong<uObject*> _object;
uStrong<uDelegate*> _prev;
void InvokeVoid();
void InvokeVoid(void* arg);
void Invoke(uTRef retval, void** args, size_t count);
void Invoke(uTRef retval, size_t count = 0, ...);
uObject* Invoke(uArray* args = NULL);
uObject* Invoke(size_t count, ...);
uDelegate* Copy();
static uDelegate* New(uType* type, const void* func, uObject* object = NULL, uType* generic = NULL);
static uDelegate* New(uType* type, uObject* object, size_t offset, uType* generic = NULL);
static uDelegate* New(uType* type, const uInterface& iface, size_t offset, uType* generic = NULL);
};
/** @} */
/**
\addtogroup Struct
@{
*/
struct uStructType : uType
{
static uStructType* New(const char* name, uTypeOptions& options);
// Value adapters (usable w/o boxing)
void(*fp_GetHashCode_struct)(void*, uType*, int32_t*);
void(*fp_Equals_struct)(void*, uType*, uObject*, bool*);
void(*fp_ToString_struct)(void*, uType*, uString**);
};
uObject* uBoxPtr(uType* type, const void* src, void* stack = NULL, bool ref = false);
void uUnboxPtr(uType* type, uObject* object, void* dst);
template<class T>
uObject* uBox(uType* type, const T& value, void* stack = NULL) {
U_ASSERT(type && type->ValueSize == sizeof(T));
return uBoxPtr(type, &value, stack, true);
}
template<class T>
T uDefault() {
T t;
return memset(&t, 0, sizeof(T)), t;
}
template<class T>
T uUnbox(uType* type, uObject* object) {
T t;
U_ASSERT(type && type->ValueSize == sizeof(T));
return uUnboxPtr(type, object, &t), t;
}
template<class T>
T uUnbox(uObject* object) {
U_ASSERT(object && object->__type->ValueSize == sizeof(T));
return *(const T*)((const uint8_t*)object + sizeof(uObject));
}
/** @} */
/**
\addtogroup Enum
@{
*/
struct uEnumLiteral
{
uString* Name;
int64_t Value;
};
struct uEnumType : uType
{
size_t LiteralCount;
uEnumLiteral* Literals;
void SetLiterals(const char* name, int64_t value, ...);
static uEnumType* New(const char* name, uType* base, size_t literalCount = 0);
};
struct uEnum
{
static bool TryParse(uType* type, uString* value, bool ignoreCase, uTRef result);
static uString* GetString(uType* type, void* value);
};
/** @} */
/**
\addtogroup Array
@{
*/
struct uArrayType : uType
{
uType* ElementType;
};
struct uArray : uObject
{
void* _ptr;
int32_t _length;
int32_t Length() const { return _length; }
const void* Ptr() const { return _ptr; }
void* Ptr() { return _ptr; }
void MarshalPtr(int32_t index, const void* value, size_t size);
uTField TItem(int32_t index);
uTField TUnsafe(int32_t index);
template<class T>
T& Item(int32_t index) {
U_ASSERT(sizeof(T) == ((uArrayType*)__type)->ElementType->ValueSize);
if (index < 0 || index >= _length)
U_THROW_IOORE();
return ((T*)_ptr)[index];
}
template<class T>
uStrong<T>& Strong(int32_t index) {
U_ASSERT(sizeof(T) == ((uArrayType*)__type)->ElementType->ValueSize);
if (index < 0 || index >= _length)
U_THROW_IOORE();
return ((uStrong<T>*)_ptr)[index];
}
template<class T>
T& Unsafe(int32_t index) {
U_ASSERT(sizeof(T) == ((uArrayType*)__type)->ElementType->ValueSize &&
index >= 0 && index < _length);
return ((T*)_ptr)[index];
}
template<class T>
uStrong<T>& UnsafeStrong(int32_t index) {
U_ASSERT(sizeof(T) == ((uArrayType*)__type)->ElementType->ValueSize &&
index >= 0 && index < _length);
return ((uStrong<T>*)_ptr)[index];
}
static uArray* New(uType* type, int32_t length, const void* optionalData = NULL);
static uArray* InitT(uType* type, int32_t length, ...);
template<class T>
static uArray* Init(uType* type, int32_t length, ...) {
va_list ap;
va_start(ap, length);
uArray* array = New(type, length);
for (int32_t i = 0; i < length; i++) {
T item = va_arg(ap, T);
array->MarshalPtr(i, &item, sizeof(T));
}
va_end(ap);
return array;
}
};
/** @} */
/**
\addtogroup String
@{
*/
struct uString : uObject
{
char16_t* _ptr;
int32_t _length;
int32_t Length() const { return _length; }
const char16_t* Ptr() const { return _ptr; }
const char16_t& Item(int32_t index) const {
if (index < 0 || index >= _length)
U_THROW_IOORE();
return _ptr[index];
}
const char16_t& Unsafe(int32_t index) const {
return _ptr[index];
}
static uString* New(int32_t length);
static uString* Ansi(const char* cstr);
static uString* Ansi(const char* cstr, size_t length);
static uString* Utf8(const char* mutf8);
static uString* Utf8(const char* mutf8, size_t length);
static uString* Utf16(const char16_t* nullTerminatedUtf16);
static uString* Utf16(const char16_t* utf16, size_t length);
static uString* Const(const char* mutf8);
static uString* CharArray(const uArray* chars);
static uString* CharArrayRange(const uArray* chars, int32_t startIndex, int32_t length);
static bool Equals(const uString* left, const uString* right, bool ignoreCase = false);
};
// Leak warning: The returned string must be deleted using free()
char* uAllocCStr(const uString* string, size_t* length = NULL);
// Deprecated: Use free() instead - the parameter type shouldn't be const
void DEPRECATED("Use free() instead") uFreeCStr(const char* cstr);
struct uCString
{
char* Ptr;
size_t Length;
uCString(const uString* string) {
Ptr = uAllocCStr(string, &Length);
}
uCString(const uSStrong<uString*>& string){
Ptr = uAllocCStr(string._object, &Length);
}
~uCString() {
free(Ptr);
}
};
/** @} */
/**
\addtogroup Generic
@{
*/
struct uGenericType : uType
{
size_t GenericIndex;
};
struct uTBase
{
uType* _type;
void* _address;
uTBase(uType* type, void* address)
: _type(type)
, _address(address) {
U_ASSERT(type && address);
}
uObject* ObjectPtr() {
return *(uObject**)_address;
}
void* ValuePtr() {
return _address;
}
operator void*() {
return U_IS_OBJECT(_type)
? *(void**)_address
: _address;
}
bool operator !() const {
return U_IS_OBJECT(_type) && !*(uObject**)_address;
}
private:
uTBase& operator =(const uTBase&) { U_FATAL(); }
uTBase() {}
};
struct uTRef
{
void* _address;
uTRef(void* address)
: _address(address) {
}
template<class T>
T& Value(uType* type) {
U_ASSERT(_address);
return *(T*)_address;
}
uTRef& Default(uType* type) {
U_ASSERT(_address && type);
memset(_address, 0, type->ValueSize);
return *this;
}
uTBase Load(uType* type) {
return uTBase(type, _address);
}
uTRef& Store(uType* type, const void* value) {
(*type->Operators->fp_StoreValue)(type, value, _address);
return *this;
}
uTRef& Store(const uTBase& value) {
(*value._type->Operators->fp_StorePtr)(value._type, value._address, _address);
return *this;
}
private:
uTRef& operator =(const uTRef&);
uTRef();
};
struct uTStrongRef : uTBase
{
uTStrongRef(uType* type, void* address)
: uTBase(type, address) {
if (U_IS_OBJECT(_type))
uAutoRelease(*(uObject**)_address);
}
uTStrongRef(const uTStrongRef& copy)
: uTBase(copy) {
if (U_IS_OBJECT(_type))
uAutoRelease(*(uObject**)_address);
}
~uTStrongRef() {
if (U_IS_OBJECT(_type))
uRetain(*(uObject**)_address);
}
operator uTRef&() {
return (uTRef&)_address;
}
};
struct uTField : uTBase
{
uTField(uType* type, void* address)
: uTBase(type, address) {
U_ASSERT(!U_IS_OBJECT(type) || !*(uObject**)address || uIs(*(uObject**)address, type));
}
uTField& Default() {
if (U_IS_OBJECT(_type))
uAutoRelease(*(uObject**)_address);
else if (_type->Flags & uTypeFlagsRetainStruct)
uAutoReleaseStruct(_type, _address);
memset(_address, 0, _type->ValueSize);
return *this;
}
template<class T>
uStrong<T>& Strong() {
U_ASSERT(sizeof(T) == _type->ValueSize);
return *(uStrong<T>*)_address;
}
template<class T>
T& Value() {
U_ASSERT(sizeof(T) == _type->ValueSize);
return *(T*)_address;
}
uTField& operator =(const uTField& value) {
(*_type->Operators->fp_StoreStrong)(_type, value._address, _address);
return *this;
}
uTField& operator =(const uTBase& value) {
(*_type->Operators->fp_StoreStrong)(_type, value._address, _address);
return *this;
}
uTField& operator =(const void* value) {
(*_type->Operators->fp_StoreStrongValue)(_type, value, _address);
return *this;
}
uTField operator [](size_t index) {
return _type->Field(_address, index);
}
uTStrongRef operator &() {
return uTStrongRef(_type, _address);
}
bool operator !() const {
return U_IS_OBJECT(_type) && !*(uObject**)_address;
}
};
struct uT : uTBase
{
uT(uType* type, void* stack)
: uTBase(type, stack) {
memset(stack, 0, type->ValueSize);
}
uT(const uT& copy)
: uTBase(copy) {
if (_type->Flags & uTypeFlagsRetainStruct)
uRetainStruct(_type, _address);
}
~uT() {
if (_type->Flags & uTypeFlagsRetainStruct)
uAutoReleaseStruct(_type, _address);
}
uT& Default() {
memset(_address, 0, _type->ValueSize);
return *this;
}
uT& operator =(const uT& value) {
(*_type->Operators->fp_StorePtr)(_type, value._address, _address);
return *this;
}
uT& operator =(const uTBase& value) {
(*_type->Operators->fp_StorePtr)(_type, value._address, _address);
return *this;
}
uT& operator =(const void* value) {
(*_type->Operators->fp_StoreValue)(_type, value, _address);
return *this;
}
uTField operator [](size_t index) {
return _type->Field(_address, index);
}
uTRef& operator &() {
return (uTRef&)_address;
}
bool operator !() const {
return U_IS_OBJECT(_type) && !*(uObject**)_address;
}
};
struct uTPtr
{
void* _ptr;
uTPtr(void* ptr)
: _ptr(ptr) {
}
uTRef& operator &() {
return *(uTRef*)this;
}
operator void*() const {
return _ptr;
}
private:
uTPtr& operator =(const uTPtr&);
uTPtr();
};
template<class T>
bool uIs(const uType* type, const T& value, const uType* test) {
U_ASSERT(type);
return U_IS_OBJECT(type)
? uIs(*(const uObject**)&value, test)
: type->Is(test);
}
template<class T>
uTPtr uConstrain(const uType* type, const T& value) {
U_ASSERT(type && type->ValueSize == sizeof(T));
return U_IS_VALUE(type)
? const_cast<T*>(&value)
: *(void**)&value;
}
inline uTPtr uUnboxAny(const uType* type, uObject* object) {
U_ASSERT(type);
return U_IS_VALUE(type)
? (uint8_t*)uPtr(object) + sizeof(uObject)
: (void*)object;
}
inline uTField uArray::TItem(int32_t index) {
if (index < 0 || index >= _length) U_THROW_IOORE();
uType* type = ((uArrayType*)__type)->ElementType;
return uTField(type, (uint8_t*)_ptr + type->ValueSize * index);
}
inline uTField uArray::TUnsafe(int32_t index) {
uType* type = ((uArrayType*)__type)->ElementType;
return uTField(type, (uint8_t*)_ptr + type->ValueSize * index);
}
inline uTField uType::Field(size_t index) {
U_ASSERT(index < FieldCount);
uFieldInfo& field = Fields[index];
U_ASSERT(field.Flags == uFieldFlagsStatic);
return uTField(field.Type, field.Address);
}
inline uTField uType::Field(uTRef object, size_t index) {
U_ASSERT(index < FieldCount);
uFieldInfo& field = Fields[index];
U_ASSERT(field.Flags == 0 && object._address);
return uTField(field.Type, (uint8_t*)object._address + field.Offset);
}
inline uType* uType::Precalced(size_t index) {
U_ASSERT(index < PrecalcCount);
return U_ASSERT_PTR(PrecalcTypes[index]);
}
inline uType* uType::T(size_t index) {
U_ASSERT(index < GenericCount);
return U_ASSERT_PTR(Generics[index]);
}
inline uType* uType::U(size_t index) {
uGenericType* generic = (uGenericType*)this;
U_ASSERT(Type == uTypeTypeGeneric &&
generic->GenericIndex + index < GenericCount);
return U_ASSERT_PTR(Generics[generic->GenericIndex + index]);
}
/** @} */
/**
\addtogroup ByRef
@{
*/
struct uByRefType : uType
{
uType* ValueType;
};
template<class T>
T* uCRef(const T& value) {
return const_cast<T*>(&value);
}
/** @} */
| [
"[email protected]"
] | |
6269ba354926148026e692cb95bd16888564dd43 | ba9322f7db02d797f6984298d892f74768193dcf | /emr/src/model/DescribeClusterServiceRequest.cc | b35aecf8a0dc080e1a5c177f3d7e62ab17b92ef2 | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 2,264 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/emr/model/DescribeClusterServiceRequest.h>
using AlibabaCloud::Emr::Model::DescribeClusterServiceRequest;
DescribeClusterServiceRequest::DescribeClusterServiceRequest() :
RpcServiceRequest("emr", "2016-04-08", "DescribeClusterService")
{}
DescribeClusterServiceRequest::~DescribeClusterServiceRequest()
{}
long DescribeClusterServiceRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void DescribeClusterServiceRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string DescribeClusterServiceRequest::getRegionId()const
{
return regionId_;
}
void DescribeClusterServiceRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
std::string DescribeClusterServiceRequest::getServiceName()const
{
return serviceName_;
}
void DescribeClusterServiceRequest::setServiceName(const std::string& serviceName)
{
serviceName_ = serviceName;
setParameter("ServiceName", serviceName);
}
std::string DescribeClusterServiceRequest::getClusterId()const
{
return clusterId_;
}
void DescribeClusterServiceRequest::setClusterId(const std::string& clusterId)
{
clusterId_ = clusterId;
setParameter("ClusterId", clusterId);
}
std::string DescribeClusterServiceRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void DescribeClusterServiceRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setParameter("AccessKeyId", accessKeyId);
}
| [
"[email protected]"
] | |
ee0b3059e9c58bbc3b38881c4eb026acd98dc3fc | 6101cf5997a2ee6b526d731fe094eb8fe102ddbf | /src/qt/recentrequeststablemodel.h | 38a0694cfff2900a0fb70d6df384a8a7f6481f45 | [
"MIT"
] | permissive | expicoin/expicore | d82458b54791f0f1b90fe394aa8c3f015b70e4d2 | 00461a9c66b2c80e6fa98601e5adabc7c50ff056 | refs/heads/master | 2020-05-23T09:01:43.348834 | 2019-05-26T13:29:47 | 2019-05-26T13:29:47 | 186,699,519 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,305 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#define BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#include "walletmodel.h"
#include <QAbstractTableModel>
#include <QDateTime>
#include <QStringList>
class CWallet;
class RecentRequestEntry
{
public:
RecentRequestEntry() : nVersion(RecentRequestEntry::CURRENT_VERSION), id(0) {}
static const int CURRENT_VERSION = 1;
int nVersion;
int64_t id;
QDateTime date;
SendCoinsRecipient recipient;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
unsigned int nDate = date.toTime_t();
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(id);
READWRITE(nDate);
READWRITE(recipient);
if (ser_action.ForRead())
date = QDateTime::fromTime_t(nDate);
}
};
class RecentRequestEntryLessThan
{
public:
RecentRequestEntryLessThan(int nColumn, Qt::SortOrder fOrder) : column(nColumn), order(fOrder) {}
bool operator()(RecentRequestEntry& left, RecentRequestEntry& right) const;
private:
int column;
Qt::SortOrder order;
};
/** Model for list of recently generated payment requests / expi: URIs.
* Part of wallet model.
*/
class RecentRequestsTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit RecentRequestsTableModel(CWallet* wallet, WalletModel* parent);
~RecentRequestsTableModel();
enum ColumnIndex {
Date = 0,
Label = 1,
Message = 2,
Amount = 3,
NUMBER_OF_COLUMNS
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex& parent) const;
int columnCount(const QModelIndex& parent) const;
QVariant data(const QModelIndex& index, int role) const;
bool setData(const QModelIndex& index, const QVariant& value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex& parent) const;
bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex& index) const;
/*@}*/
const RecentRequestEntry& entry(int row) const { return list[row]; }
void addNewRequest(const SendCoinsRecipient& recipient);
void addNewRequest(const std::string& recipient);
void addNewRequest(RecentRequestEntry& recipient);
public slots:
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
void updateDisplayUnit();
private:
WalletModel* walletModel;
QStringList columns;
QList<RecentRequestEntry> list;
int64_t nReceiveRequestsMaxId;
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void updateAmountColumnTitle();
/** Gets title for amount column including current display unit if optionsModel reference available. */
QString getAmountTitle();
};
#endif // BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
| [
"[email protected]"
] | |
2678bd45e77e9ca8bc90d7c7ab7e5385525f7c9f | 5f265e8a518b45e770a5ea3931a0913256f9a951 | /Source/Shooter/HeroAIController.cpp | 9dae9d24c78383d17850054ef6bb57f627e7acce | [] | no_license | filipstachowiak20/Shooter | 5ce00104da30e9d5135e8c2f2672cbdf0cdf84b6 | a397a8a4c156335233f2fa48a817b1233f4dbac6 | refs/heads/main | 2023-05-05T17:27:38.329250 | 2021-05-19T14:48:29 | 2021-05-19T14:48:29 | 367,042,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,925 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "HeroAIController.h"
#include "Hero.h"
#include "Perception/AIPerceptionComponent.h"
#include "Perception/AISenseConfig_Sight.h"
#include "BehaviorTree/BehaviorTree.h"
#include "BehaviorTree/BlackboardData.h"
#include "BehaviorTree/BlackboardComponent.h"
AHeroAIController::AHeroAIController()
{
PawnSensor = CreateDefaultSubobject<UAIPerceptionComponent>(TEXT("PawnSensor"));
SightConfig = CreateDefaultSubobject<UAISenseConfig_Sight>(TEXT("Sight Config"));
BlackboardComp = CreateDefaultSubobject<UBlackboardComponent>(TEXT("BlackboardComp"));
PawnSensor->SetDominantSense(SightConfig->GetSenseImplementation());
PawnSensor->ConfigureSense(*SightConfig);
SightConfig->SightRadius = 2500;
SightConfig->LoseSightRadius = (3000);
SightConfig->PeripheralVisionAngleDegrees = 120.0f;
SightConfig->DetectionByAffiliation.bDetectEnemies = true;
SightConfig->DetectionByAffiliation.bDetectNeutrals = true;
SightConfig->DetectionByAffiliation.bDetectFriendlies = true;
PawnSensor->ConfigureSense(*SightConfig);
SetPerceptionComponent(*PawnSensor);
GetPerceptionComponent()->OnTargetPerceptionUpdated.AddDynamic(this, &AHeroAIController::OnTargetPerceptionUpdated);
}
void AHeroAIController::BeginPlay()
{
Super::BeginPlay();
}
void AHeroAIController::LookForGun()
{ //check if there is a gun in radius, if so go pick it up
TArray<FHitResult> HitResultsGuns;
FCollisionObjectQueryParams QueryParams =FCollisionObjectQueryParams(ECollisionChannel::ECC_GameTraceChannel3);
if(!ControlledHero){return;}
FVector Loc = ControlledHero->GetActorLocation()+1000*ControlledHero->GetActorForwardVector();
GetWorld()->SweepMultiByObjectType(HitResultsGuns, ControlledHero->GetActorLocation(),ControlledHero->GetActorLocation(),FQuat(),
QueryParams,FCollisionShape::MakeSphere(2000));
if(HitResultsGuns.Num() > 0)
{
MoveToActor(HitResultsGuns[0].GetActor());
IsGunFound = true;
IsRunningTowardsGun = true;
return;
}
//gun not found, go to another random point
TArray<FHitResult> HitResultsPoints;
FCollisionObjectQueryParams QueryParams2 =FCollisionObjectQueryParams(ECollisionChannel::ECC_GameTraceChannel2);
GetWorld()->SweepMultiByObjectType(HitResultsPoints, ControlledHero->GetActorLocation(),ControlledHero->GetActorLocation(),FQuat(),
QueryParams2,FCollisionShape::MakeSphere(1000));
if(HitResultsPoints.Num()<1)
{return;}
auto RandomPoint = HitResultsPoints[FMath::RandRange(0,HitResultsPoints.Num()-1)].GetActor();
MoveToActor(RandomPoint);
}
void AHeroAIController::OnMoveCompleted(FAIRequestID RequestID, const FPathFollowingResult & Result)
{
Super::OnMoveCompleted(RequestID, Result);
if(IsGunFound && IsRunningTowardsGun)
{
BlackboardComp->InitializeBlackboard(*HeroAIBT->BlackboardAsset);
RunBehaviorTree(HeroAIBT);
IsRunningTowardsGun = false;
if(!ControlledHero->Gun)
{//gun was not there anymore when player got there, look for it again
IsGunFound = false;
LookForGun();
}
return;
}
if(!IsGunFound)
{//gun not found, look for it again
LookForGun();
}
}
void AHeroAIController::OnTargetPerceptionUpdated(AActor* Actor, FAIStimulus Stimulus)
{
if(Stimulus.WasSuccessfullySensed())
{
if(BlackboardComp->GetValueAsObject("Enemy"))
{//stick to first spotted enemy
return;}
if(Cast<AHero>(Actor) && IsGunFound && !IsRunningTowardsGun)
{
BlackboardComp->SetValueAsObject("Enemy", Actor);
}
}
else if(BlackboardComp && Actor == Cast<AActor>(BlackboardComp->GetValueAsObject("Enemy")))
{//allow to stop chasing only if lost sight of primary enemy
BlackboardComp->ClearValue("Enemy");
}
} | [
"[email protected]"
] | |
ba8204e06ce5265d9c60750dfbba0eb54e58aa24 | 747f684c3e988234877d581f175cddf19792d0fa | /Tests/test_kernel_module.cpp | 9bd9d9bf6150e7577a371d80d6adb24878bcb16f | [] | no_license | pv-k/NNLib4 | 0dd07a708290ca875c62ba279438a7f02a79acfa | 0ec77f2f915778a4734d1158e2ba0875b9c8ec2d | refs/heads/master | 2020-04-05T23:33:07.257135 | 2013-06-13T17:59:24 | 2013-06-13T17:59:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,969 | cpp | #include <boost/test/unit_test.hpp>
#include <vector>
#include "test_utilities.h"
#include "Tensor.h"
#include "ConstantInitializer.h"
#include "AbsRegularizer.h"
#include "KernelModule.h"
#include "MaxPoolingKernel.h"
#include "KernelFactory.h"
BOOST_AUTO_TEST_CASE(TestKernelModule_max_pooling)
{
size_t num_input_kernels = 15;
size_t num_output_kernels = 1;
size_t num_samples = 10;
std::vector<size_t> input_dims; input_dims.push_back(50); input_dims.push_back(50); input_dims.push_back(num_input_kernels);input_dims.push_back(num_samples);
Tensor<float> input_tensor = GetRandomTensor<float>(input_dims);
std::vector<size_t> kernel_dims; kernel_dims.push_back(4); kernel_dims.push_back(9); kernel_dims.push_back(1);
std::vector<size_t> strides;strides.push_back(4);strides.push_back(5);strides.push_back(1);
std::shared_ptr<ConstantInitializer<float>> initializer(new ConstantInitializer<float>(0));
KernelModule<float> kernel_module("module1", num_output_kernels,kernel_dims,strides, MaxPoolingKernelFactory<float>(),initializer);
std::vector<size_t> output_dims = kernel_module.GetKernel(0)->GetOutputTensorDimensions(input_dims);
BOOST_CHECK(output_dims.size() == 4 && output_dims[0] == 12 && output_dims[1] == 9 && output_dims[2] == 15 && output_dims[3] == 10);
kernel_module.train_fprop( std::shared_ptr<Tensor<float> >( new Tensor<float>(input_tensor)) );
std::shared_ptr<Tensor<float> > output_tensor = kernel_module.GetOutputBuffer();
BOOST_CHECK(output_tensor->GetDimensions() == output_dims);
std::vector<size_t> sample_input_dims = input_dims;
sample_input_dims.pop_back();
std::vector<size_t> sample_output_dims = output_dims;
sample_output_dims.pop_back();
Tensor<float> sample_output_tensor(nullptr, sample_output_dims);
Tensor<float> sample_input_tensor(nullptr, sample_input_dims);
for (size_t sample_ind = 0; sample_ind<num_samples; sample_ind++)
{
sample_input_tensor.SetDataPtr(input_tensor.GetStartPtr()+sample_ind*sample_input_tensor.Numel());
sample_output_tensor.SetDataPtr(output_tensor->GetStartPtr()+sample_ind*sample_output_tensor.Numel());
BOOST_CHECK(test_filter_response<float>(sample_input_tensor, sample_output_tensor, *kernel_module.GetKernel(0), kernel_dims, strides));
}
BOOST_CHECK_EQUAL(kernel_module.GetNumParams() , 0);
// test set parameters
size_t num_params = kernel_module.GetNumParams();
BOOST_CHECK( TestGetSetParameters<float>(kernel_module, kernel_module.GetNumParams()) );
}
BOOST_AUTO_TEST_CASE(TestKernelModule_convolutional)
{
size_t num_input_kernels = 8;
size_t num_output_kernels = 16;
size_t num_samples = 2;
std::vector<size_t> input_dims; input_dims.push_back(50); input_dims.push_back(50); input_dims.push_back(num_input_kernels);input_dims.push_back(num_samples);
Tensor<double> input_tensor = GetRandomTensor<double>(input_dims);
std::vector<size_t> kernel_dims; kernel_dims.push_back(4); kernel_dims.push_back(9); kernel_dims.push_back(num_input_kernels);
std::vector<double> importances;
for (size_t i=0; i<num_samples; i++)
importances.push_back(1);
std::vector<size_t> strides;strides.push_back(4);strides.push_back(5);strides.push_back(1);
std::shared_ptr<ConstantInitializer<double>> initializer(new ConstantInitializer<double>(0));
std::shared_ptr<Regularizer<double>> regularizer(new AbsRegularizer<double>(0.5));
KernelModule<double> kernel_module("module1", num_output_kernels,kernel_dims,strides, ConvolutionalKernelFactory<double>(), initializer, regularizer);
size_t num_params = kernel_module.GetNumParams();
std::vector<size_t> all_kernels_dims = kernel_dims;
all_kernels_dims.push_back(num_output_kernels);
Tensor<double> all_kernels_tensor = GetRandomTensor<double>(all_kernels_dims);
double* params = all_kernels_tensor.GetStartPtr();
kernel_module.SetParameters(params);
std::vector<size_t> output_dims = kernel_module.GetKernel(0)->GetOutputTensorDimensions(input_dims);
output_dims[2] = num_output_kernels;
kernel_module.train_fprop( std::shared_ptr<Tensor<double> >( new Tensor<double>(input_tensor)) );
std::shared_ptr<Tensor<double> > output_tensor = kernel_module.GetOutputBuffer();
BOOST_CHECK(output_tensor->GetDimensions() == output_dims);
// test regularizer
double reg_cost = kernel_module.GetCost(importances);
double expected_reg_cost = 0;
for (size_t i=0; i<all_kernels_tensor.Numel(); i++)
expected_reg_cost+=num_samples*std::abs(all_kernels_tensor[i]);
expected_reg_cost /= 2;
BOOST_CHECK(abs(reg_cost-expected_reg_cost)<0.000001);
std::vector<size_t> sample_output_dims = output_dims;
sample_output_dims.pop_back();
sample_output_dims.pop_back();
std::vector<size_t> sample_input_dims = input_dims;
sample_input_dims.pop_back();
Tensor<double> sample_output_tensor(nullptr, sample_output_dims);
Tensor<double> sample_input_tensor(nullptr, sample_input_dims);
size_t num_params_per_kernel = Tensor<double>::Numel(kernel_dims);
for (size_t sample_ind = 0; sample_ind<num_samples; sample_ind++)
{
sample_input_tensor.SetDataPtr(input_tensor.GetStartPtr()+sample_ind*sample_input_tensor.Numel());
for (size_t kernel_ind = 0; kernel_ind<num_output_kernels; kernel_ind++)
{
sample_output_tensor.SetDataPtr(output_tensor->GetStartPtr()+(num_output_kernels*sample_ind + kernel_ind)*sample_output_tensor.Numel());
BOOST_CHECK(test_filter_response<double>(sample_input_tensor, sample_output_tensor,
ConvolutionalKernel<double>(Tensor<double>(params + num_params_per_kernel*kernel_ind, kernel_dims), strides), kernel_dims, strides));
}
}
// test initializer
kernel_module.InitializeParameters();
std::vector<double> parameters;
kernel_module.GetParameters(parameters);
for (size_t i=0; i<all_kernels_tensor.Numel(); i++)
BOOST_CHECK_EQUAL(parameters[i] , 0);
BOOST_CHECK_EQUAL(kernel_module.GetNumParams() , num_output_kernels*num_input_kernels*kernel_dims[0]*kernel_dims[1]);
TestGetSetParameters<double>(kernel_module, kernel_module.GetNumParams());
} | [
"[email protected]"
] | |
a2013b57c8968c22d4d93777b40868d3a2d72bb8 | 75452de12ec9eea346e3b9c7789ac0abf3eb1d73 | /src/developer/forensics/crash_reports/info/main_service_info.h | 54bbcfd9e96d76691381e68b931f7a801b7a8f2c | [
"BSD-3-Clause"
] | permissive | oshunter/fuchsia | c9285cc8c14be067b80246e701434bbef4d606d1 | 2196fc8c176d01969466b97bba3f31ec55f7767b | refs/heads/master | 2022-12-22T11:30:15.486382 | 2020-08-16T03:41:23 | 2020-08-16T03:41:23 | 287,920,017 | 2 | 2 | BSD-3-Clause | 2022-12-16T03:30:27 | 2020-08-16T10:18:30 | C++ | UTF-8 | C++ | false | false | 1,295 | h | // Copyright 2019 The Fuchsia 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 SRC_DEVELOPER_FORENSICS_CRASH_REPORTS_INFO_MAIN_SERVICE_INFO_H_
#define SRC_DEVELOPER_FORENSICS_CRASH_REPORTS_INFO_MAIN_SERVICE_INFO_H_
#include <memory>
#include "src/developer/forensics/crash_reports/config.h"
#include "src/developer/forensics/crash_reports/info/info_context.h"
#include "src/developer/forensics/utils/inspect_protocol_stats.h"
namespace forensics {
namespace crash_reports {
// Information about the agent we want to export.
struct MainServiceInfo {
public:
MainServiceInfo(std::shared_ptr<InfoContext> context);
// Exposes the static configuration of the agent.
void ExposeConfig(const Config& config);
// Updates stats related to fuchsia.feedback.CrashReportingProductRegister.
void UpdateCrashRegisterProtocolStats(InspectProtocolStatsUpdateFn update);
// Updates stats related to fuchsia.feedback.CrashReporter.
void UpdateCrashReporterProtocolStats(InspectProtocolStatsUpdateFn update);
private:
std::shared_ptr<InfoContext> context_;
};
} // namespace crash_reports
} // namespace forensics
#endif // SRC_DEVELOPER_FORENSICS_CRASH_REPORTS_INFO_MAIN_SERVICE_INFO_H_
| [
"[email protected]"
] | |
22d02448fe3b3aa519a247b325651b6f65b7a287 | cc5a1bf6996614009c6370ee36d3210da5cb7139 | /runtime/mac/AirGame-desktop.app/Contents/Resources/res/ch23/LostRoutes/frameworks/cocos2d-x/cocos/editor-support/cocostudio/CCSGUIReader.h | 9c50b6a8ed387a929a8cc66842a15f59da23b1c4 | [
"MIT"
] | permissive | huangjin0/AirGame | fd8218f7bbe2f9ca394156d20ee1ff1f6c311826 | 0e8cb5d53b17fb701ea7fe34b2d87dde473053f3 | refs/heads/master | 2021-01-21T18:11:22.363750 | 2017-05-23T06:59:45 | 2017-05-23T06:59:45 | 92,020,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,389 | h | /****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
#ifndef __CCSGUIREADER_H__
#define __CCSGUIREADER_H__
#include "ui/UILayout.h"
#include "editor-support/cocostudio/DictionaryHelper.h"
#include "editor-support/cocostudio/WidgetReader/WidgetReaderProtocol.h"
#include "base/ObjectFactory.h"
#include "editor-support/cocostudio/CocosStudioExport.h"
#include "base/CCValue.h"
namespace protocolbuffers
{
class NodeTree;
}
namespace tinyxml2
{
class XMLElement;
}
namespace cocostudio {
class CocoLoader;
struct stExpCocoNode;
#define kCCSVersion 1.0
typedef void (cocos2d::Ref::*SEL_ParseEvent)(const std::string&, cocos2d::Ref*, const rapidjson::Value&);
#define parseselector(_SELECTOR) (SEL_ParseEvent)(&_SELECTOR)
class CC_STUDIO_DLL GUIReader : public cocos2d::Ref
{
public:
CC_DEPRECATED_ATTRIBUTE static GUIReader* shareReader() { return GUIReader::getInstance(); };
CC_DEPRECATED_ATTRIBUTE static void purgeGUIReader() { GUIReader::destroyInstance(); };
static GUIReader* getInstance();
static void destroyInstance();
cocos2d::ui::Widget* widgetFromJsonFile(const char* fileName);
cocos2d::ui::Widget* widgetFromBinaryFile(const char* fileName);
int getVersionInteger(const char* str);
/**
* @js NA
*/
void storeFileDesignSize(const char* fileName, const cocos2d::Size &size);
/**
* @js NA
*/
cocos2d::Size getFileDesignSize(const char* fileName) const;
void setFilePath(const std::string& strFilePath) { m_strFilePath = strFilePath; }
const std::string& getFilePath() const { return m_strFilePath; }
void registerTypeAndCallBack(const std::string& classType,
cocos2d::ObjectFactory::Instance ins,
Ref* object,
SEL_ParseEvent callBack);
void registerTypeAndCallBack(const std::string& classType,
cocos2d::ObjectFactory::InstanceFunc ins,
Ref* object,
SEL_ParseEvent callBack);
protected:
GUIReader();
~GUIReader();
std::string m_strFilePath;
cocos2d::ValueMap _fileDesignSizes;
typedef std::map<std::string, SEL_ParseEvent> ParseCallBackMap;
ParseCallBackMap _mapParseSelector;
typedef std::map<std::string, Ref*> ParseObjectMap;
ParseObjectMap _mapObject;
public:
ParseCallBackMap* getParseCallBackMap() { return &_mapParseSelector; };
ParseObjectMap* getParseObjectMap() { return &_mapObject; };
};
class CC_STUDIO_DLL WidgetPropertiesReader : public cocos2d::Ref
{
public:
virtual cocos2d::ui::Widget* createWidget(const rapidjson::Value& dic, const char* fullPath, const char* fileName)=0;
virtual cocos2d::ui::Widget* widgetFromJsonDictionary(const rapidjson::Value& data) = 0;
virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options) = 0;
virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType,
cocos2d::ui::Widget* widget,
const rapidjson::Value& customOptions) = 0;
//add binary parsing
virtual cocos2d::ui::Widget* createWidgetFromBinary(CocoLoader* cocoLoader,stExpCocoNode* pCocoNode, const char* fileName)=0;
virtual cocos2d::ui::Widget* widgetFromBinary(CocoLoader* cocoLoader, stExpCocoNode* pCocoNode) = 0;
virtual void setPropsForAllWidgetFromBinary(WidgetReaderProtocol* reader,
cocos2d::ui::Widget* widget,
CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode) = 0;
protected:
void setAnchorPointForWidget(cocos2d::ui::Widget* widget, const rapidjson::Value&options);
std::string getWidgetReaderClassName(const std::string& classname);
std::string getWidgetReaderClassName(cocos2d::ui::Widget *widget);
std::string getGUIClassName(const std::string& name);
cocos2d::ui::Widget *createGUI(const std::string& classname);
WidgetReaderProtocol* createWidgetReaderProtocol(const std::string& classname);
protected:
std::string m_strFilePath;
};
class CC_STUDIO_DLL WidgetPropertiesReader0250 : public WidgetPropertiesReader
{
public:
WidgetPropertiesReader0250(){};
virtual ~WidgetPropertiesReader0250(){};
virtual cocos2d::ui::Widget* createWidget(const rapidjson::Value& dic, const char* fullPath, const char* fileName) override;
virtual cocos2d::ui::Widget* widgetFromJsonDictionary(const rapidjson::Value& dic) override;
//added for binary parsing
virtual cocos2d::ui::Widget* createWidgetFromBinary(CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode,
const char* fileName)override{return nullptr;}
virtual cocos2d::ui::Widget* widgetFromBinary(CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode) override {return nullptr;}
virtual void setPropsForAllWidgetFromBinary(WidgetReaderProtocol* reader,
cocos2d::ui::Widget* widget,
CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode) override {}
virtual void setPropsForWidgetFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setColorPropsForWidgetFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForButtonFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForCheckBoxFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForImageViewFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForLabelFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForLabelAtlasFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForLabelBMFontFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForLoadingBarFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForSliderFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForTextFieldFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForLayoutFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForScrollViewFromJsonDictionary(cocos2d::ui::Widget* widget,const rapidjson::Value& options);
virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options) override;
virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType,
cocos2d::ui::Widget* widget,
const rapidjson::Value& customOptions) override;
};
class CC_STUDIO_DLL WidgetPropertiesReader0300 : public WidgetPropertiesReader
{
public:
WidgetPropertiesReader0300(){};
virtual ~WidgetPropertiesReader0300(){};
virtual cocos2d::ui::Widget* createWidget(const rapidjson::Value& dic,
const char* fullPath,
const char* fileName) override;
//add bin parse support
virtual cocos2d::ui::Widget* createWidgetFromBinary(CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode,
const char* fileName)override;
virtual cocos2d::ui::Widget* widgetFromBinary(CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode) override;
virtual void setPropsForAllWidgetFromBinary(WidgetReaderProtocol* reader,
cocos2d::ui::Widget* widget,
CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode) override;
virtual void setPropsForAllCustomWidgetFromBinary(const std::string& classType,
cocos2d::ui::Widget* widget,
CocoLoader* cocoLoader,
stExpCocoNode* pCocoNode) {
//TODO: custom property
}
virtual cocos2d::ui::Widget* widgetFromJsonDictionary(const rapidjson::Value& dic) override;
virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader,
cocos2d::ui::Widget* widget,
const rapidjson::Value& options) override;
virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType,
cocos2d::ui::Widget* widget,
const rapidjson::Value& customOptions) override;
};
}
#endif /* defined(__CCSGUIReader__) */
| [
"[email protected]"
] | |
c5d8a95187a65008742523847a9cb0ccddad6afd | 5bebabc46810b6d211daf9707ecb537534595f9a | /repositories/araSoft/programs/testing/dbWriteIdentify.cc | 45bf5b842e59839afd52efb78e37e7e3dc3b9a82 | [] | no_license | osu-particle-astrophysics/ara-daq | 9b5842f4f1ed21ada0d5796123db5001f569603e | a35d2fb89fa7957e153210f9884ecc4d9af0d4cf | refs/heads/master | 2021-01-23T14:31:10.499761 | 2017-08-23T15:30:28 | 2017-08-23T15:30:28 | 93,254,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,654 | cc | //
// dbWriteIdentify writes a daughterboard's identification EEPROM page 0.
//
// The remaining pages are undefined right now: there are several
// possibilities: either calibration data (unlikely given that it's only
// a 32k EEPROM and there are a lot more cal points for a DDA),
// operation data (more likely - as in you store the nominal operating
// Vdly/Vadj for a DDA, and the nominal thresholds for a TDA), and
// maybe tracking data as well.
//
// dbWriteIdentify takes a file containing the write page info, in ASCII.
// Format is one entry per line:
// line 0: page 0 version (max 255)
// line 1: daughterboard name (max 6 characters)
// line 2: daughterboard revision (max 1 character)
// line 3: daughterboard serial number (max 8 characters)
// line 4: daughterboard build date (max 8 characters- MM/DD/YY)
// line 5: daughterboard build location/by (max 8 characters)
// line 6: cal date (same as build date)
// line 7: cal by (same as build by)
// line 8: commission date (same as build date)
// line 9: installation location (max 8 characters)
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include <iomanip>
#include <sstream>
extern "C"
{
#include "araSoft.h"
#include "atriComLib/atriCom.h"
}
#include <getopt.h>
// why don't we have this defined anywhere. Hmm.
#define ATRI_NUM_DAUGHTERS 4
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <errno.h>
#include <sys/types.h>
#include <cstring>
#include <sys/socket.h>
#include <sys/un.h>
using std::vector;
using std::string;
using std::ifstream;
using std::cerr;
using std::cout;
using std::endl;
using std::hex;
using std::dec;
template <class T>
bool from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&)) {
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main(int argc, char **argv) {
char page0[64];
bool eos = false;
int i;
const char *p;
bool test_mode = false;
bool read_mode = false;
int daughter = -1;
int retval;
int type = -1;
// Command line processing:
// We require a page 0 file name, plus a --daughter (or -D) argument
// and a --type (or -t) argument. -t can be ASCII ("DDA","TDA","DRSV9",
// or "DRSV10")
// If --simulate (or -s) is specified, we don't actually write (or even open
// the control socket), just dump what we would write.
// If --read (or -r) is specified (conflicts with --test) we instead read
// the page 0 file name and write it into the same format text file.
static struct option options[] =
{
{"simulate", no_argument, 0, 's'},
{"read", no_argument, 0, 'r'},
{"daughter", required_argument, 0, 'D'},
{"type", required_argument, 0, 't'}
};
int c;
while (1) {
int option_index;
c = getopt_long(argc, argv, "srD:t:", options, &option_index);
if (c == -1) break;
switch (c) {
case 's': test_mode = true; break;
case 'r': read_mode = true; break;
case 'D': daughter = strtoul(optarg, NULL, 0);
if (daughter < 1 || daughter > ATRI_NUM_DAUGHTERS) {
cerr << argv[0] << " --daughter options are 1-4" << endl;
return 1;
}
// make it zero based
daughter--;
break;
case 't': if (!strcmp(optarg, "DDA")) type = 0;
if (!strcmp(optarg, "TDA")) type = 1;
if (!strcmp(optarg, "DRSV9")) type = 2;
if (!strcmp(optarg, "DRSV10")) type = 3;
if (type < 0) {
char *rp;
type = strtoul(optarg, &rp, 0);
if (rp == optarg || (type > 3)) {
cerr << argv[0] << " --type options are DDA, TDA, DRSV9, DRSV10, or 0-3" << endl;
return 1;
}
}
break;
default: exit(1);
}
}
if (test_mode && read_mode) {
cerr << argv[0] << " : --read and --simulate are exclusive" << endl;
return 1;
}
if (optind == argc) {
cerr << argv[0] << ": need a page 0 info file name" << endl;
return 1;
}
if (daughter < 0 || type < 0) {
cerr << argv[0] << ": need --daughter (-D) and --type (-t) options"
<< endl;
return 1;
}
vector<string> text_file;
string temp;
if (!read_mode) {
ifstream ifs(argv[optind]);
if (!ifs.is_open()) {
cerr << argv[0] << ": " << argv[optind] << " is not readable" << endl;
return 1;
}
while (getline(ifs, temp))
text_file.push_back(temp);
unsigned int page0_version;
if (!from_string<unsigned int>(page0_version, text_file[0], std::dec)) {
cerr << argv[0] << ": line 0 must be a decimal number from 0-255" << endl;
exit(1);
}
if (page0_version > 255) {
cerr << argv[0] << ": line 0 must be a decimal number from 0-255" << endl;
exit(1);
}
cout << "Page 0 Version: " << page0_version << endl;
cout << "Daughterboard Name: " << text_file[1] << endl;
cout << "Revision: " << text_file[2] << endl;
cout << "Serial Number: " << text_file[3] << endl;
cout << "Build Date: " << text_file[4] << endl;
cout << "Build By: " << text_file[5] << endl;
cout << "Cal Date: " << text_file[6] << endl;
cout << "Cal By: " << text_file[7] << endl;
cout << "Commission Date: " << text_file[8] << endl;
cout << "Installation Location: " << text_file[9] << endl;
cout << endl;
cout << "Raw Page 0: " << endl;
// 0, 1, 2 are chars 0->7
page0[0] = (unsigned char) page0_version;
eos = false;
p = text_file[1].c_str();
for (i=0;i<6;i++) {
if (!eos)
page0[1+i] = p[i];
else
page0[1+i] = 0;
if (p[i] == 0x00)
eos = true;
}
eos = false;
p = text_file[2].c_str();
page0[7] = p[0];
// 3 is chars 8-15
p = text_file[3].c_str();
eos = false;
for (i=0;i<8;i++) {
if (!eos)
page0[8+i] = p[i];
else
page0[8+i] = 0x00;
if (p[i] == 0x00)
eos = true;
}
// 4 is 16-23
p = text_file[4].c_str();
eos = false;
for (i=0;i<8;i++) {
if (!eos)
page0[16+i] = p[i];
else
page0[16+i] = 0x00;
if (p[i] == 0x00)
eos = true;
}
// 5 is 24-31
p = text_file[5].c_str();
eos = false;
for (i=0;i<8;i++) {
if (!eos)
page0[24+i] = p[i];
else
page0[24+i] = 0x00;
if (p[i] == 0x00)
eos = true;
}
// 32-39
p = text_file[6].c_str();
eos = false;
for (i=0;i<8;i++) {
if (!eos)
page0[32+i] = p[i];
else
page0[32+i] = 0x00;
if (p[i] == 0x00)
eos = true;
}
// 40-47
p = text_file[7].c_str();
eos = false;
for (i=0;i<8;i++) {
if (!eos)
page0[40+i] = p[i];
else
page0[40+i] = 0x00;
if (p[i] == 0x00)
eos = true;
}
// 48-55
p = text_file[8].c_str();
eos = false;
for (i=0;i<8;i++) {
if (!eos)
page0[48+i] = p[i];
else
page0[48+i] = 0x00;
if (p[i] == 0x00)
eos = true;
}
// 56-63
p = text_file[9].c_str();
eos = false;
for (i=0;i<8;i++) {
if (!eos)
page0[56+i] = p[i];
else
page0[56+i] = 0x00;
if (p[i] == 0x00)
eos = true;
}
for (i=0;i<64;i++) {
cout << "0x" << hex << (((unsigned int) (page0[i]))&0xFF);
if (!((i+1)%8))
cout << endl;
else
cout << " ";
}
if (!test_mode) {
cout << "Attempting to write page0 of daughter type " << atriDaughterTypeStrings[type]
<< " on stack " << atriDaughterStackStrings[daughter]
<< " at address " << std::hex << (unsigned int) atriEepromAddressMap[type] << endl;
// We now have 64 bytes to write to the EEPROM.
int auxFd = openConnectionToAtriControlSocket();
if (auxFd < 0) {
return 1;
}
if (atriEepromAddressMap[type] == 0x00) {
cerr << " -- I have no idea what the EEPROM address is on a "
<< atriDaughterTypeStrings[type]
<< endl;
close(auxFd);
return 1;
}
// we can only write 16 bytes at a time
// wow do I need to rewrite the I2C controller.
// so we actually only write 8 bytes at a time to keep things simple
for (int i=0;i<16;i++)
{
uint8_t buf[10];
buf[0] = 0x00;
buf[1] = i*4;
memcpy(&(buf[2]), page0+i*4, 4);
if ((retval = writeToAtriI2C(auxFd, (AtriDaughterStack_t) daughter, atriEepromAddressMap[type], 6,
buf))) {
cerr << " -- Error " << retval << " writing to page 0 ("
<< i*4 << "-" << i*4+3 << ")" << endl;
close(auxFd);
return 1;
}
usleep(500);
}
cout << " -- Write successful." << endl;
closeConnectionToAtriControlSocket(auxFd);
}
}
cout <<endl;
return 0;
}
| [
"[email protected]"
] | |
32ef73054cc8a4cbec4c905ea770d6d0cd6ccf7f | da16754e5fb7d43db986d94d1642a5a9a8213c03 | /net/third_party/quic/core/quic_packet_writer_wrapper.h | 734e4c05d245478fd7de51996be366c94b5b69c6 | [
"BSD-3-Clause"
] | permissive | tigercosmos/labium | 8fd6c91f2d956c8e838c4991723b41f55fafab8f | 6be29d13da321139520e860d9aff958592d42552 | refs/heads/master | 2020-03-19T05:23:51.854102 | 2018-06-03T17:46:56 | 2018-06-03T18:08:41 | 135,926,710 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | 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 NET_THIRD_PARTY_QUIC_CORE_QUIC_PACKET_WRITER_WRAPPER_H_
#define NET_THIRD_PARTY_QUIC_CORE_QUIC_PACKET_WRITER_WRAPPER_H_
#include <stddef.h>
#include <memory>
#include "base/macros.h"
#include "net/third_party/quic/core/quic_packet_writer.h"
namespace quic {
// Wraps a writer object to allow dynamically extending functionality. Use
// cases: replace writer while dispatcher and connections hold on to the
// wrapper; mix in monitoring; mix in mocks in unit tests.
class QuicPacketWriterWrapper : public QuicPacketWriter {
public:
QuicPacketWriterWrapper();
~QuicPacketWriterWrapper() override;
// Default implementation of the QuicPacketWriter interface. Passes everything
// to |writer_|.
WriteResult WritePacket(const char* buffer,
size_t buf_len,
const QuicIpAddress& self_address,
const QuicSocketAddress& peer_address,
PerPacketOptions* options) override;
bool IsWriteBlockedDataBuffered() const override;
bool IsWriteBlocked() const override;
void SetWritable() override;
QuicByteCount GetMaxPacketSize(
const QuicSocketAddress& peer_address) const override;
// Takes ownership of |writer|.
void set_writer(QuicPacketWriter* writer);
// Does not take ownership of |writer|.
void set_non_owning_writer(QuicPacketWriter* writer);
virtual void set_peer_address(const QuicSocketAddress& peer_address) {}
QuicPacketWriter* writer() { return writer_; }
private:
void unset_writer();
QuicPacketWriter* writer_ = nullptr;
bool owns_writer_ = false;
DISALLOW_COPY_AND_ASSIGN(QuicPacketWriterWrapper);
};
} // namespace quic
#endif // NET_THIRD_PARTY_QUIC_CORE_QUIC_PACKET_WRITER_WRAPPER_H_
| [
"[email protected]"
] | |
df002f949d23b9ef91fbdf27365130b99f3b75b8 | 9a67cb9bf1c2f684ebb230edf995fd808cf21b4e | /input_parser.h | f99c6bd45d63b863adb845e95f3f979b5b1a7ad1 | [] | no_license | nrmynitasr/playfair-1 | e6a121ad83a9d96cc9bf03fe2e48e4e3ecb7344d | e57f8f8a3fc6646c5afba7ef419399e263c1de11 | refs/heads/master | 2022-03-14T05:32:27.446548 | 2019-11-27T15:35:27 | 2019-11-27T15:35:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,525 | h | #ifndef INPUT_PARSER_H
#define INPUT_PARSER_H
#include <iostream>
using namespace std;
#include <vector>
#include <string>
#include <cctype>
#include "validation_result.h"
#include "pair.h"
using std::vector;
using std::string;
class InputParser{
public:
static ValidationResult validate(string operation, string message, string key)
{
if(operation != "e" && operation != "d" && operation != "E" && operation != "D")
return ValidationResult(false, "Operation not recognised");
// check if the input contains invalid characters
string validCharacters = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0; i < message.size(); i++)
{
if(validCharacters.find(message[i]) == string::npos)
return ValidationResult(false, "The input contains invalid characters");
}
for(int i = 0; i < key.size(); i++)
{
if(validCharacters.find(key[i]) == string::npos)
return ValidationResult(false, "The input contains invalid characters");
}
return ValidationResult(true);
}
static vector<Pair<char>> parseMessage(string messageIn)
{
messageIn = stringToLower(messageIn);
messageIn = separateDuplicates(messageIn);
// add padding if needed
if(messageIn.size() % 2 != 0)
{
if(messageIn.back() != 'x')
messageIn += "x";
else
messageIn += "q";
}
messageIn = replaceJ(messageIn);
// parse for letter pairs
vector<Pair<char>> message;
for(int i = 0; i < messageIn.size() - 1; i += 2)
{
message.push_back(Pair<char>(messageIn[i], messageIn[i + 1]));
// cout << pairS.getFirst() << "-" << pairS.getSecond() << " ";
}
return message;
}
static string parseKey(string key)
{
key = stringToLower(key);
key = removeDuplicates(key);
key = replaceJ(key);
//cout << key << endl;
return key;
}
private:
static string stringToLower(string text)
{
for(int i = 0; i < text.size(); i++)
text[i] = tolower(text[i]);
return text;
}
static string removeDuplicates(string text)
{
//cout << "Remove duplicates" << endl;
int i = 0;
while(i < text.size())
{
if(text.substr(0, i).find(text[i]) != string::npos)
text.erase(i, 1);
else
i++;
}
//cout << "Removing complete" << endl;
return text;
}
static string separateDuplicates(string text)
{
// cout << "Separating string" << endl;
int i = 0;
while(i < text.size() - 1)
{
// cout << "Comparing: " << text[i] << " " << text[i+1] << endl;
if(text[i] == text[i + 1])
{
if(text[i] != 'x')
{
text.insert(i + 1, "x");
i++;
}
else
text.erase(i, 1);
}
else
i++;
}
return text;
}
static string replaceJ(string text)
{
//cout << "Replace js" << endl;
for(int i = 0; i < text.size(); i++)
if(text[i] == 'j')
text[i] = 'i';
//cout << "Replacing complete" << endl;
return text;
}
};
#endif
| [
"[email protected]"
] | |
d66d73b422967ab59186c0338e142d371b09053d | 34f14572584c440cf92aeffb10debf20b10eca8f | /app/src/main/cpp/nbbook/tools/constant/XMLNamespace.h | e000616f90c1656e3b6966b400e79c7b552ab447 | [
"Apache-2.0"
] | permissive | Fozei/NBReader | 1624ce14569d23ede6d98eef54f095189cb52113 | e423b13915578ab95c1683bfa7a70e59f19f2eab | refs/heads/master | 2022-04-06T07:30:34.916915 | 2020-03-12T17:30:02 | 2020-03-12T17:30:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,740 | h | /*
* Copyright (C) 2008-2015 FBReader.ORG Limited <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* FBReader 中支持的匹配的 namesapce
*/
#ifndef __ZLXMLNAMESPACE_H__
#define __ZLXMLNAMESPACE_H__
#include <string>
class XMLNamespace {
private:
XMLNamespace();
public:
static const std::string DublinCore;
static const std::string DublinCoreLegacy;
static const std::string DublinCoreTerms;
static const std::string XLink;
static const std::string XHTML;
static const std::string OpenPackagingFormat;
static const std::string Atom;
static const std::string OpenSearch;
static const std::string CalibreMetadata;
static const std::string Opds;
static const std::string DaisyNCX;
static const std::string Svg;
static const std::string MarlinEpub;
static const std::string XMLEncryption;
static const std::string XMLDigitalSignature;
static const std::string EpubContainer;
static const std::string FBReaderXhtml;
};
#endif /* __ZLXMLNAMESPACE_H__ */
| [
"[email protected]"
] | |
0140fec62b05564bd68a97f0bc1588a2bd04d267 | a1fe4dc3a7a4911607ac55a2bd7da19b29f36849 | /libnet/base/Date.cc | 5650c454ea318bf0867347065b72fe5618e7df66 | [] | no_license | Monsterwi/myWebserver | 8964c6773abf637bea85dc2d2e8493590498a7dd | 264dd6079840188f76e39b88404b11edf70939c0 | refs/heads/main | 2023-07-27T03:55:28.671566 | 2021-09-10T14:46:26 | 2021-09-10T14:46:26 | 394,996,851 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,717 | cc | #include "libnet/base/Date.h"
#include <stdio.h> // snprintf
#include <time.h> // struct tm
namespace libnet
{
namespace detail
{
char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1];
// algorithm and explanation see:
// http://www.faqs.org/faqs/calendars/faq/part2/
// http://blog.csdn.net/Solstice
int getJulianDayNumber(int year, int month, int day)
{
(void) require_32_bit_integer_at_least; // no warning please
int a = (14 - month) / 12;
int y = year + 4800 - a;
int m = month + 12 * a - 3;
return day + (153*m + 2) / 5 + y*365 + y/4 - y/100 + y/400 - 32045;
}
struct Date::YearMonthDay getYearMonthDay(int julianDayNumber)
{
int a = julianDayNumber + 32044;
int b = (4 * a + 3) / 146097;
int c = a - ((b * 146097) / 4);
int d = (4 * c + 3) / 1461;
int e = c - ((1461 * d) / 4);
int m = (5 * e + 2) / 153;
Date::YearMonthDay ymd;
ymd.day = e - ((153 * m + 2) / 5) + 1;
ymd.month = m + 3 - 12 * (m / 10);
ymd.year = b * 100 + d - 4800 + (m / 10);
return ymd;
}
} // namespace detail
const int Date::kJulianDayOf1970_01_01 = detail::getJulianDayNumber(1970, 1, 1);
} // namespace libnet
using namespace libnet;
using namespace libnet::detail;
Date::Date(int y, int m, int d)
: julianDayNumber_(getJulianDayNumber(y, m, d))
{
}
Date::Date(const struct tm& t)
: julianDayNumber_(getJulianDayNumber(
t.tm_year+1900,
t.tm_mon+1,
t.tm_mday))
{
}
string Date::toIsoString() const
{
char buf[32];
YearMonthDay ymd(yearMonthDay());
snprintf(buf, sizeof buf, "%4d-%02d-%02d", ymd.year, ymd.month, ymd.day);
return buf;
}
Date::YearMonthDay Date::yearMonthDay() const
{
return getYearMonthDay(julianDayNumber_);
}
| [
"[email protected]"
] | |
fe2b0e2d59c12629fabfbbab8ba88c0b8bc06a3e | 9d48363a6125dce5a5def1ac148c4a5bd678ae3b | /Sourcecode/private/mx/core/elements/Step.h | f387ba2203fe9237c801643137fef25acb58457e | [
"MIT"
] | permissive | rphaeh/mx | 4cac321c5b55ce657e07e2e6ed01f0d8cd045757 | cdf1c97c5ebffaa81de5db77cfc6d2b06b9a94fb | refs/heads/master | 2021-10-26T00:36:24.084974 | 2019-04-09T00:11:04 | 2019-04-09T00:11:04 | 198,191,333 | 2 | 0 | null | 2019-07-22T09:30:20 | 2019-07-22T09:30:20 | null | UTF-8 | C++ | false | false | 1,403 | h | // MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#pragma once
#include "mx/core/ForwardDeclare.h"
#include "mx/core/ElementInterface.h"
#include "mx/core/Enums.h"
#include <iosfwd>
#include <memory>
#include <vector>
namespace mx
{
namespace core
{
MX_FORWARD_DECLARE_ELEMENT( Step )
inline StepPtr makeStep() { return std::make_shared<Step>(); }
inline StepPtr makeStep( const StepEnum& value ) { return std::make_shared<Step>( value ); }
inline StepPtr makeStep( StepEnum&& value ) { return std::make_shared<Step>( std::move( value ) ); }
class Step : public ElementInterface
{
public:
Step();
Step( const StepEnum& value );
virtual bool hasAttributes() const;
virtual bool hasContents() const;
virtual std::ostream& streamAttributes( std::ostream& os ) const;
virtual std::ostream& streamName( std::ostream& os ) const;
virtual std::ostream& streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const;
StepEnum getValue() const;
void setValue( const StepEnum& value );
private:
virtual bool fromXElementImpl( std::ostream& message, xml::XElement& xelement );
private:
StepEnum myValue;
};
}
}
| [
"[email protected]"
] | |
dd4fef9faf7e49ab1ed7814e07c035265d9036f7 | ea373baee35667a5f817b1f1683a8f56a58f1664 | /8L_Beizer_Curve.cpp | 90b57f86c406e421b151d790b2fa6709c029ad12 | [] | no_license | NamrathaHV/Computer_Graphics | 3ce457a4c907e3c45d17bb2b565f76d4e68dc4ed | 80f32f68f71567d5a67119a63ea9604d37f4c231 | refs/heads/master | 2023-07-14T14:11:42.274422 | 2021-08-26T12:29:14 | 2021-08-26T12:29:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,039 | cpp | // 8L. Develop a menu driven program to animate a flag using Bezier Curve algorithm.
#include<gl/glut.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define PI 3.1416
GLsizei winwidth = 600, winheight = 600;
GLfloat xwcMin = 0.0, xwcMax = 130.0;
GLfloat ywcMin = 0.0, ywcMax = 130.0;
typedef struct wcPt3D
{
GLfloat x, y, z;
};
void bino(GLint n, GLint* C)
{
GLint k, j;
for (k = 0; k <= n; k++)
{
C[k] = 1;
for (j = n; j >= k + 1; j--)
C[k] *= j;
for (j = n - k; j >= 2; j--)
C[k] /= j;
}
}
void computeBezPt(GLfloat u, wcPt3D* bezPt, GLint nCtrlPts, wcPt3D* ctrlPts, GLint* C)
{
GLint k, n = nCtrlPts - 1;
GLfloat bezBlendFcn;
bezPt->x = bezPt->y = bezPt->z = 0.0;
for (k = 0; k < nCtrlPts; k++)
{
bezBlendFcn = C[k] * pow(u, k) * pow(1 - u, n - k);
bezPt->x += ctrlPts[k].x * bezBlendFcn;
bezPt->y += ctrlPts[k].y * bezBlendFcn;
bezPt->z += ctrlPts[k].z * bezBlendFcn;
}
}
void beizer(wcPt3D* ctrlPts, GLint nCtrlPts, GLint nBezCurvePts)
{
wcPt3D bezCurvePt;
GLfloat u;
GLint *C, k;
C = new GLint[nCtrlPts];
bino(nCtrlPts - 1, C);
glBegin(GL_LINE_STRIP);
for (k = 0; k <= nBezCurvePts; k++)
{
u = GLfloat(k) / GLfloat(nBezCurvePts);
computeBezPt(u, &bezCurvePt, nCtrlPts, ctrlPts, C);
glVertex2f(bezCurvePt.x, bezCurvePt.y);
}
glEnd();
delete[]C;
}
void displayFcn()
{
GLint nCtrlPts = 4, nBezCurvePts = 20;
static float theta = 0;
wcPt3D ctrlPts[4] = { {20,100,0},{30,110,0},{50,90,0},{60,100,0} };
ctrlPts[1].x += 10 * sin(theta * PI / 180.0);
ctrlPts[1].y += 5 * sin(theta * PI / 180.0);
ctrlPts[2].x -= 10 * sin((theta + 30) * PI / 180.0);
ctrlPts[2].y -= 10 * sin((theta + 30) * PI / 180.0);
ctrlPts[3].x -= 4 * sin(theta * PI / 180.0);
ctrlPts[3].y += sin((theta - 30) * PI / 180.0);
theta += 0.1;
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(5);
glPushMatrix();
glLineWidth(5);
for (int i = 0; i < 24; i++)
{
glTranslatef(0, -0.8, 0);
beizer(ctrlPts, nCtrlPts, nBezCurvePts);
}
glPopMatrix();
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(20, 100);
glVertex2f(20, 40);
glEnd();
glFlush();
glutPostRedisplay();
glutSwapBuffers();
}
void winReshapeFun(GLint newWidth, GLint newHeight)
{
glViewport(0, 0, newWidth, newHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(xwcMin, xwcMax, ywcMin, ywcMax);
glClear(GL_COLOR_BUFFER_BIT);
}
void d_menu(int op)
{
if (op == 1)
glColor3f(1.0, 0.0, 0.0);
else if (op == 2)
glColor3f(0.0, 1.0, 0.0);
else if (op == 3)
glColor3f(0.0, 0.0, 1.0);
else if (op == 4)
exit(0);
glutPostRedisplay();
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(50, 50);
glutInitWindowSize(winwidth, winheight);
glutCreateWindow("Bezier Curve");
glutCreateMenu(d_menu);
glutAddMenuEntry("Red", 1);
glutAddMenuEntry("Green", 2);
glutAddMenuEntry("Blue", 3);
glutAddMenuEntry("Quit", 4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutDisplayFunc(displayFcn);
glutReshapeFunc(winReshapeFun);
glutMainLoop();
} | [
"[email protected]"
] | |
e36f7d16ee47a21d421588ab328e778f7b599ec0 | 8fb45ccb0212a1fa116e8fcc57247d5853ee853a | /CrosswordCreator/crossword_type.h | 396d583f74ebf7412f13b7e58eb698b405aeeb2e | [] | no_license | hunterknepshield/CrosswordCreator | 9c751e035ee75ffffcefcc5881e7b7379509fcae | e5478b0e72bbafc5ed0864025497aed376d10707 | refs/heads/master | 2021-01-19T07:05:56.302442 | 2017-04-07T07:51:16 | 2017-04-07T07:51:16 | 87,519,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,027 | h | //
// crossword_type.h
// CrosswordCreator
//
// Created by Hunter Knepshield on 4/2/17.
// Copyright © 2017 Hunter Knepshield. All rights reserved.
//
#ifndef crossword_type_h
#define crossword_type_h
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
/// A representation of a crossword puzzle.
class Crossword {
public:
/// A specification for a word's direction.
enum WordDirection { ACROSS, DOWN };
/// A character in a word that is unknown as of right now.
static const char WILDCARD;
/// The character representing a black square in the grid.
static const char BLACK_SQUARE;
/// A type representing a starting location and direction of a word.
typedef std::tuple<int, int, WordDirection> WordBeginning;
/// A tuple denoting a starting row and column, direction, and current
/// values of a particular word in the puzzle.
typedef std::tuple<WordBeginning, std::vector<char>> Word;
/// A tuple denoting the across word and down word that this cell is a part
/// of. If either value is INVALID_{DIRECTION}, that implies an absence of
/// word in that particular direction.
typedef std::tuple<char, WordBeginning, WordBeginning> Cell;
/// An value indicating no across word in this cell.
static const WordBeginning INVALID_ACROSS;
/// An value indicating no down word in this cell.
static const WordBeginning INVALID_DOWN;
/// Wrapper around the nasty nested tuple initialization.
static Word MakeWord(int row, int column, WordDirection direction,
const std::vector<char>& characters) {
return std::make_tuple(std::make_tuple(row, column, direction),
characters);
}
/// Takes a list of words, copies them into the instance and generates a
/// grid from the words.
static std::unique_ptr<Crossword> Create(int height, int width,
const std::vector<Word>& words);
/// Takes a pre-populated grid and derives the word locations from that.
static std::unique_ptr<Crossword> Create(
const std::vector<std::string>& rawGrid);
/// Takes a partially solved instance and uses a heuristic that attempts to
/// fill in the most-constrained word first using the supplied word list.
static std::pair<bool, Crossword> Solve(
Crossword puzzle, const std::set<std::string>& wordlist,
bool randomWordlistSelection, int verbosity = 0);
/// Tells this instance to dump its entire contents, including words, the
/// next time it is sent to an output stream.
const Crossword& printEverything() const {
printEverything_ = true;
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const Crossword& cw);
private:
/// An intermediate value that is the default for a not-yet-populated grid.
/// Should never appear in a valid Crossword instance.
static const Cell DEFAULT_CELL;
Crossword(int height, int width, const std::map<WordBeginning, Word>& words,
const std::vector<std::vector<Cell>>& grid)
: height_(height), width_(width), words_(words), grid_(grid) {}
/// Finds the word that is the most constrained in the given puzzle. If no
/// unconstrained words are present in the puzzle, returns false.
bool mostConstrained(Word* out);
/// Sets the specified cell in the board to be the specified character.
/// Returns false if the operation failed for some reason. Normalizes all
/// characters to uppercase.
bool setCharacter(char value, int row, int column);
/// Resets the specified cell in the board to be the wildcard character.
inline bool clearCharacter(int row, int column) {
return setCharacter(WILDCARD, row, column);
}
int height_, width_;
std::map<WordBeginning, Word> words_;
std::vector<std::vector<Cell>> grid_;
mutable bool printEverything_;
};
// Custom stream operators to make debugging prettier.
std::ostream& operator<<(std::ostream& os,
const Crossword::WordBeginning& wordBeginning);
std::ostream& operator<<(std::ostream& os, const Crossword::Word& word);
#endif /* crossword_type_h */
| [
"[email protected]"
] | |
6a7ac8bad0a5e88b86b2c25a045ef836ebc30e89 | ca4d70080ced49e6c9d5110a8563eafdbe79eec4 | /src/basis/structures/intervaltree.cpp | 66aa201ba6e90a038ef69ad88011a957a063c144 | [] | no_license | It4innovations/espreso | f6b038dcd77f7f3677694e160a984bc45f4a4850 | 5acb7651287bd5114af736abc97c84de8a6ede99 | refs/heads/master | 2023-01-28T13:35:52.731234 | 2022-05-24T14:24:05 | 2022-06-26T06:35:31 | 66,345,061 | 18 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 2,759 | cpp |
#include "intervaltree.h"
#include <algorithm>
#include <numeric>
#include <cstring>
#include <cstdio>
using namespace espreso;
IntervalTree::IntervalTree(const std::vector<Point> &start, const std::vector<Point> &end)
: istart(start), iend(end)
{
if (end.size()) {
min = start.front();
max = end.front();
for (size_t i = 1; i < end.size(); ++i) {
min.x = std::min(start[i].x, min.x);
min.y = std::min(start[i].y, min.y);
min.z = std::min(start[i].z, min.z);
max.x = std::max(end[i].x, max.x);
max.y = std::max(end[i].y, max.y);
max.z = std::max(end[i].z, max.z);
}
}
build();
}
void IntervalTree::build()
{
struct comp {
comp(const std::vector<Point> &vals, int d): vals(vals), d(d) {}
bool operator()(esint i, esint j) { return vals[i][d] < vals[j][d]; }
const std::vector<Point> &vals;
int d;
};
size_t bucketsize = 8;
size = max - min;
permutation.resize(iend.size());
std::iota(permutation.begin(), permutation.end(), 0);
levels = iend.size() < bucketsize ? 0 : std::floor(std::log2(iend.size() / bucketsize));
splitters.resize(std::exp2(levels));
Point box = size; // uniform division (denoted by the level)
for (esint ll = 0, intervals = 1; ll < levels; ++ll, intervals *= 2) {
int splitter = box.x < box.y ? box.y < box.z ? 2 : 1 : box.x < box.z ? 2 : 0;
box[splitter] /= 2;
#pragma omp parallel for
for (esint i = 0; i < intervals; ++i) {
esint index = std::exp2(ll) + i;
esint begin = this->begin(index);
esint end = this->end(index);
splitters[index].d = splitter;
splitters[index].index = begin + (end - begin) / 2;
std::nth_element(permutation.begin() + begin, permutation.begin() + splitters[index].index, permutation.begin() + end, [&] (esint i, esint j) {
return iend[i][splitters[index].d] < iend[j][splitters[index].d];
});
if (end - begin) {
splitters[index].end = iend[permutation[splitters[index].index]][splitters[index].d];
}
while ( // move to the last coordinate with the same value as mid
splitters[index].index + 1 < end &&
splitters[index].end == iend[permutation[splitters[index].index + 1]][splitters[index].d]) {
++splitters[index].index;
}
for (esint c = splitters[index].index + 2; c < end; ++c) { // there can be another in the rest of array
if (splitters[index].end == iend[permutation[c]][splitters[index].d]) {
std::swap(permutation[++splitters[index].index], permutation[c--]);
}
}
splitters[index].index = std::min(splitters[index].index + 1, end);
splitters[index].start = splitters[index].end;
for (esint c = splitters[index].index; c < end; ++c) {
splitters[index].start = std::min(splitters[index].start, istart[permutation[c]][splitters[index].d]);
}
}
}
}
| [
"[email protected]"
] | |
4245a8b6c851775c69897125dd9630f2e634bab0 | f9dc12e822ff8b505bc776daefd190b3dd2a8f4e | /CivilisedDiscussion/MsgStructure.cpp | 3e6a692020678f79bc1a5a4afbd0bc8dacfb315f | [] | no_license | Seshien/CivilizedDiscussion | d943d592177d27fad29528c185ef213615e3408e | 354c31b4c9f5ae7dd8e997767a40075e02bfc9a5 | refs/heads/master | 2023-06-04T01:40:32.189637 | 2021-06-17T18:46:42 | 2021-06-17T18:46:42 | 368,569,775 | 0 | 1 | null | 2021-06-14T20:29:49 | 2021-05-18T14:55:54 | C++ | UTF-8 | C++ | false | false | 26 | cpp | #include "MsgStructure.h"
| [
"[email protected]"
] | |
ed99fb55985c88872af5429c2f26c3d1b1b9608e | 0dca3325c194509a48d0c4056909175d6c29f7bc | /voicenavigator/include/alibabacloud/voicenavigator/model/SilenceTimeoutRequest.h | ed9b1ccb340521e3798bdefacc98747d9de8c6d8 | [
"Apache-2.0"
] | permissive | dingshiyu/aliyun-openapi-cpp-sdk | 3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62 | 4edd799a79f9b94330d5705bb0789105b6d0bb44 | refs/heads/master | 2023-07-31T10:11:20.446221 | 2021-09-26T10:08:42 | 2021-09-26T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,671 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_VOICENAVIGATOR_MODEL_SILENCETIMEOUTREQUEST_H_
#define ALIBABACLOUD_VOICENAVIGATOR_MODEL_SILENCETIMEOUTREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/voicenavigator/VoiceNavigatorExport.h>
namespace AlibabaCloud
{
namespace VoiceNavigator
{
namespace Model
{
class ALIBABACLOUD_VOICENAVIGATOR_EXPORT SilenceTimeoutRequest : public RpcServiceRequest
{
public:
SilenceTimeoutRequest();
~SilenceTimeoutRequest();
std::string getConversationId()const;
void setConversationId(const std::string& conversationId);
std::string getInitialContext()const;
void setInitialContext(const std::string& initialContext);
std::string getInstanceId()const;
void setInstanceId(const std::string& instanceId);
private:
std::string conversationId_;
std::string initialContext_;
std::string instanceId_;
};
}
}
}
#endif // !ALIBABACLOUD_VOICENAVIGATOR_MODEL_SILENCETIMEOUTREQUEST_H_ | [
"[email protected]"
] | |
a9cf1ed117bde36c5e156d6a63f183f1a61609be | 6079670a82f3b92a3e6c6ed180aa498b78baca9a | /zxq/cpp/357-count-numbers-with-unique-digits.cpp | b490abf423304f69d37405b70dce114e641a4856 | [] | no_license | sing-dance-rap-basketball/leetcode | 97d59d923dfe6a48dd5adba3fa3137a684c0b3ca | d663d8093d4547ab1c6a24203255dba004b1e067 | refs/heads/master | 2022-08-07T15:17:47.059875 | 2022-07-23T15:59:36 | 2022-07-23T15:59:36 | 194,498,806 | 0 | 1 | null | 2019-07-12T08:28:39 | 2019-06-30T09:35:12 | C++ | UTF-8 | C++ | false | false | 769 | cpp | /*
* @lc app=leetcode id=357 lang=cpp
*
* [357] Count Numbers with Unique Digits
*/
// @lc code=start
/**
* Accepted
9/9 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 100 % of cpp submissions (6 MB)
*/
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return 10;
}
int ans = 10;
for (int i = 1; i < n; ++i) {
ans *= (10 - i);
}
int temp = 9;
for (int i = 1; i < n-2; ++i) {
temp *= (9 - i);
}
temp *= (n - 2);
return ans + temp + countNumbersWithUniqueDigits(n-2);
}
};
// @lc code=end
| [
"[email protected]"
] | |
a32bac06e6b41e4a46fd017322bdd8ece8dec98a | 95f4f325d36d52b4950455fd8b05e8932c5c4273 | /src/Player.h | 3be304476c738ef380950893bc702e7db75b6ae8 | [
"MIT"
] | permissive | Ma5onic/PlaySK-Piano-Roll-Reader | 4c5d3b9d008f2cf111249beec72a31349665c931 | 80197316e58b350620dc6862a59308c421cc1593 | refs/heads/master | 2023-07-27T16:46:26.495898 | 2020-02-15T13:59:37 | 2020-02-15T13:59:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,921 | h | #pragma once
#include <mmsystem.h>
#include <opencv2/core/core.hpp>
#include "json11.hpp"
#define KeyNum 88
#define MAXNoteOnFrames 10
typedef struct tagTRACKER_HOLE {
int x;
int y;
int w;
int h;
int th_on; // hole on thereshold
int th_off; // hole off thereshold
} TRACKER_HOLE;
class Player{
public:
Player();
virtual ~Player();
int Emulate(cv::Mat &frame, const HMIDIOUT &hm);
virtual int LoadPlayerSettings();
virtual int NoteAllOff(const HMIDIOUT &hm);
virtual int GetMinVelocity();
virtual int GetMaxVelocity();
int GetBassVelocity() { return m_iBassStackVelo; }
int GetTrebleVelocity() { return m_iTrebleStackVelo; }
void SetEmulateOn() { m_bEmulateOn = true; }
void SetEmulateOff() { m_bEmulateOn = false; }
void SetRollOffset(int iOffset) { m_iTrackingOffset = iOffset; }
int GetRollOffset() { return m_iTrackingOffset; }
void SetNoteOnFrames(int iFrames) { m_iNoteOnFrames = iFrames; }
int GetNoteOnFrames() { return m_iNoteOnFrames; }
void SetFrameRate(double dfps) { m_dFrameRate = dfps; }
protected:
// tracker hole status // -2:on->off -1:off 1:off->on 2:on
enum NoteState {
offTriger = -2,
off = -1,
onTriger = 1,
on = 2,
};
NoteState m_NoteOn[KeyNum];
NoteState m_SusteinPedalOn, m_SoftPedalOn;
// tracker hole
TRACKER_HOLE m_rcSustainPedal, m_rcSoftPedal;
TRACKER_HOLE m_rcNote[KeyNum];
// split point
// bass < [split point] <= treble, with 0 start index
UINT m_uiStackSplitPoint;
// note-on delay
int m_iNoteOnFrames;
int m_iNoteOnCnt[KeyNum];
int m_iTrackingOffset;
double m_dFrameRate;
int m_iBassStackVelo, m_iTrebleStackVelo;
bool m_bEmulateOn;
virtual void EmulateVelocity(cv::Mat &frame);
void EmulatePedal(cv::Mat &frame);
void EmulateNote(cv::Mat &frame);
double GetAvgHoleBrightness(cv::Mat &frame, const TRACKER_HOLE &hole);
void DrawHole(cv::Mat &frame, const TRACKER_HOLE &hole, bool hole_on);
void SendMidiMsg(const HMIDIOUT &hm);
void SetHoleRectFromJsonObj(const json11::Json json, TRACKER_HOLE &rcSetHole);
void SetHoleRectListFromJsonObj(const json11::Json json, TRACKER_HOLE *prcSetHole, UINT rect_cnt);
void inline NoteOnMsg(int key, int velocity, const HMIDIOUT &g_hMidiOut) const{
DWORD dwMsg = velocity << 16 | key << 8 | 0x90;
midiOutShortMsg(g_hMidiOut, dwMsg);
}
void inline NoteOffMsg(int key, const HMIDIOUT &g_hMidiOut) const{
static const int iNoteOffVelocity = 90;
DWORD dwMsg = iNoteOffVelocity << 16 | key << 8 | 0x80;
midiOutShortMsg(g_hMidiOut, dwMsg);
}
void inline SusteinP(bool status, const HMIDIOUT &g_hMidiOut) const{
if (status) midiOutShortMsg(g_hMidiOut, 127 << 16 | 64 << 8 | 0xb0);
else midiOutShortMsg(g_hMidiOut, 64 << 8 | 0xb0);
}
void inline SoftP(bool status, const HMIDIOUT &g_hMidiOut) const{
if (status) midiOutShortMsg(g_hMidiOut, 127 << 16 | 67 << 8 | 0xb0);
else midiOutShortMsg(g_hMidiOut, 67 << 8 | 0xb0);
}
}; | [
"[email protected]"
] | |
45d385d3c7d2af181ec76e1c7869ce72632aee52 | 227b4701bbc342c56a1f78afee4b233c9a692581 | /Classes/About.cpp | cd305f34fc0edf4a337c3339f4ab2ac52b04728b | [] | no_license | zyjisdog/XPlane | 6941099bec263482ed88130efffe63560c833e29 | f953f44446958a3793c36941bf64d8a77f12e8e7 | refs/heads/master | 2021-01-20T05:58:41.444633 | 2014-12-05T23:41:57 | 2014-12-05T23:41:57 | 27,600,170 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,746 | cpp | #include "About.h"
#include "AppMacros.h"
#include "HelloWorldScene.h"
#include "Chinese.h"
USING_NS_CC;
Scene* About::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
About *layer = About::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool About::init()
{
//////////////////////////////
// 1. super init first
if (!Layer::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"SpookyPeas.png",
"Pea.png",
CC_CALLBACK_1(About::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height*0.2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
CCDictionary* strings = CCDictionary::createWithContentsOfFile("Chinese.plist");
const CCString* zuozhe = ((CCString*)strings->objectForKey("zuozhe"));
auto label1 = LabelTTF::create(zuozhe->getCString()/*ChineseWord("zuozhe") + ":" + zhangyunjin->getCString()
ChineseWord("zhangyunjin")*/, "fonts\\Marker Felt.ttf", TITLE_FONT_SIZE);
// position the label on the center of the screen
label1->setPosition(Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label1->getContentSize().height));
// add the label as a child to this layer
this->addChild(label1, 1);
// add "About" splash screen" 创建一个精灵
const CCString* xuehao = ((CCString*)strings->objectForKey("xuehao"));
auto label2 = LabelTTF::create(xuehao->getCString()/*ChineseWord("xuehao") + ":2012226010020"*/, "fonts\\Marker Felt.ttf", TITLE_FONT_SIZE);
// position the sprite on the center of the screen 设置精灵的位置
label2->setPosition(Vec2(visibleSize / 2) + origin);
// add the sprite as a child to this layer 把精灵添加到layer
this->addChild(label2);
return true;
}
void About::menuCloseCallback(Ref* sender)
{
//场景切换到游戏场景
auto scene = HelloWorld::createScene();
//增加场景特效
auto tr = TransitionFade::create(0.5, scene);
//场景切换
Director::getInstance()->replaceScene(tr);
}
| [
"[email protected]"
] | |
99619cba99ddfaddf7d24906595a093f8d01a556 | fec8934c49e6527505669fe9e2c753477a530850 | /Makefile/main.cpp | cdb78e741d7b42092dfc72b34a056ceed96b2821 | [] | no_license | OlenkaKornak/FindFile | e81434e5e2c5620bd68db159ab786279a8a0fd47 | 9158febe7c4eb16e884ee86ce8720797eaec7413 | refs/heads/master | 2022-11-25T19:08:01.888662 | 2020-08-05T11:08:40 | 2020-08-05T11:08:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | // I could not find the file on the C disk, maybe it's because there is no access to any folders,
// so I searched on the disk E
// There are my efforts to do something that works according to the task here
// Without multithreading everything works right, but I couldn`t fully implement it with multithreading
#include <iostream>
#include "function.hpp"
int main()
{
try {
path myPath = "E:";
string myFile;
cout << "Enter filename with an extension: ";
cin >> myFile;
path myfound;
find_file(myPath, myFile, myfound);
cout << myfound << endl;
auto current_thread = myThreads->begin();
while (current_thread != myThreads->end()) {
current_thread->join();
current_thread++;
}
}
catch (...)
{
cout << "Some error with file" << endl;
}
} | [
"[email protected]"
] | |
79067a0b5a5acbb85819e35b34126006c6394e84 | 2922cdf91069fba6d8620bbc804d432dd665e59d | /src/MsvcAppender.cpp | 103110931e7a5527ab6788a756238e225da39c5a | [
"MIT"
] | permissive | michaelstein/ProtoInfo | b1c3707d1fba0caa7d81f227c536e839a9bed1a6 | 32fbf4a44241ca80f5ad2281754ef8398dd33a14 | refs/heads/master | 2022-06-11T16:24:50.083874 | 2022-05-29T15:57:29 | 2022-05-29T15:57:29 | 174,380,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | #include "MsvcAppender.h"
#include "humblelogging/formatter.h"
#ifdef _WIN32
#include "Windows.h"
#endif
using namespace humble::logging;
MsvcAppender::MsvcAppender()
: Appender()
{
}
MsvcAppender::~MsvcAppender() = default;
void MsvcAppender::log(const humble::logging::LogEvent& logEvent)
{
#ifdef _WIN32
MutexLockGuard lock(_mutex);
if (!_formatter)
return;
const auto msg = _formatter->format(logEvent);
OutputDebugStringA(msg.c_str());
#endif
}
| [
"[email protected]"
] | |
3fd30d86cbc935588895376f7135579011a28568 | 99d0d18688b17e802f952b64f85e8ce836fdc94f | /Practice Comp code/yetAnotherMinMaxProblem.cpp | 67a8c42d25e2e934e8b530d4e42e98c7ed0a8bbe | [] | no_license | suyash0103/Competitive-Coding | b8be47d6c5a5c8e63ba4dc30a0cf39f6165a0531 | af24966916aa5dc4d39b5dbdf51bad3bd102895d | refs/heads/master | 2018-09-21T20:24:14.188721 | 2018-07-22T19:06:31 | 2018-07-22T19:06:31 | 100,601,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int a[10000];
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
int max = a[0] ^ a[1];
for(int i = 0; i < n - 1; i++)
//if(a[i] ^ a[i + 1] > max)
// max = a[i] ^ a[i + 1];
cout << (a[i]) ^ (a[i + 1]);
//cout << max;
}
| [
"Suyash Ghuge"
] | Suyash Ghuge |
a9571997e8c013f6b1ec297d920d70daa5032d4f | 48793c310d1f9027d6aa2aacedad1e1bdc50a0de | /album.h | 4cc3a87255f8bf30f98f51bb2634614348a32510 | [] | no_license | williamdewitt95/B-Tree | b555b3ea642403997c673547c74d65b6d14928e8 | b9bdbf0443ee38d1eb42e16b864715f76d21057b | refs/heads/master | 2021-01-19T19:54:13.565774 | 2017-04-22T22:45:59 | 2017-04-22T22:45:59 | 88,459,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 640 | h | #ifndef ALBUM
#define ALBUM
#include "btree.hpp"
using namespace std;
const int UpTo = 50;
typedef char String[UpTo];
class Album
{
public :
Album (const Album& otherAlbum);
Album (String upc, String artist,
String title);
Album(String Key);
Album ();
Album & operator = (const Album& otherAlbum);
bool operator < (const Album& b);
friend istream & operator >> (istream & stream, Album&C);
friend ostream & operator << (ostream & stream, Album&C);
string getStringKey ();
int recordSize();
private :
String Key, Artist, Title;
};
#endif
| [
"[email protected]"
] | |
d1deeac06d0cfc7d6bfefdeb281f8d29596995f7 | 8d5f28c1d46e284bb2badb923d32ccfa7696b4e2 | /darkstar/Ted/Code/simTed.cpp | 9144d6d995fd1e8afea76fcd4bd60a5e2144cb39 | [] | no_license | jasonmit/TribesRebirth | 0ba87778deeb86047842bcc559f232ab7ceb07fb | 1105fd0890c19c13f816b91e51b9cf0658ffc63c | refs/heads/master | 2023-03-17T01:41:03.663946 | 2015-07-20T21:12:37 | 2015-07-20T21:12:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111,553 | cpp | #include <limits.h>
#include "simAction.h"
#include "simTed.h"
#include "grdCollision.h"
#include "simSetIterator.h"
#include "simguitsctrl.h"
#include "simmoveobj.h"
#include "console.h"
#include "simGame.h"
#include "simconsoleevent.h"
static SimTerrain::Visibility DefTerrainVisibility =
{
1500.0f, // visible distance
600.0f, // haze distance
};
static SimTerrain::Detail DefTerrainDetail =
{
200.0f, // perspective distance
0.02f, // Pixel Size
};
static const char * stripPath( const char* fname )
{
// Return the file name portion without the path
const char* ptr = fname + strlen(fname) - 1;
for (; ptr != fname; ptr--)
if (*ptr == '\\' || *ptr == '/' || *ptr == ':')
return ptr + 1;
return fname;
}
SimTed::SimTed() :
scaleShift( 0 ),
blockShift( 0 ),
mouseHandler( NULL ),
mouseStartPt( 0.0, 0.0, 0.0 ),
mouseDirection( 0.0, 0.0, 0.0 ),
terrain( NULL ),
landscaper( NULL ),
focused( false ),
surface( NULL ),
pointArray( NULL ),
currentUndo( NULL ),
size( -1, -1 ),
regionSelect( false ),
selectStartPnt( -1, -1 ),
selectCanceled( false ),
selectLastPnt( -1, -1 ),
mouseLButtonAction( -1 ),
mouseRButtonAction( -1 ),
mouseProcessAction(-1),
feather( true ),
snap( true ),
brushPos( 0, 0 ),
brushDetail( 0 ),
hilightFillColor( 8 ),
hilightFrameColor( 2 ),
selectFillColor( 4 ),
selectFrameColor( 3 ),
shadowFillColor( 12 ),
shadowFrameColor( 6 ),
heightVal( 200.0 ),
adjustVal( 5.0 ),
materialIndex( 0 ),
flagVal( set ),
pasteVal( Material | Height ),
smoothVal( 0.5 ),
terrainType( 0 ),
drawNotch( true ),
scaleVal( 1.0 ),
grabMode( false ),
grabPoint( 0, 0 ),
grabDist( 0.0 ),
grabHeight( 0.0 ),
drawNeighbors(false),
blockOutline( false ),
blockFrameColor( 14 ),
pinDetail( 0 ),
selFloating( false ),
avgHeight( 0.0 ),
mouseMoved( false ),
cursorPos( 0, 0 ),
lastCursorPos( 0, 0 ),
cursorDif( 0, 0 ),
hilightShow( Frame | Fill ),
selectShow( Frame | Fill ),
shadowShow( Frame | Fill )
{
}
SimTed::~SimTed()
{
// delete the objects that this has control of
if( currentUndo )
delete currentUndo;
// delete the version string
}
void SimTed::flushTextures()
{
if( surface )
surface->flushTextureCache();
}
void SimTed::setVars()
{
scaleShift = getGridFile()->getScale();
blockShift = getGridFile()->getDetailCount()-1;
size = getGridFile()->getSize();
}
int SimTed::getActionIndex( String name )
{
for( int i = 0; i < actions.size(); i++ )
if( name == actions[i]->name )
return( i );
return( -1 );
}
void SimTed::setLButtonAction( String name )
{
mouseLButtonAction = getActionIndex( name );
}
void SimTed::setRButtonAction( String name )
{
mouseRButtonAction = getActionIndex( name );
}
void SimTed::init()
{
// add the actions
// there is the potential that an end event will never occur... design
// the mouse actions to be independant of end events
addAction( "adjustControlPoint", &SimTed::adjustControlPointAction, true, "Adjust the control point for this brush" );
addAction( "adjustCorner", &SimTed::adjustCornerAction, false, "Adjust the corner of a brush" );
addAction( "adjustHeight", &SimTed::adjustHeightAction, true, "Adjust the height of terrain" );
addAction( "clearFlags", &SimTed::clearFlagsAction, true, "Clear masked flags" );
addAction( "clearPin", &SimTed::clearPinAction, true, "Clear terrain pinning" );
addAction( "copy", &SimTed::copyAction, false, "Copy terrain info" );
addAction( "deselect", &SimTed::deselectAction, true, "Deselect terrain" );
addAction( "depress", &SimTed::depressAction, true, "Depress height" );
addAction( "elevate", &SimTed::elevateAction, true, "Elevate height" );
addAction( "getAvgHeight", &SimTed::getAvgHeightAction, false, "" );
addAction( "lowerHeight", &SimTed::lowerHeightAction, true, "Lower height" );
addAction( "noise", &SimTed::noiseAction, false, "Add noise to terrain" );
addAction( "paste", &SimTed::pasteAction, false, "Paste using paste mask" );
addAction( "pin", &SimTed::pinAction, true, "Pin down the terrain" );
addAction( "raiseHeight", &SimTed::raiseHeightAction, true, "Raise height" );
addAction( "redo", &SimTed::redoAction, true, "Redo last undo operation" );
addAction( "relight", &SimTed::relightAction, true, "Relight the terrain" );
addAction( "rotateLeft", &SimTed::rotateLeftAction, true, "Rotate terrain textures" );
addAction( "rotateRight", &SimTed::rotateRightAction, true, "Rotate terrain textures" );
addAction( "scale", &SimTed::scaleAction, true, "Scale height values" );
addAction( "select", &SimTed::selectAction, true, "Select terrain" );
addAction( "setControlHeight", &SimTed::setControlHeightAction, true, "Set control point height" );
addAction( "setCornerHeight", &SimTed::setCornerHeightAction, true, "Set the height of a corner" );
addAction( "setFlags", &SimTed::setFlagsAction, true, "Set masked flags" );
addAction( "setHeight", &SimTed::setHeightAction, true, "Set terrain height" );
addAction( "setMaterial", &SimTed::setMaterialAction, true, "Set terrain material index" );
addAction( "setTerrainType", &SimTed::setTerrainTypeAction, true, "Set terrain type using terrainValue" );
addAction( "smooth", &SimTed::smoothAction, true, "Smooth terrain" );
addAction( "undo", &SimTed::undoAction, true, "Undo last operation" );
// set the l/r mouse button actions
setLButtonAction( "select" );
setRButtonAction( "deselect" );
// need to get rid of the simted object on server deletion
SimObject * notifyObj = static_cast<SimObject*>(SimGame::get()->getManager(SimGame::SERVER)->findObject("ConsoleScheduler"));
if(notifyObj)
deleteNotify(notifyObj);
}
void SimTed::onDeleteNotify(SimObject * obj)
{
// just check if it's a SimConsoleScheduler object (already removed from the manager)
if(dynamic_cast<SimConsoleScheduler*>(obj))
deleteObject();
}
bool SimTed::getActionInfo( int index, TedAction & info )
{
if( index >= getNumActions() )
return( false );
// copy it
info = *actions[index];
return( true );
}
// set the corner height to the current height val
void SimTed::setCornerHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
switch( action )
{
case begin:
// adjust this corner - darn.. the naming is all backwards!!!
// adjustControlPoint( pos, height, undo, top, left, true );
setBrushCornerHeight( brushPos, undo, heightVal, true );
break;
}
}
void SimTed::adjustCornerAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
switch( action )
{
case begin:
{
// enter into grab mode
grabMode = true;
drawNeighbors = true;
grabPoint = brushPos;
grabHeight = getHeight( grabPoint );
// save off the info into the undo buffer
setBrushCornerHeight( grabPoint, undo, grabHeight, true );
break;
}
case update:
{
// save off the info into the undo buffer
float mouseAdj = CMDConsole::getLocked()->getFloatVariable("$TED::mouseAdjustValue", 0.25);
grabHeight -= ( ( float )cursorDif.y ) * mouseAdj;
setBrushCornerHeight( grabPoint, undo, grabHeight, false );
break;
}
case end:
grabMode = false;
getGridFile()->updateHeightRange();
break;
}
}
void SimTed::setControlHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
switch( action )
{
case begin:
// set it
setBrushCornerHeight( brushPos, undo, heightVal, true );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
void SimTed::adjustHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
static Selection initialSel;
if(!sel.points.getSize())
return;
unsigned int i;
switch(action)
{
// add to undo on begin
case begin:
initialSel.points.clear();
// enter into grab mode
grabMode = true;
drawNeighbors = false;
grabPoint = brushPos;
grabHeight = getHeight(grabPoint);
// copy the current selection into undo and initial
for(i = 0; i < sel.points.getSize(); i++)
{
Selection::Info info;
if(getInfo(sel.points[i].pos, info))
{
initialSel.addPoint(info);
undo.addPoint(info);
}
}
break;
case update:
{
if(cursorDif.y == 0)
break;
// get the adjust value
float mouseAdj = CMDConsole::getLocked()->getFloatVariable("$TED::mouseAdjustValue", 0.25);
float adjVal = ((float)-cursorDif.y) * mouseAdj;
for(i = 0; i < initialSel.points.getSize(); i++)
{
float height = getHeight(initialSel.points[i].pos) + adjVal;
setHeight(initialSel.points[i].pos, height);
}
// do the feathering
if(feather)
featherAction(action, initialSel, undo, true, adjVal);
break;
}
case end:
grabMode = false;
getGridFile()->updateHeightRange();
break;
}
}
// control adjustment mode
void SimTed::adjustControlPointAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
int brushDim = ( 1 << brushDetail );
switch( action )
{
case begin:
{
grabPoint = brushPos;
grabHeight = getHeight( grabPoint );
grabMode = true;
drawNeighbors = true;
// save all the heights...
for( int y = 0; y < brushDim; y++ )
for( int x = 0; x < brushDim; x++ )
for( int i = -1; i <=0; i++ )
for( int j = -1; j <=0; j++ )
{
Selection::Info info;
Point2I pos( brushPos );
pos.x += brushDim * i;
pos.y += brushDim * j;
if( getInfo( pos, info ) )
undo.addPoint( info );
}
break;
}
case update:
{
if( cursorDif.y == 0 )
break;
float mouseAdj = CMDConsole::getLocked()->getFloatVariable("$TED::mouseAdjustValue", 0.25);
float diff = ((float)-cursorDif.y) * mouseAdj;
// do the zero'th lvl
Selection::Info info;
if( getInfo( grabPoint, info ) )
{
info.height.height += diff;
setInfo( info );
}
for( int i = 1; i < brushDim; i++ )
{
// get the amount to adjust at each level
float adjAmt = float( float(brushDim) - float(i) ) / float(brushDim) * diff;
// just grab the outside points
for( int x = -i; x <= i; x++ )
for( int a = 0; a < 2; a++ )
if( getInfo( Point2I( grabPoint.x + x, grabPoint.y + ( a ? -i : i ) ), info ) )
{
info.height.height += adjAmt;
setInfo( info );
}
// do the sides - skip the corners...
for( int y = (-i + 1); y <= (i - 1); y++ )
for( int a = 0; a < 2; a++ )
if( getInfo( Point2I( grabPoint.x + ( a ? -i : i ), grabPoint.y + y ), info ) )
{
info.height.height += adjAmt;
setInfo( info );
}
}
break;
}
case end:
grabMode = false;
getGridFile()->updateHeightRange();
break;
}
}
// scale the terrain by a value
void SimTed::scaleAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case begin:
case update:
{
// go through the heights and scale them
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// add to undo
undo.addPoint( info );
// scale the value
info.height.height *= scaleVal;
// set the value
setInfo( info );
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// pin down the terrain to the current detail
void SimTed::pinAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case end:
// go though all of the selection
undo.pinArray.clear();
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
Point2I pos = sel.points[i].pos;
// get the info
if( getInfo( pos, info ) )
{
// add to the undo
undo.addPoint( info );
undo.undoFlags = Selection::pin;
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
if( GridBlock * block = getGridFile()->getBlock( bpos ) )
{
//get remainders
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
// pin it - position is in current detail coords
spos.x >>= pinDetail;
spos.y >>= pinDetail;
// fill in the callback info
GridBlock::pinCallbackInfo callback;
callback.obj = this;
callback.func = SimTed::pinSquareCallback;
callback.gridBlock = block;
block->pinSquare( pinDetail, spos, pinDetailMax, true, &callback );
}
}
}
}
break;
}
}
// used to collect info for an undo/redo operation
void SimTed::pinSquareCallback( GridBlock::pinCallbackInfo * info )
{
SimTed * ted = ( SimTed * )info->obj;
Selection * undo = ted->getCurrentUndo();
Selection::pinInfo pin;
// need to check if this one already exists
for( int i = 0; i < undo->pinArray.size(); i++ )
{
// check if the same
pin = undo->pinArray[i];
if( ( pin.detail == info->detail ) && ( pin.pos == info->pos ) && ( pin.gridBlock == info->gridBlock ) )
return;
}
// add a pin info
pin.detail = info->detail;
pin.pos = info->pos;
pin.val = info->val;
pin.gridBlock = info->gridBlock;
undo->pinArray.push_back( pin );
}
// clear the entire map in the current block
void SimTed::clearPinMaps()
{
GridBlockList * blockList = getGridFile()->getBlockList();
for( int i = 0; i < blockList->size(); i++ )
{
GridBlock * block = ( * blockList )[i]->block;
if( block )
block->clearPinMaps();
}
}
// clear the pin from the current brush - goes from pinDetail on up to pinDetailMax
void SimTed::clearPinAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case end:
// go though all of the selection
undo.pinArray.clear();
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
Point2I pos = sel.points[i].pos;
// get the info
if( getInfo( pos, info ) )
{
// add to the undo
undo.addPoint( info );
undo.undoFlags = Selection::unpin;
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
if( GridBlock * block = getGridFile()->getBlock( bpos ) )
{
//get remainders
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
// pin it - position is in current detail coords
spos.x >>= pinDetail;
spos.y >>= pinDetail;
// fill in the callback info
GridBlock::pinCallbackInfo callback;
callback.obj = this;
callback.func = SimTed::pinSquareCallback;
callback.gridBlock = block;
block->pinSquare( pinDetail, spos, pinDetailMax, false, &callback );
}
}
}
}
break;
}
}
// just calls relight ( so can be mapped to a mouse key )
void SimTed::relightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
sel; undo;
switch( action )
{
case begin:
relight(false);
break;
}
}
// just calls undo ( so we can use the mouse with this )
void SimTed::undoAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
sel; undo;
switch( action )
{
case begin:
SimTed::undo();
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// just calls redo ( so we can use the mouse with this )
void SimTed::redoAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
sel; undo;
switch( action )
{
case begin:
SimTed::redo();
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// set the terrain type for the selected terrain
void SimTed::setTerrainTypeAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
{
// clear the hilight selection
hilightSel.clear();
for( i = 0; i < sel.points.getSize(); i++ )
hilightSel.addPoint( sel.points[i] );
break;
}
case update:
{
// add to the hilight selection
for( i = 0; i < sel.points.getSize(); i++ )
hilightSel.addPoint( sel.points[i] );
break;
}
case end:
{
Vector<Point2I> pntList;
// add to the hilight selection
for( i = 0; i < sel.points.getSize(); i++ )
hilightSel.addPoint( sel.points[i] );
// create the pnt list
for( i = 0; i < hilightSel.points.getSize(); i++ )
{
// add to list
pntList.push_back( hilightSel.points[i].pos );
Selection::Info info;
// add to undo
if( getInfo( hilightSel.points[i].pos, info ) )
undo.addPoint( info );
}
// save the flags
UInt8 flagSave = flagVal;
// clear the edit flag
flagVal = GridBlock::Material::Edit | GridBlock::Material::Corner;
setFlagsAction( action, hilightSel, undo );
// apply the textures
landscaper->applyTextures( &pntList, terrainType );
// flush them textures
flushTextures();
// set the relight flag for this undo
undo.undoFlags = Selection::landscape | Selection::flushTextures;
// set the edit flag
flagVal = GridBlock::Material::Edit | GridBlock::Material::Corner;
setFlagsAction( action, hilightSel, undo );
// clear the hilight selection
hilightSel.clear();
// reset the flag mask
flagVal = flagSave;
break;
}
}
if( hilightShow.test( Outline ) )
clusterizeSelection( hilightClusterSel, hilightSel );
}
// copy info
void SimTed::copyAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;
switch( action )
{
case begin:
{
// clear the copy selection
copySel.clear();
if( !sel.points.getSize() )
return;
// use the first point as the one for reference
Point2I startPnt = sel.points[0].pos;
// go though all of the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// adjust the point
info.pos.x -= startPnt.x;
info.pos.y -= startPnt.y;
// add to the copy selection
copySel.addPoint( info );
}
}
// clusterize this selection in case we want it later
clusterizeSelection( copyClusterSel, copySel );
break;
}
}
}
// paste info
void SimTed::pasteAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;sel;
switch( action )
{
case begin:
{
// get the start point and check if there is something to paste
if( !copySel.points.getSize() )
return;
Point2I startPnt = brushPos;
// go though all of the copy buffer
for( unsigned int i = 0; i < copySel.points.getSize(); i++ )
{
// get the point we are going to be working with
Point2I pnt( startPnt.x + copySel.points[i].pos.x,
startPnt.y + copySel.points[i].pos.y );
if( !pointValid( pnt ) )
continue;
// get the info for this point
Selection::Info info;
undo.undoFlags = Selection::flushTextures;
UInt8 paste = selFloating ? floatPasteVal : pasteVal;
if( getInfo( pnt, info ) )
{
// add to the undo
undo.addPoint( info );
// check for material change
if( paste & Material )
info.material = copySel.points[i].material;
// check for height change
if( paste & Height )
info.height = copySel.points[i].height;
// add the info
setInfo( info );
}
// fjush the textures
flushTextures();
}
break;
}
case end:
selFloating = false;
getGridFile()->updateHeightRange();
break;
}
}
// set the material of the selections
void SimTed::setMaterialAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case begin:
case update:
{
// go though all of the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// add to the undo
undo.addPoint( info );
// set the material index
info.material.index = materialIndex;
// set the edit flag
info.material.flags |= GridBlock::Material::Edit;
// store back
setInfo( info );
}
}
// flush them textures
flushTextures();
undo.undoFlags = Selection::flushTextures;
break;
}
}
}
// raise the terrain as a smooth operation about the center of the
// selection
void SimTed::elevateAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
if( !getBrushDetail() )
raiseHeightAction( action, sel, undo );
switch( action )
{
case begin:
case update:
{
RectI bound;
Point2F center;
float radius;
// get the selection info
setSelectionVars( sel, bound, center, radius );
// walk through the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I p = sel.points[i].pos;
float dx = p.x - center.x;
float dy = p.y - center.y;
float distance = sqrt( ( dx * dx ) + ( dy *dy ) );
float scaledDelta = adjustVal * ( radius - distance );
// get the info at this point
Selection::Info info;
if( getInfo( p, info ) )
{
// add to the undo
undo.addPoint( info );
// adjust the height
setHeight( p, info.height.height + scaledDelta );
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// lower the terrain as a smooth operation about the center of the
// selection
void SimTed::depressAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
if( !getBrushDetail() )
lowerHeightAction( action, sel, undo );
switch( action )
{
case begin:
case update:
{
RectI bound;
Point2F center;
float radius;
// get the selection info
setSelectionVars( sel, bound, center, radius );
// walk through the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I p = sel.points[i].pos;
float dx = p.x - center.x;
float dy = p.y - center.y;
float distance = sqrt( ( dx * dx ) + ( dy *dy ) );
float scaledDelta = -adjustVal * ( radius - distance );
// get the info at this point
Selection::Info info;
if( getInfo( p, info ) )
{
// add to the undo
undo.addPoint( info );
// adjust the height
setHeight( p, info.height.height + scaledDelta );
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// just call into the rotate action
void SimTed::rotateRightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
rotateAction( action, sel, undo, true );
}
// just call into the rotate action
void SimTed::rotateLeftAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
rotateAction( action, sel, undo, false );
}
// rotate the selected terrain by 90 deg
void SimTed::rotateAction( SimTed::BrushAction action, Selection & sel,
Selection & undo, bool rotRight )
{
unsigned int i;
switch( action )
{
case begin:
case update:
// go through the selection
for( i = 0; i < sel.points.getSize(); i++ )
{
// get the info at this position
Selection::Info info;
if( !getInfo( sel.points[i].pos, info ) )
continue;
// add to the undo
undo.addPoint( info );
const int rot = GridBlock::Material::Rotate;
const int flipx = GridBlock::Material::FlipX;
const int flipy = GridBlock::Material::FlipY;
int f = info.material.flags;
// set all the flags
info.material.flags |= ( rot | flipx | flipy );
// this kinda sucks, but the way this was done before
// was corrupting the flags!
if( rotRight )
{
if( !( f & rot ) )
{
if( !( f & flipx ) )
info.material.flags &= ~( flipx | flipy );
}
else
{
if( !( f & flipx ) )
info.material.flags &= ~( rot );
else
info.material.flags &= ~( rot | flipx | flipy );
}
}
else
{
if( !( f & rot ) )
{
if( f & flipx )
info.material.flags &= ~( flipx | flipy );
}
else
{
if( !( f & flipx ) )
info.material.flags &= ~( rot | flipx | flipy );
else
info.material.flags &= ~( rot );
}
}
// set the info
setInfo( info );
}
// flush them textures
flushTextures();
undo.undoFlags = Selection::flushTextures;
break;
}
}
// set the flags on the selected terrain through the flagVal mask
void SimTed::setFlagsAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
flagAction( action, sel, undo, set );
}
// reset the flags on the selected terrain through the flagVal mask
void SimTed::clearFlagsAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
flagAction( action, sel, undo, clear );
}
// carry out the particular flag operation
void SimTed::flagAction( SimTed::BrushAction action, Selection & sel,
Selection & undo, SimTed::FlagOps flagOp )
{
unsigned int i;
switch( action )
{
case begin:
case update:
case end:
// go through the selection
for( i = 0; i < sel.points.getSize(); i++ )
{
// get the info at this position
Selection::Info info;
if( !getInfo( sel.points[i].pos, info ) )
continue;
// add to the undo
undo.addPoint( info );
// adjust the flags
switch( flagOp )
{
case clear:
info.material.flags &= ~( flagVal );
break;
case set:
info.material.flags |= flagVal;
break;
}
// set the info
setInfo( info );
}
// flush them textures
flushTextures();
undo.undoFlags = Selection::flushTextures;
break;
}
}
// raise the height of the selection by adjustVal amount
void SimTed::raiseHeightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
case update:
for( i = 0; i < sel.points.getSize(); i++ )
{
float height = getHeight( sel.points[i].pos ) + adjustVal;
// add to the undo before changing
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
undo.addPoint( info );
setHeight( sel.points[i].pos, height );
}
}
// check for feathering
if( feather )
featherAction( action, sel, undo, true, adjustVal );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// lower the height of the selection by adjustVal amount
void SimTed::lowerHeightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
case update:
for( i = 0; i < sel.points.getSize(); i++ )
{
float height = getHeight( sel.points[i].pos ) - adjustVal;
// add to the undo before changing
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
undo.addPoint( info );
setHeight( sel.points[i].pos, height );
}
}
// check for feathering
if( feather )
featherAction( action, sel, undo, true, -adjustVal );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// set the height for the selected terrain
void SimTed::setHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
case update:
// go through and set the heights
for( i = 0; i < sel.points.getSize(); i++ )
{
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// add to the undo
undo.addPoint( info );
setHeight( sel.points[i].pos, heightVal );
}
}
// check if we should smooth this
if( feather )
featherAction( action, sel, undo, false, heightVal );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// just force to fit
void SimTed::setSmoothVal( float smooth )
{
if( smooth < 0.0f )
smooth = 0.0f;
if( smooth > 1.0f )
smooth = 1.0f;
smoothVal = smooth;
}
// smooth the selected terrain
void SimTed::smoothAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case begin:
case update:
{
// how do you smooth a single point?
if( !getBrushDetail() )
return;
//get some information about the current selection
RectI bound;
Point2F center;
float radius;
setSelectionVars( sel, bound, center, radius );
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I pnt = sel.points[i].pos;
float dx = pnt.x - center.x;
float dy = pnt.y - center.y;
float distance = sqrt( float( ( dx * dx ) + ( dy * dy ) ) );
Selection::Info info;
if( !getInfo( pnt, info ) )
continue;
// add to info
undo.addPoint( info );
float oldHeight = info.height.height;
float sum = 0.0;
int count = 0;
if( pointValid( Point2I( pnt.x - 1, pnt.y ) ) )
{
sum += getHeight( Point2I( pnt.x - 1, pnt.y ) );
count++;
}
if( pointValid( Point2I( pnt.x + 1, pnt.y ) ) )
{
sum += getHeight( Point2I( pnt.x + 1, pnt.y ) );
count++;
}
if( pointValid( Point2I( pnt.x, pnt.y - 1 ) ) )
{
sum += getHeight( Point2I( pnt.x, pnt.y - 1 ) );
count++;
}
if( pointValid( Point2I( pnt.x, pnt.y + 1) ) )
{
sum += getHeight( Point2I( pnt.x, pnt.y + 1 ) );
count++;
}
sum /= count;
float increment = ( sum - oldHeight ) /
( ( 10 - ( smoothVal * 9.999f ) ) );
float adjust = increment - ( ( increment / 2 ) *
distance / radius );
if( fabs( adjust ) > fabs( sum - oldHeight ) )
adjust = ( sum - oldHeight );
oldHeight += adjust;
setHeight( pnt, oldHeight);
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// add noise to terrain
void SimTed::noiseAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
action;sel;undo;
}
// adjust the terrain around the selected terrain to create smooth
// transition for the heights
void SimTed::featherAction( SimTed::BrushAction action, Selection & sel,
Selection & undo, bool raise, float height )
{
switch( action )
{
case begin:
case update:
{
Selection touched;
unsigned int i;
// check at which detail we should feather things
if( !brushDetail || !snap )
{
for( i = 0; i < sel.points.getSize(); i++ )
{
int j, k;
// walk around this point and add the ones touching
for( j = -1; j <= 1; j++ )
{
for( k = -1; k <= 1; k++ )
{
if( j || k )
{
Point2I pnt;
pnt.x = sel.points[i].pos.x + k;
pnt.y = sel.points[i].pos.y + j;
if( pointValid( pnt ) && !touched.pointInSel( pnt ) &&
!sel.pointInSel( pnt ) )
touched.addPoint( pnt );
}
}
}
}
Vector < float > heights;
// go through all the points in the touched list and get an average height
for( i = 0; i < touched.points.getSize(); i++ )
{
int j, k;
int count = 0;
float sum = 0.0;
// walk around this point and sum the surrounding ones
for( j = -1; j <= 1; j++ )
{
for( k = -1; k <= 1; k++ )
{
Point2I pnt;
pnt.x = touched.points[i].pos.x + k;
pnt.y = touched.points[i].pos.y + j;
// add to the sum
if( pointValid( pnt ) )
{
count++;
sum += getHeight( pnt );
}
}
}
float height = sum / count;
heights.push_back( height );
}
// now set these heights
for( i = 0; i < touched.points.getSize(); i++ )
{
Selection::Info info;
if( !getInfo( touched.points[i].pos, info ) )
continue;
// add to the undo
undo.addPoint( info );
setHeight( touched.points[ i ].pos, heights[ i ] );
}
return;
}
for( int n = -1; n <= 1; n++ )
{
for( int m = -1; m <= 1; m++ )
{
// skip this brush
if( !m && !n )
continue;
// get the position
Point2I pos;
pos.x = brushPos.x + m * ( 1 << brushDetail );
pos.y = brushPos.y + n * ( 1 << brushDetail );
// check that the brush exists
if( !pointValid( pos ) )
continue;
// check for raising an edge or a corner
if( !m || !n )
{
SimTed::Side side;
if( !m )
side = ( n == -1 ) ? bottom : top;
else
side = ( m == -1 ) ? right : left;
// adjust the edge
raiseEdgeHeight( pos, undo, side, height, raise );
}
else
{
bool top = true;
bool left = true;
// figure out which corners to adjust to/from
if( m == -1 )
left = false;
if( n == -1 )
top = false;
// raise a corner
Point2I src;
src.x = left ? brushPos.x + ( 1 << brushDetail ) - 1 :
brushPos.x;
src.y = left ? brushPos.y + ( 1 << brushDetail ) - 1 :
brushPos.y;
if( !pointValid( src ) )
continue;
float height = getHeight( src );
adjustControlPoint( pos, height, undo, top, left, true );
}
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// set the height for an edge of the terrain
void SimTed::raiseEdgeHeight( const Point2I brush, Selection & undo, SimTed::Side side, float height, bool raise )
{
int brushDim = ( 1 << brushDetail );
// go along the edge
for( int i = 0; i < brushDim; i++ )
{
Point2I destPnt;
// look at side
switch( side )
{
case right:
destPnt.x = brush.x + brushDim - 1;
destPnt.y = brush.y + i;
break;
case bottom:
destPnt.x = brush.x + i;
destPnt.y = brush.y + brushDim - 1;
break;
case left:
destPnt.x = brush.x;
destPnt.y = brush.y + i;
break;
case top:
destPnt.x = brush.x + i;
destPnt.y = brush.y;
break;
}
// get the amount we need to adjust to
float heightStep;
if( raise )
heightStep = height / ( float )( brushDim - 1 );
else
heightStep = ( height - getHeight( destPnt ) ) / ( float )brushDim;
for( int j = 0; j < brushDim; j++ )
{
Point2I currentPnt;
// look at side
switch( side )
{
case right:
currentPnt.x = brush.x + j;
currentPnt.y = destPnt.y;
break;
case bottom:
currentPnt.x = destPnt.x;
currentPnt.y = brush.y + j;
break;
case left:
currentPnt.x = brush.x + brushDim - j - 1;
currentPnt.y = destPnt.y;
break;
case top:
currentPnt.x = destPnt.x;
currentPnt.y = brush.y + brushDim - j - 1;
break;
}
Selection::Info info;
if( !getInfo( currentPnt, info ) )
continue;
undo.addPoint( info );
setHeight( currentPnt, info.height.height + heightStep * j );
}
}
}
// adjust the corner of a brush
void SimTed::setBrushCornerHeight( const Point2I pnt, Selection & undo,
float height, bool setUndo )
{
int brushDim = ( 1 << getBrushDetail() );
// go through them
for( int i = -1; i <= 0; i++ )
{
for( int j = -1; j <= 0; j++ )
{
bool top = true;
bool left = true;
Point2I pos( pnt.x + j * brushDim, pnt.y + i * brushDim );
// check that there is a brush here
if( !pointValid( pos ) )
continue;
// get the corner pos and directions
if( j == -1 )
left = false;
if( i == -1 )
top = false;
// adjust this corner
adjustControlPoint( pos, height, undo, top, left, setUndo );
}
}
}
// adjust the height value for a corner of a brush selection
// assumes that a brush really exists at this coordinate
void SimTed::adjustControlPoint( const Point2I brush, float height, Selection & undo,
bool top, bool left, bool setUndo )
{
int brushHeight, brushWidth;
Point2I control;
Point2F endPnt;
// get the brush dimensions
brushHeight = brushWidth = ( 1 << brushDetail );
// get the control point
control.y = top ? 0 : ( brushHeight - 1 );
control.x = left ? 0 : ( brushWidth - 1 );
// get the height for this control point
Point2I pnt( control.x + brush.x, control.y + brush.y );
float controlHeight = getHeight( pnt );
for( int y = 0; y < brushHeight; y++ )
{
for( int x = 0; x < brushWidth; x++ )
{
Point2I pos( x, y );
if( pos == control )
{
pos.x += brush.x;
pos.y += brush.y;
// add to the undo
if( setUndo )
{
Selection::Info info;
if( getInfo( pos, info ) )
undo.addPoint( info );
}
setHeight( pos, height );
continue;
}
else if( pos.x == control.x )
{
endPnt.x = ( float )control.x;
endPnt.y = ( float )( top ? ( brushHeight - 1 ) : 0 );
}
else if( pos.y == control.y )
{
endPnt.x = ( float )( left ? ( brushWidth - 1 ) : 0 );
endPnt.y = ( float )control.y;
}
else
{
// get the slope
double slope;
slope = fabs( float( pos.y - control.y ) ) / fabs( float( pos.x - control.x ) );
if( slope <= 1.0 )
{
endPnt.x = ( float )( left ? ( brushWidth - 1 ) : 0 );
endPnt.y = ( float )( top ? ( slope * float( brushHeight - 1 ) ) :
float( ( brushHeight - 1 ) ) - ( slope * float( brushHeight - 1 ) ) );
}
else
{
endPnt.x = ( float )( left ? ( float( brushWidth - 1 ) / slope ) :
float( brushWidth - 1 ) - ( float( brushWidth - 1 ) / slope ) );
endPnt.y = ( float )( top ? ( brushHeight - 1 ) : 0 );
}
}
double targetD;
double endD;
// get the distances
targetD = sqrtf( ( control.x - x ) * ( control.x - x ) +
( control.y - y ) * ( control.y - y ) );
endD = sqrtf( ( endPnt.x - control.x ) * ( endPnt.x - control.x ) +
( endPnt.y - control.y ) * ( endPnt.y - control.y ) );
// adjust the coords
pos.x += brush.x;
pos.y += brush.y;
float stepInc = ( height - controlHeight ) / endD;
float posHeight = getHeight( pos );
posHeight += ( height - controlHeight ) - ( stepInc * targetD );
// add to the undo
if( setUndo )
{
Selection::Info info;
if( getInfo( pos, info ) )
undo.addPoint( info );
}
setHeight( pos, posHeight );
}
}
}
// adds the selection to the current selection ( allows for
// mass selection with the shift key )
void SimTed::selectAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
undo;
unsigned int i;
switch( action )
{
case begin:
// check for ctrl button
if( GetAsyncKeyState( VK_SHIFT ) & 0x8000 )
{
// clear out the highlight selection
hilightSel.clear();
regionSelect = true;
selectCanceled = false;
selectStartPnt = brushPos;
}
else
{
regionSelect = false;
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.addPoint( sel.points[i].pos );
}
break;
case update:
if( regionSelect && !selectCanceled )
{
hilightSel.clear();
if( GetAsyncKeyState( VK_ESCAPE ) & 0x8000 )
{
selectCanceled = true;
return;
}
Point2I tlPnt;
Point2I dim;
int length = 1 << brushDetail;
// get the coords for the box
tlPnt.x = min( selectStartPnt.x, brushPos.x );
tlPnt.y = min( selectStartPnt.y, brushPos.y );
dim.x = max( selectStartPnt.x + length, brushPos.x + length ) - tlPnt.x;
dim.y = max( selectStartPnt.y + length, brushPos.y + length ) - tlPnt.y;
int i, j;
// fill the region select with the info
for( i = 0; i < dim.y; i++ )
for( j = 0; j < dim.x; j++ )
{
Point2I pnt( tlPnt.x + j, tlPnt.y + i );
if( pointValid( pnt ) )
hilightSel.addPoint( pnt );
}
}
else
{
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.addPoint( sel.points[i].pos );
}
break;
case end:
if( regionSelect )
{
for( i = 0; i < hilightSel.points.getSize(); i++ )
currentSel.addPoint( hilightSel.points[i].pos );
hilightSel.clear();
}
break;
}
// clusterize the stuff
if( selectShow.test( Outline ) )
clusterizeSelection( currentClusterSel, currentSel );
if( hilightShow.test( Outline ) && regionSelect )
clusterizeSelection( hilightClusterSel, hilightSel );
}
// gets the average height for the selection
void SimTed::getAvgHeightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;
switch( action )
{
case begin:
case update:
unsigned int i;
int numPoints = sel.points.getSize();
float sum = 0.0;
for( i = 0; i < sel.points.getSize(); i++ )
sum += getHeight( sel.points[i].pos );
avgHeight = sum / numPoints;
break;
}
}
// remove the selected blocks from the current selection
void SimTed::deselectAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;
unsigned int i;
switch( action )
{
case begin:
// check for ctrl button
if( GetAsyncKeyState( VK_SHIFT ) & 0x8000 )
{
// clear out the highlight selection
hilightSel.clear();
regionSelect = true;
selectCanceled = false;
selectStartPnt = brushPos;
}
else
{
regionSelect = false;
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.removePoint( sel.points[i].pos );
}
break;
case update:
if( regionSelect && !selectCanceled )
{
hilightSel.clear();
if( GetAsyncKeyState( VK_ESCAPE ) & 0x8000 )
{
selectCanceled = true;
return;
}
Point2I tlPnt;
Point2I dim;
int length = 1 << brushDetail;
// get the coords for the box
tlPnt.x = min( selectStartPnt.x, brushPos.x );
tlPnt.y = min( selectStartPnt.y, brushPos.y );
dim.x = max( selectStartPnt.x + length, brushPos.x + length ) - tlPnt.x;
dim.y = max( selectStartPnt.y + length, brushPos.y + length ) - tlPnt.y;
int i, j;
// fill the region select with the info
for( i = 0; i < dim.y; i++ )
for( j = 0; j < dim.x; j++ )
{
Point2I pnt( tlPnt.x + j, tlPnt.y + i );
if( pointValid( pnt ) )
hilightSel.addPoint( pnt );
}
}
else
{
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.removePoint( sel.points[i].pos );
}
break;
case end:
if( regionSelect )
{
for( i = 0; i < hilightSel.points.getSize(); i++ )
currentSel.removePoint( hilightSel.points[i].pos );
hilightSel.clear();
}
break;
}
// clusterize the stuff
if( selectShow.test( Outline ) )
clusterizeSelection( currentClusterSel, currentSel );
if( hilightShow.test( Outline ) && regionSelect )
clusterizeSelection( hilightClusterSel, hilightSel );
}
// add an action to the internal table
void SimTed::addAction( const char * name, void ( SimTed::*callback )
( SimTed::BrushAction, Selection & sel, Selection & undo ), bool mouseAction,
const char * description )
{
TedAction * newAction = new TedAction;
newAction->name = name;
newAction->callback = callback;
newAction->mouseAction = mouseAction;
newAction->description = description;
// add to the vector
actions.push_back( newAction );
}
// call an action routine
bool SimTed::processAction( const char * name )
{
int actionIndex = getActionIndex( name );
// check that it got a good action
if( actionIndex == -1 )
return( false );
// check if there is something selected
if( !currentSel.points.getSize() )
return( true );
// create an undo selection
Selection * undo = new Selection;
// save the brush detail size
int detail = getBrushDetail();
// go into detail mode 0 for this
setBrushDetail( 0 );
// call the callback twice ( begin then end )
( this->*actions[actionIndex]->callback )( begin, currentSel, *undo );
( this->*actions[actionIndex]->callback )( end, currentSel, *undo );
// reset the detail mode
setBrushDetail( detail );
// do the undo stuff
if( undo->points.getSize() )
{
// add to the undo stack and remove the redo stack
undoStack.push( undo );
redoStack.clear();
}
else
delete undo;
dataChanged = true;
return( true );
}
void SimTed::floatCurrent()
{
// fill with info ( just has positions )
fillInfo( currentSel );
// float it
floatSelection( currentSel );
floatPasteVal = pasteVal;
currentSel.clear();
}
void SimTed::floatSelection( Selection & sel )
{
if( selFloating || !sel.points.getSize() )
return;
// grab the first position, rest are offset from this
Point2I origin = sel.points[0].pos;
// clear the copy selection
copySel.clear();
// add all the points as an offset to the first point from the sel
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I pos( sel.points[i].pos.x - origin.x,
sel.points[i].pos.y - origin.y );
Selection::Info info;
info = sel.points[i];
info.pos = pos;
copySel.addPoint( info );
}
// clusterize if wanted to
clusterizeSelection( copyClusterSel, copySel );
selFloating = true;
}
void SimTed::setBrushPos( const Point2I & pos )
{
brushPos = pos;
// check for snap
if( snap )
{
brushPos.x >>= brushDetail;
brushPos.x <<= brushDetail;
brushPos.y >>= brushDetail;
brushPos.y <<= brushDetail;
}
}
void SimTed::mouseAction( int button, SimTed::BrushAction action )
{
Point2I hitPnt;
cursorPos = getCanvas()->getCursorPos();
cursorDif = cursorPos - lastCursorPos;
lastCursorPos = cursorPos;
if( action == begin )
cursorDif.set( 0, 0 );
setVars();
if( !getInterceptCoord( hitPnt ) && ( action != end ) )
{
selectLastPnt.x = -1;
selectLastPnt.y = -1;
return;
}
// set the brush position ( will snap here if requested )
setBrushPos( hitPnt );
// check which button was pressed
if(!button)
{
// make sure the other button is not pressed
if( ::GetAsyncKeyState( ( ::GetSystemMetrics( SM_SWAPBUTTON ) ) ?
VK_LBUTTON : VK_RBUTTON ) & 0x8000 )
return;
if(action == begin)
{
// protect against multiple begins (can happen when
// lost the mouse and the mouse up event)..
if(mouseProcessAction != -1)
return;
mouseProcessAction = mouseLButtonAction;
}
}
else
{
// make sure the other button is not pressed
if( ::GetAsyncKeyState( ( ::GetSystemMetrics( SM_SWAPBUTTON ) ) ?
VK_RBUTTON : VK_LBUTTON ) & 0x8000 )
return;
if(action == begin)
{
if(mouseProcessAction != -1)
return;
mouseProcessAction = mouseRButtonAction;
}
}
// check if floating
if( selFloating )
{
// check for cancel
if( button )
{
selFloating = false;
return;
}
else if(action == begin)
mouseProcessAction = getActionIndex( "paste" );
}
// only do the comman on new position
if( ( brushPos == selectLastPnt ) && ( action == update ) && !grabMode )
return;
// update the last mouse position so that we do not apply the same action
selectLastPnt = brushPos;
// check if cool
if( ( mouseProcessAction != -1 ) && ( actions.size() > mouseProcessAction ) &&
( actions[mouseProcessAction]->callback != 0 ) )
{
Selection sel;
fillSelection( sel );
// create a new undo selection that spans the entire command
if( ( action == begin ) && currentUndo )
{
delete currentUndo;
currentUndo = NULL;
}
// create a new selection
if( !currentUndo )
currentUndo = new Selection;
// call the callback
( this->*actions[mouseProcessAction]->callback )( action, sel, *currentUndo );
// do the undo stuff
if( action == end )
{
// add to the undo if points were actually changed
if( currentUndo->points.getSize() )
{
// add to the undo but flush the redo
undoStack.push( currentUndo );
redoStack.clear();
}
else
delete currentUndo;
// reset the ptr ( the stack will deal with it )
currentUndo = NULL;
dataChanged = true;
// update the toolbar
Console->evaluate( "Ted::updateToolBar();", false );
mouseProcessAction = -1;
}
}
}
void SimTed::fillSelection( Selection & sel )
{
int i,j;
int length = 1 << brushDetail;
// add 2^detailLevelx2^detailLevel points
for( i = 0; i < length; i++ )
for( j = 0; j < length; j++ )
{
Point2I pnt( brushPos.x + j, brushPos.y + i );
if( pointValid( pnt ) )
sel.addPoint( pnt );
}
}
// apply an action to the entire terrain block.. only
// works with oneBlockmapstoall....
bool SimTed::terrainAction(const char * action)
{
if(getGridFile()->getBlockPattern() != GridFile::OneBlockMapsToAll)
return(false);
// get the width of a blcok
int n = 1 << (getMaxBrushDetail() - 1);
int actionIndex = getActionIndex(action);
if(actionIndex == -1)
return(false);
// create a selection of the entire terrain
Selection sel;
sel.createMap(n,n);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
sel.addPoint(Point2I(i,j));
// create an undo selection
Selection * undo = new Selection;
undo->createMap(n,n);
// call the function
int detail = getBrushDetail();
setBrushDetail(0);
( this->*actions[actionIndex]->callback )( begin, sel, *undo );
( this->*actions[actionIndex]->callback )( end, sel, *undo );
setBrushDetail(detail);
undo->deleteMap();
// add to the undo stack and remove the redo stack
undoStack.push( undo );
redoStack.clear();
dataChanged = true;
return(true);
}
// this will mirror the terrain according the flags... only
// mirrors the center block of a oneblockmapstoall pattern
bool SimTed::mirrorTerrain(UInt32 sides)
{
if(getGridFile()->getBlockPattern() != GridFile::OneBlockMapsToAll)
return(false);
// check the sides
if((sides & top) && (sides & bottom))
return(false);
if((sides & left) && (sides & right))
return(false);
// get the width of a blcok
int n = 1 << (getMaxBrushDetail() - 1);
Point2I src((sides & right) ? (n - 1) : 0, (sides & bottom) ? (n - 1) : 0);
Point2I dest((sides & left) ? (n - 1) : 0, (sides & top) ? (n - 1) : 0);
Point2I origSrc(src);
Point2I origDest(dest);
// check if diag...
bool diag = ((sides & right)||(sides & left)) && ((sides & top)||(sides & bottom));
// determine the run length
int minStride = ((sides & top) || (sides & bottom)) ? n : n / 2;
int majStride = ((sides & left) || (sides & right)) ? n : n / 2;
Point2I srcStep((sides & right) ? -1 : 1, (sides & bottom) ? -1 : 1);
Point2I destStep((sides & left) ? -1 : 1, (sides & top) ? -1 : 1);
// create an undo stack for this operation
Selection * undo = new Selection;
// walk through all the positions
for(int i = 0; i < majStride; i++)
{
for(int j = 0; j < minStride; j++)
{
// skip the same position
if(src != dest)
{
// set only the height...
SimTed::Selection::Info info;
if(getInfo(dest, info))
{
undo->addPoint(info);
float height = getHeight(src);
setHeight(dest, height);
}
}
// get to the new position
src.x += srcStep.x;
diag ? (dest.y += destStep.y) : (dest.x += destStep.x);
}
// get the next position for a run
src.y += srcStep.y;
diag ? (dest.x += destStep.x) : (dest.y += destStep.y);
// reset the minor run
src.x = origSrc.x;
diag ? (dest.y = origDest.y) : (dest.x = origDest.x);
// shorten the run length for diag runs
if(diag)
minStride--;
}
// add to the undo stack
undoStack.push(undo);
redoStack.clear();
dataChanged = true;
return(true);
}
bool SimTed::pointValid( const Point2I & pnt )
{
if( ( pnt.x >= 0 ) && ( pnt.x < ( size.x << blockShift ) ) &&
( pnt.y >= 0 ) && ( pnt.y < ( size.y << blockShift ) ) )
return( true );
return( false );
}
bool SimTed::onSim3DMouseEvent( const Sim3DMouseEvent * event )
{
if( !focused )
return( false );
switch( event->meType )
{
case Sim3DMouseEvent::MouseUp:
case Sim3DMouseEvent::RightMouseUp:
AssertFatal( mouseHandler, "SimTed::processEvent:: mouse handler not set" );
// send off to the tedplugin
mouseHandler->mouseCallback( true, ( event->meType == Sim3DMouseEvent::RightMouseDown ) );
mouseAction( ( event->meType == Sim3DMouseEvent::RightMouseUp ), end );
break;
case Sim3DMouseEvent::RightMouseDown:
case Sim3DMouseEvent::MouseDown:
AssertFatal( mouseHandler, "SimTed::processEvent:: mouse handler not set" );
// send to ted
mouseHandler->mouseCallback( false, ( event->meType == Sim3DMouseEvent::RightMouseDown ) );
mouseAction( ( event->meType == Sim3DMouseEvent::RightMouseDown ), begin );
break;
case Sim3DMouseEvent::MouseDragged:
case Sim3DMouseEvent::RightMouseDragged:
case Sim3DMouseEvent::MouseMove:
// update the current position and start point for the mouse
mouseStartPt = event->startPt;
mouseDirection = event->direction;
// call the drag routine
if( event->meType != Sim3DMouseEvent::MouseMove )
mouseAction( ( event->meType == Sim3DMouseEvent::RightMouseDragged ), update );
else
{
Point2I hitPnt;
setVars();
if( getInterceptCoord( hitPnt ) )
{
setBrushPos( hitPnt );
mouseMoved = true;
}
}
break;
}
return( false );
}
int SimTed::getMaxBrushDetail()
{
return( getGridFile()->getDetailCount() );
}
void SimTed::setBrushDetail( int detail )
{
// check that we are not trying to change detail too high
if( detail > ( getGridFile()->getDetailCount() ) )
return;
brushDetail = detail;
}
bool SimTed::getInterceptCoord( Point2I & pnt )
{
TMat3F tmat = getInvTransform();
LineSeg3F line;
line.start = mouseStartPt;
line.end = mouseDirection;
line.end *= 100000;
line.end += line.start;
LineSeg3F tline;
m_mul( line.start, tmat, &tline.start );
m_mul( line.end, tmat, &tline.end );
GridCollision coll( getGridFile(), 0 );
if( coll.collide( tline.start, tline.end, false, true ) )
{
Point3F potenIcept = coll.surface.position;
setVars();
Point2I potenIceptI( potenIcept.x,potenIcept.y );
potenIceptI >>= scaleShift;
if ( ( potenIceptI.x >= 0 ) && ( potenIceptI.x < ( size.x << blockShift ) ) &&
( potenIceptI.y >= 0 ) && ( potenIceptI.y < ( size.y << blockShift ) ) )
{
pnt = potenIceptI;
return( true );
}
}
return( false );
}
bool SimTed::processEvent( const SimEvent * event )
{
switch( event->type )
{
onEvent( Sim3DMouseEvent );
case SimGainFocusEventType:
focused = TRUE;
break;
case SimLoseFocusEventType:
focused = FALSE;
break;
// let the parent class handle this event
default:
return( SimObject::processEvent( event ) );
}
return( true );
}
bool SimTed::processQuery( SimQuery* query )
{
switch( query->type )
{
case SimRenderQueryImageType:
{
if( !focused )
return( false );
// setup for an overlay render
SimRenderQueryImage * queryImage =
static_cast< SimRenderQueryImage* >( query );
queryImage->count = 1;
queryImage->image[0] = this;
itype = SimRenderImage::Overlay;
break;
}
case SimInputPriorityQueryType:
// set slightly higher than normal priority
( ( SimInputPriorityQuery * )query )->priority = SI_PRIORITY_NORMAL + 2;
break;
default:
return( SimObject::processQuery( query ) );
}
return( true );
}
bool SimTed::onAdd()
{
if( !SimObject::onAdd() )
return( false );
addToSet( SimInputConsumerSetId );
addToSet( SimRenderSetId );
return( true );
}
void SimTed::onRemove()
{
removeFromSet( SimInputConsumerSetId );
removeFromSet( SimRenderSetId );
focused = false;
SimObject::onRemove();
}
void SimTed::render( TSRenderContext &rc )
{
setVars();
rc.getCamera()->pushTransform( getTransform() );
surface = rc.getSurface();
surface->setHazeSource(GFX_HAZE_NONE);
surface->setShadeSource(GFX_SHADE_NONE);
surface->setAlphaSource(GFX_ALPHA_NONE);
surface->setFillMode(GFX_FILL_CONSTANT);
surface->setTexturePerspective(FALSE);
surface->setTransparency(FALSE);
pointArray = rc.getPointArray();
pointArray->reset();
pointArray->useIntensities(false);
pointArray->useTextures(false);
pointArray->useHazes(false);
pointArray->useBackFaceTest(false);
pointArray->setVisibility( TS::ClipMask );
unsigned int i;
int fillCol, frameCol;
Selection * sel;
// turn off flipping of colors
flipColors = false;
// draw our stuff
if( selectShow.test( Outline ) )
{
sel = ¤tClusterSel;
// check if should clear
if( currentSel.points.getSize() < currentClusterSel.points.getSize() )
currentClusterSel.clear();
// check if should fill
if( currentSel.points.getSize() && !currentClusterSel.points.getSize() )
clusterizeSelection( currentClusterSel, currentSel );
}
else
{
sel = ¤tSel;
currentClusterSel.clear();
}
// set the colors
fillCol = flipColors ? selectFrameColor : selectFillColor;
frameCol = flipColors ? selectFillColor : selectFrameColor;
for( i = 0; i < sel->points.getSize(); i++ )
{
if( selectShow.test( Fill ) )
drawSquareFilled( sel->points[i].pos, rc, fillCol );
if( selectShow.test( Frame ) )
drawSquare( sel->points[i].pos, rc, frameCol );
}
// do the hilight now
if( hilightShow.test( Outline ) )
sel = &hilightClusterSel;
else
sel = &hilightSel;
// set the colors
fillCol = flipColors ? hilightFrameColor : hilightFillColor;
frameCol = flipColors ? hilightFillColor : hilightFrameColor;
for( i = 0; i < sel->points.getSize(); i++ )
{
if( hilightShow.test( Fill ) )
drawSquareFilled( sel->points[i].pos, rc, fillCol );
if( hilightShow.test( Frame ))
drawSquare( sel->points[i].pos, rc, frameCol );
}
// check for grab mode
drawMouseShadow( rc );
// check if drawing the frame around the current block
if( blockOutline )
{
// grab the first block - just need to get dimensions
Point2I size( 0, 0 );
GridBlock * block = getGridFile()->getBlock( size );
// get the size
size = block->getSize();
Point2I begin, end;
// set the start point
begin.x = brushPos.x & ~( size.x - 1 );
begin.y = brushPos.y & ~( size.y - 1 );
// set the end point
end.x = begin.x + size.x;
end.y = begin.y + size.y;
drawSquareOutline( begin, end, rc, blockFrameColor );
}
rc.getCamera()->popTransform();
}
void SimTed::drawSquareOutline( Point2I & begin, Point2I & end, TSRenderContext & rc, UInt8 col )
{
int width, height;
width = end.x - begin.x;
height = end.y - begin.y;
surface->setFillColor( col );
Point2F p1, p2;
float scale = ( float )(1 << scaleShift);
// draw the top and bottom
for( int x = 0; x < ( width - 1 ); x++ )
{
// fill in the point info
p1.x = begin.x + x;
p2.x = p1.x + 1;
p1.y = p2.y = begin.y;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
// do again for fill in the point info
p1.x = begin.x + x;
p2.x = p1.x + 1;
p1.y = p2.y = end.y;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
}
// draw the sides
for( int y = 0; y < height; y++ )
{
// fill in the point info for the left side
p1.x = p2.x = begin.x;
p1.y = begin.y + y;
p2.y = p1.y + 1;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
// fill in the point info for the right side
p1.x = p2.x = end.x;
p1.y = begin.y + y;
p2.y = p1.y + 1;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
}
}
// draw the mouse shadow, can change shapes depending on mode
void SimTed::drawMouseShadow( TSRenderContext & rc )
{
// check if floating the selection
if( selFloating )
{
int fillCol = flipColors ? shadowFrameColor : shadowFillColor;
int frameCol = flipColors ? shadowFillColor : shadowFrameColor;
Selection * sel;
if( shadowShow.test(Outline) )
sel = ©ClusterSel;
else
sel = ©Sel;
// go through and draw the squares
for( unsigned i = 0; i < sel->points.getSize(); i++ )
{
Point2I pos( sel->points[i].pos.x + brushPos.x,
sel->points[i].pos.y + brushPos.y );
// make sure a valid point
if( !pointValid( pos ) )
continue;
if( shadowShow.test( Fill ) )
drawSquareFilled( pos, rc, fillCol );
if( shadowShow.test( Frame ) )
drawSquare( pos, rc, frameCol );
}
return;
}
// create a shadow selection
Selection brushSel;
if( grabMode )
{
int brushDim = ( 1 << brushDetail );
// set the current brush position
brushPos = grabPoint;
// add all the brush edges only
addBrushEdgePoints( brushPos, brushSel );
if(drawNeighbors)
{
// walk around and add the surrounding brushes
Point2I pos( brushPos.x - brushDim, brushPos.y );
// add it
if( pointValid( pos ) )
addBrushEdgePoints( pos, brushSel );
pos.y = brushPos.y - brushDim;
// add it
if( pointValid( pos ) )
addBrushEdgePoints( pos, brushSel );
pos.x = brushPos.x;
// add it
if( pointValid( pos ) )
addBrushEdgePoints( pos, brushSel );
}
}
else
{
fillSelection( brushSel );
// check if the mouse has moved
if( mouseMoved )
{
// get the avg height for the brush ( undo param is not used )
getAvgHeightAction( begin, brushSel, brushSel );
Point2I center;
// get the center location
getBrushCenter( center, brushPos );
// write the info in the status bar
char buffer[ 128 ];
sprintf( buffer, "Ted::setStatusText(2,\"Center - ( %d, %d ) AvgHeight: %.3f\");",
center.x, center.y, avgHeight );
Console->evaluate( buffer, false );
}
// check for outline mode
if( shadowShow.test( Outline ) )
{
brushSel.clear();
addBrushEdgePoints( brushPos, brushSel );
}
}
int fillCol = flipColors ? shadowFrameColor : shadowFillColor;
int frameCol = flipColors ? shadowFillColor : shadowFrameColor;
// go through and draw the squares
for( unsigned i = 0; i < brushSel.points.getSize(); i++ )
{
if( shadowShow.test(Fill) )
drawSquareFilled( brushSel.points[i].pos, rc, fillCol );
if( shadowShow.test(Frame) )
drawSquare( brushSel.points[i].pos, rc, frameCol );
}
// draw the corner piece inverted
if( getSnap() )
{
if( shadowShow.test( Fill ) )
drawSquareFilled( brushPos, rc, shadowFrameColor );
if( shadowShow.test(Frame) )
drawSquare( brushPos, rc, shadowFillColor );
}
// check if the mouse has moved
if( mouseMoved )
{
// get the info for the brush position
Selection::Info info;
if( getInfo( brushPos, info ) )
{
char buffer[ 128 ];
sprintf( buffer, "Ted::setStatusText(1,\"Corner - ( %d, %d ) Height: %.3f\");",
brushPos.x, brushPos.y, info.height.height );
Console->evaluate( buffer, false );
}
}
// reset the mouse moved flag
mouseMoved = false;
}
void SimTed::getBrushCenter( Point2I & center, Point2I & origin )
{
int brushDim = ( 1 << brushDetail );
center.x = ( origin.x * 2 + brushDim ) / 2;
center.y = ( origin.y * 2 + brushDim ) / 2;
}
void SimTed::clusterizeSelection( Selection & dest, Selection & src )
{
dest.clear();
for( unsigned int i = 0; i < src.points.getSize(); i++ )
{
Point2I pos = src.points[i].pos;
// check the corners
if( !src.pointInSel( Point2I( pos.x - 1, pos.y ) ) ||
!src.pointInSel( Point2I( pos.x, pos.y - 1 ) ) ||
!src.pointInSel( Point2I( pos.x + 1, pos.y ) ) ||
!src.pointInSel( Point2I( pos.x, pos.y + 1) ) )
dest.addPoint( src.points[i].pos );
}
}
void SimTed::addBrushEdgePoints( const Point2I & pos, Selection & sel )
{
int brushDim = ( 1 << brushDetail );
for( int i = 0; i < brushDim; i++ )
{
Point2I newPnt;
// add all 4 points around the edge
// top row
newPnt.x = pos.x + i;
newPnt.y = pos.y;
sel.addPoint( newPnt );
// bottom row
newPnt.y += ( brushDim - 1 );
sel.addPoint( newPnt );
// left column
newPnt.x = pos.x;
newPnt.y = pos.y + i;
sel.addPoint( newPnt );
// right column
newPnt.x += ( brushDim - 1 );
sel.addPoint( newPnt );
}
}
void SimTed::drawSquareFilled( Point2I pos, TSRenderContext& rc, UInt8 col )
{
rc;
surface->setFillColor( col );
// create the points CCW
Point3F p1( pos.x, pos.y, 0.0 );
Point3F p2( pos.x, pos.y + 1, 0.0 );
Point3F p3( pos.x + 1, pos.y + 1, 0.0 );
Point3F p4( pos.x + 1, pos.y, 0.0 );
float scale = (float)( 1 << scaleShift );
p1 *= scale;
p2 *= scale;
p3 *= scale;
p4 *= scale;
// get the heights
p1.z = getHeight( pos ); pos.y++;
p2.z = getHeight( pos ); pos.x++;
p3.z = getHeight( pos ); pos.y--;
p4.z = getHeight( pos );
TS::VertexIndexPair vertexPairs[5];
vertexPairs[0].fVertexIndex = pointArray->addPoint( p1 ) ;
vertexPairs[0].fTextureIndex = 0;
vertexPairs[1].fVertexIndex = pointArray->addPoint( p2 );
vertexPairs[1].fTextureIndex = 0;
vertexPairs[2].fVertexIndex = pointArray->addPoint( p3 );
vertexPairs[2].fTextureIndex = 0;
vertexPairs[3].fVertexIndex = pointArray->addPoint( p4 );
vertexPairs[3].fTextureIndex = 0;
vertexPairs[4] = vertexPairs[0];
pointArray->drawPoly( 5, vertexPairs, 0 );
}
void SimTed::drawLine( Point2F start, Point2F end, TSRenderContext& rc,
UInt8 col )
{
rc;
Point2I st( start.x, start.y );
Point2I en( end.x, end.y );
st >>= scaleShift;
en >>= scaleShift;
float sheight = getHeight( st );
float eheight = getHeight( en );
Point3F ulft, urt, llft, lrt;
ulft = Point3F( start.x, start.y, sheight );
urt = Point3F( end.x, end.y, eheight );
pointArray->drawLine( pointArray->addPoint( ulft ),
pointArray->addPoint( urt ), col);
}
void SimTed::drawSquare( Point2I pos, TSRenderContext& rc, UInt8 col )
{
surface->setFillColor( col );
Point2F p1( pos.x, pos.y );
Point2F p2( pos.x + 1, pos.y );
Point2F p3( pos.x, pos.y + 1 );
Point2F p4( pos.x + 1, pos.y + 1 );
float scale = ( float )(1 << scaleShift);
p1 *= scale;
p2 *= scale;
p3 *= scale;
p4 *= scale;
drawLine( p3, p1, rc, col );
drawLine( p1, p2, rc, col );
drawLine( p4, p2, rc, col );
drawLine( p3, p4, rc, col );
if( drawNotch )
{
Point2F p5 = p4;
p5 -= p1;
p5 *= 0.25f;
p5 += p1;
drawLine( p1, p5, rc, col );
}
}
bool SimTed::setHeight( const Point2I& pos, const float& ht )
{
//this method assumes coords are already shifted down by scale
// and that setVars was called prior
GridBlock::Height h;
h.height = ht;
bool success = false;
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
Point2I block_coords[ 4 ];
int cnt = 0;
int blockMask = (1 << blockShift) - 1;
block_coords[ cnt++ ] = bpos;
// Also set heights of adjacent blocks, if on the border...
if ( bpos.x >= 1 && !(pos.x & blockMask) )
block_coords[ cnt++ ] = Point2I( bpos.x - 1, bpos.y );
if ( bpos.y >= 1 && !(pos.y & blockMask) )
{
block_coords[ cnt++ ] = Point2I( bpos.x, bpos.y - 1 );
if ( bpos.x >= 1 && !(pos.x & blockMask) )
block_coords[ cnt++ ] = Point2I( bpos.x - 1, bpos.y - 1 );
}
Point2I *blpos = block_coords;
for ( int i = 0; i < cnt; i++, blpos++ )
if ( GridBlock* block = getGridFile()->getBlock( *blpos ) )
{
// get remainders on coords so they are in block space
Point2I spos;
spos.x = (pos.x - (blpos->x << blockShift));
spos.y = (pos.y - (blpos->y << blockShift));
//set the height
int index = (spos.y << blockShift) + spos.y + spos.x;
int mapwid = block->getHeightMapWidth();
if (index < mapwid*mapwid )
{
block->setDirtyFlag();
GridBlock::Height* heightMap = block->getHeightMap();
if (heightMap )
heightMap[index] = h;
success = TRUE;
}
}
}
return ( success );
}
bool SimTed::setMaterial( const Point2I& pos, const GridBlock::Material & material )
{
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
if( GridBlock* block = getGridFile()->getBlock( bpos ) )
{
//get coords into block
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
//set the Material
int index = ( spos.y << blockShift ) + spos.x;
int mapwid = block->getMaterialMapWidth();
if( index < mapwid*mapwid )
{
GridBlock::Material *currMat = block->getMaterialMap();
if ( !currMat )
return ( false );
currMat[index] = material;
block->setDirtyFlag();
}
return ( true );
}
return ( false );
}
float SimTed::getHeight(const Point2I& pos)
{
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
if( GridBlock* block = getGridFile()->getBlock( bpos ))
{
//get remainders
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
//get the height
int index = ( spos.y << blockShift )+ spos.y + spos.x;
int mapwid = block->getHeightMapWidth();
if( index < mapwid*mapwid )
{
GridBlock::Height* heightMap = block->getHeightMap();
if( !heightMap )
return( 0 );
return heightMap[index].height;
}
}
}
return( 0 );
}
GridBlock::Material * SimTed::getMaterial( const Point2I& pos )
{
// coords should already be shifted down by ground scale
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = (pos.y) >> blockShift;
if( bpos.x >=0 && bpos.x < size.x && bpos.y >=0 && bpos.y < size.y )
if( GridBlock* block = getGridFile()->getBlock( bpos ) )
{
//get remainders on coords
Point2I spos;
spos.x = ( pos.x - (bpos.x << blockShift ) );
spos.y = ( ( pos.y ) - ( bpos.y << blockShift ) );
//get a ptr to the material
int index = (spos.y << blockShift) + spos.x;
int mapwid = block->getMaterialMapWidth();
if( index < mapwid*mapwid )
{
GridBlock::Material* matMap = block->getMaterialMap();
if( !matMap )
return ( NULL );
return ( &matMap[index] );
}
}
return ( NULL );
}
TSMaterialList * SimTed::getMaterialList()
{
if( getGridFile() )
return( getGridFile()->getMaterialList() );
return( NULL );
}
bool SimTed::open( const char * terrainName )
{
// close down this one
if( terrain )
deleteTerrain();
// create a new terrain
if( ( terrain = new SimTerrain ) != 0 )
{
SimManager * serverManager = SimGame::get()->getManager(SimGame::SERVER);
serverManager->addObject( terrain );
serverManager->assignName( terrain, terrainName );
deleteNotify( terrain );
terrain->load( terrainName );
if( getGridFile() )
{
newLandscaper();
loadMatList( getGridFile()->getMaterialListName() );
terrain->setContext(EulerF(.0f,.0f,.0f),Point3F(.0f,.0f,.0f));
terrain->setVisibility( &DefTerrainVisibility );
terrain->setDetail( &DefTerrainDetail );
SimGainFocusEvent::post( this );
return( true );
}
}
dataChanged = false;
return( false );
}
// create a new file
bool SimTed::newFile( int scale, int blocksWide, int blocksHigh, int blockDim,
const char * terrName, GridFile::GBPatternMap blockPattern )
{
blocksHigh;
// create a new terrain
terrain = new SimTerrain;
SimManager * serverManager = SimGame::get()->getManager(SimGame::SERVER);
serverManager->addObject( terrain );
serverManager->assignName( terrain, terrName );
deleteNotify( terrain );
terrain->create( terrName, blocksWide, scale, blockDim, 0, blockPattern );
newLandscaper();
dataChanged = true;
return true;
}
void SimTed::checkSaveChanges()
{
if( terrain && dataChanged )
{
int res = MessageBox( NULL, "save changes?", "close", MB_YESNO );
if( res == IDYES )
{
Console->evaluate( "Ted::save();", false );
}
dataChanged = false;
}
}
bool SimTed::save( const char * fileName )
{
bool success = false;
if( terrain )
{
getGridFile()->updateHeightRange();
success = terrain->save( fileName );
// save off the named selections
char selName[1024];
sprintf(selName, "temp\\%s.sel", getGridFile()->getFileName());
namedSelections.save( selName );
if( !success )
MessageBox( NULL, "Failed to save changes. File write protected?", "Warning!", MB_OK );
}
dataChanged = false;
return( success );
}
bool SimTed::attachToTerrain( const char * terrainName )
{
SimObject * obj;
SimTerrain * terr = 0;
SimManager * serverManager = SimGame::get()->getManager(SimGame::SERVER);
if( terrainName )
{
// locate the terrain
obj = serverManager->findObject( terrainName );
if( obj )
terr = dynamic_cast< SimTerrain * >( obj );
}
else
{
// find the first simterrain object
for( SimSetIterator i( serverManager ); *i; ++i )
if( ( terr = dynamic_cast< SimTerrain * >( * i ) ) != 0 )
break;
}
if( terr )
{
// check if attaching a new terain
if( terr != terrain )
{
deleteTerrain();
terrain = terr;
deleteNotify( terrain );
if( !getGridFile() )
return( false );
newLandscaper();
// load in the named selections associated with this grid file
// create the selection name ( just tack on a .sel )
char * selName = new char[ strlen( getGridFile()->getFileName() ) +
strlen( ".sel" ) + 1 ];
sprintf( selName, "%s.sel", getGridFile()->getFileName() );
// save off the named selections
namedSelections.load( selName );
delete [] selName;
loadMatList( getGridFile()->getMaterialListName() );
}
setVars();
currentSel.createMap( size.x << blockShift,
size.y << blockShift );
// set the max detail
pinDetailMax = getMaxBrushDetail() - 1;
// set the current filename
ResourceManager * resManager = SimResource::get( manager );
ResourceObject * obj = resManager ? resManager->find( getGridFile()->getFileName() ) : NULL;
if( !obj )
return( false );
CMDConsole::getLocked()->setVariable( "$TED::currFile", avar("%s\\%s", obj->filePath, obj->fileName ) );
return( true );
}
return( false );
}
// lock the material list
void SimTed::lockMatList()
{
TSMaterialList *mList = getGridFile()->getMaterialList();
if( mList && (! mList->isLocked() ) )
mList->lock( *SimResource::get( manager ), true );
}
void SimTed::deleteTerrain()
{
if( terrain )
{
clearNotify( terrain );
terrain->deleteObject();
terrain = NULL;
}
}
void SimTed::newLandscaper()
{
AssertFatal( terrain != 0, "Terrain cannot be null!" );
// remove current landscaper
if( landscaper )
{
clearNotify( landscaper );
landscaper->deleteObject( );
}
// create a new landscaper object
landscaper = new LSMapper;
manager->addObject( landscaper );
manager->assignName( landscaper, "LandScapeMapper" );
deleteNotify( landscaper );
landscaper->create( terrain );
}
bool SimTed::loadMatList( const char * matListName )
{
if ( !matListName )
return ( false );
const char *mname = extendName( matListName, ".dml" );
const char *gname = fixName( matListName, ".grid.dat" );
const char *rname = fixName( matListName, ".plr" );
// this function changes the material list name, which will
// free 'matListName' out from under us - must re-get material
// list name
landscaper->setTextures( mname, gname );
matListName = const_cast<char*>(getGridFile()->getMaterialListName());
// attemp to load the plr file, then attempt to load a dat file
if( !landscaper->setRules( rname ) )
{
// delete the string and recreate
delete [] const_cast<char *>( rname );
rname = fixName( matListName, ".rules.dat" );
// attempt load as a dat file
landscaper->setRules( rname );
}
getGridFile()->setMaterialListName( matListName );
delete [] const_cast<char*>( rname );
delete [] const_cast<char*>( gname );
delete [] const_cast<char*>( mname );
return( true );
}
// set the extension - requires that first char of extn is a '.'
// to work correctly
char * SimTed::extendName( const char * fname, const char * extn )
{
if( fname )
{
char * current = const_cast<char*>(fname) + strlen(fname);
while(current-- != fname)
if(*current == '.')
break;
int len = current - fname;
int extnLen = extn ? strlen(extn) : 0;
char * retStr = new char[ len + extnLen + 1 ];
memcpy(retStr,fname,len);
if(extn)
memcpy(retStr+len,extn,extnLen);
retStr[len+extnLen] = '\0';
return(retStr);
}
return (NULL);
}
// copys the extension onto the first part of a base name
// -- fixName( "mars.terrain.dml", "grid.dat" ) will return "mars.grid.dat"
char * SimTed::fixName( const char * fname, const char * extn )
{
if( fname )
{
// get a large enough buffer
int len = strlen( fname ) + 1;
if( extn )
len += strlen( extn );
char * retStr = new char[ len ];
strcpy( retStr, fname );
char * curr = retStr;
// get to a place to cut to
while( *curr && ( *curr != '.' ) )
curr++;
// add the extension or terminate the string
if( extn )
sprintf( curr, extn );
else
*curr = 0;
return( retStr );
}
return( NULL );
}
void SimTed::relight( bool hires )
{
// make sure terrain exists
if( terrain )
{
SimActionEvent *ev = new SimActionEvent;
ev->action = hires ? MoveDown : MoveUp;
manager->postCurrentEvent( terrain, ev );
}
}
// ------------------
// undo/redo stuff
// ------------------
bool SimTed::SelectionStack::load( const char * file )
{
FileRStream stream;
// clear the stack
clear();
// open the file
if( !stream.open( file ) )
return( false );
// read the size
int numSelections;
if( !stream.read( sizeof( int ), &numSelections ) )
return( false );
// go through the selections
for( int i = 0; i < numSelections; i++ )
{
// read the name len
int nameLen;
if( !stream.read( sizeof( int ), &nameLen ) )
return( false );
// allocate some space
char * name = new char[ nameLen + 1 ];
if( !name )
return( false );
memset( name, 0, nameLen + 1 );
// read the name
if( !stream.read( nameLen, name ) )
{
delete [] name;
return( false );
}
// create a selection
SimTed::Selection * sel = new SimTed::Selection;
if( !sel )
{
delete [] name;
return( false );
}
// assign the name and delete our allocated one
sel->name = name;
delete [] name;
// read in the number of poins
int numPoints;
if( !stream.read( sizeof( int ), &numPoints ) )
{
delete sel;
return( false );
}
// read in all the points
for( int j = 0; j < numPoints; j++ )
{
Point2I pos;
if( !stream.read( sizeof( Point2I ), &pos ) )
{
delete sel;
return( false );
}
// add to the selection
sel->addPoint( pos );
}
// add the selection to the stack
push( sel );
}
return( true );
}
void SimTed::SelectionStack::clear()
{
SimTed::Selection * sel;
while( 1 )
{
// grab the first selection and delete it
sel = pop();
if( !sel )
return;
delete sel;
}
}
bool SimTed::SelectionStack::save( const char * file )
{
FileWStream stream;
// open the file
if( !stream.open( file ) )
return( false );
// write out the size
int numSelections = getSize();
if( !stream.write( sizeof( int ), &numSelections ) )
return( false );
// go through the selections
for( int i = 0; i < numSelections; i++ )
{
// get the length of the name of this selection
int nameLen = strlen( selections[i]->name.c_str() );
if( !stream.write( sizeof( int ), &nameLen ) )
return( false );
// write out the name
if( !stream.write( nameLen, selections[i]->name.c_str() ) )
return( false );
// get the number of points and write out
int numPoints = selections[i]->points.getSize();
if( !stream.write( sizeof( int ), &numPoints ) )
return( false );
// go through the points
for( int j = 0; j < numPoints; j++ )
{
if( !stream.write( sizeof( Point2I ), &selections[i]->points[j].pos ) )
return( false );
}
}
return( true );
}
void SimTed::SelectionStack::setLimit( int num )
{
if( num > 0 )
{
// remove some if needed
while( selections.size() > num )
{
delete selections[ 0 ];
selections.erase( 0 );
}
limit = num;
}
}
SimTed::Selection * SimTed::SelectionStack::pop()
{
// make sure has some stuff in it
if( selections.size() )
{
SimTed::Selection * sel = selections[ selections.size() - 1 ];
selections.pop_back();
return( sel );
}
return( NULL );
}
void SimTed::SelectionStack::push( SimTed::Selection * sel )
{
// add to the stack
selections.push_back( sel );
if( selections.size() >= limit )
{
delete selections[ 0 ];
selections.erase( 0 );
}
}
SimTed::SelectionStack::SelectionStack() :
limit( 100 )
{
}
SimTed::SelectionStack::~SelectionStack()
{
for( int i = 0; i < selections.size(); i++ )
delete selections[i];
}
void SimTed::undo()
{
SimTed::Selection * selection;
// get the selection
selection = undoStack.pop();
if( !selection )
return;
// add to the redo stack
SimTed::Selection * redoSel = new SimTed::Selection;
// go throught the selection and set each of the info's
for( unsigned int i = 0; i < selection->points.getSize(); i++ )
{
// add to the redo
SimTed::Selection::Info info;
if( getInfo( selection->points[i].pos, info ) )
redoSel->addPoint( info );
setInfo( selection->points[i] );
}
// copy the pin info
redoSel->pinArray = selection->pinArray;
// set the flags
redoSel->undoFlags = selection->undoFlags;
processUndo( *selection, true );
delete selection;
// put into the redo stack
redoStack.push( redoSel );
}
void SimTed::redo()
{
SimTed::Selection * selection;
// get the selection
selection = redoStack.pop();
if( !selection )
return;
// add a undo selection
SimTed::Selection * undoSel = new SimTed::Selection;
// go throught the selection and set each of the info's
for( unsigned int i = 0; i < selection->points.getSize(); i++ )
{
// add to the undo
SimTed::Selection::Info info;
if( getInfo( selection->points[i].pos, info ) )
undoSel->addPoint( info );
setInfo( selection->points[i] );
}
// copy the pin info
undoSel->pinArray = selection->pinArray;
// set the flags
undoSel->undoFlags = selection->undoFlags;
processUndo( *selection, false );
delete selection;
// add to the undo stack
undoStack.push( undoSel );
}
// usually does not need to know if this is an undo or a redo operation
void SimTed::processUndo( Selection & sel, bool undo )
{
// look at the flags
if( sel.undoFlags & Selection::relight )
relight(false);
if( ( sel.undoFlags & Selection::landscape ) && landscaper )
landscaper->applyTextures();
if( sel.undoFlags & Selection::flushTextures )
flushTextures();
// go through and un/pin all the pieces
if( ( sel.undoFlags & Selection::pin ) || ( sel.undoFlags & Selection::unpin ) )
{
for( int i = 0; i < sel.pinArray.size(); i++ )
{
Selection::pinInfo info = sel.pinArray[i];
// undo resets back to last value, redo just sets the flag according to the action
if( undo )
info.gridBlock->pinSquare( info.detail, info.pos, info.detail, info.val, NULL );
else
info.gridBlock->pinSquare( info.detail, info.pos, info.detail,
( sel.undoFlags & Selection::pin ) ? true : false, NULL );
}
}
}
// ---------------------------------------------------------
// selection stuff
// ---------------------------------------------------------
bool SimTed::loadSel( const char * name )
{
Selection sel;
// load the selection
if( !sel.load( name ) )
return( false );
// float it
floatSelection( sel );
floatPasteVal = pasteVal;
return( true );
}
bool SimTed::saveCurrentSel( const char * name )
{
Selection sel;
// check if there are points
if( !currentSel.points.getSize() )
return( false );
Point2I offset = currentSel.points[0].pos;
// go though all of the selection
for( unsigned int i = 0; i < currentSel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
if( getInfo( currentSel.points[i].pos, info ) )
{
// adjust the point
info.pos.x -= offset.x;
info.pos.y -= offset.y;
// add to the copy selection
sel.addPoint( info );
}
}
// save it off
return( sel.save( name ) );
}
SimTed::Selection::Selection() :
name( "" ),
undoFlags( 0 ),
mapped( false ),
map( NULL ),
mapWidth( 0 ),
mapHeight( 0 ),
mapSize( 0 )
{
points.setSize( 0, 256 );
}
SimTed::Selection::~Selection()
{
// delete the map if it exists
if( mapped )
deleteMap();
}
void SimTed::Selection::createMap( int width, int height )
{
if( mapped )
deleteMap();
// get the width/height
mapWidth = width;
mapHeight = height;
mapSize = ( width * height );
// allocate the space
map = new int[ mapSize ];
AssertFatal( map, "Failed to allocate memory for selection map." );
// set the flag
mapped = true;
// reset the map
clearMap();
fillMap();
}
void SimTed::Selection::deleteMap()
{
if( map )
{
delete [] map;
map = NULL;
}
mapped = false;
}
void SimTed::Selection::clearMap()
{
if( !mapped || !map )
return;
// just go through
for( int i = 0; i < mapSize; i++ )
map[i] = -1;
}
void SimTed::Selection::fillMap()
{
if( !mapped || !map )
return;
// set the map location
for( unsigned int i = 0; i < points.getSize(); i++ )
{
// set the index
map[ points[i].pos.x +
( points[i].pos.y * mapWidth ) ] = i;
}
}
void SimTed::Selection::addPoint( const Info & info )
{
// check if mapped or not
if( mapped )
{
int index = info.pos.x + ( info.pos.y * mapWidth );
if( map[index] >= 0 )
return;
// set the index
map[index] = ( int )points.getSize();
// add the point
points.add( info );
}
else
{
if( !pointInSel( info.pos ) )
points.add( info );
}
}
void SimTed::Selection::addPoint( const Point2I & pnt )
{
// check if mapped or not
if( mapped )
{
int index = pnt.x + ( pnt.y * mapWidth );
if( map[index] >= 0 )
return;
map[index] = ( int )points.getSize();
Info info;
info.pos = pnt;
points.add( info );
}
else
{
if( !pointInSel( pnt ) )
{
Info info;
info.pos = pnt;
points.add( info );
}
}
}
void SimTed::Selection::removePoint( const Point2I & pnt )
{
// a tad tricky if mapped - is EXTREMELY tied to
// the infoarray class
if( mapped )
{
unsigned int index = pnt.x + ( pnt.y * mapWidth );
// check if exists
if( map[index] < 0 )
return;
// check if not the last element, and then move the
// index's
if( map[index] < ( int )( points.getSize() - 1 ) )
{
Point2I pos = points[ points.getSize() - 1 ].pos;
int lastIndex = pos.x + ( pos.y * mapWidth );
map[lastIndex] = ( int )map[index];
// remove it
points.remove( map[index] );
// clear this position
map[index] = -1;
}
else
{
// remove the last pnt
points.remove( map[index] );
map[index] = -1;
}
}
else
{
for( unsigned int i = 0; i < points.getSize(); i++ )
{
if( points[i].pos == pnt )
{
points.remove( i );
return;
}
}
}
}
void SimTed::fillInfo( Selection & sel )
{
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Selection::Info info;
getInfo( sel.points[i].pos, info );
sel.points[i] = info;
}
}
void SimTed::Selection::clear()
{
if( mapped )
clearMap();
points.clear();
}
bool SimTed::Selection::save( const char * file )
{
FileWStream stream;
// open the file
if( !stream.open( file ) )
return( false );
int numPoints = ( int )points.getSize();
// write the number of points
if( !stream.write( sizeof( int ), &numPoints ) )
return( false );
// go through and write the info out
for( unsigned int i = 0; i < points.getSize(); i++ )
{
if( !stream.write( sizeof( Selection::Info ), &points[i] ) )
return( false );
}
return( true );
}
bool SimTed::Selection::load( const char * file )
{
FileRStream stream;
// clear out the file
clear();
// open the file
if( !stream.open( file ) )
return( false );
int numPoints;
// read the number of points
if( !stream.read( sizeof( int ), &numPoints ) )
return( false );
// go through the points
for( int i = 0; i < numPoints; i++ )
{
Info info;
if( !stream.read( sizeof( Selection::Info ), &info ) )
return( false );
addPoint( info );
}
return( true );
}
bool SimTed::Selection::pointInSel( const Point2I & pnt )
{
// if( ( pnt.x == -1 ) || ( pnt.y == -1 ) )
// return( false );
// check if mapped or not
if( mapped )
{
int index = pnt.x + ( pnt.y * mapWidth );
if( map[index] >= 0 )
return( true );
}
else
{
for( unsigned int i = 0; i < points.getSize(); i++ )
if( points[i].pos == pnt )
return( true );
}
return( false );
}
bool SimTed::setInfo( const SimTed::Selection::Info & info )
{
// set the stuff
if( !setHeight( info.pos, info.height.height ) )
return( false );
if( !setMaterial( info.pos, info.material ) )
return( false );
return( true );
}
bool SimTed::getInfo( const Point2I& pos, SimTed::Selection::Info & info )
{
GridBlock::Material * mat = getMaterial( pos );
GridBlock::Height height;
height.height = getHeight( pos );
// check if got the material information
if( mat )
{
// set the info
info.pos = pos;
info.height = height;
info.material = *mat;
return( true );
}
return( false );
}
void SimTed::setSelectionVars( SimTed::Selection & sel, RectI & bound,
Point2F & center, float & radius )
{
// reset the info
bound = NULLRECT;
center.x = center.y = -1;
radius = 0.0;
// make sure there exist some points
if( !sel.points.getSize() )
return;
int left, right, top, bottom;
// set the initial val
left = right = sel.points[0].pos.x;
top = bottom = sel.points[0].pos.y;
// go through all the points
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I p = sel.points[i].pos;
// set the bounds
if( p.x < left )
left = p.x;
else if( p.x > right )
right = p.x;
if( p.y < top )
top = p.y;
else if( p.y > bottom )
bottom = p.y;
}
// set the bound dimensions
bound.upperL = Point2I( left, top );
bound.lowerR = Point2I( right, bottom );
// setup the center pnt
center.x = ( float )( left + right ) / 2.0;
center.y = ( float )( top + bottom ) / 2.0;
// get the radius
float rx = float( right - left ) / 2.0;
float ry = float( bottom - top ) / 2.0;
radius = sqrt( ( rx * rx ) + ( ry * ry ) );
}
const char * SimTed::getNamedSelection( int index )
{
// check for invalid
if( index >= getNumNamedSelections() )
return( NULL );
// get it
return( namedSelections.selections[index]->name.c_str() );
}
bool SimTed::addNamedSelection( const char * name )
{
// check the name
if( !name )
return( false );
// grow in needed
if( namedSelections.getSize() >= namedSelections.getLimit() )
namedSelections.setLimit( namedSelections.getLimit() + 1 );
SimTed::Selection * selection;
selection = new SimTed::Selection;
// set the name
selection->name = name;
// go through and add all of the currently selected points to this
for( unsigned int i = 0; i < currentSel.points.getSize(); i++ )
selection->points.add( currentSel.points[i] );
// add to the stack
namedSelections.push( selection );
return( true );
}
bool SimTed::removeNamedSelection( const char * name )
{
if( !name )
return( false );
Selection * sel;
// go through all the selections and find this one..
// if cannot just return with no error
for( int i = 0; i < namedSelections.getSize(); i++ )
{
sel = namedSelections.selections[i];
// is this the $$$?
if( sel->name == name )
{
// remove this one
delete namedSelections.selections[ i ];
namedSelections.selections.erase( i );
return( true );
}
}
return( true );
}
bool SimTed::selectNamedSelection( const char * name )
{
if( !name )
return( false );
Selection * sel;
// go through all the selections and find this one..
// if cannot just return with no error
for( int i = 0; i < namedSelections.getSize(); i++ )
{
sel = namedSelections.selections[i];
// is this the $$$?
if( sel->name == name )
{
// clear the current selection
currentSel.clear();
// select all the ones in this named selection to the current
for( unsigned int j = 0; j < sel->points.getSize(); j++ )
currentSel.addPoint( sel->points[j] );
return( true );
}
}
return( true );
}
void SimTed::Selection::InfoArray::setSize( unsigned int size, unsigned int grow )
{
growSize = grow;
if( !arraySize || ( size >= arraySize ) )
{
arraySize = size + growSize;
Info * newElements = new Info[ arraySize ];
// copy the elements
for( unsigned int i = 0; i < numElements; i++ )
newElements[i] = elements[i];
delete [] elements;
elements = newElements;
}
numElements = size;
}
void SimTed::Selection::InfoArray::remove( unsigned int index )
{
if( index < numElements )
{
numElements--;
// check for removal of last item
if( index < numElements )
elements[ index ] = elements[ numElements ];
}
}
void SimTed::Selection::InfoArray::add( Info item )
{
// adjust the size
setSize( numElements + 1, growSize );
// add to the last item
elements[ numElements - 1 ] = item;
}
| [
"[email protected]"
] | |
0f68ea9a3e981e9ccb92fd6ad1621e8524565319 | 4eb6f8b2705289308005487fc5376a50b0a4b562 | /interactiveLettersMidterm_final/src/ParticleSystemTop.hpp | 8d8ff5e3a8513c50a2cfac34db70e7c40c060a2d | [] | no_license | Nedelstein/edeln591_dtOF_2018 | 53d8190b2719c5179e38d0aa08614312278d3936 | e836915653bde5798b81c7a36ea21559477d325f | refs/heads/master | 2021-07-06T22:51:24.771923 | 2019-04-22T23:24:11 | 2019-04-22T23:24:11 | 146,637,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | hpp | #pragma once
#include "ofMain.h"
#include "Particle.hpp"
#include "Letters.hpp"
class ParticleSystemTop{
public:
ParticleSystemTop();
// ParticleSystemTop(glm::vec2 _pos);
void setup();
void update();
void attract(glm::vec2 toPos, float strength);
void applyDistanceDamping(glm::vec2 toPos, float minDist, float maxDist, float minDamp, float maxDamp);
void applyForce(glm::vec2 force);
void draw();
void applyElasticForce(float strength);
void applyDampingForce(float strength);
void init();
glm::vec2 pos;
glm::vec2 center = glm::vec2(ofGetWidth()/2, ofGetHeight()/2);
vector<Particle> particles;
int numParticles = 300;
Letters letter;
bool oForce;
bool collision;
};
| [
"[email protected]"
] | |
a6cd60569613115d6bd2d50799dc8bb027e93ab1 | 3fabd73eb8974c540fe310668b7fddfbdf70d740 | /src/qt/bitcoin.cpp | 7a15e94c3c7de75d56a2454ad7f7a02a83ad6095 | [
"MIT"
] | permissive | litecoinscrypt/litecoinscrypt | 55ad4ea0e83e364ad30d87e76121993d263c86fb | ee73b432b6e2aa93de602df016ed1f37d472e472 | refs/heads/master | 2020-05-03T01:36:18.815315 | 2014-04-02T04:11:06 | 2014-04-02T04:11:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,022 | cpp | /*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/algorithm/string/predicate.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. LiteCoinScrypt can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "litecoinscrypt:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if (mq.try_send(strURI, strlen(strURI), 0))
// if URI could be sent to the message queue exit here
exit(0);
else
// if URI could not be sent to the message queue do a normal Bitcoin-Qt startup
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
// don't log the "file not found" exception, because that's normal for
// the first start of the first instance
if (ex.get_error_code() != boost::interprocess::not_found_error)
{
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("LiteCoinScrypt");
app.setOrganizationDomain("we-have-no-domain-yet.nex");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("litecoinscrypt-qt-testnet");
else
app.setApplicationName("litecoinscrypt-qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "litecoinscrypt:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
#endif
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
| [
"root@ltcs.(none)"
] | root@ltcs.(none) |
337d156f1b7dbbd47e2019e54752d52ef28218a0 | 2fec3c84e6b2fa675857e00cc6dc0aaacc8dc969 | /ObjectARX 2016/samples/database/ARXDBG/Inc/ArxDbgSelSet.h | b1ab43e2afacc34786c00f43ce1ef296243fa536 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | presscad/AutoCADPlugin-HeatSource | 7feb3c26b31814e0899bd10ff39a2e7c72bc764d | ab0865402b41fe45d3b509c01c6f114d128522a8 | refs/heads/master | 2020-08-27T04:22:23.237379 | 2016-06-24T07:30:15 | 2016-06-24T07:30:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,536 | h | //
//////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
//
#ifndef ARXDBGSELSET_H
#define ARXDBGSELSET_H
/****************************************************************************
**
** CLASS ArxDbgSelSet:
** Thin wrapper around an AutoCAD selection set.
** The constructor creates a "NULL" set. If you want to
** actually create an AutoCAD selection set, you must use one
** of the selection mechanisms, or explicitly call createEmptySet().
**
** **jma
**
****************************/
class ArxDbgSelSet {
public:
enum SelSetStatus {
kSelected,
kNone,
kCanceled,
kRejected,
};
ArxDbgSelSet();
virtual ~ArxDbgSelSet();
// selection mechanisms
SelSetStatus createEmptySet();
SelSetStatus userSelect(const resbuf* filter = NULL);
SelSetStatus userSelect(LPCTSTR selectPrompt, LPCTSTR removePrompt, const resbuf* filter = NULL);
SelSetStatus impliedSelect(const resbuf* filter = NULL);
SelSetStatus crossingSelect(const AcGePoint3d& pt1, const AcGePoint3d& pt2, const resbuf* filter = NULL);
SelSetStatus crossingPolygonSelect(const AcGePoint3dArray& ptArray, const resbuf* filter = NULL);
SelSetStatus fenceSelect(const AcGePoint3dArray& ptArray, const resbuf* filter = NULL);
SelSetStatus lastSelect(const resbuf* filter = NULL);
SelSetStatus pointSelect(const AcGePoint3d& pt1, const resbuf* filter = NULL);
SelSetStatus previousSelect(const resbuf* filter = NULL);
SelSetStatus windowSelect(const AcGePoint3d& pt1, const AcGePoint3d& pt2, const resbuf* filter = NULL);
SelSetStatus windowPolygonSelect(const AcGePoint3dArray& ptArray, const resbuf* filter = NULL);
SelSetStatus filterOnlySelect(const resbuf* filter = NULL);
SelSetStatus allSelect(const resbuf* filter = NULL);
SelSetStatus boxSelect(const AcGePoint3d& pt1, const AcGePoint3d& pt2, const resbuf* filter = NULL);
// inquiry
SelSetStatus lastStatus() const;
// options
void setFilterLockedLayers(bool filterThem);
void setAllowDuplicates(bool dups);
void setAllAtPickBox(bool pickBox);
void setAllowSingleOnly(bool single, bool allowLast);
void setRejectNonCurrentSpace(bool rejectIt);
void setRejectPaperSpaceViewport(bool rejectId);
void setKeywordCallback(LPCTSTR extraKwords, struct resbuf* (*pFunc) (const TCHAR*));
void setOtherCallback(struct resbuf* (*pFunc) (const TCHAR*));
// operations on the selection set (backward compatibility with ADS)
long length();
void add(ads_name ent);
void add(const AcDbObjectId& objId);
void remove(ads_name ent);
void remove(const AcDbObjectId& objId);
bool member(ads_name ent);
bool member(const AcDbObjectId& objId);
bool subEntMarkerAt(long index, AcDbObjectId& objId, int& gsMarker);
// conversion to AcDbObjectIdArray, ads_name
void asArray(AcDbObjectIdArray& objIds);
void asAdsName(ads_name ss);
private:
// data members
ads_name m_ss;
SelSetStatus m_lastStatus;
bool m_allowDuplicates;
bool m_allAtPickBox;
bool m_singleOnly;
bool m_allowLast;
bool m_filterLockedLayers;
bool m_rejectNonCurrentSpace;
bool m_rejectPaperSpaceViewport;
CString m_flags;
CString m_extraKwords;
struct resbuf* (*m_kwordFuncPtr)(const TCHAR*);
struct resbuf* (*m_otherFuncPtr)(const TCHAR*);
// helper functions
bool isInitialized() const; // has the set been allocated by AutoCAD?
void clear(); // free up ss and reinitialize
SelSetStatus handleResult(int result); // common ads_ssget() return action
void setFlags(bool hasPrompts);
// outlawed functions (move these up when implemented)
ArxDbgSelSet(const ArxDbgSelSet&);
ArxDbgSelSet& operator=(const ArxDbgSelSet&);
};
#endif // ARXDBGSELSET_H
| [
"[email protected]"
] | |
4069c4a5cfff6e0b57e28fcdb03a10813fc822b6 | 73a457af0da833c743601866d046ab2d5956f603 | /src/fm/scene/graphics/OverlayRenderer.cpp | 5d6462d34aa617f5ce57f1c2c2c834f1a09f0555 | [] | no_license | Zylann/SnowfeetFramework | 41b30ac5fb9ce6847210ee7ed7f1da35f35d2cce | 4dc36d0cec0144088dfd457b26dc4f6db3d761b6 | refs/heads/master | 2020-09-22T11:41:55.080212 | 2014-11-03T12:37:10 | 2014-11-03T12:37:10 | 13,676,066 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,236 | cpp | #include <fm/scene/graphics/OverlayRenderer.hpp>
#include <fm/asset/AssetBank.hpp>
#include <fm/scene/core/Scene.hpp>
namespace zn
{
ZN_OBJECT_IMPL(zn::OverlayRenderer)
//------------------------------------------------------------------------------
OverlayRenderer::OverlayRenderer() : Renderer(),
r_texture(nullptr),
m_color(255,255,255)
{
}
//------------------------------------------------------------------------------
void OverlayRenderer::setTexture(const sf::Texture* texture)
{
r_texture = texture;
}
//------------------------------------------------------------------------------
void OverlayRenderer::setColor(sf::Color color)
{
m_color = color;
}
//------------------------------------------------------------------------------
sf::FloatRect OverlayRenderer::localBounds() const
{
return sf::FloatRect(-99999, -99999, 199999, 199999);
}
//------------------------------------------------------------------------------
void OverlayRenderer::serializeData(JsonBox::Value& o)
{
Renderer::serializeData(o);
zn::serialize(o["color"], m_color);
if(r_texture != nullptr)
{
std::string textureName = AssetBank::current()->textures.findName(r_texture);
o["texture"] = textureName;
}
else
{
o["texture"].setNull();
}
}
//------------------------------------------------------------------------------
void OverlayRenderer::unserializeData(JsonBox::Value& o)
{
Renderer::unserialize(o);
zn::unserialize(o["color"], m_color);
std::string textureName = o["texture"].getString();
if(textureName.empty())
{
log.err() << "OverlayRenderer::unserialize: texture name is empty" << log.endl();
}
else
{
const sf::Texture * texture = AssetBank::current()->textures.get(textureName);
if(texture != nullptr)
{
setTexture(texture);
}
else
{
log.err() << "OverlayRenderer::unserializeData: "
"texture not found \"" << textureName << '"' << log.endl();
}
}
}
//------------------------------------------------------------------------------
void OverlayRenderer::postUnserialize()
{
}
//------------------------------------------------------------------------------
void OverlayRenderer::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform = sf::Transform::Identity;
states.texture = r_texture;
//states.transform.combine(entity().transform.matrix());
const sf::View & view = entity().scene().renderSystem.activeCamera()->internalView();
sf::FloatRect viewBounds(view.getCenter()-view.getSize()*0.5f, view.getSize());
sf::Vector2u ts = r_texture->getSize();
sf::VertexArray mesh;
mesh.setPrimitiveType(sf::PrimitiveType::Quads);
mesh.resize(4);
mesh[0] = sf::Vertex(sf::Vector2f(viewBounds.left, viewBounds.top), m_color, sf::Vector2f(0, 0));
mesh[1] = sf::Vertex(sf::Vector2f(viewBounds.left+viewBounds.width, viewBounds.top), m_color, sf::Vector2f(ts.x, 0));
mesh[2] = sf::Vertex(sf::Vector2f(viewBounds.left+viewBounds.width, viewBounds.top+viewBounds.height), m_color, sf::Vector2f(ts.x, ts.y));
mesh[3] = sf::Vertex(sf::Vector2f(viewBounds.left, viewBounds.top+viewBounds.height), m_color, sf::Vector2f(0, ts.y));
target.draw(mesh, states);
//target.draw(sf::RectangleShape(sf::Vector2f(10,10)), states);
}
} // namespace zn
| [
"[email protected]"
] | |
40845feb01ce46fd7cd9e2ad14086734a3dcf02d | 2ca688cb5d4b9befa21d3e1282c33b5445cc0618 | /LabTradingGame/cTileMap.h | ac8264f9d3e60cf700814b575504136dfab05737 | [] | no_license | Tendoi/Trading_Game_Coursework | 67f5b3427cf2808ec286ef06da58e4748177cd57 | fde238aa96d9d295e84d4eb530850920facd3818 | refs/heads/master | 2020-06-11T00:58:57.683994 | 2016-12-07T11:35:15 | 2016-12-07T11:35:15 | 75,827,830 | 0 | 0 | null | 2016-12-07T11:38:02 | 2016-12-07T11:04:22 | C++ | UTF-8 | C++ | false | false | 1,086 | h | /*
=================
cTileMap.h
- Header file for class definition - SPECIFICATION
- Header file for the tileMap class which is a child of cSprite class
=================
*/
#ifndef _CTILEMAP_H
#define _CTILEMAP_H
#include "MazeMakerEditor.h"
#include <sstream>
class cTileMap: public cSprite
{
protected:
int tileMap[12][16];
private:
SDL_Point mapStartXY;
SDL_Point tileClickedRC;
cSprite aTile;
void initialiseMap(); // Set the initial values for the map
public:
cTileMap();
cTileMap(cFileHandler* aFile);
void initialiseMapFromFile(cFileHandler* aFile); // Set the initial values for the map from file input
void render(SDL_Window* theSDLWND, SDL_Renderer* theRenderer, cTextureMgr* theTxtMgr, vector<LPCSTR> theTxt); // Default render function
void renderGridLines(SDL_Renderer* theRenderer, SDL_Rect theRect, SDL_Color theColour); // Draw grid lines
void update(SDL_Point theMapAreaClicked, int theTileToPlace);
void setMapStartXY(SDL_Point startPosXY);
SDL_Point getMapStartXY();
string getMapData();
void writeMapDataToFile(cFileHandler* aFile);
};
#endif | [
"[email protected]"
] | |
e81ecd91325768afb391fa2f27565e1893d94b10 | bb34fff90c9e688155c3d530966b06f5a52f04c9 | /qcril-data-hal/datamodule/module/src/DataModule.cpp | 14b6518952b80fea101e86c2afb74a8c1d6d19c2 | [] | no_license | pkm774/vendor_qcom_proprietary | 27f90ae736c031497a9a26d7ebb4cf0dde62063b | 00578532a2e2e308ebcf26cf3b7c0c89b4f4cf02 | refs/heads/master | 2022-04-15T13:11:12.061157 | 2020-04-09T04:03:54 | 2020-04-09T04:03:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127,900 | cpp | /**
* Copyright (c) 2017-2020 Qualcomm Technologies, Inc.
* All Rights Reserved.
* Confidential and Proprietary - Qualcomm Technologies, Inc.
**/
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <cutils/properties.h>
#include "dlfcn.h"
#include "qmi_client.h"
#include "wireless_data_service_v01.h"
/* Framework includes */
#include "framework/Dispatcher.h"
#include "framework/Looper.h"
#include "framework/ModuleLooper.h"
#include "framework/QcrilInitMessage.h"
#include "framework/TimeKeeper.h"
#include "modules/android/ril_message_factory.h"
#include "modules/qmi/QmiIndMessage.h"
#include "modules/qmi/EndpointStatusIndMessage.h"
#include "modules/qmi/ModemEndPointFactory.h"
#include "modules/qmi/QmiSetupRequestCallback.h"
#include "qtibus/Messenger.h"
#include "data_system_determination_v01.h"
/* Module includes */
#include "local/DataModule.h"
#include "UnSolMessages/DataInitMessage.h"
#include "request/RilRequestSetupDataCallMessage.h"
#include "request/RilRequestDataCallListMessage.h"
#include "request/RilRequestGetDataCallProfileMessage.h"
#include "request/RilRequestDeactivateDataCallMessage.h"
#include "request/RilRequestEmbmsActivateDeactivateTmgiMessage.h"
#include "request/RilRequestEmbmsActivateTmgiMessage.h"
#include "request/RilRequestEmbmsContentDescUpdateMessage.h"
#include "request/RilRequestEmbmsDeactivateTmgiMessage.h"
#include "request/EmbmsEnableDataReqMessage.h"
#include "request/RilRequestEmbmsGetActiveTmgiMessage.h"
#include "request/RilRequestEmbmsGetAvailTmgiMessage.h"
#include "request/RilRequestEmbmsSendIntTmgiListMessage.h"
#include "request/RilRequestGoDormantMessage.h"
#include "request/RilRequestLastDataCallFailCauseMessage.h"
#include "request/ProcessScreenStateChangeMessage.h"
#include "request/ProcessStackSwitchMessage.h"
#include "request/RilRequestPullLceDataMessage.h"
#include "request/SetApnInfoMessage.h"
#include "request/RilRequestSetDataProfileMessage.h"
#include "request/SetIsDataEnabledMessage.h"
#include "request/SetIsDataRoamingEnabledMessage.h"
#include "request/SetLteAttachProfileMessage.h"
#include "request/SetQualityMeasurementMessage.h"
#include "request/RilRequestStartLceMessage.h"
#include "request/RilRequestStopLceMessage.h"
#include "request/ToggleDormancyIndMessage.h"
#include "request/ToggleLimitedSysIndMessage.h"
#include "request/UpdateMtuMessage.h"
#include "request/GetDdsSubIdMessage.h"
#include "request/RequestDdsSwitchMessage.h"
#include "request/RilRequestStartKeepaliveMessage.h"
#include "request/RilRequestStopKeepaliveMessage.h"
#include "request/RilRequestSetCarrierInfoImsiEncryptionMessage.h"
#include "request/SetLinkCapRptCriteriaMessage.h"
#include "request/SetLinkCapFilterMessage.h"
#include "request/SetInitialAttachApnRequestMessage.h"
#include "request/RegisterBearerAllocationUpdateRequestMessage.h"
#include "request/GetBearerAllocationRequestMessage.h"
#include "request/GetAllBearerAllocationsRequestMessage.h"
#include "request/IWLANCapabilityHandshake.h"
#include "request/GetAllQualifiedNetworkRequestMessage.h"
#include "UnSolMessages/IntentToChangeApnPreferredSystemMessage.h"
#include "request/SetupDataCallRequestMessage.h"
#include "request/DeactivateDataCallRequestMessage.h"
#include "request/GetRadioDataCallListRequestMessage.h"
#include "request/GetIWlanDataCallListRequestMessage.h"
#include "request/GetIWlanDataRegistrationStateRequestMessage.h"
#include "request/StartKeepAliveRequestMessage.h"
#include "request/StopKeepAliveRequestMessage.h"
#include "request/SetCarrierInfoImsiEncryptionMessage.h"
#include "event/RilEventDataCallback.h"
#include "request/SetDataProfileRequestMessage.h"
#include "request/SetPreferredDataModemRequestMessage.h"
#include "event/DataGetMccMncCallback.h"
#include "sync/RilDataEmbmsActiveMessage.h"
#include "UnSolMessages/SetRadioClientCapUnSolMessage.h"
#include "UnSolMessages/SetLteAttachPdnListActionResultMessage.h"
#include "UnSolMessages/SetApnPreferredSystemResultMessage.h"
#include "UnSolMessages/DataAllBearerTypeChangedMessage.h"
#include "UnSolMessages/DataBearerTypeChangedMessage.h"
#include "UnSolMessages/DsdSystemStatusPerApnMessage.h"
#include "UnSolMessages/CallStatusMessage.h"
#include "UnSolMessages/CurrentDDSIndMessage.h"
#include "UnSolMessages/DDSSwitchResultIndMessage.h"
#include "UnSolMessages/DDSSwitchIPCMessage.h"
#include "UnSolMessages/DDSSwitchTimeoutMessage.h"
#include "UnSolMessages/RadioConfigClientConnectedMessage.h"
#include "UnSolMessages/HandoverInformationIndMessage.h"
#include "UnSolMessages/DataCallTimerExpiredMessage.h"
#include "UnSolMessages/VoiceIndMessage.h"
#include "UnSolMessages/NewDDSInfoMessage.h"
#include "UnSolMessages/KeepAliveIndMessage.h"
#include "UnSolMessages/CleanDataCallStateMessage.h"
#include "UnSolMessages/VoiceCallOrigTimeoutMessage.h"
#include "event/CallBringupFallbackMessage.h"
#include "UnSolMessages/DeregisterWdsIndCompletedMessage.h"
#include "legacy/qcril_data_qmi_wds.h"
#include "legacy/qcril_data.h"
#include "AuthModemEndPoint.h"
#include "WDSModemEndPoint.h"
#include "DSDModemEndPoint.h"
#include "VoiceCallModemEndPoint.h"
#include "ProfileHandler.h"
#include "NetworkServiceHandler.h"
#include "qcril_reqlist.h"
#include "telephony/ril.h"
#include "modules/nas/NasSrvDomainPrefIndMessage.h"
#include "modules/nas/NasRequestDataShutdownMessage.h"
#include "modules/nas/NasPhysChanConfigMessage.h"
#ifndef QCRIL_RIL_VERSION
#error "undefined QCRIL_RIL_VERSION!"
#endif
#define INVALID_MSG_TOKEN -1
#define PROPERTY_MAX_PARTIAL_RETRY_TIMEOUT "persist.vendor.radio.max_retry_timeout"
#define PROPERTY_DISABLE_PARTIAL_RETRY "persist.vendor.radio.disable_retry"
#define PROPERTY_DISABLE_PARTIAL_RETRY_DEFAULT "false"
extern pthread_mutex_t ddsSubMutex;
#include "modules/uim/UimCardAppStatusIndMsg.h"
#include "modules/uim/UimGetMccMncRequestMsg.h"
#include "modules/uim/UimGetCardStatusRequestSyncMsg.h"
#define MCC_LENGTH 4
#define MNC_LENGTH 4
static load_module<rildata::DataModule> dataModule;
ProfileHandler::RilRespParams ProfileHandler::m_resp_params={ QCRIL_DEFAULT_INSTANCE_ID, QCRIL_DEFAULT_MODEM_ID, 0,0};
extern DDSSubIdInfo currentDDSSUB;
namespace rildata {
DataModule& getDataModule() {
return dataModule.get_module();
}
bool clearTimeoutForMessage( std::shared_ptr<Message> msg );
DataModule::DataModule() : mMessageList("DataModule") {
mName = "DataModule";
mLooper = std::unique_ptr<ModuleLooper>(new ModuleLooper);
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
wds_endpoint = ModemEndPointFactory<WDSModemEndPoint>::getInstance().buildEndPoint();
dsd_endpoint = ModemEndPointFactory<DSDModemEndPoint>::getInstance().buildEndPoint();
auth_endpoint = ModemEndPointFactory<AuthModemEndPoint>::getInstance().buildEndPoint();
#ifdef FEATURE_DATA_LQE
ott_endpoint = ModemEndPointFactory<OTTModemEndPoint>::getInstance().buildEndPoint();
#endif /* FEATURE_DATA_LQE */
preferred_data_sm = std::make_unique<PreferredDataStateMachine>();
preferred_data_state_info = std::make_shared<PreferredDataInfo_t>();
if(preferred_data_state_info != nullptr)
{
preferred_data_state_info->isRilIpcNotifier = false;
}
else
{
Log::getInstance().d("[DataModule]: preferred_data_state_info is NULL");
}
preferred_data_state_info->mVoiceCallInfo.voiceSubId = SubId::UNSPECIFIED;
preferred_data_sm->initialize(preferred_data_state_info);
preferred_data_sm->setCurrentState(Initial);
voiceCallEndPointSub0 = nullptr;
voiceCallEndPointSub1 = nullptr;
auth_manager = nullptr;
call_manager = nullptr;
profile_handler = nullptr;
networkavailability_handler = nullptr;
network_service_handler = nullptr;
keep_alive = std::make_shared<KeepAliveHandler>();
using std::placeholders::_1;
mMessageHandler = {
{QcrilInitMessage::get_class_message_id(), std::bind(&DataModule::handleQcrilInitMessage, this, _1)},
{RilRequestDataCallListMessage::get_class_message_id(), std::bind(&DataModule::handleDataCallListMessage, this, _1)},
{RilRequestGetDataCallProfileMessage::get_class_message_id(), std::bind(&DataModule::handleGetDataCallProfileMessage, this, _1)},
{RilRequestDeactivateDataCallMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestDeactivateDataCallMessage, this, _1)},
{RilRequestEmbmsActivateDeactivateTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsActivateDeactivateTmgiMessage, this, _1)},
{RilRequestEmbmsActivateTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsActivateTmgiMessage, this, _1)},
{RilRequestEmbmsContentDescUpdateMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsContentDescUpdateMessage, this, _1)},
{RilRequestEmbmsDeactivateTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsDeactivateTmgiMessage, this, _1)},
{EmbmsEnableDataReqMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsEnableDataReqMessage, this, _1)},
{RilRequestEmbmsGetActiveTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsGetActiveTmgiMessage, this, _1)},
{RilRequestEmbmsGetAvailTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsGetAvailTmgiMessage, this, _1)},
{RilRequestEmbmsSendIntTmgiListMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsSendIntTmgiListMessage, this, _1)},
{RilRequestGoDormantMessage::get_class_message_id(), std::bind(&DataModule::handleGoDormantMessage, this, _1)},
{RilRequestLastDataCallFailCauseMessage::get_class_message_id(), std::bind(&DataModule::handleLastDataCallFailCauseMessage, this, _1)},
{ProcessScreenStateChangeMessage::get_class_message_id(), std::bind(&DataModule::handleProcessScreenStateChangeMessage, this, _1)},
{ProcessStackSwitchMessage::get_class_message_id(), std::bind(&DataModule::handleProcessStackSwitchMessage, this, _1)},
{RilRequestPullLceDataMessage::get_class_message_id(), std::bind(&DataModule::handlePullLceDataMessage, this, _1)},
{SetApnInfoMessage::get_class_message_id(), std::bind(&DataModule::handleSetApnInfoMessage, this, _1)},
{SetIsDataEnabledMessage::get_class_message_id(), std::bind(&DataModule::handleSetIsDataEnabledMessage, this, _1)},
{SetIsDataRoamingEnabledMessage::get_class_message_id(), std::bind(&DataModule::handleSetIsDataRoamingEnabledMessage, this, _1)},
{SetQualityMeasurementMessage::get_class_message_id(), std::bind(&DataModule::handleSetQualityMeasurementMessage, this, _1)},
{RilRequestSetupDataCallMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestSetupDataCallMessage, this, _1)},
{RilRequestStartLceMessage::get_class_message_id(), std::bind(&DataModule::handleStartLceMessage, this, _1)},
{RilRequestStopLceMessage::get_class_message_id(), std::bind(&DataModule::handleStopLceMessage, this, _1)},
{ToggleDormancyIndMessage::get_class_message_id(), std::bind(&DataModule::handleToggleDormancyIndMessage, this, _1)},
{ToggleLimitedSysIndMessage::get_class_message_id(), std::bind(&DataModule::handleToggleLimitedSysIndMessage, this, _1)},
{UpdateMtuMessage::get_class_message_id(), std::bind(&DataModule::handleUpdateMtuMessage, this, _1)},
{RilDataEmbmsActiveMessage::get_class_message_id(), std::bind(&DataModule::handleDataEmbmsActiveMessage, this, _1)},
{GetDdsSubIdMessage::get_class_message_id(), std::bind(&DataModule::handleGetDdsSubIdMessage, this, _1)},
{RequestDdsSwitchMessage::get_class_message_id(), std::bind(&DataModule::handleDataRequestDDSSwitchMessage, this, _1)},
{VoiceIndMessage::get_class_message_id(), std::bind(&DataModule::handleVoiceIndMessage, this, _1)},
{DeregisterWdsIndCompletedMessage::get_class_message_id(),std::bind(&DataModule::handleDeregisterWdsIndCompletedMessage, this, _1)},
{VoiceCallOrigTimeoutMessage::get_class_message_id(), std::bind(&DataModule::handleVoiceCallOrigTimeoutMessage, this, _1)},
#if (QCRIL_RIL_VERSION >= 15)
{SetLteAttachProfileMessage_v15::get_class_message_id(), std::bind(&DataModule::handleSetLteAttachProfileMessage_v15, this, _1)},
{RilRequestSetDataProfileMessage_v15::get_class_message_id(), std::bind(&DataModule::handleSetDataProfileMessage_v15, this, _1)},
{RilRequestStartKeepaliveMessage::get_class_message_id(), std::bind(&DataModule::handleStartKeepaliveMessage, this, _1)},
{RilRequestStopKeepaliveMessage::get_class_message_id(), std::bind(&DataModule::handleStopKeepaliveMessage, this, _1)},
{RilRequestSetCarrierInfoImsiEncryptionMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestSetCarrierInfoImsiEncryptionMessage, this, _1)},
{REG_MSG("AUTH_QMI_IND"), std::bind(&DataModule::handleQmiAuthServiceIndMessage, this, _1)},
{REG_MSG("AUTH_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiAuthEndpointStatusIndMessage, this, _1)},
{SetLinkCapFilterMessage::get_class_message_id(), std::bind(&DataModule::handleSetLinkCapFilterMessage, this, _1)},
{SetLinkCapRptCriteriaMessage::get_class_message_id(), std::bind(&DataModule::handleSetLinkCapRptCriteriaMessage, this, _1)},
{SetDataProfileRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetDataProfileRequestMessage, this, _1)},
{KeepAliveIndMessage::get_class_message_id(), std::bind(&DataModule::handleKeepAliveIndMessage, this, _1)},
{CleanDataCallStateMessage::get_class_message_id(), std::bind(&DataModule::handleCleanDataCallStateMessage, this, _1)},
{StartKeepAliveRequestMessage::get_class_message_id(), std::bind(&DataModule::handleStartKeepAliveRequestMessage, this, _1)},
{StopKeepAliveRequestMessage::get_class_message_id(), std::bind(&DataModule::handleStopKeepAliveRequestMessage, this, _1)},
#else
{SetLteAttachProfileMessage::get_class_message_id(), std::bind(&DataModule::handleSetLteAttachProfileMessage, this, _1)},
{RilRequestSetDataProfileMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestSetDataProfileMessage, this, _1)},
#endif /* QCRIL_RIL_VERSION >= 15 */
{SetInitialAttachApnRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetInitialAttachApn, this, _1)},
{SetLteAttachPdnListActionResultMessage::get_class_message_id(), std::bind(&DataModule::handleSetLteAttachPdnListActionResult, this, _1)},
{NasSrvDomainPrefIndMessage::get_class_message_id(), std::bind(&DataModule::handleNasSrvDomainPrefInd, this, _1)},
{NasRequestDataShutdownMessage::get_class_message_id(), std::bind(&DataModule::handleNasRequestDataShutdown, this, _1)},
{DataBearerTypeChangedMessage::get_class_message_id(), std::bind(&DataModule::handleDataBearerTypeUpdate, this, _1)},
{DataAllBearerTypeChangedMessage::get_class_message_id(), std::bind(&DataModule::handleDataAllBearerTypeUpdate, this, _1)},
{RegisterBearerAllocationUpdateRequestMessage::get_class_message_id(), std::bind(&DataModule::handleToggleBearerAllocationUpdate, this, _1)},
{GetBearerAllocationRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetBearerAllocation, this, _1)},
{GetAllBearerAllocationsRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetAllBearerAllocations, this, _1)},
{REG_MSG("WDSModemEndPoint_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiWdsEndpointStatusIndMessage, this, _1)},
{SetPreferredDataModemRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetPreferredDataModem, this, _1)},
{CurrentDDSIndMessage::get_class_message_id(), std::bind(&DataModule::handleCurrentDDSIndMessage, this, _1)},
{DDSSwitchResultIndMessage::get_class_message_id(), std::bind(&DataModule::handleDDSSwitchResultIndMessage, this, _1)},
{RadioConfigClientConnectedMessage::get_class_message_id(), std::bind(&DataModule::handleRadioConfigClientConnectedMessage, this, _1)},
{DDSSwitchTimeoutMessage::get_class_message_id(), std::bind(&DataModule::handleDDSSwitchTimeoutMessage, this, _1)},
{DDSSwitchIPCMessage::get_class_message_id(), std::bind(&DataModule::handleDDSSwitchIPCMessage, this, _1)},
{CallStatusMessage::get_class_message_id(), std::bind(&DataModule::handleDataConnectionStateChangedMessage, this, _1)},
{REG_MSG("DSDModemEndPoint_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiDsdEndpointStatusIndMessage, this, _1)},
{IWLANCapabilityHandshake::get_class_message_id(), std::bind(&DataModule::handleIWLANCapabilityHandshake, this, _1)},
{GetAllQualifiedNetworkRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetAllQualifiedNetworksMessage, this, _1)},
{DsdSystemStatusMessage::get_class_message_id(), std::bind(&DataModule::handleDsdSystemStatusInd, this, _1)},
{DsdSystemStatusPerApnMessage::get_class_message_id(), std::bind(&DataModule::handleDsdSystemStatusPerApn, this, _1)},
{IntentToChangeApnPreferredSystemMessage::get_class_message_id(), std::bind(&DataModule::handleIntentToChangeInd, this, _1)},
{RilEventDataCallback::get_class_message_id(), std::bind(&DataModule::handleRilEventDataCallback, this, _1)},
{SetupDataCallRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetupDataCallRequestMessage, this, _1)},
{DeactivateDataCallRequestMessage::get_class_message_id(), std::bind(&DataModule::handleDeactivateDataCallRequestMessage, this, _1)},
{GetRadioDataCallListRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetRadioDataCallListRequestMessage, this, _1)},
{GetIWlanDataCallListRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetIWlanDataCallListRequestMessage, this, _1)},
{GetIWlanDataRegistrationStateRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetIWlanDataRegistrationStateRequestMessage, this, _1)},
{SetApnPreferredSystemResultMessage::get_class_message_id(), std::bind(&DataModule::handleSetApnPreferredSystemResult, this, _1)},
{HandoverInformationIndMessage::get_class_message_id(), std::bind(&DataModule::handleHandoverInformationIndMessage, this, _1)},
{DataCallTimerExpiredMessage::get_class_message_id(), std::bind(&DataModule::handleDataCallTimerExpiredMessage, this, _1)},
{SetRadioClientCapUnSolMessage::get_class_message_id(), std::bind(&DataModule::handleSetRadioClientCapUnSolMessage, this, _1)},
{NasPhysChanConfigReportingStatus::get_class_message_id(), std::bind(&DataModule::handleNasPhysChanConfigReportingStatusMessage, this, _1)},
{NasPhysChanConfigMessage::get_class_message_id(), std::bind(&DataModule::handleNasPhysChanConfigMessage, this, _1)},
{UimCardAppStatusIndMsg::get_class_message_id(), std::bind(&DataModule::handleUimCardAppStatusIndMsg, this, _1)},
#ifdef FEATURE_DATA_LQE
{REG_MSG("OTTModemEndPoint_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiOttEndpointStatusIndMessage, this, _1)},
#endif /* FEATURE_DATA_LQE */
{CallManagerEventMessage::get_class_message_id(), std::bind(&DataModule::handleCallManagerEventMessage, this, _1)},
{CallBringupFallbackMessage::get_class_message_id(), std::bind(&DataModule::handleCallBringupFallbackMessage, this, _1)},
{SetCarrierInfoImsiEncryptionMessage::get_class_message_id(), std::bind(&DataModule::handleSetCarrierInfoImsiEncryptionMessage, this, _1)},
};
//Read system property to determine IWLAN mode
//TODO:: change default value to "1" or legacy mode before initial checkin
//TODO:: change default value to "0" or default mode when we have code in place
//to determine Radio hal version
string propValue = readProperty("ro.telephony.iwlan_operation_mode", "default");
Log::getInstance().d("[" + mName + "]: IWLAN mode system property is " + propValue);
if(propValue.compare("default") == 0) {
propValue = "0";
}
else if(propValue.compare("legacy") == 0) {
propValue = "1";
}
else if(propValue.compare("AP-assisted") == 0) {
propValue = "2";
}
else {
Log::getInstance().d("ro.telephony.iwlan_operation_mode is configured with ["+
propValue + "], configuring it to default mode");
propValue = "0";
}
#ifdef QMI_RIL_UTF
mInitTracker.setIWLANMode(rildata::IWLANOperationMode::AP_ASSISTED);
#else
mInitTracker.setIWLANMode((rildata::IWLANOperationMode)atoi(propValue.c_str()));
#endif
propValue = readProperty(PROPERTY_DISABLE_PARTIAL_RETRY, PROPERTY_DISABLE_PARTIAL_RETRY_DEFAULT);
Log::getInstance().d("[" + mName + "]: Partial retry disabled property is " + propValue);
std::transform( propValue.begin(), propValue.end(), propValue.begin(),
[](char c) -> char { return std::tolower(c); });
if ("true" == propValue) {
mInitTracker.setPartialRetryEnabled(false);
}
}
DataModule::~DataModule() {
mLooper = nullptr;
//mDsdEndPoint = nullptr;
}
PendingMessageList& DataModule::getPendingMessageList() {
return mMessageList;
}
void DataModule::init() {
/* Call base init before doing any other stuff.*/
Module::init();
}
void DataModule::broadcastReady()
{
std::shared_ptr<DataInitMessage> data_init_msg =
std::make_shared<DataInitMessage>(global_instance_id);
Dispatcher::getInstance().broadcast(data_init_msg);
}
string DataModule::readProperty(string name, string defaultValue) {
char cPropValue[256] = {'\0'};
property_get(name.c_str(), cPropValue, defaultValue.c_str());
return string(cPropValue);
}
void DataModule::dump(int fd)
{
std::ostringstream ss;
if (call_manager != nullptr) {
call_manager->dump("", ss);
}
ss << "NetworkAvailabilityHandler:" << endl;
if (networkavailability_handler != nullptr) {
networkavailability_handler->dump(" ", ss);
}
ss << "NetworkServiceHandler:" << endl;
if (network_service_handler != nullptr) {
network_service_handler->dump(" ", ss);
}
ss << "InitTracker:" << endl;
mInitTracker.dump(" ", ss);
ss << " IWlanHandshakeMsgToken=" << iwlanHandshakeMsgToken << endl;
ss << " CurrentDDS=" << currentDDSSUB.dds_sub_id << endl;
ss << " SwitchType=" << currentDDSSUB.switch_type << endl;
ss << endl << "Logs:" << endl;
vector<string> logs = networkAvailabilityLogBuffer.getLogs();
ss << "NetworkAvailability:" << endl;
for (const string& msg: logs) {
ss << msg << endl;
}
ss << endl << "DataModule:" << endl;
logs = logBuffer.getLogs();
for (const string& msg: logs) {
ss << msg << endl;
}
#ifdef QMI_RIL_UTF
logBuffer.toLogcat();
cout << ss.str();
#else
LocalLogBuffer::toFd(ss.str(), fd);
#endif
}
void DataModule::handleQcrilInitMessage(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
#ifdef QMI_RIL_UTF
usleep(500000);
#endif
auto qcril_init_msg = std::static_pointer_cast<QcrilInitMessage>(msg);
if( qcril_init_msg != NULL )
{
global_instance_id = qcril_init_msg->get_instance_id();
logBuffer.setName("RIL" + std::to_string(global_instance_id));
QmiSetupRequestCallback callback("data-token");
dsd_endpoint->requestSetup("data-token-client-server", &callback);
wds_endpoint->requestSetup("data-token-client-server", &callback);
auth_endpoint->requestSetup("data-token-client-server", &callback);
#ifdef FEATURE_DATA_LQE
ott_endpoint->requestSetup("data-token-client-server", &callback);
#endif /* FEATURE_DATA_LQE */
broadcastReady();
Log::getInstance().d("[" + mName + "]: Done msg = " + msg->dump());
} else {
Log::getInstance().d("[" + mName + "]: Improper message received. =" + msg->dump() + "QCRIL DATA Init not triggered!!!");
}
}
void DataModule::handleDataCallListMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
qcril_request_return_type ret;
auto m = std::static_pointer_cast<RilRequestDataCallListMessage>(msg);
if( m != NULL ) {
qcril_data_request_data_call_list(&(m->get_params()), &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetDataCallProfileMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestGetDataCallProfileMessage> m = std::static_pointer_cast<RilRequestGetDataCallProfileMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_omh_profile_info(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestDeactivateDataCallMessage(std::shared_ptr<Message> msg) {
if( msg == NULL ) {
Log::getInstance().d("[" + mName + "]: ERROR!!! Msg received is NULL");
return;
}
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
// Cancel the default timer
clearTimeoutForMessage(msg);
//Add a new timeout handler
setTimeoutForMsg(msg, msg->getMessageExpiryTimer());
std::shared_ptr<RilRequestDeactivateDataCallMessage> m = std::static_pointer_cast<RilRequestDeactivateDataCallMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_deactivate_data_call(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received");
}
}
void DataModule::handleEmbmsActivateDeactivateTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsActivateDeactivateTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsActivateDeactivateTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsActivateDeactivateTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsActivateTmgiMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[Riddhi] DataModule Activate Embms request");
std::shared_ptr<RilRequestEmbmsActivateTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsActivateTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsActivateTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsContentDescUpdateMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsContentDescUpdateMessage> m = std::static_pointer_cast<RilRequestEmbmsContentDescUpdateMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsContentDescUpdate(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsDeactivateTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsDeactivateTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsDeactivateTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsDeactivateTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsEnableDataReqMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<EmbmsEnableDataReqMessage> m = std::static_pointer_cast<EmbmsEnableDataReqMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsEnableDataRequestMessage(req.instance_id);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsGetActiveTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsGetActiveTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsGetActiveTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsGetActiveTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsGetAvailTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsGetAvailTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsGetAvailTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsGetAvailableTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsSendIntTmgiListMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsSendIntTmgiListMessage> m = std::static_pointer_cast<RilRequestEmbmsSendIntTmgiListMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsSendInterestedList(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGoDormantMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestGoDormantMessage> m = std::static_pointer_cast<RilRequestGoDormantMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_resp_params_type resp;
resp.instance_id = req.instance_id;
resp.t = req.t;
resp.request_id = req.event_id;
resp.resp_pkt = NULL;
resp.resp_len = 0;
resp.logstr = NULL;
resp.rild_sock_oem_req = 0;
resp.ril_err_no = RIL_E_SUCCESS;
if(call_manager != nullptr)
{
bool status = call_manager->handleGoDormantRequest(req.data, req.datalen);
if (status == false) {
resp.ril_err_no = RIL_E_OEM_ERROR_3;
}
qcril_send_request_response(&resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleLastDataCallFailCauseMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestLastDataCallFailCauseMessage> m = std::static_pointer_cast<RilRequestLastDataCallFailCauseMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_last_data_call_fail_cause(&req,&ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleProcessScreenStateChangeMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ProcessScreenStateChangeMessage> m = std::static_pointer_cast<ProcessScreenStateChangeMessage>(msg);
if( m != NULL ) {
int ret = qcril_data_process_screen_state_change(m->screenState);
Message::Callback::Status status = (ret == QCRIL_DS_SUCCESS ?
Message::Callback::Status::SUCCESS : Message::Callback::Status::FAILURE);
auto resp = std::make_shared<int>(ret);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleProcessStackSwitchMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ProcessStackSwitchMessage> m = std::static_pointer_cast<ProcessStackSwitchMessage>(msg);
if( m != NULL ) {
ProcessStackSwitchMessage::StackSwitchReq info = m->getParams();
qcril_data_process_stack_switch( info.oldStackId, info.newStackId, info.instanceId);
auto resp = std::make_shared<int>(QCRIL_DS_SUCCESS);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handlePullLceDataMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestPullLceDataMessage> m = std::static_pointer_cast<RilRequestPullLceDataMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_lqe_get_info(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetApnInfoMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetApnInfoMessage> m = std::static_pointer_cast<SetApnInfoMessage>(msg);
if( m != NULL ) {
RIL_Errno ret = qcril_data_set_apn_info(&m->mParams, m->mApnType, m->mApnName, m->mIsApnValid);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetIsDataEnabledMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetIsDataEnabledMessage> m = std::static_pointer_cast<SetIsDataEnabledMessage>(msg);
if ( m != NULL ) {
qcril_request_params_type req = m->get_params();
RIL_Errno ret = qcril_data_set_is_data_enabled( &req, m->is_data_enabled);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetIsDataRoamingEnabledMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetIsDataRoamingEnabledMessage> m = std::static_pointer_cast<SetIsDataRoamingEnabledMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
RIL_Errno ret = qcril_data_set_is_data_roaming_enabled(&req, m->is_data_roaming_enabled);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#if (QCRIL_RIL_VERSION >= 15)
void DataModule::handleSetLteAttachProfileMessage_v15(std::shared_ptr<Message> msg) {
std::shared_ptr<SetLteAttachProfileMessage_v15> reqMsg = std::static_pointer_cast<SetLteAttachProfileMessage_v15>(msg);
if( reqMsg != NULL ) {
RIL_Errno ret = qcril_data_request_set_lte_attach_profile_v15 ( reqMsg->get_params() );
auto resp = std::make_shared<RIL_Errno>(ret);
reqMsg->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetDataProfileMessage_v15(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestSetDataProfileMessage_v15> m = std::static_pointer_cast<RilRequestSetDataProfileMessage_v15>(msg);
if ( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_set_data_profile(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleSetDataProfileRequestMessage
===========================================================================*/
/*!
@brief
Handler to handle SetDataProfileRequestMessage message request
@return
*/
/*=========================================================================*/
void DataModule::handleSetDataProfileRequestMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetDataProfileRequestMessage> m =
std::static_pointer_cast<SetDataProfileRequestMessage>(msg);
if( m != NULL ) {
if(profile_handler != nullptr) {
profile_handler->handleSetDataProfileRequestMessage(msg);
}
else {
RIL_Errno result = RIL_E_INTERNAL_ERR;
auto resp = std::make_shared<RIL_Errno>(result);
m->sendResponse(msg, Message::Callback::Status::FAILURE, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
if (m != NULL && networkavailability_handler != nullptr) {
networkavailability_handler->processSetDataProfileRequest(msg);
}
}
#else
void DataModule::handleSetLteAttachProfileMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetLteAttachProfileMessage> reqMsg = std::static_pointer_cast<SetLteAttachProfileMessage>(msg);
if( reqMsg != NULL ) {
RIL_Errno ret = qcril_data_request_set_lte_attach_profile ( reqMsg->get_params() );
auto resp = std::make_shared<RIL_Errno>(ret);
reqMsg->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestSetDataProfileMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestSetDataProfileMessage> m = std::static_pointer_cast<RilRequestSetDataProfileMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_set_data_profile(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#endif /* #if QCRIL_RIL_VERSION >= 15 */
void DataModule::handleSetQualityMeasurementMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetQualityMeasurementMessage> reqMsg = std::static_pointer_cast<SetQualityMeasurementMessage>(msg);
if( reqMsg != NULL ) {
dsd_set_quality_measurement_info_req_msg_v01 info = reqMsg->getInfo();
qmi_response_type_v01 ret= qcril_data_set_quality_measurement(&info);
auto resp = std::make_shared<qmi_response_type_v01>(ret);
reqMsg->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetRadioClientCapUnSolMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetRadioClientCapUnSolMessage> m = std::static_pointer_cast<SetRadioClientCapUnSolMessage>(msg);
if( m != NULL ) {
bool isAPAssistCapable = m->getParams();
if (!mInitTracker.isModeDetermined()) {
mInitTracker.setIWLANMode(isAPAssistCapable ? IWLANOperationMode::AP_ASSISTED : IWLANOperationMode::LEGACY);
performDataModuleInitialization();
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestSetupDataCallMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestSetupDataCallMessage> m = std::static_pointer_cast<RilRequestSetupDataCallMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_setup_data_call(&req, &ret);
// We don't return response here. It will be sent upon
// success/failure at a later point in time.
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStartLceMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestStartLceMessage> m = std::static_pointer_cast<RilRequestStartLceMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_lqe_start(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStopLceMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestStopLceMessage> m = std::static_pointer_cast<RilRequestStopLceMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_lqe_stop(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleToggleDormancyIndMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ToggleDormancyIndMessage> m = std::static_pointer_cast<ToggleDormancyIndMessage>(msg);
if( m != NULL ) {
int ret;
Message::Callback::Status status;
if (call_manager) {
ret = qcril_data_toggle_dormancy_indications(m->dormIndSwitch);
mLinkStatusReportEnabled = (m->dormIndSwitch == DORMANCY_INDICATIONS_ON)?true:false;
ret = call_manager->toggleLinkActiveStateChangeReport(mLinkStatusReportEnabled);
status = (ret == QCRIL_DS_SUCCESS ?
Message::Callback::Status::SUCCESS : Message::Callback::Status::FAILURE);
}
else {
Log::getInstance().d("call_manager is null");
status = Message::Callback::Status::SUCCESS;
ret = QCRIL_DS_ERROR;
}
auto resp = std::make_shared<int>(ret);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleToggleLimitedSysIndMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ToggleLimitedSysIndMessage> m = std::static_pointer_cast<ToggleLimitedSysIndMessage>(msg);
if( m != NULL ) {
int ret = qcril_data_toggle_limited_sys_indications(m->sysIndSwitch);
if (dsd_endpoint) {
mLimitedIndReportEnabled = (m->sysIndSwitch == LIMITED_SYS_INDICATIONS_ON)?true:false;
ret = dsd_endpoint->toggleLimitedSysIndicationChangeReport(mLimitedIndReportEnabled);
}
Message::Callback::Status status = (ret == QCRIL_DS_SUCCESS ?
Message::Callback::Status::SUCCESS : Message::Callback::Status::FAILURE);
auto resp = std::make_shared<int>(ret);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleUpdateMtuMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<UpdateMtuMessage> m = std::static_pointer_cast<UpdateMtuMessage>(msg);
if( m != NULL ) {
qcril_data_update_mtu(m->Mtu);
auto resp = std::make_shared<int>(QCRIL_DS_SUCCESS);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDataEmbmsActiveMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilDataEmbmsActiveMessage> m = std::static_pointer_cast<RilDataEmbmsActiveMessage>(msg);
if( m != NULL ) {
int is_Embms_Active = qcril_data_is_embms_active();
auto resp = std::make_shared<bool>(is_Embms_Active);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetDdsSubIdMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetDdsSubIdMessage> m = std::static_pointer_cast<GetDdsSubIdMessage>(msg);
if( m != NULL ) {
DDSSubIdInfo ddsInfo = qcril_data_get_dds_sub_info();
LOCK_MUTEX(ddsSubMutex);
currentDDSSUB.dds_sub_id = ddsInfo.dds_sub_id;
currentDDSSUB.switch_type = ddsInfo.switch_type;
UNLOCK_MUTEX(ddsSubMutex);
Log::getInstance().d("[" + mName + "]:Current DDS is on SUB ="+std::to_string(currentDDSSUB.dds_sub_id)+
"switch type = "+std::to_string(currentDDSSUB.switch_type));
auto resp = std::make_shared<DDSSubIdInfo>(ddsInfo);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleVoiceIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<VoiceIndMessage> m = std::static_pointer_cast<VoiceIndMessage>(msg);
if(m != NULL)
{
preferred_data_state_info->mVoiceCallInfo.voiceSubId = m->getSubId();
preferred_data_state_info->mVoiceCallInfo.voiceCallState = m->getCallState();
preferred_data_state_info->mVoiceCallInfo.voiceCallType = m->getCallType();
preferred_data_state_info->mVoiceCallInfo.voiceCallRat = m->getCallRat();
if(m->getSubId() == SubId::PRIMARY && voiceCallEndPointSub0->mIsVoiceCallOrigTimer)
{
voiceCallEndPointSub0->mIsVoiceCallOrigTimer = FALSE;
TimeKeeper::getInstance().clear_timer(voiceCallEndPointSub0->mVoiceCallOrigTimer);
}
if(m->getSubId() == SubId::SECONDARY && voiceCallEndPointSub1->mIsVoiceCallOrigTimer)
{
voiceCallEndPointSub1->mIsVoiceCallOrigTimer = FALSE;
TimeKeeper::getInstance().clear_timer(voiceCallEndPointSub1->mVoiceCallOrigTimer);
}
//Temporary switch
if((int)m->getSubId() != preferred_data_state_info->dds && m->getCallState() != VoiceCallStateEnum::CALL_STATE_END)
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_TEMPORARY_V01;
Log::getInstance().d("Temporary DDS switch on sub" + std::to_string((int)preferred_data_state_info->mVoiceCallInfo.voiceSubId));
if(m->getCallState() == VoiceCallStateEnum::CALL_STATE_CC_IN_PROGRESS)
{
if(m->getSubId() == SubId::PRIMARY)
{
voiceCallEndPointSub0->mIsVoiceCallOrigTimer = TRUE;
voiceCallEndPointSub0->mVoiceCallOrigTimer = TimeKeeper::getInstance().set_timer(std::bind(&DataModule::handleVoiceCallOrigTimerExpired, this, std::placeholders::_1), nullptr, VOICEIND_WAITING_TIMEOUT);
}
else
{
voiceCallEndPointSub1->mIsVoiceCallOrigTimer = TRUE;
voiceCallEndPointSub1->mVoiceCallOrigTimer = TimeKeeper::getInstance().set_timer(std::bind(&DataModule::handleVoiceCallOrigTimerExpired, this, std::placeholders::_1), nullptr, VOICEIND_WAITING_TIMEOUT);
}
}
}
else
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_PERMANENT_V01;
Log::getInstance().d("Permanent DDS switch on sub" + std::to_string((int)preferred_data_state_info->mVoiceCallInfo.voiceSubId));
}
if(m->getCallState() == VoiceCallStateEnum::CALL_STATE_END && preferred_data_state_info->switch_type == DSD_DDS_SWITCH_TEMPORARY_V01)
{
TempddsSwitchRequestPending = true;
tempDDSSwitchRequestTimer = TimeKeeper::getInstance().set_timer(std::bind(&DataModule::handleTempDDSSwitchTimerExpired, this, std::placeholders::_1), nullptr, TempDDS_SWITCH_REQUEST_TIMEOUT);
}
}
}
void DataModule::handleTempDDSSwitchTimerExpired(void *) {
Log::getInstance().d("Datamodule: onTempDDSSwitchRequestExpired ENTRY");
DDSTimeOutSwitchType type = DDSTimeOutSwitchType::TempDDSTimeOutSwitch;
auto msg = std::make_shared<DDSSwitchTimeoutMessage>(type);
msg->broadcast();
}
void DataModule::handleVoiceCallOrigTimerExpired(void *) {
Log::getInstance().d("DataModule: handleVoiceCallOrigTimerExpired");
auto msg = std::make_shared<VoiceCallOrigTimeoutMessage>();
msg->broadcast();
}
void DataModule::handleVoiceCallOrigTimeoutMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("DataModule: handleVoiceCallOrigTimeoutMessage");
std::shared_ptr<VoiceCallOrigTimeoutMessage> m = std::static_pointer_cast<VoiceCallOrigTimeoutMessage>(msg);
if( m != nullptr)
{
bool isCallActive = false;
if(preferred_data_state_info->mVoiceCallInfo.voiceSubId == SubId::PRIMARY)
{
voiceCallEndPointSub0->mIsVoiceCallOrigTimer = FALSE;
isCallActive = voiceCallEndPointSub0->isVoiceCall();
if(!isCallActive || preferred_data_state_info->mVoiceCallInfo.voiceCallState == VoiceCallStateEnum::CALL_STATE_CC_IN_PROGRESS)
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_PERMANENT_V01;
}
} else {
voiceCallEndPointSub1->mIsVoiceCallOrigTimer = FALSE;
isCallActive = voiceCallEndPointSub1->isVoiceCall();
if(!isCallActive || preferred_data_state_info->mVoiceCallInfo.voiceCallState == VoiceCallStateEnum::CALL_STATE_CC_IN_PROGRESS)
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_PERMANENT_V01;
}
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDataRequestDDSSwitchMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RequestDdsSwitchMessage> m = std::static_pointer_cast<RequestDdsSwitchMessage>(msg);
if( m != NULL ) {
RIL_Errno ret = qcril_data_request_dds_switch(m->dds_sub_info);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#if (QCRIL_RIL_VERSION >= 15)
void DataModule::handleStartKeepaliveMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestStartKeepaliveMessage> m = std::static_pointer_cast<RilRequestStartKeepaliveMessage>(msg);
if( m != NULL) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_start_modem_assist_keepalive(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStopKeepaliveMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestStopKeepaliveMessage> m = std::static_pointer_cast<RilRequestStopKeepaliveMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_stop_modem_assist_keepalive(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleKeepAliveIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<KeepAliveIndMessage> m = std::static_pointer_cast<KeepAliveIndMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
keep_alive_ind ind;
ind.status = m->get_status();
ind.handle = m->get_handle();
eve.event = KeepAliveInd;
eve.data = &ind ;
keep_alive->processEvent(eve);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleCleanDataCallStateMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CleanDataCallStateMessage> m = std::static_pointer_cast<CleanDataCallStateMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
eve.event = KeepAliveCleanCallState;
int cid = m->getcid();
eve.data = &cid;
keep_alive->processEvent(eve);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStartKeepAliveRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<StartKeepAliveRequestMessage> m = std::static_pointer_cast<StartKeepAliveRequestMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
KeepaliveRequest_t request = m->getKeepaliveRequest();
keep_alive_start_request ka_start_req;
if (call_manager) {
if((call_manager->findCallInfo(request.cid)) != nullptr)
{
ka_start_req.apn = call_manager->getApnByCid(request.cid);
ka_start_req.ril_ka_req = &request;
eve.data = &ka_start_req;
} else {
Log::getInstance().d("There is no call with given cid " + std::to_string(request.cid));
eve.data = nullptr;
}
eve.event = KeepAliveStartReq;
eve.msg = msg;
keep_alive->processEvent(eve);
}
else {
Log::getInstance().d("call_manager is null");
StartKeepAliveResp_t res;
res.error = ResponseError_t::INTERNAL_ERROR;
auto resp = std::make_shared<StartKeepAliveResp_t>(res);
m->sendResponse(m, Message::Callback::Status::SUCCESS, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStopKeepAliveRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<StopKeepAliveRequestMessage> m = std::static_pointer_cast<StopKeepAliveRequestMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
eve.event = KeepAliveStopReq;
eve.data = m->getHandle();
eve.msg = msg;
keep_alive->processEvent(eve);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestSetCarrierInfoImsiEncryptionMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestSetCarrierInfoImsiEncryptionMessage> m = std::static_pointer_cast<RilRequestSetCarrierInfoImsiEncryptionMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_resp_params_type resp;
resp.instance_id = QCRIL_DEFAULT_INSTANCE_ID;
resp.t = req.t;
resp.request_id = req.event_id;
resp.request_id_android = RIL_REQUEST_SET_CARRIER_INFO_IMSI_ENCRYPTION;
resp.resp_pkt = NULL;
resp.resp_len = 0;
resp.logstr = NULL;
resp.rild_sock_oem_req = 0;
if (auth_manager) {
auth_manager->setCarrierInfoImsiEncryption(&req);
resp.ril_err_no = RIL_E_SUCCESS;
}
else {
Log::getInstance().d("auth_manager is null");
resp.ril_err_no = RIL_E_INTERNAL_ERR;
}
qcril_send_request_response( &resp );
}else {
Log::getInstance().d("[" + mName + "]: Improper message received");
}
}
void DataModule::handleQmiAuthServiceIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<QmiIndMessage>(msg));
QmiIndMsgDataStruct *indData = shared_indMsg->getData();
if (indData != nullptr && auth_manager!= nullptr) {
auth_manager->qmiAuthServiceIndicationHandler(indData->msgId, indData->indData,
indData->indSize);
} else {
Log::getInstance().d("[" + mName + "] Unexpected, null data from message");
}
}
void DataModule::handleQmiAuthEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if (!mInitTracker.getAuthServiceReady()) {
mInitTracker.setAuthServiceReady(true);
performDataModuleInitialization();
}
}
else {
mInitTracker.setAuthServiceReady(false);
Log::getInstance().d("[" + mName + "]: ModemEndPoint is not operational");
}
}
void DataModule::handleQmiDsdEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if( !mInitTracker.getDsdServiceReady() ) {
mInitTracker.setDsdServiceReady(true);
performDataModuleInitialization();
}
DDSSubIdInfo ddsInfo;
Log::getInstance().d("[" + mName + "]:dispatching currentDDSSync message");
auto status = ModemEndPointFactory<DSDModemEndPoint>::getInstance().buildEndPoint()->getCurrentDDSSync(ddsInfo);
if(status == Message::Callback::Status::SUCCESS)
{
LOCK_MUTEX(ddsSubMutex);
currentDDSSUB.dds_sub_id = ddsInfo.dds_sub_id;
currentDDSSUB.switch_type = ddsInfo.switch_type;
UNLOCK_MUTEX(ddsSubMutex);
Log::getInstance().d("[" + mName + "]:Current DDS is on Sub ="+std::to_string(currentDDSSUB.dds_sub_id)+
" and Switch type = "+std::to_string(currentDDSSUB.switch_type));
//posting currentDDS
PreferredDataEventType currentDdsEvent;
DDSSwitchInfo_t eventData;
eventData.subId = ddsInfo.dds_sub_id;
currentDdsEvent.event = CurrentDDSInd;
currentDdsEvent.data = &eventData;
preferred_data_sm->processEvent(currentDdsEvent);
}
else
{
Log::getInstance().d("Failed to get the current DDS information");
}
}
else {
//Reset all interested handlers
Log::getInstance().d("[" + mName + "]: ModemEndPoint is not operational");
mInitTracker.setDsdServiceReady(false);
}
}
bool DataModule::loadDatactl() {
bool ret = false;
void *datactlLib;
do {
datactlLib = dlopen("libqcrildatactl.so", RTLD_LAZY);
if( NULL == datactlLib ) {
Log::getInstance().d("[" + mName + "]: Unable to load libqcrildatactl.so");
break;
}
dlerror();
dcSymbols.datactlInit = (datactlInitFnPtr)dlsym(datactlLib, "datactlInit");
const char *dlsym_error = dlerror();
if( dlsym_error ) {
Log::getInstance().d("[" + mName + "]: Cannot find datactlInit symbol");
break;
}
dcSymbols.datactlEnableIWlan = (datactlEnableIWlanFnPtr)dlsym(datactlLib, "datactlEnableIWlan");
dlsym_error = dlerror();
if( dlsym_error ) {
Log::getInstance().d("[" + mName + "]: Cannot find datactlEnableIWlan symbol");
break;
}
dcSymbols.datactlDisableIWlan = (datactlDisableIWlanFnPtr)dlsym(datactlLib, "datactlDisableIWlan");
dlsym_error = dlerror();
if( dlsym_error ) {
Log::getInstance().d("[" + mName + "]: Cannot find datactlDisableIWlan symbol");
break;
}
//Successfully reached the end
ret = true;
}
while( 0 );
if( ret == false ) {
if( datactlLib ) {
dlclose(datactlLib);
memset(&dcSymbols, 0, sizeof(dcSymbols)); //Reset all fn ptrs to 0
}
}
return ret;
}
void DataModule::logFn(std::string logStr) {
Log::getInstance().d(logStr);
}
//Perform initialization that are common to services being initialized
//and mode being determined
void DataModule::performDataModuleInitialization() {
if( mInitTracker.allServicesReady() && mInitTracker.isModeDetermined()) {
if( mInitTracker.servicesReadyAfterBootup() || !mInitCompleted) {
logBuffer.addLogWithTimestamp("[" + mName + "]: performDataModuleInitialization");
auth_manager = std::make_unique<AuthManager>();
profile_handler = std::make_unique<ProfileHandler>();
call_manager = std::make_unique<CallManager>(logBuffer);
string propValue = readProperty(PROPERTY_MAX_PARTIAL_RETRY_TIMEOUT, "");
Log::getInstance().d("[" + mName + "]: Partial retry max timeout property is " + propValue);
unsigned long maxTimeout = DEFAULT_MAX_PARTIAL_RETRY_TIMEOUT;
if (!propValue.empty()) {
maxTimeout = stoul(propValue);
}
call_manager->init(mInitTracker.isAPAssistMode(),
mInitTracker.isPartialRetryEnabled(), maxTimeout);
profile_handler->init(mInitTracker.isAPAssistMode());
qcril_data_init(mInitTracker.isAPAssistMode());
auth_manager->qmiAuthServiceRegisterIndications(true);
dsd_endpoint->setV2Capabilities();
dsd_endpoint->generateDsdSystemStatusInd();
dsd_endpoint->registerForSystemStatusSync();
dsd_endpoint->toggleLimitedSysIndicationChangeReport(mLimitedIndReportEnabled);
#if (QCRIL_RIL_VERSION >= 15)
/* Register for QMI_WDS_MODEM_ASSISTED_KA_STATUS_IND_V01 */
Message::Callback::Status status = wds_endpoint->registerForKeepAliveInd(TRUE);
Log::getInstance().d("[DataModule] getKeepAliveMessageSync request "
"result = " + std::to_string((int) status));
#endif
preferred_data_state_info->sub = global_instance_id;
Messenger::get().registerForMessage(DDSSwitchIPCMessage::get_class_message_id(),
std::bind(&DataModule::constructDDSSwitchIPCMessage,
this, std::placeholders::_1));
PreferredDataEventType initEvent;
initEvent.event = InitializeSM;
preferred_data_sm->processEvent(initEvent);
if( mInitTracker.isAPAssistMode() ) {
//Create AP assist variant of NetworkServiceHandler
network_service_handler = std::make_unique<ApAssistNetworkServiceHandler>();
Message::Callback::Status status = dsd_endpoint->sendAPAssistIWLANSupportedSync();
Log::getInstance().d("[DataModule] sendAPAssistIWLANSupportedSync request "
" result = " + std::to_string((int) status));
if (status == Message::Callback::Status::SUCCESS)
{
mInitTracker.setModemCapability(true);
//call datactl to enable/disable IWLAN
if (loadDatactl()) {
dcSymbols.datactlInit(global_instance_id, logFn);
if( mInitTracker.isIWLANEnabled() ) {
initializeIWLAN();
}
else {
dcSymbols.datactlDisableIWlan();
}
}
#ifdef QMI_RIL_UTF
else {
if( mInitTracker.isIWLANEnabled() ) {
initializeIWLAN();
}
}
#endif
}
else
{
//This should never happen
mInitTracker.setModemCapability(false);
if(iwlanHandshakeMsgToken != INVALID_MSG_TOKEN) {
Log::getInstance().d("[DataModule] Look for IWLANCapabilityHandshake msg "+
std::to_string((int)iwlanHandshakeMsgToken));
getDataModule().getPendingMessageList().print();
std::shared_ptr<Message> mmm = getDataModule().getPendingMessageList().find((uint16_t)iwlanHandshakeMsgToken);
if(mmm!=nullptr) {
std::shared_ptr<IWLANCapabilityHandshake> iwlanHsMsg = std::static_pointer_cast<IWLANCapabilityHandshake>(mmm);
if(iwlanHsMsg != nullptr) {
auto resp = std::make_shared<rildata::ModemIWLANCapability_t>(rildata::ModemIWLANCapability_t::not_present);
iwlanHsMsg->sendResponse(mmm, Message::Callback::Status::SUCCESS, resp);
getDataModule().getPendingMessageList().erase(mmm);
getDataModule().getPendingMessageList().print();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
} else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandShake msg. Not sending response");
}
}
else {
Log::getInstance().d("[DataModule] No IWLANCapabilityHandshake msg found");
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
}
}
else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandshake msg token");
}
}
}
else { //Legacy mode
//Create legacy mode variant of NetworkServiceHandler
network_service_handler = std::make_unique<NetworkServiceHandler>();
network_service_handler->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
}
call_manager->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
mInitCompleted = TRUE;
}
else { //Services ready after SSR
if(auth_manager != nullptr)
{
auth_manager->qmiAuthServiceRegisterIndications(true);
auth_manager->updateModemWithCarrierImsiKeyCache();
} else {
Log::getInstance().d(" auth_manager is NULL");
}
dsd_endpoint->setV2Capabilities();
dsd_endpoint->generateDsdSystemStatusInd();
dsd_endpoint->registerForSystemStatusSync();
auto status = dsd_endpoint->registerForCurrentDDSInd();
if (status == Message::Callback::Status::SUCCESS) {
Log::getInstance().d(": Successfully registered for current DDS indication");
} else {
Log::getInstance().d(": Failed to register for current DDS indication");
}
if( mInitTracker.isAPAssistMode() ) {
Message::Callback::Status status = dsd_endpoint->sendAPAssistIWLANSupportedSync();
Log::getInstance().d("[DataModule] sendAPAssistIWLANSupportedSync request "
" result = " + std::to_string((int) status));
//send message to datactl to enable/disable IWLAN
if( mInitTracker.isIWLANEnabled() ) {
if (dcSymbols.datactlEnableIWlan) {
dcSymbols.datactlEnableIWlan();
}
status = dsd_endpoint->registerForAPAsstIWlanIndsSync(true);
Log::getInstance().d("[DataModule] registerForAPAsstPrefSysChgSync request "
" result = " + std::to_string((int) status));
}
else {
if (dcSymbols.datactlDisableIWlan) {
dcSymbols.datactlDisableIWlan();
}
}
}
}
}
}
//Perform intializations that are common to services being initialized, mode
//being determined and IWLAN being enabled
void DataModule::initializeIWLAN() {
if(iwlanHandshakeMsgToken != INVALID_MSG_TOKEN) {
Log::getInstance().d("[DataModule] Look for IWLANCapabilityHandshake msg "+
std::to_string((int)iwlanHandshakeMsgToken));
getDataModule().getPendingMessageList().print();
std::shared_ptr<Message> mmm = getDataModule().getPendingMessageList().find((uint16_t)iwlanHandshakeMsgToken);
if(mmm!=nullptr) {
std::shared_ptr<IWLANCapabilityHandshake> iwlanHsMsg = std::static_pointer_cast<IWLANCapabilityHandshake>(mmm);
if(iwlanHsMsg != nullptr)
{
auto resp = std::make_shared<rildata::ModemIWLANCapability_t>(
mInitTracker.getModemCapability() ?
rildata::ModemIWLANCapability_t::present:
rildata::ModemIWLANCapability_t::not_present);
iwlanHsMsg->sendResponse(mmm, Message::Callback::Status::SUCCESS, resp);
getDataModule().getPendingMessageList().erase(mmm);
getDataModule().getPendingMessageList().print();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
} else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandShake msg. Not sending response");
}
}
else {
Log::getInstance().d("[DataModule] No IWLANCapabilityHandshake msg found");
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
}
}
else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandshake msg token");
}
Message::Callback::Status status = dsd_endpoint->registerForAPAsstIWlanIndsSync(true);
Log::getInstance().d("[DataModule] registerForIndications requst"
" result = "+ std::to_string((int) status));
networkavailability_handler = std::make_unique<NetworkAvailabilityHandler>(networkAvailabilityLogBuffer);
if (mCachedSystemStatus.apn_avail_sys_info_valid) {
networkavailability_handler->processQmiDsdSystemStatusInd(mCachedSystemStatus.apn_avail_sys_info,
mCachedSystemStatus.apn_avail_sys_info_len);
}
#ifndef QMI_RIL_UTF
//send message to datactl to enable IWLAN
if (dcSymbols.datactlEnableIWlan) dcSymbols.datactlEnableIWlan();
#endif
}
void DataModule::deinitializeIWLAN() {
Message::Callback::Status status = dsd_endpoint->registerForAPAsstIWlanIndsSync(false);
if (status != Message::Callback::Status::SUCCESS)
{
Log::getInstance().d("[DataModule] deregisterForIndications requst failed,"
" result = "+ std::to_string((int) status));
}
else
{
Log::getInstance().d("[DataModule] deregisterForIndications request successful"
", result = "+ std::to_string((int) status));
}
networkavailability_handler.reset();
networkavailability_handler = nullptr;
//Send message on datactl to disable IWLAN
if (dcSymbols.datactlDisableIWlan) dcSymbols.datactlDisableIWlan();
}
void DataModule::handleSetLinkCapFilterMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetLinkCapFilterMessage> m = std::static_pointer_cast<SetLinkCapFilterMessage>(msg);
if( m != NULL ) {
auto rf = m->getParams();
int result = -1;
if (lceHandler.toggleReporting(rf)) {
result = 0;
}
auto resp = std::make_shared<int>(result);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
}
else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetLinkCapRptCriteriaMessage(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetLinkCapRptCriteriaMessage> m = std::static_pointer_cast<SetLinkCapRptCriteriaMessage>(msg);
if( m != NULL ) {
auto rf = m->getParams();
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
LinkCapCriteriaResult_t result = lceHandler.setCriteria(rf);
if (result != rildata::LinkCapCriteriaResult_t::success) {
status = Message::Callback::Status::FAILURE;
}
auto resp = std::make_shared<rildata::LinkCapCriteriaResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#endif
void DataModule::handleRilEventDataCallback(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
if (call_manager) {
call_manager->handleRilEventDataCallback(msg);
}
else {
Log::getInstance().d("call_manager is null");
}
}
void DataModule::handleDeregisterWdsIndCompletedMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DeregisterWdsIndCompletedMessage> m = std::static_pointer_cast<DeregisterWdsIndCompletedMessage>(msg);
if( m!= NULL )
{
if(call_manager) {
call_manager->deleteWdsCallEndPoint(m->getCid(), m->getIpFamilyType());
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleSetInitialAttachApn
===========================================================================*/
/*!
@brief
Handler to handle SetInitialAttachApnRequestMessage message request
@return
*/
/*=========================================================================*/
void DataModule::handleSetInitialAttachApn(std::shared_ptr<Message> msg)
{
RIL_Errno res = RIL_E_SUCCESS;
qcril_request_resp_params_type resp;
qcril_reqlist_public_type qcril_req_info;
IxErrnoType reqlist_status = E_SUCCESS;
std::shared_ptr<SetInitialAttachApnRequestMessage> m =
std::static_pointer_cast<SetInitialAttachApnRequestMessage>(msg);
memset(&resp,0,sizeof(qcril_request_resp_params_type));
memset(&qcril_req_info,0,sizeof(qcril_reqlist_public_type));
if (m!= nullptr)
{
Log::getInstance().d("[DataModule]: Handling msg = " + m->dump());
const qcril_request_params_type *params_ptr = m->get_params();
if( params_ptr == NULL )
{
Log::getInstance().d("ERROR!!params_ptr is NULL . Returning error response to telephony");
return;
}
do
{
Log::getInstance().d("[DataModule]: Inserting"
" QCRIL_EVT_QMI_REQUEST_INIT_ATTACH_APN event in reqlist ");
qcril_reqlist_default_entry( params_ptr->t,
params_ptr->event_id,
params_ptr->modem_id,
QCRIL_REQ_AWAITING_MORE_AMSS_EVENTS,
QCRIL_EVT_QMI_REQUEST_INIT_ATTACH_APN,
NULL,
&qcril_req_info );
if (( reqlist_status = qcril_reqlist_new( params_ptr->instance_id,
&qcril_req_info )) != E_SUCCESS)
{
Log::getInstance().d("Reqlist entry failure..status: "+ std::to_string(reqlist_status));
res = map_internalerr_from_reqlist_new_to_ril_err(reqlist_status);
break;
}
ProfileHandler::RilRespParams resp_params{ params_ptr->instance_id,
params_ptr->modem_id,
params_ptr->event_id,
params_ptr->t
};
Log::getInstance().d("[DataModule]: Handling token = " + std::to_string((long long)params_ptr->t)) ;
if( profile_handler )
{
profile_handler->handleInitialAttachRequest(m->get_attach_params(), resp_params);
} else
{
Log::getInstance().d("[DataModule]: Profile Handler is NULL. Returning ERROR response") ;
qcril_default_request_resp_params( params_ptr->instance_id,
params_ptr->t,
params_ptr->event_id,
RIL_E_INTERNAL_ERR,
&resp );
qcril_send_request_response( &resp );
}
} while(0);
if (res != RIL_E_SUCCESS)
{
Log::getInstance().d("[DataModule]:handleSetInitialAttachApn:"
" Sending Error response");
qcril_default_request_resp_params( params_ptr->instance_id,
params_ptr->t,
params_ptr->event_id,
res,
&resp );
qcril_send_request_response( &resp );
}
} else
{
Log::getInstance().d("[" + mName + "]: Improper message received for handleSetInitialAttachApn");
}
}
/*===========================================================================
FUNCTION: handleSetLteAttachPdnListActionResult
===========================================================================*/
/*!
@brief
Handler to handle SetInitialAttachApnRequestMessage message request
@return
*/
/*=========================================================================*/
void DataModule::handleSetLteAttachPdnListActionResult(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetLteAttachPdnListActionResultMessage> m = std::static_pointer_cast<SetLteAttachPdnListActionResultMessage>(msg);
if( m != NULL && profile_handler != NULL ) {
Log::getInstance().d("[DataModule]::Invoking handleWdsUnSolInd" );
profile_handler->handleWdsUnSolInd(&(m->getParams()));
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleNasSrvDomainPrefInd
===========================================================================*/
/*!
@brief
Handler which gets invoked when NasSrvDomainPrefIndMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleNasSrvDomainPrefInd(std::shared_ptr<Message> m)
{
Log::getInstance().d("[DataModule]: Handling msg = " + m->dump());
std::shared_ptr<NasSrvDomainPrefIndMessage> msg = std::static_pointer_cast<NasSrvDomainPrefIndMessage>(m);
if (msg != NULL)
{
uint8_t domainPrefValid;
nas_srv_domain_pref_enum_type_v01 domainPref;
msg->getDomainPref(domainPrefValid,domainPref);
if(profile_handler)
{
Log::getInstance().d("[DataModule]::Invoking qcril_data_nas_detach_attach_ind_hdlr" );
profile_handler->qcril_data_nas_detach_attach_ind_hdlr(domainPrefValid, domainPref);
} else
{
Log::getInstance().d("[DataModule]::Invalid nas_helper object. Returning");
}
Log::getInstance().d("[DataModule]::handleNasSrvDomainPrefInd EXIT" );
}
}
/*===========================================================================
FUNCTION: handleNasRequestDataShutdown
===========================================================================*/
/*!
@brief
Handler which gets invoked when NasRequestDataShutdownMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleNasRequestDataShutdown(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<NasRequestDataShutdownMessage> m = std::static_pointer_cast<NasRequestDataShutdownMessage>(msg);
if (m != NULL)
{
NasRequestDataShutdownResponse ret = NasRequestDataShutdownResponse::FAILURE;
if(qcril_data_device_shutdown()) {
ret = NasRequestDataShutdownResponse::SUCCESS;
}
auto resp = std::make_shared<NasRequestDataShutdownResponse>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleDataAllBearerTypeUpdate
===========================================================================*/
/*!
@brief
Handler which gets invoked when DataBearerTypeChangedMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleDataAllBearerTypeUpdate(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DataAllBearerTypeChangedMessage> m = std::static_pointer_cast<DataAllBearerTypeChangedMessage>(msg);
if (m != NULL)
{
AllocatedBearer_t bearerInfo = m->getBearerInfo();
if (call_manager) {
call_manager->handleDataAllBearerTypeUpdate(bearerInfo);
}
else {
Log::getInstance().d("call_manager is null");
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleDataBearerTypeUpdate
===========================================================================*/
/*!
@brief
Handler which gets invoked when DataBearerTypeChangedMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleDataBearerTypeUpdate(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DataBearerTypeChangedMessage> m = std::static_pointer_cast<DataBearerTypeChangedMessage>(msg);
if (m != NULL)
{
int32_t cid = m->getCid();
BearerInfo_t bearer = m->getBearerInfo();
if (call_manager) {
call_manager->handleDataBearerTypeUpdate(cid, bearer);
}
else {
Log::getInstance().d("call_manager is null");
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleToggleBearerAllocationUpdate
===========================================================================*/
/*!
@brief
Handler which gets invoked when RegisterBearerAllocationUpdateRequestMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleToggleBearerAllocationUpdate(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<RegisterBearerAllocationUpdateRequestMessage> m =
std::static_pointer_cast<RegisterBearerAllocationUpdateRequestMessage>(msg);
if (m != NULL)
{
bool enable = m->getToggleSwitch();
ResponseError_t ret;
if (call_manager) {
ret = call_manager->handleToggleBearerAllocationUpdate(enable);
}
else {
Log::getInstance().d("call_manager is null");
ret = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<ResponseError_t>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleGetBearerAllocation
===========================================================================*/
/*!
@brief
Handler which gets invoked when GetBearerAllocationRequestMessage is received
Invokes the callback with the allocated bearers that were retrieved
@return
*/
/*=========================================================================*/
void DataModule::handleGetBearerAllocation(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<GetBearerAllocationRequestMessage> m =
std::static_pointer_cast<GetBearerAllocationRequestMessage>(msg);
if (m != NULL)
{
int32_t cid = m->getCallId();
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
AllocatedBearerResult_t bearerAllocations;
if (call_manager) {
bearerAllocations = call_manager->handleGetBearerAllocation(cid);
}
else {
Log::getInstance().d("call_manager is null");
bearerAllocations.error = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<AllocatedBearerResult_t>(bearerAllocations);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*============================================================================
retrieveUIMAppStatusFromAppInfo
============================================================================*/
/*!
@brief
Retrieve aid buffer application info
@return
None
*/
/*=========================================================================*/
int DataModule::retrieveUIMAppStatusFromAppInfo(RIL_UIM_AppStatus *application, string &aid_buffer, RIL_UIM_AppType *app_type)
{
int res = E_FAILURE;
Log::getInstance().d("[Datamodule]: handling retrieveUIMAppStatusFromAppInfo");
if (application && app_type)
{
Log::getInstance().d("app type " + std::to_string(application->app_type));
Log::getInstance().d("app State " + std::to_string(application->app_state));
if ((application->app_state == RIL_UIM_APPSTATE_READY) &&
!application->aid_ptr.empty())
{
aid_buffer = application->aid_ptr;
Log::getInstance().d("aid buffer " + aid_buffer);
*app_type = application->app_type;
res = E_SUCCESS;
}
}
return res;
}
/*============================================================================
retrieveUIMCardStatus
============================================================================*/
/*!
@brief
Retrieve aid buffer card status info
@return
None
*/
/*=========================================================================*/
int DataModule::retrieveUIMCardStatus( std::shared_ptr<RIL_UIM_CardStatus> ril_card_status, string &aid_buffer, RIL_UIM_AppType *app_type)
{
int res = E_FAILURE;
int index;
Log::getInstance().d("[Datamodule]: handling retrieveUIMCardStatus");
if (ril_card_status)
{
if (ril_card_status->card_state == RIL_UIM_CARDSTATE_PRESENT)
{
Log::getInstance().d("card is present");
if (ril_card_status->gsm_umts_subscription_app_index != -1)
{
index = ril_card_status->gsm_umts_subscription_app_index;
/* retrieve aid from gsm umts subscription app info */
res = retrieveUIMAppStatusFromAppInfo(
&ril_card_status->applications[index],
aid_buffer, app_type);
Log::getInstance().d("res " + std::to_string(res));
}
if ((res == E_FAILURE) &&
(ril_card_status->cdma_subscription_app_index != -1))
{
index = ril_card_status->cdma_subscription_app_index;
/* retrieve aid from cdma subscription app info */
res = retrieveUIMAppStatusFromAppInfo(
&ril_card_status->applications[index],
aid_buffer, app_type);
}
if ((res == E_FAILURE) &&
(ril_card_status->ims_subscription_app_index != -1))
{
index = ril_card_status->ims_subscription_app_index;
/* retrieve aid from ims subscription app info */
res = retrieveUIMAppStatusFromAppInfo(
&ril_card_status->applications[index],
aid_buffer, app_type);
}
}
}
return res;
}
/*===========================================================================
qcrilDataUimEventAppStatusUpdate
============================================================================*/
/*!
@brief
Handles QCRIL_EVT_CM_CARD_APP_STATUS_CHANGED
@return
None
*/
/*=========================================================================*/
void DataModule::qcrilDataUimEventAppStatusUpdate ( const qcril_request_params_type *const params_ptr, qcril_request_return_type *const ret_ptr)
{
RIL_UIM_AppStatus *card_app_info;
string aid = {};
RIL_UIM_AppType request_app_type;
qcril_modem_id_e_type modem_id;
Log::getInstance().d("qcrilDataUimEventAppStatusUpdate:: ENTRY");
QCRIL_NOTUSED(ret_ptr);
if (!params_ptr)
{
Log::getInstance().d("PARAMS ptr is NULL");
return;
}
modem_id = params_ptr->modem_id;
card_app_info = (RIL_UIM_AppStatus *)(params_ptr->data);
/* Process only this slots SIM card applications */
if (card_app_info != NULL &&
card_app_info->app_state == RIL_UIM_APPSTATE_READY)
{
Log::getInstance().d("app type"+std::to_string(card_app_info->app_type)+
"app state"+std::to_string(card_app_info->app_state));
auto card_status = std::make_shared<UimGetCardStatusRequestSyncMsg>(qmi_ril_get_process_instance_id());
std::shared_ptr<RIL_UIM_CardStatus> ril_card_status = nullptr;
/* retrieve card status info */
if (card_status != nullptr && (card_status->dispatchSync(ril_card_status) != Message::Callback::Status::SUCCESS))
{
Log::getInstance().d("Get card status request failed");
return;
}
if(ril_card_status != nullptr && ril_card_status->err != RIL_UIM_E_SUCCESS)
{
Log::getInstance().d("ril card status failed");
return;
}
/* retrieve aid from card status */
if ((retrieveUIMCardStatus(ril_card_status, aid, &request_app_type))!= E_SUCCESS)
{
Log::getInstance().d("Retrieval of AID from card status failed");
return;
}
Log::getInstance().d("Received SIM aid_buffer="+aid);
qcril_uim_app_type app_type = QCRIL_UIM_APP_UNKNOWN;
//proceed only when memory is allocated
if(aid.empty())
{
Log::getInstance().d("AID Memory allocation failed");
return;
}
switch(request_app_type)
{
case RIL_UIM_APPTYPE_SIM:
app_type = QCRIL_UIM_APP_SIM;
break;
case RIL_UIM_APPTYPE_USIM:
app_type = QCRIL_UIM_APP_USIM;
break;
case RIL_UIM_APPTYPE_RUIM:
app_type = QCRIL_UIM_APP_RUIM;
break;
case RIL_UIM_APPTYPE_CSIM:
app_type = QCRIL_UIM_APP_CSIM;
break;
default:
app_type = QCRIL_UIM_APP_UNKNOWN;
break;
}
DataGetMccMncCallback Cb("set-cb-token");
std::shared_ptr<UimGetMccMncRequestMsg> req =
std::make_shared<UimGetMccMncRequestMsg>(aid, app_type, &Cb);
if(req)
{
Log::getInstance().d("Dispatching UimGetMccMncRequestMsg Message");
req->dispatch();
}
} else {
Log::getInstance().d("Card APP info is NULL or slot id mismatch or Card APP status isn't READY");
}
}
void DataModule::handleUimCardAppStatusIndMsg(std::shared_ptr<Message> m)
{
qcril_request_return_type ret_ptr;
qcril_request_params_type params_ptr;
Log::getInstance().d("[DataModule]: Handling msg = " + m->dump());
std::shared_ptr<UimCardAppStatusIndMsg> msg =
std::static_pointer_cast<UimCardAppStatusIndMsg>(m);
std::memset(¶ms_ptr, 0, sizeof(params_ptr));
std::memset(&ret_ptr, 0, sizeof(ret_ptr));
if( msg != NULL )
{
params_ptr.data = static_cast<void *>(new char[sizeof(RIL_UIM_AppStatus)]);
if(params_ptr.data)
{
std::memcpy(params_ptr.data, &msg->get_app_info(), sizeof(RIL_UIM_AppStatus));
params_ptr.datalen = sizeof(RIL_UIM_AppStatus);
params_ptr.modem_id = QCRIL_DEFAULT_MODEM_ID;
#ifndef QMI_RIL_UTF
qcrilDataUimEventAppStatusUpdate (¶ms_ptr, &ret_ptr);
#endif
} else
{
Log::getInstance().d("[DataModule]: Memory allocation failure");
}
} else
{
Log::getInstance().d("[" + mName + "]: Improper message received");
}
}
/*===========================================================================
FUNCTION: handleGetAllBearerAllocations
===========================================================================*/
/*!
@brief
Handler which gets invoked when GetAllBearerAllocationsRequestMessage is received
Invokes the callback with the allocated bearers that were retrieved
@return
*/
/*=========================================================================*/
void DataModule::handleGetAllBearerAllocations(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<GetBearerAllocationRequestMessage> m =
std::static_pointer_cast<GetBearerAllocationRequestMessage>(msg);
if (m != NULL)
{
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
AllocatedBearerResult_t bearerAllocations;
if (call_manager) {
bearerAllocations = call_manager->handleGetAllBearerAllocations();
}
else {
Log::getInstance().d("call_manager is null");
bearerAllocations.error = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<AllocatedBearerResult_t>(bearerAllocations);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleQmiWdsEndpointStatusIndMessage
===========================================================================*/
/*!
@brief
Handler which gets invoked when QMI WDS modem endpoint status is changed
@return
*/
/*=========================================================================*/
void DataModule::handleQmiWdsEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if (!mInitTracker.getWdsServiceReady()) {
mInitTracker.setWdsServiceReady(true);
performDataModuleInitialization();
}
} else if (shared_indMsg->getState() == ModemEndPoint::State::NON_OPERATIONAL) {
if (call_manager) {
call_manager->cleanUpAllBearerAllocation();
} else {
Log::getInstance().d("call_manager is null");
}
//Reset all interested handlers
mInitTracker.setWdsServiceReady(false);
// release QDP attach profile
if(profile_handler) {
profile_handler->releaseQdpAttachProfile();
}
Log::getInstance().d("[" + mName + "]: WDSModemEndPoint is not operational");
}
}
#ifdef FEATURE_DATA_LQE
/*===========================================================================*/
/*!
@brief
Handler which gets invoked when QMI OTT modem endpoint status is changed
@return
*/
/*=========================================================================*/
void DataModule::handleQmiOttEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if (!mInitTracker.getOttServiceReady()) {
mInitTracker.setOttServiceReady(true);
qcril_data_ott_lqe_init();
}
} else if (shared_indMsg->getState() == ModemEndPoint::State::NON_OPERATIONAL) {
mInitTracker.setOttServiceReady(false);
Log::getInstance().d("[" + mName + "]: OTTModemEndPoint is not operational");
}
}
#endif /* FEATURE_DATA_LQE */
/*===========================================================================
FUNCTION: handleDataConnectionStateChangedMessage
===========================================================================*/
/*!
@brief
Handler when data connection state is changed
@return
*/
/*=========================================================================*/
void DataModule::handleDataConnectionStateChangedMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CallStatusMessage> m = std::static_pointer_cast<CallStatusMessage>(msg);
if (m != NULL) {
const CallStatusParams callParams = m->getCallParams();
if (callParams.evt == QCRIL_DATA_EVT_CALL_RELEASED) {
if (call_manager) {
call_manager->cleanUpBearerAllocation((int32_t)m->getCallId());
} else {
Log::getInstance().d("call_manager is null");
}
}
}
}
/*===========================================================================
FUNCTION: handleIWLANCapabilityHandshake
===========================================================================*/
/*!
@brief
Handler which gets invoked when IWLANCapabilityHandshake is received.
@return
*/
/*=========================================================================*/
void DataModule::handleIWLANCapabilityHandshake(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<IWLANCapabilityHandshake> m = std::static_pointer_cast<IWLANCapabilityHandshake>(msg);
if (m != NULL) {
Log::getInstance().d("[ getPendingMessageList test ]: insert message = " +
msg->get_message_name());
std::pair<uint16_t, bool> result = getDataModule().getPendingMessageList().insert(msg);
iwlanHandshakeMsgToken = (int32_t)result.first;
Log::getInstance().d("[ getPendingMessageList test ]: insert result token = " +
std::to_string((int)iwlanHandshakeMsgToken));
getDataModule().getPendingMessageList().print();
if (m->isIWLANEnabled()) {
mInitTracker.setIWLANEnabled(true);
if (mInitTracker.allServicesReady() && mInitTracker.isModeDetermined()) {
initializeIWLAN();
}
} else {
mInitTracker.setIWLANEnabled(false); //TODO: handled disabled
deinitializeIWLAN();
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleGetAllQualifiedNetworksMessage
===========================================================================*/
/*!
@brief
Handler which gets invoked when GetAllQualifiedNetworkRequestMessage is received.
@return
*/
/*=========================================================================*/
void DataModule::handleGetAllQualifiedNetworksMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<GetAllQualifiedNetworkRequestMessage> m = std::static_pointer_cast<GetAllQualifiedNetworkRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
QualifiedNetworkResult_t result;
if (!mInitTracker.isAPAssistMode()) {
result.respErr = ResponseError_t::NOT_SUPPORTED;
} else if (!mInitTracker.isIWLANEnabled() || !mInitTracker.allServicesReady()) {
result.respErr = ResponseError_t::NOT_AVAILABLE;
} else {
if (networkavailability_handler) {
result.respErr = ResponseError_t::NO_ERROR;
networkavailability_handler->getQualifiedNetworks(result.qualifiedNetwork);
}
else {
Log::getInstance().d("networkavailability_handler is null");
result.respErr = ResponseError_t::INTERNAL_ERROR;
}
}
auto resp = std::make_shared<QualifiedNetworkResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleDsdSystemStatusInd
===========================================================================*/
/*!
@brief
Handler which gets invoked when DsdSystemStatusMessage is received.
@return
*/
/*=========================================================================*/
void DataModule::handleDsdSystemStatusInd(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DsdSystemStatusMessage> m = std::static_pointer_cast<DsdSystemStatusMessage>(msg);
if (m != NULL) {
mCachedSystemStatus = m->getParams();
if (network_service_handler) {
network_service_handler->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
}
if (networkavailability_handler) {
if (mCachedSystemStatus.apn_avail_sys_info_valid) {
networkavailability_handler->processQmiDsdSystemStatusInd(mCachedSystemStatus.apn_avail_sys_info,
mCachedSystemStatus.apn_avail_sys_info_len);
}
}
if (call_manager) {
call_manager->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDsdSystemStatusPerApn(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DsdSystemStatusPerApnMessage> m = std::static_pointer_cast<DsdSystemStatusPerApnMessage>(msg);
if (m != NULL)
{
if ( networkavailability_handler ) {
auto apnAvailSys = m->getAvailSys();
networkavailability_handler->processQmiDsdSystemStatusInd(apnAvailSys.data(), apnAvailSys.size());
}
}
else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleIntentToChangeInd
===========================================================================*/
/*!
@brief
Handler which gets invoked when IntentToChangeApnPreferredSystemMessage is received.
@return
*/
/*=========================================================================*/
void DataModule::handleIntentToChangeInd(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<IntentToChangeApnPreferredSystemMessage> m =
std::static_pointer_cast<IntentToChangeApnPreferredSystemMessage>(msg);
if (m != NULL) {
dsd_intent_to_change_apn_pref_sys_ind_msg_v01 intent = m->getParams();
if (networkavailability_handler) {
networkavailability_handler->processQmiDsdIntentToChangeApnPrefSysInd(&intent);
}
if (call_manager) {
call_manager->processQmiDsdIntentToChangeApnPrefSysInd(&intent);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleSetPreferredDataModem
===========================================================================*/
/*!
@brief
Handler for AP triggered DDS switch
@return
*/
/*=========================================================================*/
void DataModule::handleSetPreferredDataModem(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetPreferredDataModemRequestMessage> m = std::static_pointer_cast<SetPreferredDataModemRequestMessage>(msg);
if (m != NULL) {
if (TempddsSwitchRequestPending) {
TimeKeeper::getInstance().clear_timer(tempDDSSwitchRequestTimer);
}
PreferredDataEventType setPreferredDataEvent;
DDSSwitchInfo_t eventData;
eventData.subId = m->getModemId();
eventData.msg = m;
setPreferredDataEvent.event = SetPreferredDataModem;
setPreferredDataEvent.data = &eventData;
preferred_data_sm->processEvent(setPreferredDataEvent);
}
}
/*===========================================================================
FUNCTION: handleCurrentDDSIndMessage
===========================================================================*/
/*!
@brief
Handler for MP triggered DDS switch
@return
*/
/*=========================================================================*/
void DataModule::handleCurrentDDSIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CurrentDDSIndMessage> m = std::static_pointer_cast<CurrentDDSIndMessage>(msg);
if (m != NULL) {
DDSSubIdInfo ddsInfo;
ddsInfo.dds_sub_id = m->getSubId();
ddsInfo.switch_type = m->getSwitchType();
LOCK_MUTEX(ddsSubMutex)
currentDDSSUB.dds_sub_id = ddsInfo.dds_sub_id;
currentDDSSUB.switch_type = ddsInfo.switch_type;
UNLOCK_MUTEX(ddsSubMutex);
Log::getInstance().d("[" + mName + "]: Sending response to qcril common");
auto msg = std::make_shared<rildata::NewDDSInfoMessage>(global_instance_id, ddsInfo);
msg->broadcast();
Log::getInstance().d("[" + mName + "]:Current DDS is on SUB =" + std::to_string(currentDDSSUB.dds_sub_id) + "with switch type = " + std::to_string(currentDDSSUB.switch_type));
// only listen for current DDS indication on main ril
if (preferred_data_state_info != nullptr &&
preferred_data_state_info->isRilIpcNotifier) {
PreferredDataEventType currentDdsEvent;
DDSSwitchInfo_t eventData;
eventData.subId = m->getSubId();
currentDdsEvent.event = CurrentDDSInd;
currentDdsEvent.data = &eventData;
preferred_data_sm->processEvent(currentDdsEvent);
}
}
}
/*===========================================================================
FUNCTION: handleDDSSwitchResultIndMessage
===========================================================================*/
/*!
@brief
Handler when DDS switch started by modem
@return
*/
/*=========================================================================*/
void DataModule::handleDDSSwitchResultIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DDSSwitchResultIndMessage> m = std::static_pointer_cast<DDSSwitchResultIndMessage>(msg);
if (m != NULL) {
PreferredDataEventType ddsSwitchEvent;
DDSSwitchInfo_t eventData;
eventData.msg = m;
eventData.switchAllowed = DDSSwitchRes::FAIL;
if (m->getAllowed()) {
eventData.switchAllowed = DDSSwitchRes::ALLOWED;
}
if (m->getError() != TriggerDDSSwitchError::NO_ERROR) {
eventData.switchAllowed = DDSSwitchRes::ERROR;
}
ddsSwitchEvent.event = DDSSwitchInd;
ddsSwitchEvent.data = &eventData;
preferred_data_sm->processEvent(ddsSwitchEvent);
}
}
/*===========================================================================
FUNCTION: handleRadioConfigClientConnectedMessage
===========================================================================*/
/*!
@brief
Handler when client registers response functions with RadioConfig HAL
@return
*/
/*=========================================================================*/
void DataModule::handleRadioConfigClientConnectedMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
Log::getInstance().d("Client connected to ril instance " + std::to_string(global_instance_id));
// this flag indicates that the current ril instance will be broadcasting IPC messages
preferred_data_state_info->isRilIpcNotifier = true;
QmiSetupRequestCallback callback("voice-token");
if (voiceCallEndPointSub0 == nullptr) {
voiceCallEndPointSub0 = std::shared_ptr<VoiceCallModemEndPoint>(new VoiceCallModemEndPoint("VoiceSub0EndPoint", SubId::PRIMARY));
voiceCallEndPointSub0->requestSetup("voice-token-client-server", &callback);
}
if (voiceCallEndPointSub1 == nullptr) {
voiceCallEndPointSub1 = std::shared_ptr<VoiceCallModemEndPoint>(new VoiceCallModemEndPoint("VoiceSub1EndPoint", SubId::SECONDARY));
voiceCallEndPointSub1->requestSetup("voice-token-client-server", &callback);
}
}
/*===========================================================================
FUNCTION: handleDDSSwitchTimeoutMessage
===========================================================================*/
/*!
@brief
@return
*/
/*=========================================================================*/
void DataModule::handleDDSSwitchTimeoutMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DDSSwitchTimeoutMessage> m = std::static_pointer_cast<DDSSwitchTimeoutMessage>(msg);
if (m != NULL) {
PreferredDataEventType timeoutEvent;
DDSSwitchInfo_t eventData;
eventData.msg = m;
switch (m->getType()) {
case DDSTimeOutSwitchType::DDSTimeOutSwitch:
timeoutEvent.event = DDSSwitchTimerExpired;
break;
case DDSTimeOutSwitchType::TempDDSTimeOutSwitch:
timeoutEvent.event = TempDDSSwitchTimerExpired;
break;
}
timeoutEvent.data = &eventData;
preferred_data_sm->processEvent(timeoutEvent);
}
}
/*===========================================================================
FUNCTION: handleDDSSwitchIPCMessage
===========================================================================*/
/*!
@brief
@return
*/
/*=========================================================================*/
void DataModule::handleDDSSwitchIPCMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DDSSwitchIPCMessage> m = std::static_pointer_cast<DDSSwitchIPCMessage>(msg);
if (m != NULL) {
// do not listen for IPC messages on main ril
if (preferred_data_state_info != nullptr &&
!preferred_data_state_info->isRilIpcNotifier) {
PreferredDataEventType ipcEvent;
DDSSwitchInfo_t eventData;
eventData.subId = m->getSubId();
ipcEvent.data = &eventData;
switch (m->getState()) {
case DDSSwitchIPCMessageState::ApStarted:
ipcEvent.event = DDSSwitchApStarted;
preferred_data_sm->processEvent(ipcEvent);
break;
case DDSSwitchIPCMessageState::Completed:
ipcEvent.event = DDSSwitchCompleted;
preferred_data_sm->processEvent(ipcEvent);
break;
case DDSSwitchIPCMessageState::MpStarted:
ipcEvent.event = DDSSwitchMpStarted;
preferred_data_sm->processEvent(ipcEvent);
break;
default:
Log::getInstance().d("Invalid DDSSwitchIPCMessage state = " + std::to_string(static_cast<int>(m->getState())));
break;
}
} else {
Log::getInstance().d("Ignoring IPC message on self");
}
}
}
/*===========================================================================
FUNCTION: constructDDSSwitchIPCMessage
===========================================================================*/
/*!
@brief
@return
*/
/*=========================================================================*/
std::shared_ptr<IPCMessage> DataModule::constructDDSSwitchIPCMessage(IPCIStream& is) {
// The message will have its members initialized in deserialize
std::shared_ptr<DDSSwitchIPCMessage> ipcMessage = std::make_shared<DDSSwitchIPCMessage>(
DDSSwitchIPCMessageState::ApStarted, -1);
if (ipcMessage != nullptr) {
ipcMessage->deserialize(is);
} else {
Log::getInstance().d("[DataModule] Invalid DDSSwitchIPCMessage");
}
return ipcMessage;
}
/*===========================================================================
FUNCTION: map_internalerr_from_reqlist_new_to_ril_err
===========================================================================*/
/*!
@brief
Helper API to convert data of IxErrnoType type to RIL_Errno type
input: data of IxErrnoType type
@return
*/
/*=========================================================================*/
RIL_Errno DataModule::map_internalerr_from_reqlist_new_to_ril_err(IxErrnoType error) {
RIL_Errno ret;
switch (error) {
case E_SUCCESS:
ret = RIL_E_SUCCESS;
break;
case E_NOT_ALLOWED:
ret = RIL_E_INVALID_STATE; //needs to be changed after internal discussion
break;
case E_NO_MEMORY:
ret = RIL_E_NO_MEMORY;
break;
case E_NO_RESOURCES:
ret = RIL_E_NO_RESOURCES;
break;
case E_RADIO_NOT_AVAILABLE:
ret = RIL_E_RADIO_NOT_AVAILABLE;
break;
case E_INVALID_ARG:
ret = RIL_E_INVALID_ARGUMENTS;
break;
default:
ret = RIL_E_INTERNAL_ERR;
break;
}
return ret;
}
void DataModule::handleSetupDataCallRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetupDataCallRequestMessage> m = std::static_pointer_cast<SetupDataCallRequestMessage>(msg);
if (m != NULL) {
logBuffer.addLogWithTimestamp("[" + mName + "]: " + std::to_string(m->getSerial()) + "> setupDataCallRequest");
if (call_manager) {
call_manager->handleSetupDataCallRequestMessage(msg);
} else {
Log::getInstance().d("call_manager is null");
SetupDataCallResponse_t result;
result.respErr = ResponseError_t::INTERNAL_ERROR;
result.call.cause = DataCallFailCause_t::ERROR_UNSPECIFIED;
result.call.suggestedRetryTime = -1;
auto resp = std::make_shared<SetupDataCallResponse_t>(result);
m->sendResponse(m, Message::Callback::Status::SUCCESS, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDeactivateDataCallRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DeactivateDataCallRequestMessage> m = std::static_pointer_cast<DeactivateDataCallRequestMessage>(msg);
if (m != NULL) {
logBuffer.addLogWithTimestamp("[" + mName + "]: " + std::to_string(m->getSerial()) + "> deactivateDataCallRequest");
if (call_manager) {
call_manager->handleDeactivateDataCallRequestMessage(msg);
} else {
Log::getInstance().d("call_manager is null");
ResponseError_t result = ResponseError_t::INTERNAL_ERROR;
auto resp = std::make_shared<ResponseError_t>(result);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetRadioDataCallListRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetRadioDataCallListRequestMessage> m = std::static_pointer_cast<GetRadioDataCallListRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
DataCallListResult_t result;
result.respErr = ResponseError_t::NO_ERROR;
if (call_manager) {
call_manager->getRadioDataCallList(result.call);
} else {
Log::getInstance().d("call_manager is null");
result.respErr = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<DataCallListResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetIWlanDataCallListRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetIWlanDataCallListRequestMessage> m = std::static_pointer_cast<GetIWlanDataCallListRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
DataCallListResult_t result;
result.respErr = ResponseError_t::NO_ERROR;
if (call_manager) {
call_manager->getIWlanDataCallList(result.call);
} else {
Log::getInstance().d("call_manager is null");
result.respErr = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<DataCallListResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetIWlanDataRegistrationStateRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetIWlanDataRegistrationStateRequestMessage> m = std::static_pointer_cast<GetIWlanDataRegistrationStateRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
IWlanDataRegistrationStateResult_t result;
result.respErr = ResponseError_t::NO_ERROR;
result.regState = DataRegState_t::NOT_REG_AND_NOT_SEARCHING;
result.reasonForDenial = 0;
if (network_service_handler && mInitTracker.isAPAssistMode()) {
result.regState = static_cast<ApAssistNetworkServiceHandler *>(network_service_handler.get())->getIWlanDataRegistrationState();
}
auto resp = std::make_shared<IWlanDataRegistrationStateResult_t>(result);
m->sendResponse(msg, status, resp);
}
}
void DataModule::handleSetApnPreferredSystemResult(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetApnPreferredSystemResultMessage> m = std::static_pointer_cast<SetApnPreferredSystemResultMessage>(msg);
if (m != NULL && call_manager != NULL) {
Log::getInstance().d("[DataModule]::Invoking processQmiDsdApnPreferredSystemResultInd");
call_manager->processQmiDsdApnPreferredSystemResultInd(&(m->getParams()));
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleHandoverInformationIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<HandoverInformationIndMessage> m = std::static_pointer_cast<HandoverInformationIndMessage>(msg);
if (m != NULL && call_manager != NULL) {
call_manager->handleHandoverInformationIndMessage(m);
}
}
void DataModule::handleCallBringupFallbackMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CallBringupFallbackMessage> m = std::static_pointer_cast<CallBringupFallbackMessage>(msg);
if (m != NULL && call_manager != NULL) {
call_manager->handleCallBringupFallbackMessage(m);
}
}
void DataModule::handleDataCallTimerExpiredMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DataCallTimerExpiredMessage> m = std::static_pointer_cast<DataCallTimerExpiredMessage>(msg);
if (m != NULL && call_manager != NULL) {
switch (m->getType()) {
case DataCallTimerType::Handover:
call_manager->handleHandoverTimeout(m->getCid());
break;
case DataCallTimerType::SetupDataCall:
call_manager->handleSetupDataCallTimeout(m->getCid());
break;
case DataCallTimerType::PartialRetry:
call_manager->handlePartialRetryTimeout(m->getCid());
break;
case DataCallTimerType::PartialRetryResponse:
call_manager->handlePartialRetryResponseTimeout(m->getCid());
break;
case DataCallTimerType::DeactivateDataCall:
call_manager->handleDeactivateDataCallTimeout(m->getCid());
break;
default:
break;
}
}
}
void DataModule::handleNasPhysChanConfigReportingStatusMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<NasPhysChanConfigReportingStatus> m = std::static_pointer_cast<NasPhysChanConfigReportingStatus>(msg);
if (m != nullptr && call_manager != nullptr) {
call_manager->enablePhysChanConfigReporting(m->isPhysChanConfigReportingEnabled());
} else {
Log::getInstance().d("No call_manager created");
}
}
void DataModule::handleNasPhysChanConfigMessage(std::shared_ptr<Message> msg) {
if (call_manager != nullptr) {
call_manager->handleNasPhysChanConfigMessage(msg);
} else {
Log::getInstance().d("No call_manager created");
}
}
void DataModule::handleCallManagerEventMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
if (call_manager) {
call_manager->handleCallManagerEventMessage(msg);
}
else {
Log::getInstance().d("call_manager is null");
}
}
void DataModule::handleSetCarrierInfoImsiEncryptionMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetCarrierInfoImsiEncryptionMessage> m = std::static_pointer_cast<SetCarrierInfoImsiEncryptionMessage>(msg);
if (auth_manager) {
auth_manager->setCarrierInfoImsiEncryption(m->getImsiEncryptionInfo());
}
else {
Log::getInstance().d("auth_manager is null");
}
}
/*===========================================================================
FUNCTION: setTimeoutForMsg
===========================================================================*/
/*!
@brief
API to set the timeout for message
@return
TimeKeeper::timer_id value
*/
/*=========================================================================*/
TimeKeeper::timer_id DataModule::setTimeoutForMsg
(
std::shared_ptr<Message> msg, TimeKeeper::millisec maxTimeout
) {
if (msg == NULL) {
Log::getInstance().d("[" + mName + "]: ERROR!!! Msg received is NULL");
return 0; /*'0' is the init value of timer_id parameter */
}
Log::getInstance().d("[DataModule: set timeout for " + msg->dump());
TimeKeeper::timer_id tid = TimeKeeper::getInstance().set_timer(
[this, msg](void *user_data){
QCRIL_NOTUSED(user_data);
if (!(msg->isCallbackExecuting() || msg->isCallbackExecuted()))
{
Log::getInstance().d("[DataModule:: Timer expired for " +
msg->dump());
msg->cancelling();
Log::getInstance().d("[DataModule]: calling dispatcher inform fun");
Dispatcher::getInstance().informMessageDispatchFailure(
msg, Message::Callback::Status::TIMEOUT);
Log::getInstance().d("Finished");
msg->cancelled();
deleteEntryInReqlist(msg);
}
},
nullptr,
maxTimeout);
Log::getInstance().d("[" + msg->to_string() + "]: timer_id = " + std::to_string(tid));
msg->setTimerId(tid);
return tid;
}
/*===========================================================================
FUNCTION: deleteEntryInReqlist
===========================================================================*/
/*!
@brief
API to delete request from reqlist
===========================================================================*/
/*!
@brief
API to delete request from reqlist
@return
None
*/
/*=========================================================================*/
void DataModule::deleteEntryInReqlist
(
std::shared_ptr<Message> msg
)
{
/* Remove entry from reqlist */
std::shared_ptr<RilRequestDeactivateDataCallMessage> m = std::static_pointer_cast<RilRequestDeactivateDataCallMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
IxErrnoType reqlistErrno = qcril_data_reqlist_free(&req);
if( reqlistErrno == E_SUCCESS)
{
Log::getInstance().d("qcril_data_deactivate_timeout_handle::Reqlist Free SUCCESS");
}
else
{
Log::getInstance().d("qcril_data_deactivate_timeout_handler::Reqlist Free failed!!! with Error code "+ std::to_string(reqlistErrno));
}
} else {
Log::getInstance().d("[" + mName + "]: Message received is not DeactivateDataCall message!!!");
}
}
/*===========================================================================
FUNCTION: clearTimeoutForMsg
===========================================================================*/
/*!
@brief
API to clear the existing timeout for message
@return
TimeKeeper::timer_id value
*/
/*=========================================================================*/
bool clearTimeoutForMessage
(
std::shared_ptr<Message> msg
)
{
return TimeKeeper::getInstance().clear_timer(msg->getTimerId());
}
/*============================================================================
qcrilDataprocessMccMncInfo
============================================================================*/
/*!
@brief
Process mcc mnc info
@return
None
*/
/*=========================================================================*/
void qcrilDataprocessMccMncInfo
(
const qcril_request_params_type *const params_ptr,
qcril_request_return_type *const ret_ptr
)
{
qcril_uim_mcc_mnc_info_type *uim_mcc_mnc_info = NULL;
Log::getInstance().d("qcrilDataprocessMccMncInfo: ENTRY");
if ((params_ptr == NULL) || (ret_ptr == NULL))
{
Log::getInstance().d("ERROR!! Invalid input, cannot process request");
return;
}
uim_mcc_mnc_info = (qcril_uim_mcc_mnc_info_type*)params_ptr->data;
if (uim_mcc_mnc_info == NULL)
{
Log::getInstance().d("NULL uim_mcc_mnc_info");
return;
}
if (uim_mcc_mnc_info->err_code != RIL_UIM_E_SUCCESS)
{
Log::getInstance().d("uim_get_mcc_mnc_info error:"+ std::to_string(uim_mcc_mnc_info->err_code));
return;
}
//According to the declaration of size in 'UimGetMccMncRequestMsg.h'
//each of mcc & mnc is 4 bytes, adding the error check based on this size
if ( (uim_mcc_mnc_info->mcc[MCC_LENGTH - 1] != '\0')
|| (uim_mcc_mnc_info->mnc[MNC_LENGTH - 1] != '\0') )
{
Log::getInstance().d("ERROR!! Improper input received. Either of MCC or MNC is not NULL terminated");
return;
}
std::string str = uim_mcc_mnc_info->mcc;
std::string str1 = uim_mcc_mnc_info->mnc;
Log::getInstance().d("mcc:"+ str+"mnc="+ str1);
qdp_compare_and_update(uim_mcc_mnc_info->mcc,
uim_mcc_mnc_info->mnc);
}
#ifdef QMI_RIL_UTF
void qcril_qmi_hal_data_module_cleanup() {
getDataModule().cleanup();
}
void DataModule::cleanup()
{
std::shared_ptr<DSDModemEndPoint> mDsdModemEndPoint =
ModemEndPointFactory<DSDModemEndPoint>::getInstance().buildEndPoint();
DSDModemEndPointModule* mDsdModemEndPointModule =
(DSDModemEndPointModule*)mDsdModemEndPoint->mModule;
mDsdModemEndPointModule->cleanUpQmiSvcClient();
std::shared_ptr<AuthModemEndPoint> mAuthModemEndPoint =
ModemEndPointFactory<AuthModemEndPoint>::getInstance().buildEndPoint();
AuthModemEndPointModule* mAuthModemEndPointModule =
(AuthModemEndPointModule*)mAuthModemEndPoint->mModule;
mAuthModemEndPointModule->cleanUpQmiSvcClient();
std::shared_ptr<WDSModemEndPoint> mWDSModemEndPoint =
ModemEndPointFactory<WDSModemEndPoint>::getInstance().buildEndPoint();
WDSModemEndPointModule* mWDSModemEndPointModule =
(WDSModemEndPointModule*)mWDSModemEndPoint->mModule;
mWDSModemEndPointModule->cleanUpQmiSvcClient();
mInitTracker = InitTracker();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
preferred_data_sm = std::make_unique<PreferredDataStateMachine>();
preferred_data_state_info = std::make_shared<PreferredDataInfo_t>();
preferred_data_state_info->isRilIpcNotifier = false;
preferred_data_state_info->mVoiceCallInfo.voiceSubId = INVALID_VOICE_SUB_ID;
preferred_data_sm->initialize(preferred_data_state_info);
preferred_data_sm->setCurrentState(Initial);
voiceCallEndPointSub0 = nullptr;
voiceCallEndPointSub1 = nullptr;
currentDDSSUB = { QCRIL_INVALID_MODEM_STACK_ID, DSD_DDS_DURATION_PERMANANT_V01 };
auth_manager = nullptr;
profile_handler = nullptr;
call_manager = nullptr;
network_service_handler = nullptr;
keep_alive = std::make_shared<KeepAliveHandler>();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
getPendingMessageList().clear();
mInitTracker.setIWLANMode(rildata::IWLANOperationMode::AP_ASSISTED);
qcril_data_qmi_wds_release();
// dump(0);
}
#endif
}//namespace
| [
"[email protected]"
] | |
bf154c9926e85b71046b0d14b2e4b73693d7298a | 8d8701540dd968681f82eb9294f71376d6512abe | /src/experiment_async_rdma/rdma_environment.cpp | 734084f9fcfa2695d55c13770e724e326a4c84b0 | [] | no_license | xiaobaidemu/ATI | 1ba9bf74dc56587a0f6143f8978847f7828023d0 | 12e71bd14e97e857a4006a5be5c53216aaa6c5b9 | refs/heads/master | 2020-03-17T10:05:26.006279 | 2018-05-15T10:45:40 | 2018-05-15T10:45:40 | 133,499,782 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,706 | cpp | #include "rdma_header.h"
#include <net.h>
#include <sys/epoll.h>
#define CQ_SIZE 100
rdma_environment::rdma_environment()
{
_dispose_required.store(false);
env_ec = rdma_create_event_channel();
_efd_rdma_fd = CCALL(epoll_create1(EPOLL_CLOEXEC));
_notification_event_rdma_fd = CCALL(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
_notification_event_rdma_fddata = rdma_fd_data(this, _notification_event_rdma_fd);
MAKE_NONBLOCK(env_ec->fd);
_rdma_channel_fddata = rdma_fd_data(this, env_ec->fd, true);
epoll_add(&_rdma_channel_fddata, EPOLLIN|EPOLLET);
epoll_add(&_notification_event_rdma_fddata, EPOLLIN | EPOLLET);
_loop_thread = new std::thread([this](){
main_loop();
CCALL(close(_notification_event_rdma_fd));
_notification_event_rdma_fd = INVALID_FD;
CCALL(close(_efd_rdma_fd));
_efd_rdma_fd = INVALID_FD;
rdma_destroy_event_channel(env_ec);
DEBUG("main_loop have already closed.\n");
});
}
/*void rdma_environment::sighandler(int)
{
printf("xxxxxxxxxxxxxxxxxx %d\n", pthread_self());
}*/
rdma_environment::~rdma_environment()
{
}
void rdma_environment::epoll_add(rdma_fd_data* fddata, const uint32_t events) const
{
ASSERT(fddata); ASSERT_RESULT(fddata->fd);
epoll_event event; event.events = events; event.data.ptr = fddata;
CCALL(epoll_ctl(_efd_rdma_fd, EPOLL_CTL_ADD, fddata->fd, &event));
}
void rdma_environment::push_and_trigger_notification(const rdma_event_data& notification)
{
const size_t new_size = _notification_rdma_queue.push(notification);
TRACE("push a rdma_event_data into the _notification_rdma_queue(size:%ld).\n", new_size);
ASSERT_RESULT(_notification_event_rdma_fd);
if(new_size == 1){
uint64_t value = 1;
CCALL(write(_notification_event_rdma_fd, &value, sizeof(value)));
}
else{
DEBUG("skip write(_notification_event_rdma_fd): queued notification count = %lld\n",(long long)new_size);
}
}
void rdma_environment::dispose()
{
// for all_debug
DEBUG("environment begin close.\n");
push_and_trigger_notification(rdma_event_data::rdma_environment_dispose(this));
_loop_thread->join();
DEBUG("environment is closeing.\n");
}
void rdma_environment::build_params(struct rdma_conn_param *params)
{
memset(params, 0, sizeof(*params));
params->retry_count = 10;
params->rnr_retry_count = 10;
}
void rdma_environment::process_rdma_channel(const uint32_t events)
{
ASSERT(events & EPOLLIN);
struct rdma_cm_event *event = nullptr;
struct rdma_conn_param cm_params;
build_params(&cm_params);
while(rdma_get_cm_event(env_ec, &event) == 0){
struct rdma_cm_event event_copy;
memcpy(&event_copy, event, sizeof(*event));
rdma_ack_cm_event(event);
switch(event_copy.event){
case RDMA_CM_EVENT_ADDR_RESOLVED:{
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->build_conn_res();
CCALL(rdma_resolve_route(event_copy.id, TIMEOUT_IN_MS));
break;
}
case RDMA_CM_EVENT_ROUTE_RESOLVED:{
CCALL(rdma_connect(event_copy.id, &cm_params));
TRACE("Finish rdma_cm_event_rout_resolved event.\n");
break;
}
case RDMA_CM_EVENT_CONNECT_REQUEST:{
rdma_connection *new_conn = create_rdma_connection_passive(event_copy.id, event_copy.listen_id);
//if(((rdma_fd_data*)(event_copy.listen_id->context))->owner) printf("------------------\n");
//event_copy.id->context = new_conn;
if(map_id_conn.find((intptr_t)(event_copy.id)) == map_id_conn.end()){
map_id_conn[(intptr_t)(event_copy.id)] = new_conn;
}
else{
FATAL("Cannot fix bug when handle rdma_cm_event_connect_request.\n");
ASSERT(0);
}
//记录id和
CCALL(rdma_accept(event_copy.id, &cm_params));
TRACE("Listener finish rdma_cm_event_connect_request event.\n");
break;
}
case RDMA_CM_EVENT_ESTABLISHED:{
//DEBUG("handle rdma_cm_event_established event.\n");
if(map_id_conn.find((intptr_t)(event_copy.id)) == map_id_conn.end()){
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->process_established();
NOTICE("%s to %s active connection established.\n",
conn->local_endpoint().to_string().c_str(),
conn->remote_endpoint().to_string().c_str());
}
else{
rdma_connection *new_passive_conn = map_id_conn[(intptr_t)(event_copy.id)];
rdma_listener *listen = new_passive_conn->conn_lis;
listen->process_accept_success(new_passive_conn);
NOTICE("%s from %s passive connection established.\n",
new_passive_conn->local_endpoint().to_string().c_str(),
new_passive_conn->remote_endpoint().to_string().c_str());
}
break;
}
case RDMA_CM_EVENT_DISCONNECTED:{
DEBUG("handle rdma_cm_event_disconnected event.\n");
rdma_connection *conn = nullptr;
if(map_id_conn.find((intptr_t)(event_copy.id)) == map_id_conn.end()){
conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->_status.store(CONNECTION_CLOSED);
DEBUG("Active connection is disconneting.\n");
}
else{
conn = map_id_conn[(intptr_t)(event_copy.id)];
conn->_status.store(CONNECTION_CLOSED);
map_id_conn.erase((intptr_t)(event_copy.id));
DEBUG("Passive connection is disconnecting.\n");
}
conn->close_rdma_conn();
break;
}
case RDMA_CM_EVENT_ADDR_ERROR:
case RDMA_CM_EVENT_ROUTE_ERROR:
case RDMA_CM_EVENT_UNREACHABLE:
case RDMA_CM_EVENT_REJECTED:{
if(event_copy.id && event_copy.id->context){
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->process_established_error();
}
break;
}
case RDMA_CM_EVENT_CONNECT_ERROR:{
if(event_copy.listen_id && event_copy.listen_id->context){
rdma_listener* lis = (rdma_listener*)(((rdma_fd_data*)(event_copy.listen_id->context))->owner);
lis->process_accept_fail();
}
else if(event_copy.id && event_copy.id->context){
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->process_established_error();
}
else{
FATAL("BUG: Cannot handle error event %s because cannot find conn/listen object.\n", rdma_event_str(event_copy.event));
ASSERT(0);break;
}
break;
}
default:{
FATAL("BUG: Cannot handle event:%s\n",rdma_event_str(event_copy.event));
ASSERT(0);
break;
}
}
}
return;
}
void rdma_environment::main_loop()
{
DEBUG("ENVIRONMENT start main_loop.\n");
const int EVENT_BUFFER_COUNT = 256;
epoll_event* events_buffer = new epoll_event[EVENT_BUFFER_COUNT];
struct ibv_wc ret_wc_array[CQE_MIN_NUM];
while(true){
// DEBUG("---------------------------------------------\n");
const int readyCnt = epoll_wait(_efd_rdma_fd, events_buffer, EVENT_BUFFER_COUNT, -1);
if(readyCnt<0){
const int error = errno;
if(error == EINTR) continue;
ERROR("[rdma_environment] epoll_wait failed with %d (%s)\n",
error, strerror(error));
break;
}
for(int i = 0;i < readyCnt;++i){
const uint32_t curr_events = events_buffer[i].events;
const rdma_fd_data* curr_rdmadata = (rdma_fd_data*)events_buffer[i].data.ptr;
switch(curr_rdmadata->type){
case rdma_fd_data::RDMATYPE_CHANNEL_EVENT:{
TRACE("trigger rdma_channel fd = %d.\n", env_ec->fd);
ASSERT(this == curr_rdmadata->owner);
ASSERT(curr_rdmadata->fd == env_ec->fd);
this->process_rdma_channel(curr_events);
break;
}
case rdma_fd_data::RDMATYPE_NOTIFICATION_EVENT:{
TRACE("trigger rdma_eventfd = %d %d\n", curr_rdmadata->fd, _notification_event_rdma_fd);
ASSERT(this == curr_rdmadata->owner);
ASSERT(curr_rdmadata->fd == _notification_event_rdma_fd);
this->process_epoll_env_notificaton_event_rdmafd(curr_events);
break;
}
case rdma_fd_data::RDMATYPE_ID_CONNECTION:{
//表示当前已经有完成任务发生了,可以通过ibv_get_cq_event获取
struct ibv_cq *ret_cq; void *ret_ctx; struct ibv_wc wc;
rdma_connection *conn = (rdma_connection*)curr_rdmadata->owner;
CCALL(ibv_get_cq_event(conn->conn_comp_channel, &ret_cq, &ret_ctx));
conn->ack_num++;
//此处会有坑
if(conn->ack_num == ACK_NUM_LIMIT){
ibv_ack_cq_events(ret_cq, conn->ack_num);
TRACE("ibv_ack_cq_events %d\n", ACK_NUM_LIMIT);
conn->ack_num = 0;
}
CCALL(ibv_req_notify_cq(ret_cq, 0));
int num_cqe;
while(num_cqe = ibv_poll_cq(ret_cq, CQE_MIN_NUM, ret_wc_array)){
TRACE("ibv_poll_cq() get %d cqe.\n", num_cqe);
conn->process_poll_cq(ret_cq, ret_wc_array, num_cqe);
}
break;
}
default:{
FATAL("BUG: Unknown rdma_fd_data: %d\n", (int)curr_rdmadata->type);
ASSERT(0);break;
}
}
}
if(_dispose_required.load()){
DEBUG("ready to close the main_loop.\n");
break;
}
}
delete[] events_buffer;
return;
}
long long rdma_environment::get_curtime(){
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000000 + tv.tv_usec;
}
void rdma_environment::process_close_queue(){
while(true){
close_conn_info *conn_info;
bool issuc = _ready_close_queue.try_front(&conn_info);
if(!issuc) break;
else{
if(get_curtime() - (conn_info->time_ready_close) >= 0){
if(conn_info->closing_conn->_status.load() == CONNECTION_CONNECTED){
WARN("ready to rdma_disconnection.\n");
conn_info->closing_conn->close_rdma_conn();
//rdma_destroy_qp(conn_info->closing_conn->conn_id);
//conn_info->closing_conn->conn_id = nullptr;
//rdma_disconnect(conn_info->closing_conn->conn_id);
}
else{
ASSERT(conn_info->closing_conn->_status.load() == CONNECTION_CLOSED);
}
_ready_close_queue.pop();
continue;
}
else break;
}
}
if(_ready_close_queue.size() > 0){
push_and_trigger_notification(rdma_event_data::rdma_connection_close());
}
}
//目前要处理的内容只有发送操作
void rdma_environment::process_epoll_env_notificaton_event_rdmafd(const uint32_t events)
{
uint64_t dummy; ASSERT(events & EPOLLIN);
CCALL(read(_notification_event_rdma_fd, &dummy, sizeof(dummy)));
//处理_notification_rdma_queue中的事物
rdma_event_data evdata;
while(_notification_rdma_queue.try_pop(&evdata)){
switch(evdata.type){
case rdma_event_data::RDMA_EVENTTYPE_ASYNC_SEND:{
rdma_connection* conn = (rdma_connection*)evdata.owner;
conn->process_rdma_async_send();
break;
}
case rdma_event_data::RDMA_EVENTTYPE_CONNECTION_CLOSE:{
//rdma_connection* conn = (rdma_connection*)evdata.owner;
//conn->_rundown.release();
this->process_close_queue();
break;
}
case rdma_event_data::RDMA_EVENTTYPE_FAILED_CONNECTION_CLOSE:{
WARN("ready to close failed_connected connectioni......\n");
rdma_connection* conn = (rdma_connection*)evdata.owner;
conn->close_rdma_conn();
conn->_rundown.release();
}
case rdma_event_data::RDMA_EVENTTYPE_LISTENER_CLOSE:{
rdma_listener* lis = (rdma_listener*)evdata.owner;
lis->_rundown.release();
break;
}
case rdma_event_data::RDMA_EVENTTYPE_ENVIRONMENT_DISPOSE:{
_dispose_required.store(true);
TRACE("trigger RDMA_EVENTTYPE_ENVIRONMENT_DISPOSE .\n");
break;
}
default: {
FATAL("BUG: Unknown rdma_environment event_type: %d\n", (int)evdata.type);
ASSERT(0);break;
}
}
}
}
rdma_connection* rdma_environment::create_rdma_connection(const char* connect_ip, const uint16_t port)
{
return new rdma_connection(this, connect_ip, port);
}
rdma_listener* rdma_environment::create_rdma_listener(const char* bind_ip, const uint16_t port)
{
return new rdma_listener(this, bind_ip, port);
}
rdma_connection* rdma_environment::create_rdma_connection_passive(struct rdma_cm_id *new_conn, struct rdma_cm_id *listen_id)
{
return new rdma_connection(this, new_conn, listen_id);
}
| [
"[email protected]"
] | |
b18a5e6efedaae9e597ab42b3a7656370db26e40 | 030730ffbeeaae0082b8b04c878d737b2a3a8713 | /C++/Maze/MazePerson.cpp | c4198c1ab421ca24f294b7230818ec46860d2f89 | [] | no_license | whjkm/project | fcdc3a738e8006e9dfa54a751895dc6575bf19e2 | 29cdf1f572584f13c812935de2c4c78e9868b2f6 | refs/heads/master | 2021-01-18T15:21:39.349185 | 2018-08-14T01:58:37 | 2018-08-14T01:58:37 | 21,820,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 107 | cpp | #include "MazePerson.h"
MazePerson::MazePerson()
{
//ctor
}
MazePerson::~MazePerson()
{
//dtor
}
| [
"[email protected]"
] | |
22c5f99701e09f637a33e660f4027984a3a8bfcf | 14ce793aedf5fcc1a685ee7173e1333210b46553 | /src/qtest/abuild-basic/data/msvc/main.cc | a8c8b471d572e37841515afc09ac8e3a78cfb510 | [
"Apache-2.0",
"Artistic-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Artistic-1.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | abuild-org/abuild | a569fca784b1a113f65c510233b9d97773c84674 | 54c003b2bf2e544bb25d7727fb4ba6297bc4a61e | refs/heads/master | 2020-11-27T07:39:14.413974 | 2019-12-20T23:38:41 | 2019-12-20T23:38:41 | 229,351,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | cc | #include <iostream>
#include <cstring>
int main(int argc, char* argv[])
{
if ((argc == 2) && (std::strcmp(argv[1], "ver") == 0))
{
std::cout << _MSC_VER << std::endl;
return 0;
}
try
{
#ifdef _MANAGED
std::cout << "managed" << std::endl;
#else
std::cout << "not managed" << std::endl;
#endif
throw 5;
}
catch (int x)
{
std::cout << "threw " << x << std::endl;
}
return 0;
}
| [
"[email protected]"
] | |
b1436d8dd67d1f821cf3c27a494aea0f10e59e25 | 69b0dd68ce4a6975636909d5dae74f5229615c85 | /FinalVersioncpp02/wywidget.cpp | 8e938313be32964f0827de89c9098bf1e07c55a8 | [] | no_license | ZeroneJerrymo/QtCodeDemo | 5600ace3c83b04f8438a0897b47dd83a32ab9fe6 | 0c08798273f06622454531ce8230efa0e0d690a0 | refs/heads/master | 2020-04-23T00:54:32.937028 | 2019-02-15T03:52:46 | 2019-02-15T03:52:46 | 170,796,207 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 15,602 | cpp | #include "wyface.h"
#include "wywidget.h"
#include "ui_wywidget.h"
#include <QUdpSocket>
#include <QHostInfo>
#include <QMessageBox>
#include <QScrollBar>
#include <QDateTime>
#include <QNetworkInterface>
#include <QProcess>
#include <QFileDialog>
#include <QColorDialog>
#include <QFileDialog>
#include <QColorDialog>
#include "wytcpserver.h"
#include "wytcpclient.h"
#include <QImageReader>
#include <QImageWriter>
WyWidget::WyWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::WyWidget)
{
ui->setupUi(this);
udpSocket = new QUdpSocket(this);
port = 45454;
udpSocket->bind(port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
server = new WyTcpServer(this);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
sendMessage(WyNewParticipant);
connect(server, SIGNAL(sendFileName(QString)), this, SLOT(getFileName(QString)));
}
WyWidget::~WyWidget()
{
delete ui;
}
// 使用UDP广播发送信息
void WyWidget::sendMessage(WyMessageType type, QString serverAddress)
{
QByteArray data;
QDataStream out(&data, QIODevice::WriteOnly);
QString localHostName = QHostInfo::localHostName();
QString address = getIP();
out << type << getUserName() << localHostName;
switch(type)
{
case WyMessage :
// if (ui->messageTextEdit->toPlainText() == "") {
// QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok);
// return;
// }
out << address << getMessage();
ui->messageBrowser->verticalScrollBar()
->setValue(ui->messageBrowser->verticalScrollBar()->maximum());
break;
case WyNewParticipant :
out << address;
break;
case WyParticipantLeft :
break;
case WyFileName :
{
int row = ui->userTableWidget->currentRow();
QString clientAddress = ui->userTableWidget->item(row, 2)->text();
out << address << clientAddress << fileName;
break;
}
case WyRefuse :
out << serverAddress;
break;
case Image:
{
qDebug()<<imageName<<tr("未发送");
out << address << imageName;
qDebug()<<tr("准备发送")<<imageName;
out << QFileInfo(imageName).fileName();
//qDebug()<<tr("开始写入UDP数据报");
QImageReader imageReader(imageName);
imageReader.setFormat(QFileInfo(imageName).suffix().toLatin1());
out << imageReader.read();
ui->messageBrowser->verticalScrollBar()
->setValue(ui->messageBrowser->verticalScrollBar()->maximum());
ui->messageTextEdit->clear();
}break;
}
udpSocket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port);
}
// 接收UDP信息
void WyWidget::processPendingDatagrams()
{
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size());
QDataStream in(&datagram, QIODevice::ReadOnly);
int messageType;
in >> messageType;
QString userName,localHostName,ipAddress,message;
QString time = QDateTime::currentDateTime()
.toString("yyyy-MM-dd hh:mm:ss");
switch(messageType)
{
case WyMessage:
in >> userName >> localHostName >> ipAddress >> message;
ui->messageBrowser->setTextColor(Qt::blue);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman",12));
ui->messageBrowser->append("[ " +userName+" ] "+ time);
ui->messageBrowser->append(message);
break;
case WyNewParticipant:
in >>userName >>localHostName >>ipAddress;
newParticipant(userName,localHostName,ipAddress);
break;
case WyParticipantLeft:
in >>userName >>localHostName;
participantLeft(userName,localHostName,time);
break;
case WyFileName:
{
in >> userName >> localHostName >> ipAddress;
QString clientAddress, fileName;
in >> clientAddress >> fileName;
hasPendingFile(userName, ipAddress, clientAddress, fileName);
break;
}
case WyRefuse:
{
in >> userName >> localHostName;
QString serverAddress;
in >> serverAddress;
QString ipAddress = getIP();
/*if(ipAddress == serverAddress)
{
server->refused();
}break;*/
}
case Image:
{
in >> userName >> localHostName >> ipAddress >> message;
ui->messageBrowser->setTextColor(Qt::blue);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman",12));
ui->messageBrowser->append("[ " +userName+" ] "+ time);
QString tempFileName;
in >> tempFileName;
//是图像文件UDP数据包,保存图片到文件夹 temp-image/下
createTempimageDir();
tempFileName = QString(("temp-image/") + tempFileName);
QImage image;
in >> image;
QImageWriter imageWrite(tempFileName);
imageWrite.setFormat(QFileInfo(tempFileName).suffix().toLatin1());
imageWrite.write(image);
qDebug() << tr("已存放至temp-image1文件夹内");
QPixmap* pic = new QPixmap(tempFileName);
int width = 100;
int newwidth = width*(pic->size().width())/(pic->size().height());
QString imgPath = QString("<img src=\"%1\" height=\"%2\" width=\"%3\" />").arg(tempFileName)
.arg(QString::number(width,10)).arg(QString::number(newwidth,10));
//"<img src=\":"+imgFileName+"\" />";
ui->messageBrowser->append(imgPath);
//continue;
}break;
}
}
}
// 处理新用户加入
void WyWidget::newParticipant(QString userName, QString localHostName, QString ipAddress)
{
bool isEmpty = ui->userTableWidget->findItems(localHostName, Qt::MatchExactly).isEmpty();
if (isEmpty) {
QTableWidgetItem *user = new QTableWidgetItem(userName);
QTableWidgetItem *host = new QTableWidgetItem(localHostName);
QTableWidgetItem *ip = new QTableWidgetItem(ipAddress);
ui->userTableWidget->insertRow(0);
ui->userTableWidget->setItem(0,0,user);
ui->userTableWidget->setItem(0,1,host);
ui->userTableWidget->setItem(0,2,ip);
ui->messageBrowser->setTextColor(Qt::gray);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman",10));
ui->messageBrowser->append(tr("%1 在线!").arg(userName));
ui->userNumLabel->setText(tr("在线人数:%1").arg(ui->userTableWidget->rowCount()));
sendMessage(WyNewParticipant);
}
}
// 处理用户离开
void WyWidget::participantLeft(QString userName, QString localHostName, QString time)
{
int rowNum = ui->userTableWidget->findItems(localHostName, Qt::MatchExactly).first()->row();
ui->userTableWidget->removeRow(rowNum);
ui->messageBrowser->setTextColor(Qt::gray);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman", 10));
ui->messageBrowser->append(tr("%1 于 %2 离开!").arg(userName).arg(time));
ui->userNumLabel->setText(tr("在线人数:%1").arg(ui->userTableWidget->rowCount()));
}
// 获取ip地址
QString WyWidget::getIP()
{
// QList<QHostAddress> list = QNetworkInterface::allAddresses();
// foreach (QHostAddress address, list) {
// if(address.protocol() == QAbstractSocket::IPv4Protocol)
// return address.toString();
// }
// return 0;
QString localHostName = QHostInfo::localHostName();
QHostInfo info = QHostInfo::fromName(localHostName);
foreach(QHostAddress address, info.addresses())
{
if(address.protocol() == QAbstractSocket::IPv4Protocol)
return address.toString();
}
return NULL;
}
// 获取用户名
QString WyWidget::getUserName()
{
QStringList envVariables;
envVariables << "USERNAME.*" << "USER.*" << "USERDOMAIN.*"
<< "HOSTNAME.*" << "DOMAINNAME.*";
QStringList environment = QProcess::systemEnvironment();
foreach (QString string, envVariables) {
int index = environment.indexOf(QRegExp(string));
if (index != -1) {
QStringList stringList = environment.at(index).split('=');
if (stringList.size() == 2) {
return stringList.at(1);
break;
}
}
}
return "unknown";
}
// 获得要发送的消息
QString WyWidget::getMessage()
{
QString msg = ui->messageTextEdit->toHtml();
ui->messageTextEdit->clear();
ui->messageTextEdit->setFocus();
return msg;
}
// 发送消息
void WyWidget::on_sendButton_clicked()
{
if (ui->messageTextEdit->toPlainText() == "") {
QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok);
return;
}
QString msg = ui->messageTextEdit->toHtml();
if(msg.contains("<img src=")){
if(msg.contains("<img src=\":/images")){
sendMessage(WyMessage);
}else{
sendMessage(Image);
}
}else{
sendMessage(WyMessage);
}
}
//更改字体族
void WyWidget::on_fontComboBox_currentFontChanged(const QFont &f)
{
//获取了当前选择的字体,然后在消息文本中使用该字体
ui->messageTextEdit->setCurrentFont(f);
ui->messageTextEdit->setFocus();
}
//更改字体大小
void WyWidget::on_sizeComboBox_currentIndexChanged(const QString &arg1)
{
ui->messageTextEdit->setFontPointSize(arg1.toDouble());
ui->messageTextEdit->setFocus();
}
//字体加粗
void WyWidget::on_boldToolBtn_clicked(bool checked)
{
if(checked)
ui->messageTextEdit->setFontWeight((QFont::Bold));
else
ui->messageTextEdit->setFontWeight(QFont::Normal);
ui->messageTextEdit->setFocus();
}
//字体倾斜
void WyWidget::on_italicToolBtn_clicked(bool checked)
{
ui->messageTextEdit->setFontItalic(checked);
ui->messageTextEdit->setFocus();
}
//下划线
void WyWidget::on_underlineToolBtn_clicked(bool checked)
{
ui->messageTextEdit->setFontUnderline(checked);
ui->messageTextEdit->setFocus();
}
//颜色设置
void WyWidget::on_colorToolBtn_clicked()
{
color = QColorDialog::getColor(color, this);
if (color.isValid()) {
ui->messageTextEdit->setTextColor(color);
ui->messageTextEdit->setFocus();
}
}
//保存聊天记录
void WyWidget::on_saveToolBtn_clicked()
{
if (ui->messageBrowser->document()->isEmpty()) {
QMessageBox::warning(0, tr("警告"), tr("聊天记录为空,无法保存!"), QMessageBox::Ok);
} else {
QString fileName = QFileDialog::getSaveFileName(this,
tr("保存聊天记录"), tr("聊天记录"), tr("文本(*.txt);;All File(*.*)"));
if(!fileName.isEmpty())
saveFile(fileName);
}
}
//保存聊天记录
bool WyWidget::saveFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("保存文件"),
tr("无法保存文件 %1:\n %2").arg(fileName)
.arg(file.errorString()));
return false;
}
QTextStream out(&file);
out << ui->messageBrowser->toPlainText();
return true;
}
//清空聊天记录
void WyWidget::on_clearToolBtn_clicked()
{
ui->messageBrowser->clear();
}
//关闭程序的时候,发送用户离开的广播,让其他端点的用户在用户列表中删除其用户
void WyWidget::closeEvent(QCloseEvent *e)
{
sendMessage(WyParticipantLeft);
QWidget::closeEvent(e);
}
//获取要发送的文件名
void WyWidget::getFileName(QString name)
{
fileName = name;
sendMessage(WyFileName);
}
//传输文件按钮
void WyWidget::on_sendToolBtn_clicked()
{
if(ui->userTableWidget->selectedItems().isEmpty())
{
QMessageBox::warning(0, tr("选择用户"),
tr("请先从用户列表选择要传送的用户!"), QMessageBox::Ok);
return;
}
server->show();
server->initServer();
}
//是否接收文件
void WyWidget::hasPendingFile(QString userName, QString serverAddress,
QString clientAddress, QString fileName)
{
QString ipAddress = getIP();
if(ipAddress == clientAddress)
{
int btn = QMessageBox::information(this,tr("接受文件"),
tr("来自%1(%2)的文件:%3,是否接收?")
.arg(userName).arg(serverAddress).arg(fileName),
QMessageBox::Yes,QMessageBox::No);
if (btn == QMessageBox::Yes) {
QString name = QFileDialog::getSaveFileName(0,tr("保存文件"),fileName);
if(!name.isEmpty())
{
WyTcpClient *client = new WyTcpClient(this);
client->setFileName(name);
client->setHostAddress(QHostAddress(serverAddress));
client->show();
}
} else {
sendMessage(WyRefuse, serverAddress);
}
}
}
//表情添加按钮的实现
void WyWidget::on_biaoqing_Button_clicked()
{
QString str;
WyFace *face = new WyFace();
face->show();
QString pth = "<img src=\":";
face->exec();
str = face->getPth();
qDebug()<<str;
pth += str;
//delete face;
pth += "\" />";
qDebug()<<pth;
const QString lujing = pth;
ui->messageTextEdit->append(lujing);
}
void WyWidget::on_tupian_clicked()
{
//实现图像同步的策略为,先复制图像到自己和别人机器的 temp-image/ 下,然后在数据包中加入HTML的显示本地图像代码
QString image = QFileDialog::getOpenFileName(this, tr("打开图片"),QDir::currentPath(), tr("Images (*.png *.bmp *.jpg)"));
imageName = image;
createTempimageDir();
QFile::copy(image, QString("temp-image/") + QFileInfo(image).fileName());
if (image.isEmpty())
{
return;
}
QPixmap* pic = new QPixmap(image);
int width = 100;
int newwidth = width*(pic->size().width())/(pic->size().height());
QString imgPath = QString("<img src=\"%1\" height=\"%2\" width=\"%3\" />").arg(image)
.arg(QString::number(width,10)).arg(QString::number(newwidth,10));
//"<img src=\":"+imgFileName+"\" />";
ui->messageTextEdit->append(imgPath);
//ui->messageTextEdit->append("<img src='temp-image/" + QFileInfo(image).fileName() + "' />");
}
void WyWidget::createTempimageDir()
{
QDir *temp = new QDir;
bool exist = temp->exists("temp-image");
if(exist)
return;
else
{
temp->mkdir("temp-image");
}
}
| [
"[email protected]"
] | |
1b6568a08e44ec57534da8b78ba4292aa511fac8 | 08bdd164c174d24e69be25bf952322b84573f216 | /opencores/client/foundation classes/j2sdk-1_4_2-src-scsl/j2se/src/share/native/sun/awt/font/opentype/ArabicShaping.cpp | c01ab2281e9c7128320e4ea33a97875ca501d878 | [] | no_license | hagyhang/myforthprocessor | 1861dcabcf2aeccf0ab49791f510863d97d89a77 | 210083fe71c39fa5d92f1f1acb62392a7f77aa9e | refs/heads/master | 2021-05-28T01:42:50.538428 | 2014-07-17T14:14:33 | 2014-07-17T14:14:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,681 | cpp | /*
* @(#)ArabicShaping.cpp 1.15 01/10/09
*
* (C) Copyright IBM Corp. 1998, 1999, 2000 - All Rights Reserved
*
*/
#include "LETypes.h"
#include "OpenTypeTables.h"
#include "ArabicShaping.h"
enum {
_c_ = ArabicShaping::ST_NOSHAPE_DUAL,
_d_ = ArabicShaping::ST_DUAL,
_n_ = ArabicShaping::ST_NONE,
_r_ = ArabicShaping::ST_RIGHT,
_t_ = ArabicShaping::ST_TRANSPARENT,
_x_ = ArabicShaping::ST_NOSHAPE_NONE
};
const ArabicShaping::ShapeType ArabicShaping::shapeTypes[] =
{
_n_, _r_, _r_, _r_, _r_, _d_, _r_, _d_, _r_, _d_, _d_, _d_, _d_, _d_, _r_, _r_, // 0x621 - 0x630
_r_, _r_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _x_, _x_, _x_, _x_, _x_, _c_, // 0x631 - 0x640
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _r_, _d_, _d_, _t_, _t_, _t_, _t_, _t_, _t_, // 0x641 - 0x650
_t_, _t_, _t_, _t_, _t_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _n_, // 0x651 - 0x660
_n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _x_, _x_, _t_, // 0x661 - 0x670
_r_, _r_, _r_, _x_, _r_, _r_, _r_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, // 0x671 - 0x680
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, // 0x681 - 0x690
_r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, // 0x691 - 0x6a0
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, // 0x6a1 - 0x6b0
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _x_, _x_, _d_, _d_, _d_, _d_, _d_, _x_, _r_, // 0x6b1 - 0x6c0
_d_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _d_, _r_, _d_, _x_, _d_, // 0x6c1 - 0x6d0
_d_, _r_, _r_, _x_, _x_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, // 0x6d1 - 0x6e0
_t_, _t_, _t_, _t_, _n_, _n_, _t_, _t_, _n_, _t_, _t_, _t_, _t_, _x_, _x_, _n_, // 0x6e1 - 0x6f0
_n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _x_, _x_, _x_, _x_, _x_, _x_ // 0x6f1 - 0x6ff
};
/*
shaping array holds types for arabic chars between 0621 and 0700
other values are either unshaped, or transparent if a mark or format
code, except for format codes 200c (zero-width non-joiner) and 200d
(dual-width joiner) which are both unshaped and non_joining or
dual-joining, respectively.
*/
ArabicShaping::ShapeType ArabicShaping::getShapeType(LEUnicode c)
{
if (c >= 0x0621 && c <= 0x206f) {
if (c < 0x0700) {
return shapeTypes[c - 0x0621];
} else if (c == 0x200c) { // ZWNJ
return ST_NOSHAPE_NONE;
} else if (c == 0x200d) { // ZWJ
return ST_NOSHAPE_DUAL;
} else if (c >= 0x202a && c <= 0x202e) { // LRE - RLO
return ST_TRANSPARENT;
} else if (c >= 0x206a && c <= 0x206f) { // Inhibit Symmetric Swapping - Nominal Digit Shapes
return ST_TRANSPARENT;
}
}
return ST_NOSHAPE_NONE;
}
const LETag GlyphShaper::isolFeatureTag = 0x69736F6C; // 'isol'
const LETag GlyphShaper::initFeatureTag = 0x696E6974; // 'init'
const LETag GlyphShaper::mediFeatureTag = 0x6D656469; // 'medi'
const LETag GlyphShaper::finaFeatureTag = 0x66696E61; // 'fina'
const LETag GlyphShaper::ligaFeatureTag = 0x6C696761; // 'liga'
const LETag GlyphShaper::msetFeatureTag = 0x6D736574; // 'mset'
const LETag GlyphShaper::markFeatureTag = 0x6D61726B; // 'mark'
const LETag GlyphShaper::emptyTag = 0x00000000; // ''
const LETag GlyphShaper::tagArray[] =
{
isolFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag,
finaFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag,
initFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag,
mediFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag
};
#define TAGS_PER_GLYPH (sizeof GlyphShaper::tagArray / sizeof(LETag) / 4)
void ArabicShaping::shape(const LEUnicode *chars, le_int32 offset, le_int32 charCount, le_int32 charMax,
le_bool rightToLeft, Shaper &shaper)
{
// iterate in logical order, store tags in visible order
//
// the effective right char is the most recently encountered
// non-transparent char
//
// four boolean states:
// the effective right char shapes
// the effective right char causes left shaping
// the current char shapes
// the current char causes right shaping
//
// if both cause shaping, then
// shaper.shape(errout, 2) (isolate to initial, or final to medial)
// shaper.shape(out, 1) (isolate to final)
ShapeType rightType = ST_NOSHAPE_NONE, leftType = ST_NOSHAPE_NONE;
le_int32 i;
for (i = offset - 1; i >= 0; i -= 1) {
rightType = getShapeType(chars[i]);
if (rightType != ST_TRANSPARENT) {
break;
}
}
for (i = offset + charCount; i < charMax; i += 1) {
leftType = getShapeType(chars[i]);
if (leftType != ST_TRANSPARENT) {
break;
}
}
// erout is effective right logical index
le_int32 erout = -1;
le_bool rightShapes = false;
le_bool rightCauses = (rightType & MASK_SHAPE_LEFT) != 0;
le_int32 in, e, out = 0, dir = 1;
if (rightToLeft) {
out = charCount - 1;
erout = charCount;
dir = -1;
}
for (in = offset, e = offset + charCount; in < e; in += 1, out += dir) {
LEUnicode c = chars[in];
ShapeType t = getShapeType(c);
shaper.init(c, out, (t & (MASK_TRANSPARENT | MASK_NOSHAPE)) == 0);
if ((t & MASK_TRANSPARENT) != 0) {
continue;
}
le_bool curShapes = (t & MASK_NOSHAPE) == 0;
le_bool curCauses = (t & MASK_SHAPE_RIGHT) != 0;
if (rightCauses && curCauses) {
if (rightShapes) {
shaper.shape(erout, 2);
}
if (curShapes) {
shaper.shape(out, 1);
}
}
rightShapes = curShapes;
rightCauses = (t & MASK_SHAPE_LEFT) != 0;
erout = out;
}
if (rightShapes && rightCauses && (leftType & MASK_SHAPE_RIGHT) != 0) {
shaper.shape(erout, 2);
}
}
GlyphShaper::GlyphShaper(const LETag **outputTags)
{
charTags = outputTags;
}
GlyphShaper::~GlyphShaper()
{
// nothing to do
}
void GlyphShaper::init(LEUnicode ch, le_int32 outIndex, le_bool isloate)
{
charTags[outIndex] = tagArray;
}
void GlyphShaper::shape(le_int32 outIndex, le_int32 shapeOffset)
{
charTags[outIndex] = &charTags[outIndex][TAGS_PER_GLYPH * shapeOffset];
}
CharShaper::CharShaper(LEUnicode *outputChars)
{
chars = outputChars;
}
CharShaper::~CharShaper()
{
// nothing to do
}
void CharShaper::init(LEUnicode ch, le_int32 outIndex, le_bool isloate)
{
if (isloate) {
chars[outIndex] = getToIsolateShape(ch);
} else {
chars[outIndex] = ch;
}
}
void CharShaper::shape(le_int32 outIndex, le_int32 shapeOffset)
{
chars[outIndex] += (LEUnicode) shapeOffset;
}
LEUnicode CharShaper::isolateShapes[] =
{
0xfe80, 0xfe81, 0xfe83, 0xfe85, 0xfe87, 0xfe89, 0xfe8d, 0xfe8f, 0xfe93, 0xfe95,
0xfe99, 0xfe9d, 0xfea1, 0xfea5, 0xfea9, 0xfeab, 0xfead, 0xfeaf, 0xfeb1, 0xfeb5,
0xfeb9, 0xfebd, 0xfec1, 0xfec5, 0xfec9, 0xfecd, 0x063b, 0x063c, 0x063d, 0x063e,
0x063f, 0x0640, 0xfed1, 0xfed5, 0xfed9, 0xfedd, 0xfee1, 0xfee5, 0xfee9, 0xfeed,
0xfeef, 0xfef1, 0x064b, 0x064c, 0x064d, 0x064e, 0x064f, 0x0650, 0x0651, 0x0652,
0x0653, 0x0654, 0x0655, 0x0656, 0x0657, 0x0658, 0x0659, 0x065a, 0x065b, 0x065c,
0x065d, 0x065e, 0x065f, 0x0660, 0x0661, 0x0662, 0x0663, 0x0664, 0x0665, 0x0666,
0x0667, 0x0668, 0x0669, 0x066a, 0x066b, 0x066c, 0x066d, 0x066e, 0x066f, 0x0670,
0xfb50, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0xfbdd, 0x0678, 0xfb66, 0xfb5e,
0xfb52, 0x067c, 0x067d, 0xfb56, 0xfb62, 0xfb5a, 0x0681, 0x0682, 0xfb76, 0xfb72,
0x0685, 0xfb7a, 0xfb7e, 0xfb88, 0x0689, 0x068a, 0x068b, 0xfb84, 0xfb82, 0xfb86,
0x068f, 0x0690, 0xfb8c, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0xfb8a,
0x0699, 0x069a, 0x069b, 0x069c, 0x069d, 0x069e, 0x069f, 0x06a0, 0x06a1, 0x06a2,
0x06a3, 0xfb6a, 0x06a5, 0xfb6e, 0x06a7, 0x06a8, 0xfb8e, 0x06aa, 0x06ab, 0x06ac,
0xfbd3, 0x06ae, 0xfb92, 0x06b0, 0xfb9a, 0x06b2, 0xfb96, 0x06b4, 0x06b5, 0x06b6,
0x06b7, 0x06b8, 0x06b9, 0xfb9e, 0xfba0, 0x06bc, 0x06bd, 0xfbaa, 0x06bf, 0xfba4,
0xfba6, 0x06c2, 0x06c3, 0x06c4, 0xfbe0, 0xfbd9, 0xfbd7, 0xfbdb, 0xfbe2, 0x06ca,
0xfbde, 0xfbfc, 0x06cd, 0x06ce, 0x06cf, 0xfbe4, 0x06d1, 0xfbae, 0xfbb0
};
LEUnicode CharShaper::getToIsolateShape(LEUnicode ch)
{
if (ch < 0x0621 || ch > 0x06d3) {
return ch;
}
return isolateShapes[ch - 0x0621];
}
| [
"[email protected]"
] | |
d681b826277d421d4daedd46b0a8443bf01cd154 | da2fac467da6cb1b0cc420d02f72b30bfd87eefc | /semantics-parser/main.cc | 0efe7b97b5f6abfc5ca4ecb5d0dc91bb16dbdb12 | [] | no_license | dyninst/tools | f500ba1b3900345fc2fb760db7710232be7a7a37 | 801dc122b706834cefa673ad15579c179cb2943c | refs/heads/master | 2023-07-31T22:36:46.141775 | 2023-03-15T04:22:11 | 2023-03-15T04:22:11 | 58,003,524 | 27 | 18 | null | 2023-03-15T04:22:12 | 2016-05-03T21:44:32 | C | UTF-8 | C++ | false | false | 6,236 | cc | /*
* See the dyninst/COPYRIGHT file for copyright information.
*
* We provide the Paradyn Tools (below described as "Paradyn")
* on an AS IS basis, and do not warrant its validity or performance.
* We reserve the right to update, modify, or discontinue this
* software at any time. We shall have no obligation to supply such
* updates or modifications or any other form of support to you.
*
* By your use of Paradyn, you understand and agree that we (or any
* other person or entity with proprietary rights in Paradyn) are
* under no obligation to provide either maintenance services,
* update services, notices of latent defects, or correction of
* defects for Paradyn.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "driver.h"
#include "scanner.h"
#include <sys/stat.h>
bool file_exists(const char *fname) {
struct stat buf;
return stat(fname, &buf) == 0;
}
int main() {
/*
* List of files that need to be parsed. Currently roughly organized categorically.
*
* This would ideally contain all files under ISA_ps. However, currently, only a subset is included since I wanted to be selective about
* what to parse. It is possible to just include all files and later choose which ones to parse - shouldn't be too hard to implement; this
* solution works fine though for now.
*
* Even in this subset, comment the ones you don't need to filter parsing further.
*/
const char *fnames[] = {/*"add_addsub_imm", "adds_addsub_imm", "sub_addsub_imm", "subs_addsub_imm",
"add_addsub_ext", "adds_addsub_ext", "sub_addsub_ext", "subs_addsub_ext",
"add_addsub_shift", "adds_addsub_shift", "sub_addsub_shift", "subs_addsub_shift",
"adc", "adcs", "adr", "adrp", "tbz", "tbnz", "b_uncond", "b_cond", "br", "blr", "bl", "cbz", "cbnz",
"cmp_subs_addsub_imm", "cmp_subs_addsub_ext", "cmp_subs_addsub_shift",
"cmn_adds_addsub_imm", "cmn_adds_addsub_ext", "cmn_adds_addsub_shift",
"ccmn_reg", "ccmn_imm",
"ldr_imm_gen", "str_imm_gen", "ldrb_imm", "strb_imm", "ldrh_imm", "ldrsb_imm", "ldrsh_imm", "ldrsw_imm", "strh_imm",
"ldr_reg_gen", "ldrb_reg", "ldrh_reg", "ldrsb_reg", "ldrsh_reg", "ldrsw_reg", "str_reg_gen", "strb_reg", "strh_reg",
"ldr_lit_gen", "ldrsw_lit",
"ubfm", "uxtb_ubfm", "uxth_ubfm", "ubfiz_ubfm", "ubfx_ubfm", "sbfm", "sxth_sbfm", "sxtb_sbfm", "sbfiz_sbfm", "sbfx_sbfm", "sxtw_sbfm",
"movz", "mov_movz", "movn", "mov_movn", "movk",
"orr_log_shift", "mov_orr_log_shift", "mov_orr_log_imm", "orn_log_shift", "orr_log_imm",
"and_log_imm", "and_log_shift", "ands_log_imm", "ands_log_shift", "eor_log_shift", "eor_log_imm", "eon",
"lsl_ubfm", "lsr_ubfm", "asr_sbfm",
"bfm", "bfxil_bfm", "bfi_bfm", "bic_log_shift", "bics", "stp_gen", "ldp_gen", "stnp_gen", "ldpsw", "ldnp_gen", "stnp_gen",
"ldtr", "ldtrb", "ldtrh", "ldtrsb", "ldtrsh", "sttr", "sttrb", "sttrh",
"ldur_gen", "ldurb", "ldurh", "ldursb", "ldursh", "ldursw", "sturb", "sturh", "stur_gen",
"asr_asrv", "asrv", "lsl_lslv", "lslv", "lsr_lsrv", "lsrv", "ror_rorv", "rorv"
"tst_ands_log_imm", "tst_ands_log_shift", "sbc", "sbcs", "ngc_sbc", "ngcs_sbcs", "neg_sub_addsub_shift", "negs_subs_addsub_shift",
"mvn_orn_log_shift", "mov_add_addsub_imm",
"csinv", "csinc", "csneg", "csel",
"cls_int", "clz_int",
"madd", "msub", "mneg_msub", "mul_madd", "smaddl", "smsubl", "smnegl_smsubl","smulh", "smull_smaddl","umaddl", "umsubl", "umnegl_umsubl", "umulh", "umull_umaddl",
"ldar", "ldarb", "ldarh", "stlr", "stlrb", "stlrh",
"udiv", */"sdsiv"};
/** Root folder containing the pseudocode files created by the pseudocode extractor script. Change as necessary. */
std::string pcode_files_dir("/u/s/s/ssunny/dev-home/dyninst/dyninst-code/instructionAPI/ISA_ps/");
/** Iterate over all files in the list above and parse them. */
Dyninst_aarch64::Driver driver;
std::map<const char *, bool> notExists;
for(int fidx = 0; fidx < sizeof(fnames)/sizeof(char *); fidx++) {
if(file_exists(fnames[fidx]))
driver.pcode_parse(pcode_files_dir + std::string(fnames[fidx]));
else
notExists[fnames[fidx]] = true;
}
/** For each file above, output the iproc_set statement for the corresponding instruction.
* This needs to go into the iproc_init method of the Dispatcher. */
for(int idx = 0; idx < sizeof(fnames)/sizeof(char *); idx++)
if(!notExists.count(fnames[idx]))
std::cout<<"iproc_set (rose_aarch64_op_"<<fnames[idx]<<", new ARM64::IP_"<<fnames[idx]<<"_execute);"<<std::endl;
if(notExists.size()) {
std::cout<<std::endl;
std::cout<<"### Some files not found:"<<std::endl;
for (std::map<const char *, bool>::iterator itr = notExists.begin(); itr != notExists.end(); itr++) {
std::cout << "Could not find file " << itr->first << "." << std::endl;
}
}
return 0;
}
| [
"[email protected]"
] | |
1628e7dc364729c2566d8ce363d2cdef4c28cad6 | 8eeef5237d7b5e2a6322bdbea667a4cdaaa7ee0d | /Engine/Code/Engine/Math/Plane2.hpp | ec1943bb6eea32e1a1032b137d1ab9a6aacfb7c0 | [
"MIT"
] | permissive | sam830917/TenNenDemon | 28a07f066b0d627026bd96859e2e71a3547938e2 | a5f60007b73cccc6af8675c7f3dec597008dfdb4 | refs/heads/main | 2023-03-19T00:34:48.742275 | 2021-03-12T01:36:54 | 2021-03-12T01:36:54 | 282,079,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | hpp | #pragma once
#include "Engine/Math/Vec2.hpp"
#include "Engine/Math/MathUtils.hpp"
class Plane2
{
Vec2 normal;
float distance;
public:
// methods
Plane2()
: normal( 0, 1 )
, distance( 0 ) {}
Plane2( Vec2 n, Vec2 pointOnPlane )
: normal( n )
, distance( DotProduct2D( pointOnPlane, n ) ) {}
bool GetPointIsInFront( Vec2 point ) const;
float GetSignedDistanceFromPlane( Vec2 point ) const;
}; | [
"[email protected]"
] | |
24748b0bd213c5e46c480b492502be9f6aa0efb2 | 7ccf448165ef01b8c70fc084e2c767a6971c1a5e | /lexis_syntax.cpp | 2aa64f711ea8dcedbe778c1791bd7fb4e6e2ecb1 | [] | no_license | kolomeytsev/game-manager | a650a12d3e19790f7bf64d45e7d0a1a3ea560789 | 21634484e1533771374881152db980c5e30db14e | refs/heads/master | 2021-05-31T19:04:38.670128 | 2016-03-27T11:04:56 | 2016-03-27T11:04:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,816 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <typeinfo>
enum type_of_lex
{ keyword, function, function_with_param, function_without_param,
label, variable, number, string, assignment, separator,
error_funct, error_keyword, error };
enum type_of_state { H, N, F, L, V, K, A, S, ERR };
struct Lexeme_list {
int num_str;
type_of_lex type;
char* lex;
struct Lexeme_list* next;
};
class PolizElem;
struct PolizItem {
PolizElem* elem;
struct PolizItem* next;
};
struct StructVar {
char *name;
int value;
};
struct VarTable { // table->elem->name
StructVar* elem;
struct VarTable* next;
};
struct LabelTable {
char* name;
PolizItem* pointer;
struct LabelTable* next;
};
class PolizEx {
};
class PolizExNotInt: public PolizEx {
public:
PolizExNotInt(PolizElem *elem) {}
};
class PolizExNotLabel: public PolizEx {
public:
PolizExNotLabel(PolizElem *elem) {}
};
class PolizExNotConst: public PolizEx {
public:
PolizExNotConst(PolizElem *elem) {}
};
class PolizElem {
public:
virtual ~PolizElem() {}
virtual void Evaluate(PolizItem **stack,
PolizItem **cur_cmd) const = 0;
protected:
static void Push(PolizItem **stack, PolizElem *elem);
static PolizElem* Pop(PolizItem **stack);
};
void PolizElem::Push(PolizItem **stack, PolizElem *elem)
{
//printf("push\n");
PolizItem* tmp = new PolizItem;
tmp->elem = elem;
tmp->next = *stack;
*stack = tmp;
}
PolizElem* PolizElem::Pop(PolizItem **stack)
{
//printf("pop\n");
PolizItem* tmp = *stack;
PolizElem* tmp_elem = tmp->elem;
*stack = (*stack)->next;
delete tmp;
return tmp_elem;
}
class PolizConst: public PolizElem {
public:
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
Push(stack, Clone());
*cur_cmd = (*cur_cmd)->next;
}
virtual PolizElem* Clone() const = 0;
};
class PolizInt: public PolizConst {
int value;
public:
PolizInt(int a) { value = a; }
virtual ~PolizInt() {}
virtual PolizElem* Clone()const {
return new PolizInt(value);
}
int Get() const {
return value;
}
};
class PolizString: public PolizConst {
char *str;
public:
PolizString(char *s) { str = s; }
virtual ~PolizString() { delete str;}
virtual PolizElem* Clone() const {
int len;
len = strlen(str);
char *s = new char[len+1];
for (int i = 0; i < len + 1; i++)
s[i] = str[i];
return new PolizString(s);
}
char *Get() const {
return str;
}
};
class PolizVarAddr: public PolizConst {
VarTable* addr;
public:
PolizVarAddr(VarTable* a) { addr = a; }
virtual ~PolizVarAddr() {}
virtual PolizElem* Clone() const {
return new PolizVarAddr(addr);
}
VarTable* Get() const {
return addr;
}
};
class PolizLabel: public PolizConst {
char *name;
PolizItem* value;
public:
PolizLabel(char *s, PolizItem* a) {
name = s;
value = a;
}
virtual ~PolizLabel() {}
virtual PolizElem* Clone() const {
return new PolizLabel(name, value);
}
PolizItem* Get() const {
return value;
}
char* Get_name() const {
return name;
}
void set_addr(PolizItem *ptr) {
value = ptr;
}
};
class PolizFunction: public PolizElem {
public:
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
PolizElem *res = EvaluateFun(stack);
if (res)
Push(stack, res);
*cur_cmd = (*cur_cmd)->next;
}
virtual PolizElem* EvaluateFun(PolizItem **stack) const = 0;
};
class PolizVar: public PolizFunction {
public:
};
class PolizSell: public PolizFunction {
public:
PolizSell() {}
virtual ~PolizSell() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
printf("sell %d, %d\n", i2->Get(), i1->Get());
delete operand1;
delete operand2;
return 0;
}
};
class PolizBuy: public PolizFunction {
public:
PolizBuy() {}
virtual ~PolizBuy() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
printf("buy %d, %d\n", i2->Get(), i1->Get());
delete operand1;
delete operand2;
return 0;
}
};
class PolizProd: public PolizFunction {
public:
PolizProd() {}
virtual ~PolizProd() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
printf("prod %d\n", i1->Get());
delete operand1;
return 0;
}
};
class PolizBuild: public PolizFunction {
public:
PolizBuild() {}
virtual ~PolizBuild() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
printf("build %d\n", i1->Get());
delete operand1;
return 0;
}
};
class PolizEndTurn: public PolizFunction {
public:
PolizEndTurn() {}
virtual ~PolizEndTurn() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
printf("end turn\n");
return 0;
}
};
class PolizPrint: public PolizFunction {
public:
PolizPrint() {}
virtual ~PolizPrint() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) {
PolizString *i1 = dynamic_cast<PolizString*>(operand1);
if (!i1) throw PolizExNotConst(operand1);
printf("<%s>\n", i1->Get());
} else {
printf("<%d>\n", i1->Get());
}
delete operand1;
return 0;
}
};
class PolizFunNOP: public PolizFunction {
int a;
public:
PolizFunNOP() { a = 505; }
virtual ~PolizFunNOP() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
return 0;
}
};
class PolizFunPlus: public PolizFunction {
public:
PolizFunPlus() {}
virtual ~PolizFunPlus() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i1->Get() + i2->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunMinus: public PolizFunction {
public:
PolizFunMinus() {}
virtual ~PolizFunMinus() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i2->Get() - i1->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunMult: public PolizFunction {
public:
PolizFunMult() {}
virtual ~PolizFunMult() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i1->Get() * i2->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunDiv: public PolizFunction {
public:
PolizFunDiv() {}
virtual ~PolizFunDiv() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i2->Get()/i1->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunMod: public PolizFunction {
public:
PolizFunMod() {}
virtual ~PolizFunMod() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i2->Get()%i1->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunGreater: public PolizFunction {
public:
PolizFunGreater() {}
virtual ~PolizFunGreater() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
bool t = i2->Get() > i1->Get();
int res;
if (t) res = 1;
else res = 0;
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunLess: public PolizFunction {
public:
PolizFunLess() {}
virtual ~PolizFunLess() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
bool t = i2->Get() < i1->Get();
int res;
if (t) res = 1;
else res = 0;
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunEqual: public PolizFunction {
public:
PolizFunEqual() {}
virtual ~PolizFunEqual() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
bool t = i2->Get() == i1->Get();
int res;
if (t) res = 1;
else res = 0;
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
void lprint(PolizItem* lst);
class PolizOpGo: public PolizElem {
public:
PolizOpGo() {}
virtual ~PolizOpGo() {}
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
printf("OpGO!\n");
PolizElem *operand1 = Pop(stack);
PolizLabel *lab = dynamic_cast<PolizLabel*>(operand1);
if (!lab) throw PolizExNotLabel(operand1);
PolizItem *addr = lab->Get();
//lprint(addr->next); //print string
*cur_cmd = addr;
delete operand1;
}
};
class PolizOpGoFalse: public PolizElem {
public:
PolizOpGoFalse() {}
virtual ~PolizOpGoFalse() {}
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
PolizElem *operand1 = Pop(stack);
PolizLabel *lab = dynamic_cast<PolizLabel*>(operand1);
if (!lab) throw PolizExNotLabel(operand1);
PolizItem *addr = lab->Get();
PolizElem *operand2 = Pop(stack);
PolizInt *val = dynamic_cast<PolizInt*>(operand2);
if (!val) throw PolizExNotInt(operand2);
if (val==0)
*cur_cmd = addr;
else
*cur_cmd = (*cur_cmd)->next;
delete operand1;
delete operand2;
}
};
class SyntaxAnalizer {
Lexeme_list *cur;
Lexeme_list *list;
Lexeme_list *pointer;
void S();
void assignment_statement();
void goto_statement();
void if_statement();
void game_statement();
void print_statement();
void expression();
void op1();
void ending1();
void op2();
void ending2();
void op3();
void ending3();
void funct();
void var();
void index();
void element();
void add_poliz_list(PolizElem* element) {
PolizItem *t = new PolizItem;
PolizItem *temp;
temp = poliz_list;
t->elem = element;
t->next = 0;
if (poliz_list == 0)
poliz_list = t;
else {
while (temp->next!=0)
temp = temp->next;
temp->next = t;
}
}
void add_label_list(PolizItem* p, char* s) {
LabelTable* t = new LabelTable;
LabelTable* temp;
temp = label_list;
t->name = s;
t->pointer = p;
t->next = 0;
if (label_list==0)
label_list = t;
else {
while (temp->next!=0)
temp = temp->next;
temp->next = t;
}
}
void next()
{
cur = pointer;
if ((pointer->next!=0)&&(strcmp(pointer->lex, ".")!=0))
pointer = pointer->next;
}
PolizItem* search_address(char *name);
bool is_first_label(char *name);
void add_address(PolizItem *p, char *name);
void add_address_poliz(PolizItem *p, char *name);
public:
void set_list(Lexeme_list *lst)
{
list = lst;
pointer = list;
poliz_list = 0;
label_list = 0;
var_list = 0;
}
void analyze();
PolizItem* poliz_list;
LabelTable* label_list;
VarTable* var_list;
};
class Exeption {
char *comment;
int nstr;
char *lexeme;
public:
Exeption(const char *cmt, int num, const char *lex);
Exeption(const Exeption& other);
~Exeption();
const char *GetComment() const
{
return comment;
}
int GetNstr() const
{
return nstr;
}
const char *GetLexeme() const
{
return lexeme;
}
private:
static char *strdup(const char *str);
};
Exeption::Exeption(const char *cmt, int num, const char *lex) {
comment = strdup(cmt);
nstr = num;
lexeme = strdup(lex);
}
Exeption::Exeption(const Exeption& other) {
comment = strdup(other.comment);
nstr = other.nstr;
lexeme = strdup(other.lexeme);
}
Exeption::~Exeption() {
delete[] comment;
}
char* Exeption::strdup(const char *str) {
char *res;
res = new char [strlen(str)+1];
strcpy(res, str);
return res;
}
void SyntaxAnalizer::analyze()
{
next();
S();
if (strcmp(cur->lex, ".")!=0)
throw Exeption("dot expected", cur->num_str, cur->lex);
}
void SyntaxAnalizer::S()
{
if ((cur->type == keyword)&&
(strcmp(cur->lex, "end")!=0)) {
if (strcmp(cur->lex, "if")==0) {
next();
if_statement();
S();
}
else
if (strcmp(cur->lex, "goto")==0) {
next();
goto_statement();
PolizOpGo* tmp = new PolizOpGo;
add_poliz_list(tmp);
S();
}
else
if (strcmp(cur->lex, "print")==0) {
next();
print_statement();
PolizPrint* tmp = new PolizPrint;
add_poliz_list(tmp);
S();
}
else
if (strcmp(cur->lex, "then")!=0) {
game_statement();
S();
}
else
throw Exeption("unexpected then", cur->num_str, cur->lex);
}
else
if (cur->type == variable) {
next();
assignment_statement();
S();
}
else
if (cur->type == label) {
PolizFunNOP* tmp = new PolizFunNOP;
add_poliz_list(tmp);
PolizItem* p = poliz_list;
while (p->next!=0)
p = p->next;
if (is_first_label(cur->lex))
add_label_list(p, cur->lex);
else {
add_address(p, cur->lex);
add_address_poliz(p, cur->lex); //doesn't work FUCK!!!!!!!
}
next();
if (strcmp(cur->lex, ">")!=0)
throw Exeption("'>' expected", cur->num_str, cur->lex);
next();
S();
}
else {
if (strcmp(cur->lex, "end")!=0)
throw Exeption("end expected", cur->num_str, cur->lex);
else
next();
}
}
void SyntaxAnalizer::if_statement()
{
expression();
if (strcmp(cur->lex, "then") != 0)
throw Exeption("then expected", cur->num_str, cur->lex);
next();
S();
if (strcmp(cur->lex, ";") != 0)
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::goto_statement()
{
if (cur->type != label)
throw Exeption("label expected", cur->num_str, cur->lex);
PolizItem* item = search_address(cur->lex);
PolizLabel* tmp = new PolizLabel(cur->lex, item); // 0 if goto @m...@m>
add_poliz_list(tmp);
if (item == 0)
add_label_list(0, cur->lex);
next();
if (strcmp(cur->lex, ";") !=0 )
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::print_statement()
{
if (cur->type == string) {
PolizString* tmp = new PolizString(cur->lex);
add_poliz_list(tmp);
next();
}
else
expression();
if (strcmp(cur->lex, ";") !=0 )
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::game_statement()
{
if (strcmp(cur->lex, "endturn")==0) {
PolizEndTurn* tmp = new PolizEndTurn();
add_poliz_list(tmp);
next();
} else
if ((strcmp(cur->lex,"prod")==0)||(strcmp(cur->lex,"build")==0)) {
bool is_prod = false;
if (strcmp(cur->lex, "prod")==0) is_prod = true;
next();
expression();
if (is_prod) {
PolizProd* tmp = new PolizProd();
add_poliz_list(tmp);
} else {
PolizBuild* tmp = new PolizBuild();
add_poliz_list(tmp);
}
}
else
if ((strcmp(cur->lex,"buy")==0)||(strcmp(cur->lex,"sell")==0)) {
bool is_buy = false;
if (strcmp(cur->lex, "buy")==0) is_buy = true;
next();
expression();
expression();
if (is_buy) {
PolizBuy* tmp = new PolizBuy();
add_poliz_list(tmp);
} else {
PolizSell* tmp = new PolizSell();
add_poliz_list(tmp);
}
}
if (strcmp(cur->lex,";")!=0)
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::assignment_statement()
{
if (cur->type == assignment)
next();
else
if (strcmp(cur->lex, "[")==0) { //index
next();
expression();
if (strcmp(cur->lex, "]")!=0)
throw Exeption("']' expected", cur->num_str, cur->lex);
next();
if (cur->type != assignment)
throw Exeption("':=' expected", cur->num_str, cur->lex);
next();
}
else
throw Exeption("':=' or index expected", cur->num_str, cur->lex);
expression();
if (strcmp(cur->lex,";")!=0)
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::expression()
{
op1();
ending1();
}
void SyntaxAnalizer::op1()
{
op2();
ending2();
}
void SyntaxAnalizer::op2()
{
op3();
ending3();
}
void SyntaxAnalizer::op3()
{
if (cur->type==number) {
PolizInt* tmp = new PolizInt(atoi(cur->lex));
add_poliz_list(tmp);
next();
} else
if (cur->type==variable) {
next();
if (strcmp(cur->lex, "[")==0) { //index
next();
expression();
if (strcmp(cur->lex, "]")!=0)
throw Exeption("']' expected", cur->num_str, cur->lex);
next();
}
}
else
if (cur->type==function_without_param)
next();
else
if (cur->type==function_with_param) {
next();
if (strcmp(cur->lex, "(")!=0)
throw Exeption("'(' expected in funct",
cur->num_str, cur->lex);
next();
expression();
if (strcmp(cur->lex, ")")!=0)
throw Exeption("')' expected in funct",
cur->num_str, cur->lex);
next();
}
else
{
if (strcmp(cur->lex, "(")!=0)
throw Exeption("'(' expected", cur->num_str, cur->lex);
next();
expression();
if (strcmp(cur->lex, ")")!=0)
throw Exeption("')' expected", cur->num_str, cur->lex);
next();
}
}
void SyntaxAnalizer::ending3()
{
if ((strcmp(cur->lex, "*")==0)||
(strcmp(cur->lex, "/")==0)||
(strcmp(cur->lex, "%")==0)) {
bool is_mult = false;
bool is_div = false;
bool is_mod = false;
if (strcmp(cur->lex, "*")==0) is_mult = true;
if (strcmp(cur->lex, "/")==0) is_div = true;
if (strcmp(cur->lex, "%")==0) is_mod = true;
next();
op2();
if (is_mult) {
PolizFunMult* tmp = new PolizFunMult();
add_poliz_list(tmp);
}
if (is_div) {
PolizFunDiv* tmp = new PolizFunDiv();
add_poliz_list(tmp);
}
if (is_mod) {
PolizFunMod* tmp = new PolizFunMod();
add_poliz_list(tmp);
}
}
}
void SyntaxAnalizer::ending2()
{
if ((strcmp(cur->lex, "+")==0)||
(strcmp(cur->lex, "-")==0)) {
bool is_plus = false;
if (strcmp(cur->lex, "+")==0) is_plus = true;
next();
op1();
if (is_plus) {
PolizFunPlus* tmp = new PolizFunPlus();
add_poliz_list(tmp);
} else {
PolizFunMinus* tmp = new PolizFunMinus();
add_poliz_list(tmp);
}
}
}
void SyntaxAnalizer::ending1()
{
if ((strcmp(cur->lex, "=")==0)||
(strcmp(cur->lex, ">")==0)||
(strcmp(cur->lex, "<")==0)) {
bool is_greater = false;
bool is_less = false;
bool is_equal = false;
if (strcmp(cur->lex, ">")==0) is_greater = true;
if (strcmp(cur->lex, "<")==0) is_less = true;
if (strcmp(cur->lex, "=")==0) is_equal = true;
next();
expression();
if (is_greater) {
PolizFunGreater* tmp = new PolizFunGreater();
add_poliz_list(tmp);
}
if (is_less) {
PolizFunLess* tmp = new PolizFunLess();
add_poliz_list(tmp);
}
if (is_equal) {
PolizFunEqual* tmp = new PolizFunEqual();
add_poliz_list(tmp);
}
}
}
PolizItem* SyntaxAnalizer::search_address(char *name)
{
LabelTable* tmp = label_list;
while (tmp!=0) {
if (strcmp(tmp->name, name)==0) {
printf("found1 %s\n", tmp->name);
return tmp->pointer;
}
tmp = tmp->next;
}
return 0;
}
bool SyntaxAnalizer::is_first_label(char *name)
{
LabelTable* tmp = label_list;
while (tmp!=0) {
if (strcmp(tmp->name, name)==0) {
printf("found2 %s\n", tmp->name);
return false;
}
tmp = tmp->next;
}
printf("name first\n");
return true;
}
void SyntaxAnalizer::add_address(PolizItem *p, char *name)
{
LabelTable* tmp = label_list;
while (tmp!=0) {
if (strcmp(tmp->name, name)==0) {
printf("name was found\n");
tmp->pointer = p;
lprint(tmp->pointer);
return;
}
tmp = tmp->next;
}
}
void SyntaxAnalizer::add_address_poliz(PolizItem *p, char *name)
{
PolizItem *tmp;
while (tmp!=0) {
printf("xui\n");
PolizLabel *ptr = dynamic_cast<PolizLabel*>(tmp->elem);
if (ptr) {
printf("xui2\n");
if (strcmp(ptr->Get_name(), name)==0)
ptr->set_addr(p);
}
tmp = tmp->next;
}
}
class Executer {
PolizItem* stack;
PolizItem* prog;
public:
Executer(PolizItem *lst) {
prog = lst;
stack = 0;
}
void execute();
};
void lprint(PolizItem* lst)
{
while (lst!=0) {
PolizPrint* p2 = dynamic_cast<PolizPrint*>(lst->elem);
if (p2) printf("print\n");
PolizString* p1 = dynamic_cast<PolizString*>(lst->elem);
if (p1) printf("string: %s\n", p1->Get());
PolizInt* p3 = dynamic_cast<PolizInt*>(lst->elem);
if (p3) printf("int: %d\n", p3->Get());
PolizEndTurn* p4 = dynamic_cast<PolizEndTurn*>(lst->elem);
if (p4) printf("end_turn\n");
PolizBuild* p5 = dynamic_cast<PolizBuild*>(lst->elem);
if (p5) printf("build\n");
PolizProd* p6 = dynamic_cast<PolizProd*>(lst->elem);
if (p6) printf("prod\n");
PolizBuy* p7 = dynamic_cast<PolizBuy*>(lst->elem);
if (p7) printf("buy\n");
PolizSell* p8 = dynamic_cast<PolizSell*>(lst->elem);
if (p8) printf("sell\n");
PolizFunPlus* p9 = dynamic_cast<PolizFunPlus*>(lst->elem);
if (p9) printf("+\n");
PolizFunMinus* p10 = dynamic_cast<PolizFunMinus*>(lst->elem);
if (p10) printf("-\n");
PolizFunMult* p11 = dynamic_cast<PolizFunMult*>(lst->elem);
if (p11) printf("*\n");
PolizFunDiv* p12 = dynamic_cast<PolizFunDiv*>(lst->elem);
if (p12) printf("/\n");
PolizFunMod* p13 = dynamic_cast<PolizFunMod*>(lst->elem);
if (p13) printf("mod\n");
PolizFunGreater* p14= dynamic_cast<PolizFunGreater*>(lst->elem);
if (p14) printf(">\n");
PolizFunLess* p15= dynamic_cast<PolizFunLess*>(lst->elem);
if (p15) printf("<\n");
PolizFunEqual* p16= dynamic_cast<PolizFunEqual*>(lst->elem);
if (p16) printf("=\n");
PolizFunNOP* p17 = dynamic_cast<PolizFunNOP*>(lst->elem);
if (p17) printf("NOP\n");
PolizOpGo* p18 = dynamic_cast<PolizOpGo*>(lst->elem);
if (p18) printf("goto\n");
PolizLabel* p19 = dynamic_cast<PolizLabel*>(lst->elem);
if (p19) printf("label: %s\n", p19->Get_name());
lst = lst->next;
}
printf("\n");
}
void delete_poliz_list(PolizItem* lst)
{
if (lst!=0) {
delete_poliz_list(lst->next);
delete lst->elem;
delete lst;
}
}
void print_table_list(LabelTable *lst)
{
int t =0;
while (lst!=0) {
printf("label: %s\n", lst->name);
if (t==0) {
PolizInt* p5 = dynamic_cast<PolizInt*>(lst->pointer->next->elem);
if (p5) printf("label->next -> int\n");
}
t = 1;
lst = lst->next;
}
}
void Executer::execute() {
//lprint(prog);
while (prog!=0) {
prog->elem->Evaluate(&stack, &prog);
}
}
int main()
{
Automat a;
int c;
Lexeme_list *list;
c = getchar();
try {
for (;;) {
if (c==EOF) break;
a.feed_char(c);
a.run();
if (a.full_lex())
a.add_new_elem();
if (a.use_prev==0) {
if (c=='\n')
a.inc_nstr();
c = getchar();
}
if (a.is_long())
throw "too long name";
}
}
catch (const char *s) {
printf("Error: %s\n", s);
return 1;
}
a.print_list();
if (a.is_any_errors()) {
printf("Some lexical errors detected!\n");
return 1;
}
list = a.get_list();
PolizItem *lst; // PolizItem *lst
LabelTable *table_lst;
SyntaxAnalizer s;
s.set_list(list);
try {
s.analyze();
printf("SUCCESS!!!\n");
lst = s.poliz_list;
table_lst = s.label_list;
lprint(lst); // print poliz list:
}
catch (const Exeption &ex) {
printf("Error: %s\nbut found %s\nstr# %d\n",
ex.GetComment(), ex.GetLexeme(), ex.GetNstr());
return 1;
}
Executer e(lst);
e.execute();
printf("\n");
print_table_list(table_lst);
delete_poliz_list(lst);
return 0;
}
| [
"[email protected]"
] | |
a17ffde8037d25bced9fe5c7ea5bf1639d83766c | f821c7899dc26c31091409589a77dc4f5a26952b | /helpers.cpp | 31bed71de5515099b96f7d657819318f35f68aaa | [] | no_license | caytar/Create-YourHome-in-3D | a847972b3d383c046e31acf801981965d7492b9b | cd0f57ecbf7540f6dbff878c43bddb9d187b04f4 | refs/heads/master | 2021-01-11T16:33:00.469909 | 2020-06-03T09:34:15 | 2020-06-03T09:34:15 | 80,107,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,943 | cpp | // Helper Functions
#ifndef HELPERS
#define HELPERS
#include "variables.cpp"
////// PTOTOTYPES
// PICKING
void drawRects(GLenum mode);
void SetupRC();
void KeyboardAction(int key, int x, int y);
void InitModels();
void DrawModel();
void BuildMenu();
void ProcessMenuSelection(int value);
void InitializeLighting();
void printControls();
void RotateCurrentObj(GLfloat x,GLfloat y,GLfloat z);
void SetPositionOfCurrentObj(GLfloat x,GLfloat y,GLfloat z);
void phase3GlutDisplay( void );
void CALLBACK tessBeginCB(GLenum which);
void CALLBACK tessEndCB();
void CALLBACK tessErrorCB(GLenum errorCode);
void CALLBACK tessVertexCB(const GLvoid *data);
void callDrawPolygon (int value);
void callSpinners (int value);
int ccw(struct vertex p0, struct vertex p1, struct vertex p2);
void changePhase (int value);
void create3dPoints();
void createPoly(vertex a, vertex b);
void doDelete();
void doInsertRectangle();
void doMerge();
void doSubtract();
void drawDoors();
void drawWindows();
void drawLine (GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
void drawThickLine(struct vertex v1, struct vertex v2, int size);
void drawWall(struct vertex v1,struct vertex v2,int wall_width,int wall_height,int which);
void enlightMe();
void find8Points(struct vertex v1,struct vertex v2,int wall_width,int h0, int h1,struct wall3D *which);
int insidePoly(struct vertex v, vector<struct vertex> &poly);
int intersected();
int lineIntersect(struct vertex v0,struct vertex v1,struct vertex v2,struct vertex v3,struct vertex *v4);
void phase1Save();
void phase1Load();
void phase2Save();
void phase2Load();
void phase3Save();
void phase3Load();
void purgePolygon();
void RenderText(int x, int y, char *string);
GLuint renderPolygon();
void rotateRect(int value);
void rotateRect(struct vertex pivot,struct fur *furniture, GLdouble angle);
void rotateRect(struct vertex pivot, GLdouble angle, GLint vertex_num);
void rotateWall(struct vertex pivot,struct wall3D *one_wall, GLdouble angle);
void scaleRect(struct vertex pivot, GLfloat sx, GLfloat sy, GLint vertex_num);
void scaleRect(int value);
void scaleRect(struct vertex pivot, GLfloat sx, GLfloat sy, struct fur *furniture);
void showLightSources();
//void statusBar(char *str);
//// FUNCTION DEFINITIONS
//Draws the house by calling all necessary sub-functions
void DrawModel() {
CurrentModel->Render();
}
void openDoor(int k) {
if(doors3DAngle[k]==0)
doors3DAngle[k]=1;
}
void closeDoor(int k) {
if(doors3DAngle[k]==50)
doors3DAngle[k]=51;
}
void updatePosition(double diffx, double diffy, double diffz) {
int i, pass=1;
struct vertex cur, next, bw, fw, t;
if(freeMode==1) {
xx0+=diffx;
yy0+=diffy;
zz0+=diffz;
xref=xx0+cos(walkDir)*5;
yref=yy0+sin(walkDir)*5;
zref=zz0+sin(walkDirV)*5;
return;
}
zref=80; zz0=80;
cur.coord[0]=xx0;
cur.coord[1]=yy0;
next.coord[0]=xx0+diffx*5;
next.coord[1]=yy0+diffy*5;
bw.coord[0]=xx0+cos(walkDir+M_PI)*50;
bw.coord[1]=yy0+sin(walkDir+M_PI)*50;
fw.coord[0]=xx0+cos(walkDir)*100;
fw.coord[1]=yy0+sin(walkDir)*100;
for(i=0; i<doors.size(); i++)
if(lineIntersect(bw, fw, doors[i].points[0], doors[i].points[1], &t))
{ pass=2; openDoor(i); }
else closeDoor(i);
if(pass!=2)
for(i=0; i<walls.size(); i++)
if(lineIntersect(cur, next, walls[i].points[0], walls[i].points[1], &t))
pass=0;
if(pass) { xx0+=diffx; yy0+=diffy; }
xref=xx0+cos(walkDir)*5;
yref=yy0+sin(walkDir)*5;
// printf("%lf %lf\n", xx0, yy0);
}
void GlutPassiveMotion(int x, int y ) {
walkDir+=(mouseX-x)/100.0;
if(freeMode) {
walkDirV+=(mouseY-y)/100.0;
if(walkDirV> M_PI/2) walkDirV=M_PI/2;
if(walkDirV< -M_PI/2) walkDirV=-M_PI/2;
}
updatePosition(0, 0, 0);
mouseX=x;
mouseY=y;
glutPostRedisplay();
}
void KeyboardAction(int key, int x, int y)
{
if(key == 27) //i.e. escape character
exit(0);
if(key == GLUT_KEY_UP) {
updatePosition(cos(walkDir)*5, sin(walkDir)*5, sin(walkDirV)*5);
}
if(key == GLUT_KEY_DOWN) {
updatePosition(cos(walkDir+M_PI)*5, sin(walkDir+M_PI)*5, -sin(walkDirV)*5);
}
if(key == GLUT_KEY_LEFT) {
updatePosition(cos(walkDir+M_PI/2)*5, sin(walkDir+M_PI/2)*5, 0);
}
if(key == GLUT_KEY_RIGHT) {
updatePosition(cos(walkDir-M_PI/2)*5, sin(walkDir-M_PI/2)*5, 0);
}
glutPostRedisplay();
}
void BuildMenu() {
// Create the Menu
glutAddMenuEntry("Cem Aytar",1);
glutAddMenuEntry("Yunus Esencayi",2);
glutAddMenuEntry("Kaan Yasin Ceylan",3);
glutAttachMenu(GLUT_RIGHT_BUTTON); //attach to right click
}
void ProcessMenuSelection(int value)
{
CurrentModel = &model01; //load red wagon
//reset the rotations for the newly referenced model
xRotation = 0.0f;
yRotation = 0.0f;
zRotation = 0.0f;
//reset the rotaiton of the currentmodel to its natural orientation
CurrentModel->ResetRotation();
phase3GlutDisplay();
}
//************************************************************************
//********** **********
//********** Initialization Functions **********
//********** **********
//************************************************************************
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
//Default variable values
CurrentModel = &model01; //default model is the red wagon
xRotation = 0.0f; //start with no rotations applied
yRotation = 0.0f; //start with no rotations applied
zRotation = 0.0f; //start with no rotations applied
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
//glEnable(GL_CULL_FACE); // Do not calculate inside of objects
InitializeLighting();
// Black background
glClearColor(0.3, 0.3, 0.3, 1.0); //redundant call for clarity
}
//This funciton INitializes all of the 3DS objects to the respective
//global Object3DS instance
void setModels(char *fileName,GLfloat sScalar,GLfloat x, GLfloat y,GLfloat z, int which) {
if (which==1)
{
CurrentModel = &model01;
model01.Initialize(fileName);
model01.SetScalar(sScalar);
model01.SetPosition(x, y, z);
}
if (which==2)
{
CurrentModel = &model02;
model02.Initialize(fileName);
model02.SetScalar(sScalar);
model02.SetPosition(x, y, z);
}
if (which==3)
{
CurrentModel = &model03;
model03.Initialize(fileName);
model03.SetScalar(sScalar);
model03.SetPosition(x, y, z);
model03.Rotate(90,0,0);
}
}
void RotateCurrentObj(GLfloat x,GLfloat y,GLfloat z)
{
CurrentModel->Rotate(x,y,z); //mevcut modeli x,y,z kadar cevir.
}
void SetPositionOfCurrentObj(GLfloat x,GLfloat y,GLfloat z)
{
CurrentModel->SetPosition(x,y,z); //mevcut modeli x,y,z koordinatlarina koy.
}
// This funciton initializes all lighting for the VR World
void InitializeLighting() {
enlightMe();
}
void RenderText(int x, int y, char *string) {
int len, i;
glRasterPos2f(x, y);
len=strlen(string);
for (i = 0; i < len; i++)
glutBitmapCharacter( GLUT_BITMAP_HELVETICA_12, string[i]);
}
int equivelent(double a, double b) {
a=a-b;
if(a<0.0) a=-a;
if(a<0.05) return 1;
return 0;
}
int cmp(const void *p1, const void *p2) {
struct vertex *a=(struct vertex *)p1, *b=(struct vertex *)p2;
if(!equivelent(a->coord[0], b->coord[0])) return (a->coord[0] > b->coord[0]) - (a->coord[0] < b->coord[0]);
if(!equivelent(a->coord[1], b->coord[1])) return (a->coord[1] > b->coord[1]) - (a->coord[1] < b->coord[1]);
if(!equivelent(a->coord[2], b->coord[2])) return (a->coord[2] > b->coord[2]) - (a->coord[2] < b->coord[2]);
return 0;
}
void create3dPoints() {
int wall_size,i,j,k,t=0, door_number,window_number;
struct vertex liste[20];
wall_size=walls.size();
door_number=doors.size();
window_number=windows.size();
walls3D.clear();
doors3D.clear();
doors3DAngle.clear();
windows3D.clear();
minx=10000;
miny=10000;
maxx=-10000;
maxy=-10000;
for(i=0; i<wall_size; i++) {
minx=min(minx, walls[i].points[0].coord[0]);
maxx=max(maxx, walls[i].points[0].coord[0]);
miny=min(miny, walls[i].points[0].coord[1]);
maxy=max(maxy, walls[i].points[0].coord[1]);
}
minx-=50;
miny-=50;
maxx+=50;
maxy+=50;
printf("%lf %lf %lf %lf\n", minx, maxx, miny, maxy);
for(i=0; i<wall_size; i++)
{
j=0;
// walls3D.push_back(new_3d_wall);
liste[j++]=walls[i].points[0];
liste[j++]=walls[i].points[1];
for (k=0;k<door_number;k++)
if (i==doors[k].parent)
{
liste[j++]=doors[k].points[0];
liste[j++]=doors[k].points[1];
}
for (k=0;k<window_number;k++)
if (i==windows[k].parent)
{
liste[j++]=windows[k].points[0];
liste[j++]=windows[k].points[1];
}
qsort(liste, j, sizeof(struct vertex), cmp);
for(k=0; k<j; k+=2) {
walls3D.push_back(new_3d_wall);
find8Points(liste[k],liste[k+1],wall_width, 0, wall_height, &walls3D[t++]);
}
}
for (k=0;k<door_number;k++) {
walls3D.push_back(new_3d_wall);
find8Points(doors[k].points[0],doors[k].points[1],wall_width, wall_height-40, wall_height, &walls3D[t++]);
doors3D.push_back(new_3d_wall);
doors3DAngle.push_back(0);
find8Points(doors[k].points[0],doors[k].points[1],wall_width/2, 0, wall_height-40, &doors3D[k]);
}
for (k=0;k<window_number;k++) {
walls3D.push_back(new_3d_wall);
find8Points(windows[k].points[0],windows[k].points[1],wall_width, 0, 50, &walls3D[t++]);
walls3D.push_back(new_3d_wall);
find8Points(windows[k].points[0],windows[k].points[1],wall_width, wall_height-30, wall_height, &walls3D[t++]);
windows3D.push_back(new_3d_wall);
find8Points(windows[k].points[0],windows[k].points[1],wall_width/5, 50, wall_height-30, &windows3D[k]);
}
}
void updateDoorAngles() {
int i;
for(i=0; i<doors.size(); i++)
if(doors3DAngle[i]!=0 && doors3DAngle[i]!=50) {
doors3DAngle[i]++;
if(doors3DAngle[i]<50)
rotateWall(doors[i].points[0], &doors3D[i], M_PI/100);
else if(doors3DAngle[i]<99)
rotateWall(doors[i].points[0], &doors3D[i], -M_PI/100);
else doors3DAngle[i]=0;
}
}
void find8Points(struct vertex v1,struct vertex v2,int wall_width,int h0, int h1, struct wall3D* which) {
GLfloat m;
GLfloat w2=wall_width/2, h2=wall_height/2;
m=(v2.coord[1]-v1.coord[1])/(v2.coord[0]-v1.coord[0]);
if (m>0)
{
which->points[0].coord[0]=v1.coord[0]-w2*sqrt(m*m/(m*m+1));
which->points[0].coord[1]=v1.coord[1]+w2*sqrt(1/(m*m+1));
which->points[0].coord[2]=h0;
which->points[1].coord[0]=v1.coord[0]+w2*sqrt(m*m/(m*m+1));
which->points[1].coord[1]=v1.coord[1]-w2*sqrt(1/(m*m+1));
which->points[1].coord[2]=h0;
which->points[2].coord[0]=v2.coord[0]+w2*sqrt(m*m/(m*m+1));
which->points[2].coord[1]=v2.coord[1]-w2*sqrt(1/(m*m+1));
which->points[2].coord[2]=h0;
which->points[3].coord[0]=v2.coord[0]-w2*sqrt(m*m/(m*m+1));
which->points[3].coord[1]=v2.coord[1]+w2*sqrt(1/(m*m+1));
which->points[3].coord[2]=h0;
which->points[4].coord[0]=which->points[0].coord[0];
which->points[4].coord[1]=which->points[0].coord[1];
which->points[4].coord[2]=h1;
which->points[5].coord[0]=which->points[1].coord[0];
which->points[5].coord[1]=which->points[1].coord[1];
which->points[5].coord[2]=h1;
which->points[6].coord[0]=which->points[2].coord[0];
which->points[6].coord[1]=which->points[2].coord[1];
which->points[6].coord[2]=h1;
which->points[7].coord[0]=which->points[3].coord[0];
which->points[7].coord[1]=which->points[3].coord[1];
which->points[7].coord[2]=h1;
}
else
{
which->points[0].coord[0]=v1.coord[0]+w2*sqrt(m*m/(m*m+1));
which->points[0].coord[1]=v1.coord[1]+w2*sqrt(1/(m*m+1));
which->points[0].coord[2]=h0;
which->points[1].coord[0]=v1.coord[0]-w2*sqrt(m*m/(m*m+1));
which->points[1].coord[1]=v1.coord[1]-w2*sqrt(1/(m*m+1));
which->points[1].coord[2]=h0;
which->points[2].coord[0]=v2.coord[0]-w2*sqrt(m*m/(m*m+1));
which->points[2].coord[1]=v2.coord[1]-w2*sqrt(1/(m*m+1));
which->points[2].coord[2]=h0;
which->points[3].coord[0]=v2.coord[0]+w2*sqrt(m*m/(m*m+1));
which->points[3].coord[1]=v2.coord[1]+w2*sqrt(1/(m*m+1));
which->points[3].coord[2]=h0;
which->points[4].coord[0]=which->points[0].coord[0];
which->points[4].coord[1]=which->points[0].coord[1];
which->points[4].coord[2]=h1;
which->points[5].coord[0]=which->points[1].coord[0];
which->points[5].coord[1]=which->points[1].coord[1];
which->points[5].coord[2]=h1;
which->points[6].coord[0]=which->points[2].coord[0];
which->points[6].coord[1]=which->points[2].coord[1];
which->points[6].coord[2]=h1;
which->points[7].coord[0]=which->points[3].coord[0];
which->points[7].coord[1]=which->points[3].coord[1];
which->points[7].coord[2]=h1;
}
}
void drawDoors()
{
int i;
int w2=wall_width/2, h2=wall_height/2;
glColor3f(0.0,0.0,0.0);
for (i=0;i<doors.size();i++)
{
glBegin(GL_QUADS);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]-w2,wall_height);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]+w2,wall_height);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]+w2,wall_height);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]-w2,wall_height);
glEnd();
glBegin(GL_QUADS);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]-w2,h2);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]+w2,h2);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]+w2,h2);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]-w2,h2);
glEnd();
glBegin(GL_QUADS);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]-w2,wall_height);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]+w2,wall_height);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]+w2,h2);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]-w2,h2);
glEnd();
glBegin(GL_QUADS);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]-w2,wall_height);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]+w2,wall_height);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]+w2,h2);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]-w2,h2);
glEnd();
glBegin(GL_QUADS);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]-w2,wall_height);
glVertex3d(doors[i].points[0].coord[0],doors[i].points[0].coord[1]-w2,h2);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]-w2,h2);
glVertex3d(doors[i].points[1].coord[0],doors[i].points[1].coord[1]-w2,wall_height);
glEnd();
}
}
void drawWindows()
{
int i;
int w2=wall_width/2, h2=wall_height/2;
glColor3f(1.0,1.0,1.0);
for (i=0;i<windows.size();i++)
{
glBegin(GL_QUADS);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]-w2,40);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]+w2,40);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]+w2,40);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]-w2,40);
glEnd();
glBegin(GL_QUADS);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]-w2,20);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]+w2,20);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]+w2,20);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]-w2,20);
glEnd();
glBegin(GL_QUADS);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]-w2,40);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]+w2,40);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]+w2,20);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]-w2,20);
glEnd();
glBegin(GL_QUADS);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]-w2,40);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]+w2,40);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]+w2,20);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]-w2,20);
glEnd();
glBegin(GL_QUADS);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]-w2,40);
glVertex3d(windows[i].points[0].coord[0],windows[i].points[0].coord[1]-w2,20);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]-w2,20);
glVertex3d(windows[i].points[1].coord[0],windows[i].points[1].coord[1]-w2,40);
glEnd();
}
}
void showLightSources(){
glColor3f(1.0,1.0,1.0);
// Light Source 1
glBegin(GL_QUADS);
glVertex3f(light0x+light_width,light0y-light_width,light0z+light_width);
glVertex3f(light0x+light_width,light0y+light_width,light0z+light_width);
glVertex3f(light0x-light_width,light0y+light_width,light0z+light_width);
glVertex3f(light0x-light_width,light0y-light_width,light0z+light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light0x+light_width,light0y-light_width,light0z-light_width);
glVertex3f(light0x+light_width,light0y+light_width,light0z-light_width);
glVertex3f(light0x-light_width,light0y+light_width,light0z-light_width);
glVertex3f(light0x-light_width,light0y-light_width,light0z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light0x+light_width,light0y-light_width,light0z+light_width);
glVertex3f(light0x+light_width,light0y+light_width,light0z+light_width);
glVertex3f(light0x+light_width,light0y+light_width,light0z-light_width);
glVertex3f(light0x+light_width,light0y-light_width,light0z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light0x-light_width,light0y-light_width,light0z+light_width);
glVertex3f(light0x-light_width,light0y+light_width,light0z+light_width);
glVertex3f(light0x-light_width,light0y+light_width,light0z-light_width);
glVertex3f(light0x-light_width,light0y-light_width,light0z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light0x-light_width,light0y+light_width,light0z+light_width);
glVertex3f(light0x+light_width,light0y+light_width,light0z+light_width);
glVertex3f(light0x+light_width,light0y+light_width,light0z-light_width);
glVertex3f(light0x-light_width,light0y+light_width,light0z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light0x-light_width,light0y-light_width,light0z+light_width);
glVertex3f(light0x+light_width,light0y-light_width,light0z+light_width);
glVertex3f(light0x+light_width,light0y-light_width,light0z-light_width);
glVertex3f(light0x-light_width,light0y-light_width,light0z-light_width);
glEnd();
// Light Source 2
glBegin(GL_QUADS);
glVertex3f(light1x+light_width,light1y-light_width,light1z+light_width);
glVertex3f(light1x+light_width,light1y+light_width,light1z+light_width);
glVertex3f(light1x-light_width,light1y+light_width,light1z+light_width);
glVertex3f(light1x-light_width,light1y-light_width,light1z+light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light1x+light_width,light1y-light_width,light1z-light_width);
glVertex3f(light1x+light_width,light1y+light_width,light1z-light_width);
glVertex3f(light1x-light_width,light1y+light_width,light1z-light_width);
glVertex3f(light1x-light_width,light1y-light_width,light1z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light1x+light_width,light1y-light_width,light1z+light_width);
glVertex3f(light1x+light_width,light1y+light_width,light1z+light_width);
glVertex3f(light1x+light_width,light1y+light_width,light1z-light_width);
glVertex3f(light1x+light_width,light1y-light_width,light1z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light1x-light_width,light1y-light_width,light1z+light_width);
glVertex3f(light1x-light_width,light1y+light_width,light1z+light_width);
glVertex3f(light1x-light_width,light1y+light_width,light1z-light_width);
glVertex3f(light1x-light_width,light1y-light_width,light1z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light1x-light_width,light1y+light_width,light1z+light_width);
glVertex3f(light1x+light_width,light1y+light_width,light1z+light_width);
glVertex3f(light1x+light_width,light1y+light_width,light1z-light_width);
glVertex3f(light1x-light_width,light1y+light_width,light1z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light1x-light_width,light1y-light_width,light1z+light_width);
glVertex3f(light1x+light_width,light1y-light_width,light1z+light_width);
glVertex3f(light1x+light_width,light1y-light_width,light1z-light_width);
glVertex3f(light1x-light_width,light1y-light_width,light1z-light_width);
glEnd();
glColor3f(1.0,1.0,0.0);
// Light Source 3
glBegin(GL_QUADS);
glVertex3f(light2x+light_width,light2y-light_width,light2z+light_width);
glVertex3f(light2x+light_width,light2y+light_width,light2z+light_width);
glVertex3f(light2x-light_width,light2y+light_width,light2z+light_width);
glVertex3f(light2x-light_width,light2y-light_width,light2z+light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light2x+light_width,light2y-light_width,light2z-light_width);
glVertex3f(light2x+light_width,light2y+light_width,light2z-light_width);
glVertex3f(light2x-light_width,light2y+light_width,light2z-light_width);
glVertex3f(light2x-light_width,light2y-light_width,light2z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light2x+light_width,light2y-light_width,light2z+light_width);
glVertex3f(light2x+light_width,light2y+light_width,light2z+light_width);
glVertex3f(light2x+light_width,light2y+light_width,light2z-light_width);
glVertex3f(light2x+light_width,light2y-light_width,light2z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light2x-light_width,light2y-light_width,light2z+light_width);
glVertex3f(light2x-light_width,light2y+light_width,light2z+light_width);
glVertex3f(light2x-light_width,light2y+light_width,light2z-light_width);
glVertex3f(light2x-light_width,light2y-light_width,light2z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light2x-light_width,light2y+light_width,light2z+light_width);
glVertex3f(light2x+light_width,light2y+light_width,light2z+light_width);
glVertex3f(light2x+light_width,light2y+light_width,light2z-light_width);
glVertex3f(light2x-light_width,light2y+light_width,light2z-light_width);
glEnd();
glBegin(GL_QUADS);
glVertex3f(light2x-light_width,light2y-light_width,light2z+light_width);
glVertex3f(light2x+light_width,light2y-light_width,light2z+light_width);
glVertex3f(light2x+light_width,light2y-light_width,light2z-light_width);
glVertex3f(light2x-light_width,light2y-light_width,light2z-light_width);
glEnd();
}
void phase1Save() {
int i;
FILE *f;
f=fopen("phase1.txt","w");
fprintf(f,"%d %d %d %d %d\n",walls.size(),my_poly.size(),doors.size(),windows.size(),furnitures.size());
for (i=0;i<walls.size();i++)
{
fprintf(f,"%lf %lf %lf ",walls[i].points[0].coord[0],walls[i].points[0].coord[1],walls[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf\n",walls[i].points[1].coord[0],walls[i].points[1].coord[1],walls[i].points[1].coord[2]);
}
fprintf(f,"\n");
for (i=0;i<my_poly.size();i++)
fprintf(f,"%lf %lf %lf ",my_poly[i].coord[0],my_poly[i].coord[1],my_poly[i].coord[2]);
fprintf(f,"\n");
for (i=0;i<doors.size();i++)
{
fprintf(f,"%lf %lf %lf ",doors[i].points[0].coord[0],doors[i].points[0].coord[1],doors[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf ",doors[i].points[1].coord[0],doors[i].points[1].coord[1],doors[i].points[1].coord[2]);
fprintf(f,"%d ",doors[i].parent);
}
fprintf(f,"\n");
for (i=0;i<windows.size();i++)
{
fprintf(f,"%lf %lf %lf ",windows[i].points[0].coord[0],windows[i].points[0].coord[1],windows[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf ",windows[i].points[1].coord[0],windows[i].points[1].coord[1],windows[i].points[1].coord[2]);
fprintf(f,"%d ",windows[i].parent);
}
fprintf(f,"\n");
for (i=0;i<furnitures.size();i++)
{
int j=0;
fprintf(f,"%d \n",furnitures[i].polygon.size());
fprintf(f,"%d \n",furnitures[i].type);
for (j=0;j<furnitures[i].polygon.size();j++)
fprintf(f,"%lf %lf %lf ",furnitures[i].polygon[j].coord[0],furnitures[i].polygon[j].coord[1],furnitures[i].polygon[j].coord[2]);
fprintf(f,"\n");
fprintf(f,"%f %f %f \n",furnitures[i].color[0],furnitures[i].color[1],furnitures[i].color[2]);
fprintf(f,"%c ",furnitures[i].letter);
}
fclose(f);
}
void phase1Load() {
int i,s_walls,s_my_poly,s_doors,s_windows,s_furnitures;
FILE *f;
struct wall t_wall, t_door, t_window;
struct vertex t_poly,tmp;
struct fur t_fur;
f=fopen("phase1.txt","r");
fscanf(f,"%d %d %d %d %d",&s_walls,&s_my_poly,&s_doors,&s_windows,&s_furnitures);
t_wall.points.push_back(t_poly);
t_wall.points.push_back(tmp);
t_door.points.push_back(t_poly);
t_door.points.push_back(tmp);
t_window.points.push_back(t_poly);
t_window.points.push_back(tmp);
my_poly.clear();
for (i=s_walls;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_wall.points[0].coord[0]),&(t_wall.points[0].coord[1]),&(t_wall.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_wall.points[1].coord[0]),&(t_wall.points[1].coord[1]),&(t_wall.points[1].coord[2]));
walls.push_back(t_wall);
}
for (i=s_my_poly;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_poly.coord[0]),&(t_poly.coord[1]),&(t_poly.coord[2]));
my_poly.push_back(t_poly);
}
for (i=s_doors;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_door.points[0].coord[0]),&(t_door.points[0].coord[1]),&(t_door.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_door.points[1].coord[0]),&(t_door.points[1].coord[1]),&(t_door.points[1].coord[2]));
fscanf(f,"%d",&(t_door.parent));
doors.push_back(t_door);
}
for (i=s_windows;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_window.points[0].coord[0]),&(t_window.points[0].coord[1]),&(t_window.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_window.points[1].coord[0]),&(t_window.points[1].coord[1]),&(t_window.points[1].coord[2]));
fscanf(f,"%d",&(t_window.parent));
windows.push_back(t_window);
}
for (i=s_furnitures;i>0;i--)
{
int j;
fscanf(f,"%d",&j);
fscanf(f,"%d",&(t_fur.type));
for (;j>0;j--)
{
fscanf(f,"%lf %lf %lf",&(tmp.coord[0]),&(tmp.coord[1]),&(tmp.coord[2]));
t_fur.polygon.push_back(tmp);
}
fscanf(f,"%f %f %f",&(t_fur.color[0]),&(t_fur.color[1]),&(t_fur.color[2]));
fscanf(f,"%c",&(t_fur.letter));
furnitures.push_back(t_fur);
}
fclose(f);
state=10;
}
void phase2Save() {
int i;
FILE *f;
f=fopen("phase2.txt","w");
fprintf(f,"%d %d %d %d %d %d %d\n",walls.size(),my_poly.size(),doors.size(),windows.size(),furnitures.size(),wall_width,wall_height);
for (i=0;i<walls.size();i++)
{
fprintf(f,"%lf %lf %lf ",walls[i].points[0].coord[0],walls[i].points[0].coord[1],walls[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf\n",walls[i].points[1].coord[0],walls[i].points[1].coord[1],walls[i].points[1].coord[2]);
}
fprintf(f,"\n");
for (i=0;i<my_poly.size();i++)
fprintf(f,"%lf %lf %lf ",my_poly[i].coord[0],my_poly[i].coord[1],my_poly[i].coord[2]);
fprintf(f,"\n");
for (i=0;i<doors.size();i++)
{
fprintf(f,"%lf %lf %lf ",doors[i].points[0].coord[0],doors[i].points[0].coord[1],doors[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf ",doors[i].points[1].coord[0],doors[i].points[1].coord[1],doors[i].points[1].coord[2]);
fprintf (f,"%d ",doors[i].parent);
}
fprintf(f,"\n");
for (i=0;i<windows.size();i++)
{
fprintf(f,"%lf %lf %lf ",windows[i].points[0].coord[0],windows[i].points[0].coord[1],windows[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf ",windows[i].points[1].coord[0],windows[i].points[1].coord[1],windows[i].points[1].coord[2]);
fprintf (f,"%d ",windows[i].parent);
}
fprintf(f,"\n");
for (i=0;i<furnitures.size();i++)
{
int j=0;
fprintf(f,"%d \n",furnitures[i].polygon.size());
fprintf(f,"%d \n",furnitures[i].type);
for (j=0;j<furnitures[i].polygon.size();j++)
fprintf(f,"%lf %lf %lf ",furnitures[i].polygon[j].coord[0],furnitures[i].polygon[j].coord[1],furnitures[i].polygon[j].coord[2]);
fprintf(f,"\n");
fprintf(f,"%f %f %f \n",furnitures[i].color[0],furnitures[i].color[1],furnitures[i].color[2]);
fprintf(f,"%c ",furnitures[i].letter);
}
fclose(f);
}
void phase2Load() {
int i,s_walls,s_my_poly,s_doors,s_windows,s_furnitures;
FILE *f;
struct wall t_wall, t_door, t_window;
struct vertex t_poly,tmp;
struct fur t_fur;
f=fopen("phase2.txt","r");
fscanf(f,"%d %d %d %d %d %d %d",&s_walls,&s_my_poly,&s_doors,&s_windows,&s_furnitures,&wall_width,&wall_height);
t_wall.points.push_back(t_poly);
t_wall.points.push_back(tmp);
t_door.points.push_back(t_poly);
t_door.points.push_back(tmp);
t_window.points.push_back(t_poly);
t_window.points.push_back(tmp);
my_poly.clear();
for (i=s_walls;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_wall.points[0].coord[0]),&(t_wall.points[0].coord[1]),&(t_wall.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_wall.points[1].coord[0]),&(t_wall.points[1].coord[1]),&(t_wall.points[1].coord[2]));
walls.push_back(t_wall);
}
for (i=s_my_poly;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_poly.coord[0]),&(t_poly.coord[1]),&(t_poly.coord[2]));
my_poly.push_back(t_poly);
}
for (i=s_doors;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_door.points[0].coord[0]),&(t_door.points[0].coord[1]),&(t_door.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_door.points[1].coord[0]),&(t_door.points[1].coord[1]),&(t_door.points[1].coord[2]));
fscanf (f,"%d",&(t_door.parent));
doors.push_back(t_door);
}
for (i=s_windows;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_window.points[0].coord[0]),&(t_window.points[0].coord[1]),&(t_window.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_window.points[1].coord[0]),&(t_window.points[1].coord[1]),&(t_window.points[1].coord[2]));
fscanf (f,"%d",&(t_window.parent));
windows.push_back(t_window);
}
for (i=s_furnitures;i>0;i--)
{
int j;
fscanf(f,"%d",&j);
fscanf(f,"%d",&(t_fur.type));
for (;j>0;j--)
{
fscanf(f,"%lf %lf %lf",&(tmp.coord[0]),&(tmp.coord[1]),&(tmp.coord[2]));
t_fur.polygon.push_back(tmp);
}
fscanf(f,"%f %f %f",&(t_fur.color[0]),&(t_fur.color[1]),&(t_fur.color[2]));
fscanf(f,"%c",&(t_fur.letter));
furnitures.push_back(t_fur);
}
fclose(f);
state=10;
}
void phase3Save() {
int i;
FILE *f;
f=fopen("phase3.txt","w");
fprintf(f,"%d %d %d %d %d %d %d\n",walls.size(),my_poly.size(),doors.size(),windows.size(),furnitures.size(),wall_width,wall_height);
for (i=0;i<walls.size();i++)
{
fprintf(f,"%lf %lf %lf ",walls[i].points[0].coord[0],walls[i].points[0].coord[1],walls[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf\n",walls[i].points[1].coord[0],walls[i].points[1].coord[1],walls[i].points[1].coord[2]);
}
fprintf(f,"\n");
for (i=0;i<my_poly.size();i++)
fprintf(f,"%lf %lf %lf ",my_poly[i].coord[0],my_poly[i].coord[1],my_poly[i].coord[2]);
fprintf(f,"\n");
for (i=0;i<doors.size();i++)
{
fprintf(f,"%lf %lf %lf ",doors[i].points[0].coord[0],doors[i].points[0].coord[1],doors[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf ",doors[i].points[1].coord[0],doors[i].points[1].coord[1],doors[i].points[1].coord[2]);
fprintf (f,"%d ",doors[i].parent);
}
fprintf(f,"\n");
for (i=0;i<windows.size();i++)
{
fprintf(f,"%lf %lf %lf ",windows[i].points[0].coord[0],windows[i].points[0].coord[1],windows[i].points[0].coord[2]);
fprintf(f,"%lf %lf %lf ",windows[i].points[1].coord[0],windows[i].points[1].coord[1],windows[i].points[1].coord[2]);
fprintf (f,"%d ",windows[i].parent);
}
fprintf(f,"\n");
for (i=0;i<furnitures.size();i++)
{
int j=0;
fprintf(f,"%d \n",furnitures[i].polygon.size());
fprintf(f,"%d \n",furnitures[i].type);
for (j=0;j<furnitures[i].polygon.size();j++)
fprintf(f,"%lf %lf %lf ",furnitures[i].polygon[j].coord[0],furnitures[i].polygon[j].coord[1],furnitures[i].polygon[j].coord[2]);
fprintf(f,"\n");
fprintf(f,"%f %f %f \n",furnitures[i].color[0],furnitures[i].color[1],furnitures[i].color[2]);
fprintf(f,"%c ",furnitures[i].letter);
}
fprintf(f,"\n\n\n\n\n");
/////////////////////////////////////////////////////
fprintf (f,"%f %f %f %f %f %f %f %f %f %f %f %f ",xx0,yy0,zz0,xref,yref,zref,vx,vy,vz,walkDir,walkDirV,freeMode);
fprintf (f,"%d %d %d %d %d %d %d %d ",wall_width,wall_height,inside,mouseX, mouseY,model_num,model_dir,cati_goster);
fprintf (f,"%f %f %f %f %f %f %f %f %f %f ",uzunluk,light0x,light0y,light0z,light1x,light1y,light1z,light2x,light2y,light2z);
fprintf (f,"%f %f %f %f %f %f %f %f %f ",atten0_cons,atten0_lin,atten0_quad,atten1_cons,atten1_lin,atten1_quad,atten2_cons,atten2_lin,atten2_quad);
fprintf (f,"%f %f %f %f %f ",spot_angle, spot_exp, spot_x, spot_y, spot_z);
fprintf (f,"%f %f %f %f %f %f %f %f %f ",amb0_r,amb0_g,amb0_b,amb1_r,amb1_g,amb1_b,amb2_r,amb2_g,amb2_b);
fprintf (f,"%f %f %f %f %f %f %f %f %f ",dif0_r,dif0_g,dif0_b,dif1_r,dif1_g,dif1_b,dif2_r,dif2_g,dif2_b);
fprintf (f,"%f %f %f %f %f %f %f %f ",tex1_x1,tex1_x2,tex1_y1,tex1_y2,tex2_x1,tex2_x2,tex2_y1,tex2_y2);
fprintf (f,"%f %f %f %f %f ",minx, miny, maxx, maxy,xyzRotationAngle);
fprintf (f,"%s %s %s ",fileName1,fileName2,fileName3);
fprintf (f,"%f %f %f %f %f ",sc1,sc2,sc3,light_width,shine);
fprintf (f,"%f %f %f %f %f %f %f %f %f ",model1x,model1y,model1z,model2x,model2y,model2z,model3x,model3y,model3z);
fprintf (f,"%f %f %f ",xRotation,yRotation,zRotation);
fprintf (f,"%f %f %f %f %f %f %f %f %f ",rotx0,roty0,rotz0,rotx1,roty1,rotz1,rotx2,roty2,rotz2);
fprintf (f,"%s %s ",texture_name,wall_top_texture);
fclose(f);
}
void phase3Load() {
int i,s_walls,s_my_poly,s_doors,s_windows,s_furnitures;
FILE *f;
struct wall t_wall, t_door, t_window;
struct vertex t_poly,tmp;
struct fur t_fur;
f=fopen("phase3.txt","r");
fscanf(f,"%d %d %d %d %d %d %d",&s_walls,&s_my_poly,&s_doors,&s_windows,&s_furnitures,&wall_width,&wall_height);
t_wall.points.push_back(t_poly);
t_wall.points.push_back(tmp);
t_door.points.push_back(t_poly);
t_door.points.push_back(tmp);
t_window.points.push_back(t_poly);
t_window.points.push_back(tmp);
my_poly.clear();
for (i=s_walls;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_wall.points[0].coord[0]),&(t_wall.points[0].coord[1]),&(t_wall.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_wall.points[1].coord[0]),&(t_wall.points[1].coord[1]),&(t_wall.points[1].coord[2]));
walls.push_back(t_wall);
}
for (i=s_my_poly;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_poly.coord[0]),&(t_poly.coord[1]),&(t_poly.coord[2]));
my_poly.push_back(t_poly);
}
for (i=s_doors;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_door.points[0].coord[0]),&(t_door.points[0].coord[1]),&(t_door.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_door.points[1].coord[0]),&(t_door.points[1].coord[1]),&(t_door.points[1].coord[2]));
fscanf (f,"%d",&(t_door.parent));
doors.push_back(t_door);
}
for (i=s_windows;i>0;i--)
{
fscanf(f,"%lf %lf %lf",&(t_window.points[0].coord[0]),&(t_window.points[0].coord[1]),&(t_window.points[0].coord[2]));
fscanf(f,"%lf %lf %lf",&(t_window.points[1].coord[0]),&(t_window.points[1].coord[1]),&(t_window.points[1].coord[2]));
fscanf (f,"%d",&(t_window.parent));
windows.push_back(t_window);
}
for (i=s_furnitures;i>0;i--)
{
int j;
fscanf(f,"%d",&j);
fscanf(f,"%d",&(t_fur.type));
for (;j>0;j--)
{
fscanf(f,"%lf %lf %lf",&(tmp.coord[0]),&(tmp.coord[1]),&(tmp.coord[2]));
t_fur.polygon.push_back(tmp);
}
fscanf(f,"%f %f %f",&(t_fur.color[0]),&(t_fur.color[1]),&(t_fur.color[2]));
fscanf(f,"%c",&(t_fur.letter));
furnitures.push_back(t_fur);
}
//////////////////////////
fscanf (f,"%f %f %f %f %f %f %f %f %f %f %f %f",&xx0,&yy0,&zz0,&xref,&yref,&zref,&vx,&vy,&vz,&walkDir,&walkDirV,&freeMode);
fscanf (f,"%d %d %d %d %d %d %d %d",&wall_width,&wall_height,&inside,&mouseX,&mouseY,&model_num,&model_dir,&cati_goster);
fscanf (f,"%f %f %f %f %f %f %f %f %f %f",&uzunluk,&light0x,&light0y,&light0z,&light1x,&light1y,&light1z,&light2x,&light2y,&light2z);
fscanf (f,"%f %f %f %f %f %f %f %f %f",&atten0_cons,&atten0_lin,&atten0_quad,&atten1_cons,&atten1_lin,&atten1_quad,&atten2_cons,&atten2_lin,&atten2_quad);
fscanf (f,"%f %f %f %f %f",&spot_angle,&spot_exp,&spot_x,&spot_y,&spot_z);
fscanf (f,"%f %f %f %f %f %f %f %f %f",&amb0_r,&amb0_g,&amb0_b,&amb1_r,&amb1_g,&amb1_b,&amb2_r,&amb2_g,&amb2_b);
fscanf (f,"%f %f %f %f %f %f %f %f %f",&dif0_r,&dif0_g,&dif0_b,&dif1_r,&dif1_g,&dif1_b,&dif2_r,&dif2_g,&dif2_b);
fscanf (f,"%f %f %f %f %f %f %f %f",&tex1_x1,&tex1_x2,&tex1_y1,&tex1_y2,&tex2_x1,&tex2_x2,&tex2_y1,&tex2_y2);
fscanf (f,"%f %f %f %f %f",&minx,&miny,&maxx,&maxy,&xyzRotationAngle);
fscanf (f,"%s %s %s",fileName1,fileName2,fileName3);
fscanf (f,"%f %f %f %f %f",&sc1,&sc2,&sc3,&light_width,&shine);
fscanf (f,"%f %f %f %f %f %f %f %f %f",&model1x,&model1y,&model1z,&model2x,&model2y,&model2z,&model3x,&model3y,&model3z);
fscanf (f,"%f %f %f",&xRotation,&yRotation,&zRotation);
fscanf (f,"%f %f %f %f %f %f %f %f %f",&rotx0,&roty0,&rotz0,&rotx1,&roty1,&rotz1,&rotx2,&roty2,&rotz2);
fscanf (f,"%s %s",texture_name,wall_top_texture);
fclose(f);
state=10;
create3dPoints();
enlightMe();
updateDoorAngles();
if ( glutGetWindow() != phase3_window)
glutSetWindow(phase3_window);
updatePosition(0,0,0);
CurrentModel = &model01;
CurrentModel->Rotate(rotx0,roty0,rotz0);
CurrentModel->SetPosition(model1x,model1y,model1z);
CurrentModel->SetScalar(sc1);
CurrentModel = &model02;
CurrentModel->Rotate(rotx1,roty1,rotz1);
CurrentModel->SetPosition(model2x,model2y,model2z);
CurrentModel->SetScalar(sc2);
CurrentModel = &model03;
CurrentModel->Rotate(rotx2,roty2,rotz2);
CurrentModel->SetPosition(model3x,model3y,model3z);
CurrentModel->SetScalar(sc3);
}
void drawLine (GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2) {
glBegin (GL_LINES);
glVertex2f (x1, y1);
glVertex2f (x2, y2);
glEnd ();
}
void enlightMe()
{
GLfloat ambience0[] = {amb0_r, amb0_g, amb0_b, 1.0};
GLfloat ambience1[] = {amb1_r, amb1_g, amb1_b, 1.0};
GLfloat ambience2[] = {amb2_r, amb2_g, amb2_b, 1.0};
GLfloat diffuse0[] = {dif0_r, dif0_g, dif0_b, 1.0};
GLfloat diffuse1[] = {dif1_r, dif1_g, dif1_b, 1.0};
GLfloat diffuse2[] = {dif2_r, dif2_g, dif2_b, 1.0};
GLfloat white[] = { 1.0 , 1.0 , 1.0 , 1.0 };
GLfloat specularColor[] = { 1.0 , 1.0 , 1.0 };
GLfloat direction0[] = { light0x, light0y, light0z, 0.0};
GLfloat direction1[] = { light1x, light1y, light1z, 1.0};
GLfloat direction2[] = { light2x, light2y, light2z, 1.0};
GLfloat spot_direction[] = { spot_x, spot_y, spot_z };
glLightfv(GL_LIGHT0, GL_AMBIENT, ambience0 );
glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1 );
glLightfv(GL_LIGHT2, GL_SPECULAR, white);
glLightfv(GL_LIGHT2, GL_DIFFUSE, white);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, atten0_cons);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, atten0_lin);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, atten0_quad);
glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, atten1_cons);
glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, atten1_lin);
glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, atten1_quad);
glLightf(GL_LIGHT2, GL_CONSTANT_ATTENUATION, atten2_cons);
glLightf(GL_LIGHT2, GL_LINEAR_ATTENUATION, atten2_lin);
glLightf(GL_LIGHT2, GL_QUADRATIC_ATTENUATION, atten2_quad);
glLightf (GL_LIGHT2, GL_SPOT_CUTOFF, spot_angle);
glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, spot_direction);
glLightf (GL_LIGHT2, GL_SPOT_EXPONENT, spot_exp);
glLightfv(GL_LIGHT0, GL_POSITION, direction0 );
glLightfv(GL_LIGHT1, GL_POSITION, direction1 );
glLightfv(GL_LIGHT2, GL_POSITION, direction2 );
glEnable(GL_COLOR_MATERIAL);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &shine);
glMaterialfv(GL_FRONT, GL_AMBIENT, white);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glEnable(GL_LIGHT2);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void drawWall(struct vertex v1,struct vertex v2,int wall_width,int wall_height,int which)
{
int i;
GLfloat a1_l,a1_r,b1_l,b1_r,a2_l,a2_r,b2_l,b2_r;
GLdouble tan,ang;
int w2=wall_width/2, h2=wall_height/2;
tan=(v2.coord[1]-v1.coord[1])/(v2.coord[0]-v1.coord[0]);
ang=atan(tan);
uzunluk=sqrt((v2.coord[1]-v1.coord[1])*(v2.coord[1]-v1.coord[1]) + (v2.coord[0]-v1.coord[0])*(v2.coord[0]-v1.coord[0]));
if ((v2.coord[1]-v1.coord[1])/(v2.coord[0]-v1.coord[0])>1.0 || (v2.coord[1]-v1.coord[1])/(v2.coord[0]-v1.coord[0])<-1.0)
{
a1_l=v1.coord[0]-w2;
a1_r=v1.coord[0]+w2;
b1_l=v1.coord[1];
b1_r=v1.coord[1];
a2_l=v2.coord[0]-w2;
a2_r=v2.coord[0]+w2;
b2_l=v2.coord[1];
b2_r=v2.coord[1];
}
else
{
a1_l=v1.coord[0];
a1_r=v1.coord[0];
b1_l=v1.coord[1]-w2;
b1_r=v1.coord[1]+w2;
a2_l=v2.coord[0];
a2_r=v2.coord[0];
b2_l=v2.coord[1]-w2;
b2_r=v2.coord[1]+w2;
}
// Yanal Alanlar
glColor3f(1.0,0.0,0.0);
glBegin(GL_QUADS);
glVertex3f(a1_l,b1_l,0);
glVertex3f(a1_l,b1_l,wall_height);
glVertex3f(a2_l,b2_l,wall_height);
glVertex3f(a2_l,b2_l,0);
glEnd();
glBegin(GL_QUADS);
glVertex3f(a1_r,b1_r,0);
glVertex3f(a1_r,b1_r,wall_height);
glVertex3f(a2_r,b2_r,wall_height);
glVertex3f(a2_r,b2_r,0);
glEnd();
// Ust ve Alt Alanlar
glColor3f(0.0,0.0,1.0);
glBegin(GL_QUADS);
glVertex3f(a1_l,b1_l,0);
glVertex3f(a1_r,b1_r,0);
glVertex3f(a2_r,b2_r,0);
glVertex3f(a2_l,b2_l,0);
glEnd();
drawWindows();
drawDoors();
}
/*
void statusBar(char *str) {
int i;
char koordinat[20];
float tmp,tmp2;
glColor4f( 0.92, 0.92, 0.95, 1.0 );
glBegin(GL_POLYGON);
for (i=0;i<4;i++)
glVertex3dv(status_poly[i].coord);
glEnd();
glColor4f( 0.4, 0.4, 0.4 , 0.7 );
drawThickLine(status_poly[0], status_poly[1], 1);
glColor4f( 0.0, 0.0, 0.0, 1.0 );
RenderText(5, height-5,str);
RenderText(width-620, height-5,"Selected Area : ");
tmp=mouse.coord[0]-bdown.coord[0];
if (tmp<0) tmp=-1*tmp;
tmp2=mouse.coord[1]-bdown.coord[1];
if (tmp2<0) tmp2=-1*tmp2;
sprintf(koordinat,"%fx%f",tmp,tmp2);
RenderText(width-530, height-5,koordinat);
}
*/
void doMerge() {
int a, b, c, d, i;
int r1, r2, doBreak=0, firstLine;
struct vertex int_point, cur;
int_point.coord[2]=0;
new_poly.clear();
doBreak=0;
for(a=0; a<my_poly.size() && !doBreak; a++) {
b=(a+1)%my_poly.size();
for(c=0; c<4 && !doBreak; c++) {
d=(c+1)%4;
if(lineIntersect(my_poly[a], my_poly[b], my_rect[c], my_rect[d], &int_point)
&& ccw(my_poly[b], int_point, my_rect[d])==1)
{ firstLine=b; doBreak=1; break; }
}
}
doBreak=0;
memcpy(&cur, &int_point, sizeof(struct vertex));
while(!doBreak) {
new_poly.push_back(cur);
for(a=0; a<my_poly.size(); a++) {
b=(a+1)%my_poly.size();
if(lineIntersect(my_poly[a], my_poly[b], cur, my_rect[d], &int_point)
&& ccw(my_rect[d], int_point, my_poly[b])==1)
{ doBreak=1; break; }
}
memcpy(&cur, &my_rect[d], sizeof(struct vertex));
d=(d+1)%4;
}
new_poly.push_back(int_point);
new_poly.push_back(my_poly[b]);
for(i=0; i<my_poly.size(); i++) {
b=(b+1)%my_poly.size();
if(b==firstLine) break;
new_poly.push_back(my_poly[b]);
}
my_poly=new_poly;
doDelete();
purgePolygon();
}
void doDelete() {
int i;
for(i=0; i<4; i++)
my_rect[i].coord[0]=my_rect[i].coord[1]=0;
}
void doSubtract() {
int a, b, c, d, i, k=0;
int r1, r2, doBreak=0, firstLine;
struct vertex int_point, cur;
int_point.coord[2]=0;
new_poly.clear();
doBreak=0;
for(a=0; a<my_poly.size() && !doBreak; a++) {
b=(a+1)%my_poly.size();
for(c=0; c<4 && !doBreak; c++) {
d=(c+3)%4;
if(lineIntersect(my_poly[a], my_poly[b], my_rect[c], my_rect[d], &int_point)
&& ccw(my_poly[b], int_point, my_rect[d])==-1)
{ firstLine=b; doBreak=1; break; }
}
}
doBreak=0;
memcpy(&cur, &int_point, sizeof(struct vertex));
while(!doBreak) {
new_poly.push_back(cur);
for(a=0; a<my_poly.size(); a++) {
b=(a+1)%my_poly.size();
if(lineIntersect(my_poly[a], my_poly[b], cur, my_rect[d], &int_point)
&& ccw(my_rect[d], int_point, my_poly[b])==-1)
{ doBreak=1; break; }
}
memcpy(&cur, &my_rect[d], sizeof(struct vertex));
d=(d+3)%4;
}
new_poly.push_back(int_point);
new_poly.push_back(my_poly[b]);
for(i=0; i<my_poly.size(); i++) {
b=(b+1)%my_poly.size();
if(b==firstLine) break;
new_poly.push_back(my_poly[b]);
}
my_poly[0].coord[0]=0;
my_poly=new_poly;
doDelete();
purgePolygon();
}
void rotateRect(int value) {
struct vertex den;
den.coord[0]=(my_rect[0].coord[0]+my_rect[2].coord[0])/2;
den.coord[1]=(my_rect[0].coord[1]+my_rect[2].coord[1])/2;
den.coord[2]=0.0;
rotateRect(den, rotate_value , 4);
trans_type = 0;
}
void rotateRect(struct vertex pivot,struct fur *furniture, GLdouble angle)
{
int vertex_num=furniture->polygon.size();
vector<struct vertex> tmp(vertex_num);
int i;
angle=angle*DEG2RAD;
for (i=0;i<vertex_num;i++)
{
tmp[i].coord[0] = pivot.coord[0] + (furniture->polygon[i].coord[0]-pivot.coord[0])*cos(angle)
- (furniture->polygon[i].coord[1]-pivot.coord[1])*sin(angle);
tmp[i].coord[1] = pivot.coord[1] + (furniture->polygon[i].coord[0]-pivot.coord[0])*sin(angle)
+ (furniture->polygon[i].coord[1]-pivot.coord[1])*cos(angle);
}
for (i=0;i<vertex_num;i++)
{
furniture->polygon[i].coord[0]=tmp[i].coord[0];
furniture->polygon[i].coord[1]=tmp[i].coord[1];
}
}
void rotateWall(struct vertex pivot,struct wall3D *one_wall, GLdouble angle)
{
int vertex_num=8;
vector<struct vertex> tmp(vertex_num);
int i;
for (i=0;i<vertex_num;i++)
{
tmp[i].coord[0] = pivot.coord[0] + (one_wall->points[i].coord[0]-pivot.coord[0])*cos(angle)
- (one_wall->points[i].coord[1]-pivot.coord[1])*sin(angle);
tmp[i].coord[1] = pivot.coord[1] + (one_wall->points[i].coord[0]-pivot.coord[0])*sin(angle)
+ (one_wall->points[i].coord[1]-pivot.coord[1])*cos(angle);
}
for (i=0;i<vertex_num/2;i++)
{
one_wall->points[i].coord[0]=tmp[i].coord[0];
one_wall->points[i].coord[1]=tmp[i].coord[1];
// one_wall->points[i].coord[2]=0;
}
for (;i<vertex_num;i++)
{
one_wall->points[i].coord[0]=tmp[i].coord[0];
one_wall->points[i].coord[1]=tmp[i].coord[1];
// one_wall->points[i].coord[2]=wall_height;
}
}
void rotateRect(struct vertex pivot, GLdouble angle, GLint vertex_num)
{
vector<struct vertex> tmp(4);
int i;
angle=angle*DEG2RAD;
for (i=0;i<vertex_num;i++)
{
tmp[i].coord[0] = pivot.coord[0] + (my_rect[i].coord[0]-pivot.coord[0])*cos(angle)
- (my_rect[i].coord[1]-pivot.coord[1])*sin(angle);
tmp[i].coord[1] = pivot.coord[1] + (my_rect[i].coord[0]-pivot.coord[0])*sin(angle)
+ (my_rect[i].coord[1]-pivot.coord[1])*cos(angle);
}
for (i=0;i<vertex_num;i++)
{
my_rect[i].coord[0]=tmp[i].coord[0];
my_rect[i].coord[1]=tmp[i].coord[1];
}
}
void doInsertRectangle() {
state=2;
}
void scaleRect(struct vertex pivot, GLfloat sx, GLfloat sy, GLint vertex_num) {
vector<struct vertex> tmp(4);
int i;
for (i=0;i<vertex_num;i++)
{
tmp[i].coord[0] = my_rect[i].coord[0]*sx + pivot.coord[0]*(1-sx);
tmp[i].coord[1] = my_rect[i].coord[1]*sy + pivot.coord[1]*(1-sy);
}
for (i=0;i<vertex_num;i++)
{
my_rect[i].coord[0]=tmp[i].coord[0];
my_rect[i].coord[1]=tmp[i].coord[1];
}
}
void scaleRect(int value) {
struct vertex den;
den.coord[0]=(my_rect[0].coord[0]+my_rect[2].coord[0])/2;
den.coord[1]=(my_rect[0].coord[1]+my_rect[2].coord[1])/2;
den.coord[2]=0.0;
scaleRect(den,scale_value,scale_value, 4);
trans_type=0;
}
void scaleRect(struct vertex pivot, GLfloat sx, GLfloat sy, struct fur *furniture) {
int i,vertex_num=furniture->polygon.size();
vector<struct vertex> tmp(vertex_num);
for (i=0;i<vertex_num;i++)
{
tmp[i].coord[0] = furniture->polygon[i].coord[0]*sx + pivot.coord[0]*(1-sx);
tmp[i].coord[1] = furniture->polygon[i].coord[1]*sy + pivot.coord[1]*(1-sy);
}
for (i=0;i<vertex_num;i++)
{
furniture->polygon[i].coord[0]=tmp[i].coord[0];
furniture->polygon[i].coord[1]=tmp[i].coord[1];
}
}
void purgePolygon() {
struct wall w;
int a, b;
walls.clear();
for(a=0; a<my_poly.size(); a++) {
b=(a+1)%my_poly.size();
w.points.clear();
w.points.push_back(my_poly[a]);
w.points.push_back(my_poly[b]);
walls.push_back(w);
}
}
void callDrawPolygon (int value) {
if (value==2) doMerge();
if (value==3) doSubtract();
if (value==5) rotateRect(value);
if (value==6) scaleRect(value);
if (value==7 && !state) doInsertRectangle();
if (value==9) doDelete();
if (value==10) { state=10; panel1->disable(); panelindoor->enable();}
if (value==14) { state=11; new_wall.points.clear(); }
if (value==11) { state=12; }
if (value==12) { state=13; }
if (value==50) { state=14; }
if (value==20) { phase1Save(); }
if (value==21) { phase1Load(); }
if (value==100) { phase2Save(); }
if (value==101) { phase2Load(); }
if (value==200) { phase3Save(); }
if (value==201) { phase3Load(); }
if (value==400) { xx0=width/2; yy0=height/2; zz0=-10; xref=0; yref=height/3; zref=-20; vx=0; vy=0; vz=-1; inside=1; }
if (value==401) { xx0=width/2; yy0=height/2; zz0=-300; xref=width/2; yref=height/2; zref=0; vx=0; vy=-1; vz=0; inside=0;}
if (value==202) { strcpy(texture_name,texture_panel1->get_text()); }
if (value==203) { strcpy(wall_top_texture,texture_panel2->get_text()); }
}
void callSpinners (int value){
}
int insidePoly(struct vertex v, vector<struct vertex> &poly) {
int i, count=0, b;
struct vertex v1, dummy, a;
v1.coord[0]=v1.coord[1]=0;
for(i=0; i<poly.size(); i++) {
b=(i==poly.size()-1)?0:(i+1);
if(lineIntersect(v1,v, poly[i], poly[b], &dummy)) count++;
}
return count%2;
}
void createPoly(vertex a, vertex b) {
struct vertex v;
int i;
double t,p, q, r, s;
new_fur.polygon.clear();
if(fur_type==0) {
v.coord[0]=a.coord[0]+(b.coord[0]-a.coord[0])/2;
v.coord[1]=a.coord[1];
new_fur.polygon.push_back(v);
v.coord[0]=a.coord[0];
v.coord[1]=b.coord[1];
new_fur.polygon.push_back(v);
new_fur.polygon.push_back(b);
}
if(fur_type==1) {
new_fur.polygon.push_back(a);
v.coord[0]=b.coord[0];
v.coord[1]=a.coord[1];
new_fur.polygon.push_back(v);
new_fur.polygon.push_back(b);
v.coord[0]=a.coord[0];
v.coord[1]=b.coord[1];
new_fur.polygon.push_back(v);
}
if(fur_type==2) {
p=(a.coord[0]+b.coord[0])/2; q=(a.coord[1]+b.coord[1])/2;
r=(b.coord[0]-a.coord[0])/2; s=(b.coord[1]-a.coord[1])/2;
t=M_PI*2.0/50.0;
for(i=0; i<50; i++) {
v.coord[0]=p+cos(i*t)*r;
v.coord[1]=q+sin(i*t)*s;
new_fur.polygon.push_back(v);
}
}
}
int intersected() {
int i, a, b;
struct vertex int_point;
for(i=0; i<walls.size(); i++) {
for(a=0; a<(*holding_object).size(); a++) {
b=(a+1)%(*holding_object).size();
if(lineIntersect(walls[i].points[0], walls[i].points[1], (*holding_object)[a], (*holding_object)[b], &int_point))
return 1;
}
}
return 0;
}
int ccw(struct vertex p0, struct vertex p1, struct vertex p2) {
int dx1, dx2, dy1, dy2;
dx1=(int)p1.coord[0]-(int)p0.coord[0]; dy1=(int)p1.coord[1]-(int)p0.coord[1];
dx2=(int)p2.coord[0]-(int)p0.coord[0]; dy2=(int)p2.coord[1]-(int)p0.coord[1];
if(dx1*dy2>dy1*dx2) return +1;
if(dx1*dy2<dy1*dx2) return -1;
if((dx1*dx2<0) || (dy1*dy2<0)) return -1;
if((dx1*dx1+dy1*dy1) < (dx2*dx2+dy2*dy2)) return +1;
return 0;
}
int lineIntersect(struct vertex v0,struct vertex v1,struct vertex v2,struct vertex v3,struct vertex *v4) {
float a1,b1,c1, a2,b2,c2, det_inv, m1,m2;
if ((v1.coord[0]-v0.coord[0])!=0)
m1 = (v1.coord[1]-v0.coord[1])/(v1.coord[0]-v0.coord[0]);
else
m1 = (float)1e+10;
if ((v3.coord[0]-v2.coord[0])!=0)
m2 = (v3.coord[1]-v2.coord[1])/(v3.coord[0]-v2.coord[0]);
else
m2 = (float)1e+10;
a1 = m1;
a2 = m2;
b1 = -1;
b2 = -1;
c1 = (v0.coord[1]-m1*v0.coord[0]);
c2 = (v2.coord[1]-m2*v2.coord[0]);
det_inv = 1/(a1*b2 - a2*b1);
v4->coord[0]=((b1*c2 - b2*c1)*det_inv);
v4->coord[1]=((a2*c1 - a1*c2)*det_inv);
return ((ccw(v0, v1, v2)
*ccw(v0, v1, v3)) <=0)
&&((ccw(v2, v3, v0)
*ccw(v2, v3, v1)) <=0);
}
void drawThickLine(struct vertex v1, struct vertex v2, int size) {
int i, j;
for(i=-size; i<size+1; i++)
for(j=-size; j<size+1; j++)
drawLine(v1.coord[0]+i, v1.coord[1]+j, v2.coord[0]+i, v2.coord[1]+j);
}
GLuint renderPolygon() {
int i;
GLuint list_id = glGenLists(1);
GLUtesselator *tobj = gluNewTess();
gluTessCallback(tobj, GLU_TESS_BEGIN, (TessFuncPtr)tessBeginCB);
gluTessCallback(tobj, GLU_TESS_END, (TessFuncPtr)tessEndCB);
gluTessCallback(tobj, GLU_TESS_ERROR, (TessFuncPtr)tessErrorCB);
gluTessCallback(tobj, GLU_TESS_VERTEX, (TessFuncPtr)tessVertexCB);
glNewList(list_id, GL_COMPILE);
glColor4f( 1.0, 1.0, 1.0 , 1.0);
gluTessBeginPolygon(tobj, 0);
gluTessBeginContour(tobj);
for (i=0;i<my_poly.size();i++)
gluTessVertex(tobj, my_poly[i].coord, my_poly[i].coord);
gluTessEndContour(tobj);
gluTessEndPolygon(tobj);
glEndList();
gluDeleteTess(tobj);
return list_id;
}
///////////////////////////////////////////////////////////////////////////////
// GLU_TESS CALLBACKS
///////////////////////////////////////////////////////////////////////////////
void CALLBACK tessBeginCB(GLenum which)
{ glBegin(which); }
void CALLBACK tessEndCB()
{ glEnd(); }
void CALLBACK tessVertexCB(const GLvoid *data)
{
const GLdouble *ptr = (const GLdouble*)data;
glVertex3dv(ptr);
}
void CALLBACK tessErrorCB(GLenum errorCode)
{
const GLubyte *errorStr;
errorStr = gluErrorString(errorCode);
cerr << "[ERROR]: " << errorStr << endl;
}
#endif
| [
"[email protected]"
] | |
34c3a4fae24738ab6946984a1268aecf34abca3c | d56bd63f49a4545ba1262b2fa19ff889388dcd17 | /rsa.h | fcac0693549865c9fb702ae1a7a8cebf82f09c9e | [] | no_license | elpidifor/lab01_rsa | 332de5d8c76168f0cb34b291812dd30d584d8c11 | 1106a9a3de61f2821e2fc2080526fd175614d75f | refs/heads/master | 2020-04-05T07:01:40.455187 | 2018-11-08T06:32:18 | 2018-11-08T06:32:18 | 156,660,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | h | #pragma once
#include <map>
#include <string>
#include <vector>
namespace RSA
{
using ui64 = unsigned long long int;
// Генерирует открытый и закрытый ключи
// открытый ключ - {e, n}
// закрытый ключ - {d, n}
// возвращает пару {public key, private key}
std::pair<std::pair<ui64, ui64>, std::pair<ui64, ui64>> GenerateKeys();
std::string BytesToHex(const std::vector<byte>&);
std::vector<byte> BytesFromHex(const std::string&);
class RSAEncryptor
{
public:
RSAEncryptor(std::pair<ui64, ui64> publicKey);
std::vector<byte> Encrypt(const std::vector<ui64>& message) const;
std::vector<byte> Encrypt(const std::string& message) const;
};
class RSADecryptor
{
public:
RSAEncryptor(std::pair<ui64, ui64> privateKey);
std::vector<ui64> DecryptBytes(const std::vector<byte>& cipherText) const;
std::string Decrypt(const std::vector<byte>& cipherText) const;
};
};
| [
"[email protected]"
] | |
56dc4622a9353efded63c843cddefced664cd5d1 | cb7fec3b5e18c64cedf39857daceb2bc561eef78 | /src/lr0-items.h | 78c01afb01c93874c7f6e1925607d1bccdadc71e | [] | no_license | voyagerok/text-processor | 8826a445202da02a0afbeb8c891ec05074879aae | c1dbcfb4640cfbbe0a633e633cbd09ede27895c8 | refs/heads/master | 2021-01-19T17:55:01.074808 | 2017-06-15T05:09:54 | 2017-06-15T05:09:54 | 88,347,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,231 | h | #ifndef LRO_ITEMS_H_
#define LRO_ITEMS_H_
#include "grammar.h"
#include "grammar-rule.h"
#include <memory>
#include <iostream>
namespace tproc {
struct LR0Item {
GRuleWordPtr rule;
// int position;
WordIndex wordIndex;
GRuleWordPtr getWordAtCurrentPosition();
// bool atEndPosition() { return rule-> <= position; }
bool atEndPosition() {
return rule->getChildWords().at(wordIndex.ruleIndex).size() <= wordIndex.position;
}
bool operator==(const LR0Item &other);
bool operator!=(const LR0Item &other);
friend std::ostream &operator<<(std::ostream &os, const LR0Item &item);
};
struct LR0ItemSet {
using iter = std::vector<LR0Item>::iterator;
using const_iter = std::vector<LR0Item>::const_iterator;
// UnicodeString incomingWord;
GRuleWordPtr incomingWord = nullptr;
int itemsetIndex = 0;
std::vector<LR0Item> items;
std::map<GRuleWordPtr, int> transitions;
void addItem(const LR0Item &item) { items.push_back(item); }
void addItem(LR0Item &&item) { items.push_back(std::move(item)); }
template<class ...Args>
void emplaceItem(Args&&...args) { items.emplace_back(&args...); }
int getNextStateForWord(const GRuleWordPtr &word);
std::map<GRuleWordPtr, int> getTransitions() const { return transitions; }
iter begin() { return items.begin(); }
iter end() { return items.end(); }
const_iter begin() const { return items.begin(); }
const_iter end() const { return items.end(); }
bool operator==(const LR0ItemSet &other);
friend std::ostream &operator<<(std::ostream &os, const LR0ItemSet &itemSet);
};
class LR0ItemSetCollection {
public:
LR0ItemSetCollection();
bool build(const Grammar &grammar);
std::vector<LR0ItemSet> getItemSetCollection() const { return itemSetCollection; }
int size() const { return itemSetCollection.size(); }
private:
void build(const Grammar &grammar, LR0ItemSet &itemSet, int itemSetIndex);
void closure(LR0ItemSet &itemSet, const LR0Item ¤tItem);
void addItemSetToHistory(const LR0ItemSet &itemSet);
std::vector<LR0ItemSet> itemSetCollection;
std::map<GRuleWordPtr, std::vector<LR0ItemSet>> history;
};
}
#endif //LR0_ITEMS_H_
| [
"[email protected]"
] | |
645ebb15d33e5a8e009796f04f5009bb3e314ee9 | 342aedc6768d530d0d1a8496e5a36bb07ceaca92 | /Classes/Utility/SpriteUtils.h | d17ddd2e488eb2a45fda91a3acf9dab266974d4a | [
"MIT"
] | permissive | Riyaaaaa/Cocos2dxAdvLuaEngine | 4e4d88010cb290672a22fdbbcbee0002d10a886a | f00ff97b44b25198bc02dc24411245448d81845f | refs/heads/master | 2021-01-25T11:33:38.925331 | 2017-07-30T09:22:53 | 2017-07-30T09:22:53 | 93,933,227 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | h | //
// SpriteUtils.hpp
// Cocos2dxAdvLuaEngine
//
// Created by Riya.Liel on 2017/06/19.
//
//
#ifndef SpriteUtils_h
#define SpriteUtils_h
#include "cocos2d.h"
namespace SpriteUtils {
void fadeIn(cocos2d::Sprite* sprite, float duration, std::function<void()> endCallback);
}
#endif /* SpriteUtils_hpp */
| [
"[email protected]"
] | |
c6d56491a85ed3964e3d3e05c3cdbeac824ccf15 | b6ed2145ed73919ec42f3d34ccb67a7ecc621b3a | /algorithm/Codeforces/ECRound53/a.cpp | 5ae57362243361d728317b6cdc0117aff480621c | [] | no_license | gilsaia/college-study | 26d9813ab5e5f125618aec787c942e442b0fb630 | 66d2dda1b322077fd58abe56ba602da5260856be | refs/heads/master | 2021-06-03T06:23:05.770868 | 2019-09-22T14:22:22 | 2019-09-22T14:22:22 | 138,689,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | cpp | #include<cstring>
#include<cstdio>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
int num[240];
int main()
{
int n;
scanf("%d",&n);
string s;
cin>>s;
int flag=1;
for(int i=0;i<s.size();++i)
{
for(int j=s.size()-1;j>=i;--j)
{
int pan=0;
string tmp=s.substr(i,j-i+1);
memset(num,0,sizeof(num));
int len=tmp.size();
for(int t=0;t<len;++t)
{
num[tmp[t]]++;
}
for(int t=0;t<150;++t)
{
if(num[t]>len/2)
{
pan=1;
break;
}
}
if(pan==0)
{
printf("YES\n");
cout<<tmp<<endl;
flag=0;
break;
}
}
if(flag==0)
{
break;
}
}
if(flag)
{
printf("NO\n");
}
return 0;
} | [
"[email protected]"
] | |
021525bf1d1e34f38dc382064d775506c4069988 | bb7e1ee8c50d76252290f244d0a8172562a73ee3 | /mmtk.cpp | 364b0601047fdc6e5a65a5519df308de99314ad5 | [] | no_license | vkc12uec/temp-prgs | d2441181c9c74abd817a046444fd7feaa9e31ae9 | 821d14ec259c62eee7ed75b84d4095d37b276a78 | refs/heads/master | 2021-01-15T16:57:42.116352 | 2013-07-08T17:11:59 | 2013-07-08T17:11:59 | 32,124,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 572 | cpp | int cricBinsearch (int *a, int l, int h, int find) {
if (h < l) return -1;
int mid = (l+h)/2;
if (a[l] < a[mid]) //sorted
{
if (find < a[mid])
h = mid-1;
else
l = mid+1; // in bad part
}
else if (a[mid] < a[h]) //sorted
{
if (find > a[mid])
l = mid+1;
else
h = mid-1;
}
return cricBinsearch (a, l, h, find);
}
int main () {
int a [] = {4, 5 , 6, 7, 8, 9, 1, 2,3};
int find = 3;
if (searchincircularsorterlist(a,9, find) == 1)
cout << "\nfound";
//if (cricBinsearch(a, 0, 8, find) == 1)
else cout << "\nnot -found";
return 0;
}
| [
"[email protected]"
] | |
df7ee0d9b03ead708380db03634c05109f6f133a | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /dsgc/src/v20190723/model/DescribeDSPAAssessmentRiskLevelTrendRequest.cpp | 786b9f22d72eb5a023ebe8d1a58b90d30e772aee | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,131 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/dsgc/v20190723/model/DescribeDSPAAssessmentRiskLevelTrendRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Dsgc::V20190723::Model;
using namespace std;
DescribeDSPAAssessmentRiskLevelTrendRequest::DescribeDSPAAssessmentRiskLevelTrendRequest() :
m_dspaIdHasBeenSet(false),
m_startTimeHasBeenSet(false),
m_endTimeHasBeenSet(false),
m_templateIdHasBeenSet(false)
{
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_dspaIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DspaId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_dspaId.c_str(), allocator).Move(), allocator);
}
if (m_startTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StartTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator);
}
if (m_endTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EndTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator);
}
if (m_templateIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TemplateId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_templateId.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetDspaId() const
{
return m_dspaId;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetDspaId(const string& _dspaId)
{
m_dspaId = _dspaId;
m_dspaIdHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::DspaIdHasBeenSet() const
{
return m_dspaIdHasBeenSet;
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetStartTime() const
{
return m_startTime;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetStartTime(const string& _startTime)
{
m_startTime = _startTime;
m_startTimeHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::StartTimeHasBeenSet() const
{
return m_startTimeHasBeenSet;
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetEndTime() const
{
return m_endTime;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetEndTime(const string& _endTime)
{
m_endTime = _endTime;
m_endTimeHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::EndTimeHasBeenSet() const
{
return m_endTimeHasBeenSet;
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetTemplateId() const
{
return m_templateId;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetTemplateId(const string& _templateId)
{
m_templateId = _templateId;
m_templateIdHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::TemplateIdHasBeenSet() const
{
return m_templateIdHasBeenSet;
}
| [
"[email protected]"
] | |
7ca817811ec94d06cc2d31ce3ad0dc17b4f228eb | 3f1dc92ed9d39ee93f8d3895f71b12623efd4f4f | /WLModBus/CMyComObject.h | 7c23fbe9173db1eb90d55a89b6d801a46fdd872b | [] | no_license | Junkg/ModBusProtocol | 6202abb63dccbec515b285aeb1713f1b0821b734 | fae57d8b4f0dd7481c64ffdfbcdf35aa71fafb72 | refs/heads/master | 2020-06-13T23:50:48.183078 | 2019-07-02T08:57:41 | 2019-07-02T08:57:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,202 | h | #ifndef __CMYCOMOBJECT_H__
#define __CMYCOMOBJECT_H__
#pragma once
#include "MBInterface.h"
extern "C" ULONG g_ObjNumber;
// {33C2DAE3-6F89-4318-9F06-9820C87DE202}
extern "C" CLSID CLSID_MODBUS;
class CModBus
{
public:
CModBus();
virtual ~CModBus();
//PDU
/*检查功能吗是否正确*/
ModbusStatus CheckFunctionCode(FunctionCode fc);
/*作为RTU主站或TCP客户端)时,生成读写RTU从站或TCP服务器)对象的命令*/
uint16_t GenerateReadWriteCommand(ObjAccessInfo objInfo, bool* statusList, uint16_t* registerList, uint8_t* commandBytes);
/*解析RTU主站或 TCP客户端)从服务器读取的数据 */
void TransformClientReceivedData(uint8_t* receivedMessage, uint16_t quantity, bool* statusList, uint16_t* registerLister);
//RTU
/*通过CRC校验校验接收的信息是否正确*/
bool CheckRTUMessageIntegrity(uint8_t* message, uint16_t length);
/*生成CRC-16/MODBUS 校验码 多项式: x16 + x15 + x2 + 1 */
uint16_t GenerateCRC16CheckCode(uint8_t* puckData, uint16_t usDataLen);
//COMMON
/*将接收到的写单个Coil值转化为布尔量,对应0x05功能码*/
bool CovertSingleCommandCoilToBoolStatus(uint16_t coilValue, bool value);
/*将布尔量(线圈和输入状态)数组转化为MB字节数组,返回最终数组的长度 */
static uint8_t ConvertBoolArrayToMBByteArray(bool* sData, uint16_t length, uint8_t* oData);
/*将寄存器(输入寄存器和保持寄存器)数组转化为MB字节数组,返回最终数组的长度*/
static uint8_t ConvertRegisterArrayToMBByteArray(uint16_t* sData, uint16_t length, uint8_t* oData);
/*将接收到的写Coil字节数组转化为布尔数组*/
static void ConvertMBByteArrayTotBoolArray(uint8_t* sData, bool* oData);
/*将接收到的写保持寄存器的字节数组专为寄存器数组*/
static void ConvertMBByteArrayToRegisterArray(uint8_t* sData, uint16_t* oData);
/*获取字节中某一个位的值 从0开始*/
bool GetBitValue(uint8_t nData, char nChar);
/*设置某一位上的值,返回原来的值*/
void SetBitValue(uint8_t& nData, char nChar, bool value);
protected:
public:
ModbusStatus m_status;
};
class CModBusStorage
{
public:
/*初始化数据存储区域(创建线圈量、输入状态量、保持寄存器、输入寄存器的存储区域) 输入为结构体数组,在应用程序中定义*/
void InitializeDataStorageStructure(DataObject dataObject[], int length);
protected:
/*获取想要读取的Coil量的值*/
void GetCoilStatus(uint16_t startAddress, uint16_t quantity, bool* statusList);
/*获取想要读取的InputStatus量的值*/
void GetInputStatus(uint16_t startAddress, uint16_t quantity, bool* statusValue);
/*获取想要读取的保持寄存器的值*/
void GetHoldingRegister(uint16_t startAddress, uint16_t quantity, uint16_t* registerValue);
/*获取想要读取的输入寄存器的值*/
void GetInputRegister(uint16_t startAddress, uint16_t quantity, uint16_t* registerValue);
/*设置单个线圈的值*/
bool SetSingleCoil(uint16_t coilAddress, bool coilValue);
/*设置单个寄存器的值*/
void SetSingleRegister(uint16_t registerAddress, uint16_t registerValue);
/*设置多个线圈的值*/
void SetMultipleCoil(uint16_t startAddress, uint16_t quantity, bool* statusValue);
/*设置多个寄存器的值*/
void SetMultipleRegister(uint16_t startAddress, uint16_t quantity, uint16_t* registerValue);
private:
/*重置线圈对象的值*/
void ResetCoilStructure();
/*重置输入状态对象的值*/
void ResetInputStatusStructure();
/*重置输入寄存器对象的值*/
void ResetInputRegisterStructure();
/*重置保持对象的值*/
void ResetHoldingRegisterStructure();
private:
StatusObject m_coilObject;
StatusObject m_inputStatusObject;
RegisterObject m_inputRegisterObject;
RegisterObject m_holdingRegisterObject;
private:
CRITICAL_SECTION m_csCoil;
CRITICAL_SECTION m_csInputStatus;
CRITICAL_SECTION m_csInputRegister;
CRITICAL_SECTION m_csHodingRegister;
};
class INodelegationUnknown
{
public:
virtual HRESULT __stdcall NodelegationQueryInyterface(const IID& iid, void** ppv) = 0;
virtual ULONG __stdcall NodelegationAddRef() = 0;
virtual ULONG __stdcall NodelegationRelease() = 0;
};
class CMyComObject : public INodelegationUnknown , public IModBusTCPServer , public IModBusTCPClient , public IModBusRTUServer , public IModBusRTUClient
{
public:
CMyComObject(IUnknown* pUnknownOuter = NULL);
~CMyComObject();
public:
// IUnKnown
virtual HRESULT STDMETHODCALLTYPE QueryInterface(_In_opt_ REFIID riid, _COM_Outptr_ void __RPC_FAR* __RPC_FAR* ppv);
virtual ULONG STDMETHODCALLTYPE AddRef(void);
virtual ULONG STDMETHODCALLTYPE Release(void);
//INodelegationUnknown
virtual HRESULT STDMETHODCALLTYPE NodelegationQueryInyterface(const IID& iid, void** ppv);
virtual ULONG STDMETHODCALLTYPE NodelegationAddRef(void) ;
virtual ULONG STDMETHODCALLTYPE NodelegationRelease(void) ;
//IModBusTCPServer
/*解析接收到的信息,返回响应命令的长度*/
virtual uint16_t STDMETHODCALLTYPE ParsingClientAccessCommand(uint8_t* receivedMessage, uint8_t* respondBytes) ;
//IModBusTCPClient
/*生成访问服务器的命令*/
virtual uint16_t STDMETHODCALLTYPE CreateAccessServerCommand(ObjAccessInfo objInfo, void* dataList, uint8_t* commandBytes) ;
/*解析收到的服务器相应信息*/
virtual void STDMETHODCALLTYPE ParsingServerRespondMessage(uint8_t* recievedMessage, void* dataList) ;
//IModBusRTUServer
/*解析接收到的信息,并返回合成的回复信息和信息的字节长度,通过回调函数*/
virtual uint16_t STDMETHODCALLTYPE ParsingMasterAccessCommand(uint8_t* receivedMesasage, uint8_t* respondBytes, uint16_t rxLength) ;
//IModBusRTUClient
/*生成访问服务器的命令*/
virtual uint16_t STDMETHODCALLTYPE CreateAccessSlaveCommand(ObjAccessInfo objInfo, void* dataList, uint8_t* commandBytes);
/*解析收到的服务器相应信息*/
virtual void STDMETHODCALLTYPE ParsingSlaveRespondMessage(uint8_t* recievedMessage, uint8_t* command) ;
private:
ULONG m_Ref;
IUnknown* m_pUnknownOuter;
};
#endif //__CMYCOMOBJECT_H__ | [
"[email protected]"
] | |
2da759cc2cfc9cca70035efa421cb690d401a8b1 | 071896f5b8d9034a3874c3d43d0c0f5fb4ef9b61 | /AvidApplicationManager.app/Contents/Frameworks/QtCore.framework/Versions/4/Headers/qmimedata.h | 77f59cf270acd2e2d701d080090dc3b689983caa | [] | no_license | s10331/Application-Manager | b591e6e60f8e3b05936b0b8d7456fcfbc959f950 | 89faca8db246f28bef1b9847c483c0b79e0ead7d | refs/heads/master | 2021-01-10T03:54:46.660443 | 2016-03-17T01:45:45 | 2016-03-17T01:45:45 | 54,079,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,495 | h | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QMIMEDATA_H
#define QMIMEDATA_H
#include <QtCore/qvariant.h>
#include <QtCore/qobject.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Core)
class QUrl;
class QMimeDataPrivate;
class Q_CORE_EXPORT QMimeData : public QObject
{
Q_OBJECT
public:
QMimeData();
~QMimeData();
QList<QUrl> urls() const;
void setUrls(const QList<QUrl> &urls);
bool hasUrls() const;
QString text() const;
void setText(const QString &text);
bool hasText() const;
QString html() const;
void setHtml(const QString &html);
bool hasHtml() const;
QVariant imageData() const;
void setImageData(const QVariant &image);
bool hasImage() const;
QVariant colorData() const;
void setColorData(const QVariant &color);
bool hasColor() const;
QByteArray data(const QString &mimetype) const;
void setData(const QString &mimetype, const QByteArray &data);
void removeFormat(const QString &mimetype);
virtual bool hasFormat(const QString &mimetype) const;
virtual QStringList formats() const;
void clear();
bool getDropped() const;
Qt::KeyboardModifiers getDroppedModifiers() const;
void setDropped(bool dropped, Qt::KeyboardModifiers modifiers = Qt::NoModifier);
protected:
virtual QVariant retrieveData(const QString &mimetype,
QVariant::Type preferredType) const;
private:
Q_DISABLE_COPY(QMimeData)
Q_DECLARE_PRIVATE(QMimeData)
};
QT_END_NAMESPACE
QT_END_HEADER
#endif // QMIMEDATA_H
| [
"[email protected]"
] | |
587741e225d64b743f13fea5d0b4d3b5fc109d1b | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/com/oleutest/cachetst/genenum.h | 0734cf7e8ce6c16d4e37f9db81b9d1fde52a2f65 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,898 | h | //+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1993.
//
// File: genenum.hxx
//
// Contents: Declaration of a generic enum object and test object.
//
// Classes: CGenEnumObject
//
// Functions:
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author! author!
//
//--------------------------------------------------------------------------
#ifndef _GENENUM_H
#define _GENENUM_H
#include <windows.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <ole2.h>
//
// This macro allows the code to use a different outputstring function.
//
EXTERN_C HRESULT TestEnumerator(
void *penum,
size_t ElementSize,
LONG ElementCount,
BOOL (*verify)(void*),
BOOL (*verifyall)(void*,LONG),
void (*cleanup)(void*));
//
// Classes are exposed for C++ clients only
//
#ifdef __cplusplus
//+-------------------------------------------------------------------------
//
// Class: IGenEnum
//
// Purpose: generic enumerator
//
// Interface: Abstract class
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author
//
// Notes:
//
//--------------------------------------------------------------------------
class IGenEnum
{
public:
STDMETHOD(QueryInterface)(REFIID riid, void **ppvObj) = 0;
STDMETHOD_(ULONG,AddRef)(void) = 0;
STDMETHOD_(ULONG,Release)(void) = 0;
STDMETHOD(Next) (ULONG celt, void *rgelt,
ULONG *pceltFetched) = 0;
STDMETHOD(Skip) (ULONG celt) = 0;
STDMETHOD(Reset) (void) = 0;
STDMETHOD(Clone) (void **ppenum) = 0;
};
//+-------------------------------------------------------------------------
//
// Class: CEnumeratorTest
//
// Purpose: enumerator test class
//
// Interface:
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author
//
// Notes:
//
//--------------------------------------------------------------------------
class CEnumeratorTest
{
public:
//
// Constructor
//
CEnumeratorTest(IGenEnum * enumtest, size_t elementsize, LONG elementcount);
//
// Test for each enumerator object
//
HRESULT TestAll(void);
HRESULT TestNext(void);
HRESULT TestSkip(void);
HRESULT TestClone(void);
HRESULT TestRelease(void);
//
// Verification functions
//
virtual BOOL Verify(void *);
virtual BOOL VerifyAll(void*, LONG);
virtual void Cleanup(void *);
protected:
CEnumeratorTest();
BOOL GetNext(ULONG celt, ULONG* pceltFetched, HRESULT* phresult);
IGenEnum * m_pEnumTest;
size_t m_ElementSize;
LONG m_ElementCount;
};
#endif
#endif // !_GENENUM_H
| [
"[email protected]"
] | |
2b57f2e03cc674f87dae1430e91771ec81d4a552 | ef8e28a7b0648d3e09e39d037c0d313a98ef3cea | /D3/3456. 직사각형 길이 찾기.cpp | d9a7bb27dee695d5b55b130dc768372397692f4d | [] | no_license | RBJH/SWExpertAcademy | 07eecf6039e8178797e0a9ac3b0e9c8aa43f0c3e | 3b3cb2f71ce33e8f748831e4cb8c5b032551f846 | refs/heads/master | 2020-07-03T09:12:44.652707 | 2019-10-25T12:33:55 | 2019-10-25T12:33:55 | 201,862,798 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | cpp | #include <iostream>
using namespace std;
int T;
int result;
int main() {
cin >> T;
for (int t = 1; t <= T; t++) {
int a, b, c;
cin >> a >> b >> c;
if (a == b)
result = c;
else if (b == c)
result = a;
else
result = b;
cout << '#' << t << ' ' << result << '\n';
}
return 0;
} | [
"[email protected]"
] | |
46fd2bdc5974730302844cf0a395fe4d7772676b | 088f6b9c903359167ab92422d869b5a7bd0f1521 | /src/bll/AgendaService.h | c1ef509ba0d9ea6e217d3204f3aef880cd062a83 | [
"MIT"
] | permissive | donydchen/Agenda | ccc3a7a1e0f404bf94df08f5235562bed028b973 | 9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a | refs/heads/master | 2021-06-17T00:33:08.344625 | 2017-05-26T16:54:24 | 2017-05-26T16:54:24 | 58,138,327 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | h | #ifndef AGENDASERVICE_H
#define AGENDASERVICE_H
#include "../entity/User.h"
#include "../entity/Meeting.h"
#include <list>
#include <string>
class AgendaService {
public:
virtual bool userLogIn(std::string userName, std::string password) = 0;
virtual bool userRegister(std::string userName, std::string password,
std::string email, std::string phone) = 0;
virtual bool deleteUser(std::string userName, std::string password) = 0;
// a user can only delete itself
virtual std::list<User> listAllUsers(void) const = 0;
virtual bool createMeeting(std::string userName, std::string title,
std::string participator,
std::string startDate, std::string endDate) = 0;
virtual std::list<Meeting> meetingQuery(std::string userName, std::string title) const = 0;
virtual std::list<Meeting> meetingQuery(std::string userName, std::string startDate,
std::string endDate) const = 0;
virtual std::list<Meeting> listAllMeetings(std::string userName) const = 0;
virtual std::list<Meeting> listAllSponsorMeetings(std::string userName) const = 0;
virtual std::list<Meeting> listAllParticipateMeetings(std::string userName) const = 0;
virtual bool deleteMeeting(std::string userName, std::string title) = 0;
virtual bool deleteAllMeetings(std::string userName) = 0;
std::string getServiceName(void) {return serviceName_;}
protected:
std::string serviceName_;
};
#endif
| [
"[email protected]"
] | |
cc195c69a4b9b99274016030db3d9aea92fda2a5 | b43f60bde4985a855e880822085e8c47c1c8b0ed | /moses/FF/SoftMatchingFeature.h | 5f0268e81b7d45d8ca0b164635a3d0814c0863d1 | [] | no_license | BinaryBlob/mosesdecoder | 2cf806c579cbe0b8b4769f2273d2a134ba8271ad | 4488d97629017a644681e008168c891c46fc95b6 | refs/heads/master | 2021-04-18T18:41:05.452146 | 2014-02-14T11:22:53 | 2014-02-14T11:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,329 | h | #pragma once
#include <stdexcept>
#include "moses/Util.h"
#include "moses/Word.h"
#include "StatelessFeatureFunction.h"
#include "moses/TranslationModel/PhraseDictionaryNodeMemory.h"
#ifdef WITH_THREADS
#include <boost/thread/shared_mutex.hpp>
#endif
namespace Moses
{
class SoftMatchingFeature : public StatelessFeatureFunction
{
public:
SoftMatchingFeature(const std::string &line);
bool IsUseable(const FactorMask &mask) const {
return true;
}
virtual void EvaluateChart(const ChartHypothesis& hypo,
ScoreComponentCollection* accumulator) const;
void Evaluate(const Phrase &source
, const TargetPhrase &targetPhrase
, ScoreComponentCollection &scoreBreakdown
, ScoreComponentCollection &estimatedFutureScore) const {};
void Evaluate(const InputType &input
, const InputPath &inputPath
, const TargetPhrase &targetPhrase
, ScoreComponentCollection &scoreBreakdown
, ScoreComponentCollection *estimatedFutureScore = NULL) const {};
void Evaluate(const Hypothesis& hypo,
ScoreComponentCollection* accumulator) const {};
bool Load(const std::string &filePath);
std::map<Word, std::set<Word> >& Get_Soft_Matches() {
return m_soft_matches;
}
std::map<Word, std::set<Word> >& Get_Soft_Matches_Reverse() {
return m_soft_matches_reverse;
}
const std::string& GetFeatureName(const Word& LHS, const Word& RHS) const;
void SetParameter(const std::string& key, const std::string& value);
private:
std::map<Word, std::set<Word> > m_soft_matches; // map LHS of old rule to RHS of new rle
std::map<Word, std::set<Word> > m_soft_matches_reverse; // map RHS of new rule to LHS of old rule
typedef std::pair<Word, Word> NonTerminalMapKey;
#if defined(BOOST_VERSION) && (BOOST_VERSION >= 104200)
typedef boost::unordered_map<NonTerminalMapKey,
std::string,
NonTerminalMapKeyHasher,
NonTerminalMapKeyEqualityPred> NonTerminalSoftMatchingMap;
#else
typedef std::map<NonTerminalMapKey, std::string> NonTerminalSoftMatchingMap;
#endif
mutable NonTerminalSoftMatchingMap m_soft_matching_cache;
#ifdef WITH_THREADS
//reader-writer lock
mutable boost::shared_mutex m_accessLock;
#endif
};
}
| [
"[email protected]"
] | |
98e60c687ddd4b87f50735b00d2f1aea3a1c4bf6 | f4bafe2eadf7c541d70278aa57c70dd902e954bd | /Source/TowerDefence/Turrets/TDFlamethrowerTurret.h | e3aa6f8e1799fb40efa2a924f0b9fca073856d6c | [] | no_license | MelnichenkoDA/UE4_TowerDefence | 3aea920d91168252ff60012f45e389ed3472aacc | 0f4a2a6dae0744b152e5aa6ae3640b6c54fb348d | refs/heads/master | 2022-03-12T14:55:54.598260 | 2019-11-06T14:57:46 | 2019-11-06T14:57:46 | 213,161,355 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,608 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Animation/AnimSequence.h"
#include "UI/TDConstructionBarWidget.h"
#include "DamageTypes/TDDamageTypeFlame.h"
#include "Components/BoxComponent.h"
#include "TDFlamethrowerTurret.generated.h"
UCLASS()
class TOWERDEFENCE_API ATDFlamethrowerTurret : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ATDFlamethrowerTurret();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void Initialise(const float & Timer);
private:
UFUNCTION()
void OnFlameBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult);
UFUNCTION()
void OnFlameEndOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult);
UPROPERTY(EditAnywhere)
USkeletalMeshComponent* TurretMeshComponent;
UPROPERTY(EditAnywhere)
UTDConstructionBarWidget* ConstructionBarWidget;
UPROPERTY(EditAnywhere)
UStaticMeshComponent* FlameMeshComponent;
UPROPERTY(EditAnywhere)
UBoxComponent* CollisionComponent;
UParticleSystemComponent* ParticleComponentCreation;
float ConstructionTimer;
UPROPERTY(EditAnywhere)
float Damage;
bool bConstructed;
};
| [
"[email protected]"
] | |
87d18d90b40ea0ce78371fc959061d30be0fff03 | e5a078e8d7f1da417da6315f7f4080fee16dac0e | /huffmanCode/huffman_code.cpp | 8d1fc135e6a38325cf1acaf2f24996e44f01927b | [] | no_license | Aierhaimian/data-structures | 2fcdab5a31b9d910e39d558ff83918b71d378c27 | 7b3bfbd7f9b12104a2f899258830c05114c0ec22 | refs/heads/master | 2020-04-01T14:24:12.688295 | 2019-09-08T07:33:19 | 2019-09-08T07:33:19 | 153,292,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,456 | cpp | //
// Created by scu_d on 2017/11/17.
//
#include <iostream>
#include <climits>
#include <cstring>
#include <algorithm>
#include <functional>
#include <fstream>
#include "huffman_code.h"
// 选择最小和次小的两个结点,建立哈夫曼树调用
void huffman_code::select(HufNode *huf_tree, unsigned int n, int &s1, int &s2){
unsigned long min = ULONG_MAX;
//find the minimum node
for (int i = 0; i < n; ++i) {
if (huf_tree[i].parent == 0 && huf_tree[i].weight <min){
min = huf_tree[i].weight;
s1 = i;
}
}
huf_tree[s1].parent = 1;// Ok, it's the minimum node now.
//find the second minimum node
min = ULONG_MAX;
for (int i = 0; i < n; ++i) {
if (huf_tree[i].parent == 0 && huf_tree[i].weight < min){
min = huf_tree[i].weight;
s2 = i;
}
}
}
// 建立哈夫曼树
void huffman_code::CreateTree(HufNode *huf_tree, unsigned int char_kinds, unsigned int node_num){
int s1, s2;
for (int i = char_kinds; i < node_num; ++i) {
select(huf_tree, i, s1, s2);//选择最小的两个结点
huf_tree[s1].parent = i;
huf_tree[s2].parent = i;
huf_tree[i].lchild = s1;
huf_tree[i].rchild = s2;
huf_tree[i].weight = huf_tree[s1].weight + huf_tree[s2].weight;
}
}
// 生成哈夫曼编码
void huffman_code::HufCode(HufNode *huf_tree, unsigned char_kinds){
int cur, next, index;
char *code_tmp;
code_tmp = new char[256];//Temporary code, up to 256 leaves, coding length does not exceed 255
code_tmp[256-1] = '\0';
for (int i = 0; i < char_kinds; ++i) {
index = 256 - 1;//Encoding temporary space index initialization
//Reverse traversal from leaf to root for encoding
for (cur = i, next = huf_tree[i].parent; next != 0; cur = next, next = huf_tree[next].parent) {
if (huf_tree[next].lchild == cur)
code_tmp[--index] = '0';//left '0'
else
code_tmp[--index] = '1';//right '1
}
huf_tree[i].code = new char[256-index];//The i_th character encoding dynamic allocation of memory space
strcpy(huf_tree[i].code, &code_tmp[index]);//Forward save encoding to the corresponding node in the tree
}
delete [] code_tmp;
}
// 压缩函数
int huffman_code::compress(std::string file_name, std::string out_filename){
unsigned int char_kinds;// 字符种类
unsigned long file_len = 0;
unsigned char char_temp;// 暂存8bits字符
TmpNode node_temp;
unsigned int node_num;
HufTree huf_tree;
char code_buf[256] = "\0";// 待存编码缓冲区
unsigned int code_len;
//Dynamically allocate 256 nodes, temporary storage character frequency,
// statistics and copied to the tree node immediately after the release
TmpNode *tmp_nodes = new TmpNode[256];
//Init temporary node
for (int i = 0; i < 256; ++i) {
tmp_nodes[i].weight = 0;
tmp_nodes[i].uch = i;//The 256 subscripts of the array correspond to 256 characters
}
//Traverse the file, get the character frequency
std::ifstream in_file(file_name, std::ios::in|std::ios::binary);
if(!in_file){
return -1;
}
in_file.read((char *)&char_temp, sizeof(unsigned char));
while (!in_file.eof()){
++tmp_nodes[char_temp].weight;
++file_len;
in_file.read((char *)&char_temp, sizeof(unsigned char));
}
in_file.close();
//Sort, the frequency of zero put last, remove
for (int i = 0; i < 256-1; ++i) {
for (int j = i + 1; j < 256; ++j) {
if (tmp_nodes[i].weight < tmp_nodes[j].weight) {
node_temp = tmp_nodes[i];
tmp_nodes[i] = tmp_nodes[j];
tmp_nodes[j] = node_temp;
}
}
}
//Statistics of the actual character types (the number of occurrences is not 0)
for (unsigned int i = 0; i < 256; ++i) {
if(tmp_nodes[i].weight == 0){
char_kinds = i;
break;
}
}
std::cout<<"writing compressed file..."<<std::endl;
if (char_kinds == 1){
std::cout<<"char_kinds == 1"<<std::endl;
std::ofstream out_file(out_filename);
out_file.write((char *)&char_kinds, sizeof(unsigned int));
out_file.write((char *)&tmp_nodes[0].uch, sizeof(unsigned char));
out_file.write((char *)&tmp_nodes[0].weight, sizeof(unsigned long));
delete[] tmp_nodes;
out_file.close();
}
else{
//According to the number of characters, calculate the number of nodes needed to establish Huffman tree
node_num = 2 * char_kinds -1;
//Dynamically establish the necessary nodes of the Huffman tree
huf_tree = new HufNode[node_num];
//init the 0 to char_kinds-1 nodes
for (int i = 0; i < char_kinds; ++i) {
//Copy the characters and frequency of the temporary node to the tree node
huf_tree[i].uch = tmp_nodes[i].uch;
huf_tree[i].weight = tmp_nodes[i].weight;
huf_tree[i].parent = 0;
}
delete[] tmp_nodes;
//init the char_kinds to node_num nodes
for (int i = char_kinds; i < node_num; ++i) {
huf_tree[i].parent = 0;
}
//Create the Huffman Tree
huffman_code::CreateTree(huf_tree, char_kinds, node_num);
//Create the Huffman Encode
huffman_code::HufCode(huf_tree,char_kinds);
//write char and weight, for extract process to rebuild Huffman Tree
std::ofstream out_file(out_filename);
out_file.write((char *)&char_kinds, sizeof(unsigned int));
for (int i = 0; i < char_kinds; ++i) {
out_file.write((char *)&huf_tree[i].uch, sizeof(unsigned char));
out_file.write((char *)&huf_tree[i].weight, sizeof(unsigned long));
}
//write file length and weight information
out_file.write((char *)&file_len, sizeof(unsigned long));
std::ifstream in_file(file_name, std::ios::in|std::ios::binary);
if(!in_file){
return -1;
}
in_file.read((char *)&char_temp, sizeof(unsigned char));
while (!in_file.eof()){
//匹配字符对应编码
for (int i = 0; i < char_kinds; ++i) {
if (char_temp == huf_tree[i].uch){
strcat(code_buf, huf_tree[i].code);
}
}
//以8位(1Byte)为处理单元
while (strlen(code_buf) >= 8){
char_temp = '\0';//清空字符暂存空间,改为暂存字符对应编码
for (int k = 0; k < 8; ++k) {
char_temp <<= 1;//左移一位,为下一个bit腾出位置
if (code_buf[k] == '1')
char_temp |= 1;//当编码为"1",通过或操作符将其添加到字节的最低位
}
out_file.write((char *)&char_temp, sizeof(unsigned char));// 将字节对应编码存入文件
strcpy(code_buf, code_buf+8);//编码缓存去除已处理的前八位
}
in_file.read((char *)&char_temp, sizeof(unsigned char));
}
//处理最后不足8bits编码
code_len = strlen(code_buf);
if(code_len > 0){
char_temp = '\0';
for (int i = 0; i < code_len; ++i) {
if(code_buf[i] == '1'){
char_temp |= 1;
}
}
char_temp <<=8-code_len;
out_file.write((char *)&char_temp, sizeof(unsigned char));
}
in_file.close();
out_file.close();
delete [] huf_tree;
}
double rsize_d,dsize_d;
std::ifstream rfile(file_name);
if(!rfile.is_open()) return -1;
rfile.seekg(0,std::ios_base::end);
std::streampos rsize = rfile.tellg();
rfile.close();
std::ifstream dfile(out_filename);
if(!dfile.is_open()) return -1;
dfile.seekg(0,std::ios_base::end);
std::streampos dsize = dfile.tellg();
dfile.close();
rsize_d = rsize;
dsize_d = dsize;
std::cout<<"The "<<file_name<<" is: "<<rsize/1024<<" KB."<<std::endl;
std::cout<<"The compressed file "<<out_filename<<" is: "<<dsize/1024<<" KB."<<std::endl;
std::cout<<"The compression ratio is: "<<(rsize_d - dsize_d)/rsize_d *100<<"%"<<std::endl;
return 1;
}//compress
// 解压函数
int huffman_code::extract(std::string file_name, std::string out_filename){
unsigned long writen_len = 0;// 控制文件写入长度
unsigned long file_len;
unsigned int char_kinds;
unsigned int node_num;
HufTree huf_tree;
unsigned char code_temp;
unsigned int root;// 保存根节点索引,供匹配编码使用
std::ifstream in_file(file_name, std::ios::in|std::ios::binary);
if(!in_file){
return -1;
}
in_file.read((char *)&char_kinds, sizeof(unsigned int));
if (char_kinds == 1){
in_file.read((char *)&code_temp, sizeof(unsigned char));
in_file.read((char *)&file_len, sizeof(unsigned long));
std::ofstream out_file(out_filename);
while (file_len--){
out_file.write((char *)&code_temp, sizeof(unsigned char));
}
in_file.close();
out_file.close();
}else{
node_num = 2*char_kinds - 1;
huf_tree = new HufNode[node_num];
//读取字符及对应权重,存入哈夫曼树结点
//buffer[1]~buffer[152]
for (int i = 0; i < char_kinds; ++i) {
in_file.read((char *)&huf_tree[i].uch, sizeof(unsigned char));
in_file.read((char *)&huf_tree[i].weight, sizeof(unsigned long));
huf_tree[i].parent = 0;
}
//初始化后node_num-char_kins个结点的parent
for (int i = char_kinds; i < node_num; ++i) {
huf_tree[i].parent = 0;
}
//重建哈夫曼树
huffman_code::CreateTree(huf_tree, char_kinds, node_num);
//读完字符和权重信息,紧接着读取文件长度和编码,进行解码
in_file.read((char *)&file_len, sizeof(unsigned long));
std::ofstream out_file(out_filename);
root = node_num-1;
int cnt = 154;
while(1) {
in_file.read((char *)&code_temp, sizeof(unsigned char));
for (int i = 0; i < 8; ++i) {
if (code_temp & 128)
root = huf_tree[root].rchild;
else
root = huf_tree[root].lchild;
if (root < char_kinds){
out_file.write((char *)&huf_tree[root].uch, sizeof(unsigned char));
++writen_len;
if (writen_len == file_len)
break;
root = node_num - 1;
}
code_temp <<= 1;
}
if (writen_len == file_len)
break;
++cnt;
}
in_file.close();
out_file.close();
delete [] huf_tree;
}
return 1;
}//extract
| [
"[email protected]"
] | |
30599d3311bf95f06c167072c49f27d202f68cd0 | 5bae9cd60b37145ebdb7555eeda44610fd8b2451 | /MultiCameraTrafficSignDetection/KalmanFilterTracker.cpp | 308f66b1a35a387df1b35aa1a8217c90d127cb9c | [] | no_license | JayYangSS/ResearchMaster | 1097674bd5d62a433108471f128496ab94d1481a | 87ca8571e2c5272b49a69c227a1f38708214ae4f | refs/heads/master | 2021-01-15T08:30:59.835558 | 2015-02-27T19:20:16 | 2015-02-27T19:20:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,697 | cpp |
#include "stdafx.h"
using namespace cv;
using namespace std;
const int stateNum = 8; //x,y,width,height,detax,detay,deta width,deta height
const int measureNum = 4; //detax,detay,deta width,deta height
KalmanFilterTracker::KalmanFilterTracker()
{
KF = KalmanFilter(stateNum, measureNum, 0);
statePostMat = Mat (stateNum, measureNum, CV_32F);
statePreMat = Mat(measureNum, 1, CV_32F);
precessNoise = Mat(stateNum, 1, CV_32F);
measurement = Mat (measureNum, 1, CV_32F);
measurement.setTo(Scalar::all(0));
init = false;
}
void KalmanFilterTracker::initKF(int x, int y, int width, int height)
{
cout<<"KalmanFilterTrackerInitialization"<<endl;
if(!measureRectVector.empty() )
{
measureRectVector.clear();
cout << "clear measureRectVector"<<endl;
}
if(!predictRectVector.empty() )
{
predictRectVector.clear();
cout << "clear predictRectVector"<<endl;
}
KF.statePost.at<float>(0) = x;
KF.statePost.at<float>(1) = y;
KF.statePost.at<float>(2) = width;
KF.statePost.at<float>(3) = height;
KF.statePost.at<float>(4) = 0;
KF.statePost.at<float>(5) = 0;
KF.statePost.at<float>(6) = 0;
KF.statePost.at<float>(7) = 0;
KF.transitionMatrix = *(Mat_<float>(8, 8) << 1,0,0,0,1,0,0,0, //initialize post state of kalman filter at random
0,1,0,0,0,1,0,0, //state(x,y,width,height,detaX,detaY,detawidth,detaheight), the bigger value of detaX and detaY,
0,0,1,0,0,0,1,0, //the faster tracking speed,original 1,1
0,0,0,1,0,0,0,1,
0,0,0,0,1,0,0,0,
0,0,0,0,0,1,0,0,
0,0,0,0,0,0,1,0,
0,0,0,0,0,0,0,1);
//setIdentity(KF.measurementMatrix);
//setIdentity(KF.processNoiseCov, Scalar::all(1e-4));
//setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));
//setIdentity(KF.errorCovPost, Scalar::all(.1));
//measurement matrix (H) 观测模型
setIdentity(KF.measurementMatrix); //setIdentity: initializes a scaled identity matrix; 缩放的单位对角矩阵;
//process noise covariance matrix (Q)
setIdentity(KF.processNoiseCov, Scalar::all(1e-5)); // wk 是过程噪声,并假定其符合均值为零,协方差矩阵为Qk(Q)的多元正态分布;
//measurement noise covariance matrix (R)
setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1)); //vk 是观测噪声,其均值为零,协方差矩阵为Rk,且服从正态分布;
//priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/ A代表F: transitionMatrix
setIdentity(KF.errorCovPost, Scalar::all(1)); //预测估计协方差矩阵;
//corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
initRect = Rect(x, y, width, height);
predictRectVector.push_back(initRect);
init = true;
counter = 0;
}
void KalmanFilterTracker::updateKF(int x, int y, int width, int height)
{
cout<<"KalmanFilterTrackerUpdateKF"<<endl;
if ( !init )
initKF(x, y, width, height);
//step 1: predit next position based on former position
Mat predictionb = KF.predict(); //prediction before update
Rect predictRect(predictionb.at<float>(0), predictionb.at<float>(1),predictionb.at<float>(2),predictionb.at<float>(3));
//step 2: update measurement
measurement.at<float>(0) = x;
measurement.at<float>(1) = y;
measurement.at<float>(2) = width;
measurement.at<float>(3) = height;
Rect measureRect(measurement.at<float>(0), measurement.at<float>(1),measurement.at<float>(2),measurement.at<float>(3));
measureRectVector.push_back(measureRect); //update measurement
if(measureRectVector.size() > 20) //keep 10 point to draw line
measureRectVector.erase(measureRectVector.begin()); //delete first element
//step 3: give corrected position based on updated measurement and prediction
Mat correct = KF.correct(measurement); //update statepost
Rect stateRect( correct.at<float>(0), correct.at<float>(1), correct.at<float>(2), correct.at<float>(3) );
predictRectVector.push_back(stateRect); //keep 10 point to draw line
if(predictRectVector.size() > 20)
predictRectVector.erase(predictRectVector.begin()); //delete first element
}
void KalmanFilterTracker::updateWithoutMeasurement()
{
cout<<"KalmanFilterTrackerUpdateWithoutMeasurement"<<endl;
//step 1: predit next position based on former position
Mat predictionb = KF.predict(); //prediction before update
Rect predictRect(predictionb.at<float>(0), predictionb.at<float>(1),predictionb.at<float>(2),predictionb.at<float>(3));
//step 2: update measurement
measurement.at<float>(0) = predictionb.at<float>(0);
measurement.at<float>(1) = predictionb.at<float>(1);
measurement.at<float>(2) = predictionb.at<float>(2);
measurement.at<float>(3) = predictionb.at<float>(3);
Rect measureRect(measurement.at<float>(0), measurement.at<float>(1),measurement.at<float>(2),measurement.at<float>(3));
measureRectVector.push_back(measureRect); //update measurement
if(measureRectVector.size() > 20) //keep 10 point to draw line
measureRectVector.erase(measureRectVector.begin()); //delete first element
//step 3: give corrected position based on updated measurement and prediction
Mat correct = KF.correct(measurement); //update statepost
Rect stateRect( correct.at<float>(0), correct.at<float>(1), correct.at<float>(2), correct.at<float>(3) );
predictRectVector.push_back(stateRect); //keep 10 point to draw line
if(predictRectVector.size() > 20)
predictRectVector.erase(predictRectVector.begin()); //delete first element
}
void KalmanFilterTracker::changeStatus(Mat& img)
{
size_t i,j;
warningStatus = ("");
dangerStatus = ("");
space = (" + ");
if( predictRectVector.size() > 0 && predictRectVector.size() < 3)
{
warningStatus = string("Tracking Initialized");
}
else if( predictRectVector.size() > 3 )
{
j = predictRectVector.size() - 1;
i = predictRectVector.size()/2;
if( abs((predictRectVector[j].x+(predictRectVector[j].width/2)) - (img.cols/2)) <
abs((predictRectVector[i].x+(predictRectVector[i].width/2)) - (img.cols/2)) )
{
warningStatus = string("Warning");
if( (predictRectVector[j].y+predictRectVector[j].height) > (img.rows/2) )
{
dangerStatus = string("DANGER!");
}
}
}
}
void KalmanFilterTracker::putStatusText(Mat& img)
{
size_t j;
if(predictRectVector.size() > 0)
{
j = predictRectVector.size() - 1;
putText(img, warningStatus, Point( predictRectVector[j].br().x, predictRectVector[j].br().y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 255), 1, 8, false);//rbg,255,255,0
putText(img, dangerStatus, Point( predictRectVector[j].x, predictRectVector[j].y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 1, 8, false);//scalar:bgr
}
}
void KalmanFilterTracker::drawPredictLine(Mat& img)
{
size_t j = predictRectVector.size() - 1;
for (size_t i=0; i<predictRectVector.size()-1; ++i)
{
line(img, Point((predictRectVector.at(i).x + predictRectVector.at(i).width/2),(predictRectVector.at(i).y + predictRectVector.at(i).height)),
Point((predictRectVector.at(i+1).x + predictRectVector.at(i+1).width/2),(predictRectVector.at(i+1).y + predictRectVector.at(i+1).height)), Scalar(0,255,0), 2, 8);//green line
}
rectangle(img, predictRectVector.at(j).tl(), predictRectVector.at(j).br(),Scalar(0,255,0), 2, 8);//green rectangle
cout<<"predictRectVector.size() : "<< j <<endl;
}
void KalmanFilterTracker::drawMeasureLine(Mat& img)
{
size_t j = measureRectVector.size() - 1;
for (size_t i=0; i<measureRectVector.size()-1; ++i)
{
line(img, Point((measureRectVector.at(i).x + measureRectVector.at(i).width/2),(measureRectVector.at(i).y + measureRectVector.at(i).height)),
Point((measureRectVector.at(i+1).x + measureRectVector.at(i+1).width/2),(measureRectVector.at(i+1).y + measureRectVector.at(i+1).height)), Scalar(255,0,0), 2, 8);
}
rectangle(img, measureRectVector.at(j).tl(), measureRectVector.at(j).br(),Scalar(255,0,0), 2, 8);//blue rectangle
cout<<"measureRectVector.size() : "<< j <<endl;
}
void KalmanFilterTracker::addcounter()
{
counter += 1;
}
int KalmanFilterTracker::getcounter()
{
return counter;
}
void KalmanFilterTracker::drawPretictLinelns(Mat img, double ratio, int resx, int resy, int tempx, int tempy)
{
}
void KalmanFilterTracker::drawMeasureLinelns(Mat img, double ratio, int resx, int resy, int tempx, int tempy)
{
}
| [
"[email protected]"
] | |
56de8778468991181376e8746c8c7ada8d31f380 | f5d87ed79a91f17cdf2aee7bea7c15f5b5258c05 | /MDE/GME/paradigms/CHAOS/interpreters/codegen/BE_Workspace_Generators_T.inl | 71edcdfacfd1b162b5b741ea035a19637a07c454 | [] | no_license | SEDS/CUTS | a4449214a894e2b47bdea42090fa6cfc56befac8 | 0ad462fadcd3adefd91735aef6d87952022db2b7 | refs/heads/master | 2020-04-06T06:57:35.710601 | 2016-08-16T19:37:34 | 2016-08-16T19:37:34 | 25,653,522 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,603 | inl | // -*- C++ -*-
// $Id$
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_File_Open_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Open_T <CONTEXT>::
CUTS_BE_Workspace_File_Open_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Open_T <CONTEXT>::~CUTS_BE_Workspace_File_Open_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_File_Open_T <CONTEXT>::generate (const std::string & name)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_Begin_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_Begin_T <CONTEXT>::
CUTS_BE_Workspace_Begin_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_Begin_T <CONTEXT>::~CUTS_BE_Workspace_Begin_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_Begin_T <CONTEXT>::generate (const std::string & name)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_Project_Include_T
template <typename CONTEXT, typename NODE_TYPE>
CUTS_INLINE
CUTS_BE_Workspace_Project_Include_T <CONTEXT, NODE_TYPE>::
CUTS_BE_Workspace_Project_Include_T (CONTEXT & context)
{
}
template <typename CONTEXT, typename NODE_TYPE>
CUTS_INLINE
CUTS_BE_Workspace_Project_Include_T <CONTEXT, NODE_TYPE>::
~CUTS_BE_Workspace_Project_Include_T (void)
{
}
template <typename CONTEXT, typename NODE_TYPE>
CUTS_INLINE
void CUTS_BE_Workspace_Project_Include_T <CONTEXT, NODE_TYPE>::
generate (const NODE_TYPE & node)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_End_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_End_T <CONTEXT>::
CUTS_BE_Workspace_End_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_End_T <CONTEXT>::~CUTS_BE_Workspace_End_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_End_T <CONTEXT>::generate (const std::string & name)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_File_Close_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Close_T <CONTEXT>::
CUTS_BE_Workspace_File_Close_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Close_T <CONTEXT>::~CUTS_BE_Workspace_File_Close_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_File_Close_T <CONTEXT>::generate (void)
{
}
| [
"[email protected]"
] | |
98a29a5429645a9da996e4e682f57ef8332e6721 | 15d85f364067b7f1820bf69b3f17eaf6a3e4b1ce | /year_1/lab2/2C/code.cpp | 7c7dc24f1b9534513c4db883b8f675dbe7284325 | [] | no_license | iilnar/algo | e8d79022b1c03064c4f4a1837a6f2c9278a520eb | 6814bff22c3bb3ada1751c51f4b1a084789970f4 | refs/heads/master | 2021-01-20T21:07:00.963386 | 2016-05-28T20:56:09 | 2016-05-28T20:56:09 | 59,911,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,323 | cpp |
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
using namespace std;
#define FILENAME "num2choose"
long long n, k, m;
vector <int> ans;
vector <int> num2perm (int n, long long k) {
vector <int> res(n), able;
vector <long long> fact(n + 1);
int j;
fact[0] = 1;
for (long long i = 1; i <= n; i++) {
fact[i] = fact[i - 1] * i;
able.push_back(i);
}
for (int i = 0; i < n; i++) {
j = k / fact[n - i - 1];
k %= fact[n - i - 1];
res[i] = able[j];
able.erase(able.begin() + j, able.begin() + j + 1);
}
return res;
}
long long perm2num (int n, vector <int> v) {
vector <long long> fact(n + 1);
vector <int> able;
fact[0] = 1;
long long res = 0;
for (long long i = 1; i <= n; i++) { fact[i] = fact[i - 1] * i; able.push_back(i);}
for (int i = 0; i < v.size(); i++) {
int j = 0;
while (able[j] != v[i]) j++;
able.erase(able.begin() + j, able.begin() + j + 1);
res += fact[n - i - 1] * j;
}
return res;
}
vector <vector <long long> > Pascal (int n) {
vector <vector <long long> > p;
p.resize(n);
p[0].push_back(1);
for (int i = 1; i < n; i++) {
p[i].push_back(1);
for (int j = 1; j < p[i - 1].size(); j++) {
p[i].push_back(p[i - 1][j - 1] + p[i - 1][j]);
}
p[i].push_back(1);
}
return p;
}
vector <int> num2choose (int n, int k, long long m) {
vector <vector <long long> > pas = Pascal(n);
vector <int> res(k);
int j = 0, last = 0;
for (int i = 0; i < k; i++) {
j = last + 1;
while (k - i - 1 >= 0 && m >= pas[n - j][k - i - 1]) {
m -= pas[n - j][k - i - 1];
j++;
}
res[i] = j;
last = j;
}
return res;
}
int main () {
//freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
freopen(FILENAME".in", "r", stdin); freopen(FILENAME".out", "w", stdout);
cin >> n >> k >> m;
ans = num2choose(n, k, m);
for (int i = 0; i < k; i++) {
cout << ans[i] << ' ';
}
return 0;
} | [
"[email protected]"
] | |
4201e04e517e4197a374132fa38ec0a4a5fe22f6 | d556a95cded3a906cf4acd06e92daf4701d80c9a | /Level 2/Lab3/TransactionAccount.cpp | e30f05a2e5eb481498173163bca362657147b549 | [] | no_license | Hergeirs/Cpp-Obj | 4402fb6db7664908760b3962774086fb33d201f0 | 7b968b0463cc56e1bc9e0d27be3eb6e3e49acdf2 | refs/heads/master | 2021-01-17T12:26:15.478314 | 2017-11-01T19:47:33 | 2017-11-01T19:47:33 | 84,065,899 | 1 | 0 | null | 2017-03-07T18:25:59 | 2017-03-06T11:33:04 | C++ | UTF-8 | C++ | false | false | 624 | cpp | #include "TransactionAccount.hpp"
TransactionAccount::TransactionAccount(const unsigned int accountNo,const double amount,const double pCredit)
:Account(accountNo,amount,TRANSACTION),credit(pCredit)
{
//
}
const bool TransactionAccount::withdraw(const double amount)
{
return balance+credit < amount ? false : (balance-=amount);
}
const bool TransactionAccount::setCredit(const double newCredit)
{
return balance+newCredit < 0 ? false : (credit=newCredit);
}
const double TransactionAccount::getUsableBalance() const
{
return balance+credit;
}
const double TransactionAccount::getCredit() const
{
return credit;
} | [
"[email protected]"
] | |
674ec817498caa5ae04f180e05fde9d58e2b7b20 | 18c95cc0e34c1a77e46774feb939762aca390d73 | /src/GraphicAPI.cpp | 09716f091e06965cfe6fb60912eae8c88ba3f7a0 | [] | no_license | aleiii/GraphicAPI | d8d5c506bc6e355bb0f5f48f8cc24cd4146949f5 | ffc3c144d99d679f2ad83b8381faffe72551206c | refs/heads/master | 2022-07-11T23:02:02.372103 | 2020-05-07T05:19:28 | 2020-05-07T05:19:28 | 261,947,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,026 | cpp | // GraphicAPI.cpp : 定义应用程序的入口点。
//
//#include "framework.h"
#include "GraphicAPI.h"
#include "GraphicDraw.h"
#define MAX_LOADSTRING 100
#define WIN_WIDTH 1200
#define WIN_HEIGHT 800
using namespace ALEI;
// 全局变量:
HINSTANCE hInst; // 当前实例
WCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本
WCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名
// 此代码模块中包含的函数的前向声明:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int, HWND&);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
void MY_PAINT_MISSION(HDC hdc);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
//HINSTANCE hInstance = GetModuleHandle(0);
//int nCmdShow = 10;
// 初始化全局字符串
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_GRAPHICAPI, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
HWND hWnd;
// 执行应用程序初始化:
if (!InitInstance (hInstance, nCmdShow, hWnd))
{
return FALSE;
}
HDC hdc = GetDC(hWnd);
// TODO: 在此处放置代码。
// MY_PAINT_MISSION(hdc);
//ALEI::line(hdc, 100, 100, 200, 300);
//ALEI::circle(hdc, 150, 150, 100, 3*pi/4, 2*pi);
//ALEI::ellipse(hdc, 400, 400, 100, 50);
//用线段画一个矩形
ALEI::line(hdc, 500, 200, 600, 200);
ALEI::line(hdc, 500, 250, 600, 250);
ALEI::line(hdc, 500, 200, 500, 250);
ALEI::line(hdc, 600, 200, 600, 250);
ALEI::Flood_Fill_4(hdc, 550, 210, RGB(255,255,255), RGB(255,0,0));
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GRAPHICAPI));
MSG msg;
// 主消息循环:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// 函数: MyRegisterClass()
//
// 目标: 注册窗口类。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GRAPHICAPI));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
// wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_GRAPHICAPI);
// 菜单栏
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// 函数: InitInstance(HINSTANCE, int)
//
// 目标: 保存实例句柄并创建主窗口
//
// 注释:
//
// 在此函数中,我们在全局变量中保存实例句柄并
// 创建和显示主程序窗口。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow, HWND &hWnd)
{
hInst = hInstance; // 将实例句柄存储在全局变量中
hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, WIN_WIDTH, WIN_HEIGHT, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 目标: 处理主窗口的消息。
//
// WM_COMMAND - 处理应用程序菜单
// WM_PAINT - 绘制主窗口
// WM_DESTROY - 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
//case WM_COMMAND:
// {
// int wmId = LOWORD(wParam);
// // 分析菜单选择:
// switch (wmId)
// {
// case IDM_ABOUT:
// DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
// break;
// case IDM_EXIT:
// DestroyWindow(hWnd);
// break;
// default:
// return DefWindowProc(hWnd, message, wParam, lParam);
// }
// }
// break;
//case WM_PAINT:
// {
// //PAINTSTRUCT ps;
// //HDC hdc = BeginPaint(hWnd, &ps);
// //// TODO: 在此处添加使用 hdc 的任何绘图代码...
// //EndPaint(hWnd, &ps);
// }
// break;
case WM_ERASEBKGND:
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
//// “关于”框的消息处理程序。
//INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
//{
// UNREFERENCED_PARAMETER(lParam);
// switch (message)
// {
// case WM_INITDIALOG:
// return (INT_PTR)TRUE;
//
// case WM_COMMAND:
// if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
// {
// EndDialog(hDlg, LOWORD(wParam));
// return (INT_PTR)TRUE;
// }
// break;
// }
// return (INT_PTR)FALSE;
//}
// 此处为绘图任务内容
void MY_PAINT_MISSION(HDC hdc) {
for (int i = 0; i < 400; i++)
{
for (int j = 0; j < 400; j++)
SetPixel(hdc, i, j, RGB(255, 182, 193));
}
SetPixel(hdc, 200, 200, RGB(255, 0, 0));
}
| [
"[email protected]"
] | |
bfaebbfa1a5ecfcc3e1ec91cb2ee5c0b3ae531d8 | b32b94b936f87d8b2fcc823040a4df43f6590614 | /Codeforces/Round231/A.cpp | 1eeb0374349a8e9b8235a5111f957534cf7478d1 | [] | no_license | nitish1402/OPC | e856e9d00664741f2f533706cd4c6702b9ff1759 | 98f2e8dfe78ca8b5bc09a92bcbed1a5d4304a71f | refs/heads/master | 2016-09-06T08:14:04.967108 | 2014-03-26T09:01:40 | 2014-03-26T09:01:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,905 | cpp | /* @author :nitish bhagat */
//header files
#include <cstdlib>
#include <stdio.h>
#include <cstring>
#include <complex>
#include <vector>
#include <cmath>
#include <ctime>
#include <iostream>
#include <numeric>
#include <algorithm>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <iomanip>
#include <utility>
#include <locale>
#include <sstream>
#include <string> // this should be already included in <sstream>
using namespace std;
//short lazieeeeeee
#define FOR(i,n) for(i=0;i<n;i++)
#define FORI(i,a,n) for(i=a;i<n;i++)
#define FORC(it,C) for(it=C.begin();it!=C.end();it++)
#define scanI(x) scanf("%d",&x)
#define scanD(x) scanf("%lf",&x)
#define print(x) printf("%d\n",x)
#define ll long long
#define number32 4294967296ull
#define MAX 1000005
#define len(s) s.length()
#define MOD 1000000007
#define ff first
#define ss second
#define all(C) (C.begin(),C.end())
#define pb(k) push_back(k)
#define mp(i,j) make_pair(i,j)
//shorter Containers
#define Mii map<int,int>
#define Mci map<char,int>
#define Msi map<string,int>
#define Si set<int>
#define Sc set<char>
#define Ss set<string>
#define Pii pair<int,int>
#define PLL pair<ll,ll>
#define Pci pair<char,int>
#define Psi pair<string,int>
#define vi vector<int>
#define vl vector<ll>
#define vc vector<int>
//iterators
#define Miii map<int,int>::iterator
#define Mcii map<char,int>::iterator
#define Msii map<string,int>::iterator
#define Sii set<int>::iterator
#define Sci set<char>::iterator
#define Ssi set<string>::iterator
#define Piii pair<int,int>::iterator
#define Pcii pair<char,int>::iterator
#define Psii pair<string,int>::iterator
#define PLLi pair<ll,ll>::iterator
#define vii vector<int>::iterator
#define vli vector<ll> :: iterator
#define vci vector<int>::iterator
///cout<<(double)(clock() - tStart)/CLOCKS_PER_SEC<<endl;
///clock_t tStart = clock();
int main()
{
return 0;
}
| [
"[email protected]"
] | |
e232da49934a42ca9c44c03e990b3b55ebb80a5e | 20fc58fb946302e700f03ee0b20c8da07eb42563 | /code/Motor2D/UI_Scrollbar.h | d5ae9f27247d5069947351707b0a844afb49a927 | [
"MIT"
] | permissive | paupedra/Sprite-Ordering-and-Camera-Culling | 78a54976003884ef2359e4341f4c3d3738391b3c | 2774bad9d751df665dc78fbf8c34a27393efa35f | refs/heads/master | 2022-08-30T03:46:36.092765 | 2020-05-22T15:59:18 | 2020-05-22T15:59:18 | 254,883,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,647 | h | #ifndef __UI_SCROLLBAR_H__
#define __UI_SCROLLBAR_H__
#include "UI.h"
class UI_Image;
class UI_Scrollbar : public UI
{
public:
UI_Scrollbar(UI_ELEMENT element, int x, int y, SDL_Rect hitbox, SDL_Rect thumbSize, iPoint thumbOffset, SDL_Rect dragArea, float dragFactor, bool dragXAxis = false, bool dragYAxis = true,
bool invertedScrolling = false, bool isVisible = true, bool isInteractible = false, bool isDraggable = false, Module* listener = nullptr, UI* parent = nullptr,
SDL_Rect* scrollMask = nullptr, iPoint maskOffset = iPoint(0, 0), bool emptyElements = false);
bool Draw();
void CheckInput();
public:
void DrawScrollbarElements();
void LinkScroll(UI* element);
void UpdateLinkedElements();
bool LinkedElementsBeingHovered();
bool MouseWithinDragArea();
float GetDragFactor(UI* element);
bool GetDragXAxis() const;
bool GetDragYAxis() const;
iPoint GetThumbLocalPos();
SDL_Rect GetThumbHitbox();
void SetThumbHitbox(SDL_Rect hitbox);
void PlaceThumbOnMousePos();
void CheckKeyboardInputs();
void DragThumbWithMousewheel();
bool ThumbIsWithinVerticalScrollbarBounds();
bool ThumbIsAtUpperBound();
bool ThumbIsAtLowerBound();
bool ThumbIsWithinHorizontalScrollbarBounds();
bool ThumbIsAtLeftBound();
bool ThumbIsAtRightBound();
void CheckScrollbarBounds();
private:
UI_Image* bar;
UI_Image* thumb;
UI_Image* scrollMask;
int scrollbarWidth;
int scrollbarHeight;
SDL_Rect dragArea;
float dragFactor;
iPoint dragDisplacement;
iPoint mouseWheelScroll;
bool invertedScrolling;
float arrowPosFactor;
iPoint newThumbPos;
std::vector<UI*> linkedElements;
};
#endif // !__UI_SCROLLBAR_H__ | [
"[email protected]"
] | |
4f8f74686682f975ecb1419fbcdb1747c9dcdf1e | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE134_Uncontrolled_Format_String/s01/CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G.cpp | 325ffff5528105ccb4cc14db3ff2ec165f8e7004 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 2,411 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-83_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: console Read input from the console
* GoodSource: Copy a fixed string into data
* Sinks: vprintf
* GoodSink: vprintf with a format string
* BadSink : vprintf without a format string
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include <stdarg.h>
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__char_console_vprintf_83.h"
namespace CWE134_Uncontrolled_Format_String__char_console_vprintf_83
{
CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G::CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G(char * dataCopy)
{
data = dataCopy;
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
}
static void goodB2GVaSink(char * data, ...)
{
{
va_list args;
va_start(args, data);
/* FIX: Specify the format disallowing a format string vulnerability */
vprintf("%s", args);
va_end(args);
}
}
CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G::~CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G()
{
goodB2GVaSink(data, data);
}
}
#endif /* OMITGOOD */
| [
"[email protected]"
] | |
40ee8a170d90789e7c8f5ba48366dfebbd99d0e6 | a947e018ec7036b98520aefea01d3ade68fafa92 | /src/CommandLineParser.hpp | e29c0aeb25179c729d88432b3c86d85d32d76e5d | [] | no_license | qutab/ata_identify | 1db9885a3c6c31c8562dc5f33895e7734b45190f | 755a82ec9f632ad4a2159b8dd2d2fd570d446af6 | refs/heads/master | 2020-04-08T06:08:30.810334 | 2018-11-26T00:09:17 | 2018-11-26T00:09:17 | 159,086,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | hpp | #pragma once
#include <string>
#include <vector>
namespace utils {
/** Parser for command line arguments */
class CommandLineParser final
{
public:
/**
* @param argc number of command line args
* @param argv array of command line args
*/
CommandLineParser(int argc, char* argv[]);
~CommandLineParser();
/** @return upstream endpoint parsed from command line */
std::string getFilename() const;
/** @return whether verbose logging is requested */
bool isVerbose() const;
std::string getUsageMsg() const;
private:
std::vector<std::string> argsM;
};
} /* namespace utils */
| [
"[email protected]"
] | |
6c35b31836f4223aa440417d0cb4eec077bf1849 | 6562bf42f158ac2e16d4b90fe12a8c815fced159 | /openshares-node/libraries/chain/include/capricorn/chain/balance_evaluator.hpp | 6e20f39036ee7ec42145cda4598a891232cc8525 | [
"MIT"
] | permissive | moonstonedac/openshares | 3c302211bfa8e8e8194a2b43b61b06c8c3a55bbe | c6ecee64bd36cb473f24d34669401e712365f2da | refs/heads/master | 2021-01-11T22:21:37.470987 | 2017-01-27T14:53:14 | 2017-01-27T14:53:14 | 78,952,910 | 0 | 0 | null | 2017-01-27T14:53:14 | 2017-01-14T16:49:35 | C++ | UTF-8 | C++ | false | false | 1,952 | hpp | /*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <capricorn/chain/protocol/transaction.hpp>
#include <capricorn/chain/database.hpp>
#include <capricorn/chain/balance_object.hpp>
#include <capricorn/chain/evaluator.hpp>
#include <capricorn/chain/exceptions.hpp>
namespace capricorn { namespace chain {
class balance_claim_evaluator : public evaluator<balance_claim_evaluator>
{
public:
typedef balance_claim_operation operation_type;
const balance_object* balance = nullptr;
void_result do_evaluate(const balance_claim_operation& op);
/**
* @note the fee is always 0 for this particular operation because once the
* balance is claimed it frees up memory and it cannot be used to spam the network
*/
void_result do_apply(const balance_claim_operation& op);
};
} } // capricorn::chain
| [
"[email protected]"
] | |
98ac9d660780fca490a2ad762f2930118f8f05d3 | b8c8a7c9747d4ded741e6aa7465e954d676d3cba | /my.cpp | 5f2a51ab8ebb51b9d11a57e4df61d8781b27ee9e | [] | no_license | BinwuPeng/ECE551-C-Course-Work | f0ac812726eea3a7cde5655838273cce8d6ef126 | 885b3a7291479a28623299a00661122504a1dc25 | refs/heads/master | 2020-04-22T19:39:11.364974 | 2019-08-20T20:12:38 | 2019-08-20T20:12:38 | 170,614,744 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
extern char **environ;
int main(int argc, char **argv, char** env) {
system("env");
//printf("%s\n", " ");
//printf("%s\n", " ");
//char *argt[] = {"env", NULL};
//execve("env", {"env",NULL}, environ);
}
| [
"[email protected]"
] | |
559b6871162434517e9881d1284e8d76539471f1 | f816c668c0a43c702884558867300db94651269d | /StoreFrontEnd/Views/CollectionView/VCollectionView.cpp | f7d3eaa42a5890634cb6fadc00129da1d13fab06 | [] | no_license | MRobertEvers/Card-Collection-Manager | a77de7df7d80e712d1318b2a8abed1a6492454f7 | 8ff77956c70bbbaa803f88061208e681a4533917 | refs/heads/master | 2021-07-11T23:43:26.051644 | 2018-12-09T01:17:56 | 2018-12-09T01:17:56 | 114,420,990 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,510 | cpp | #include "VCollectionView.h"
#include "CCollectionView.h"
#include "CubeRenderer.h"
#include "../Views/CardView/VCardView.h"
#include "../Views/CollectionEditor/viCollectionEditor.h"
wxBEGIN_EVENT_TABLE( VCollectionView, wxPanel )
//EVT_BUTTON( viCardEditor::Changes_Submit, vCollectionCube::onCardChanged )
//EVT_BUTTON( viCardEditor::Image_Changed, vCollectionCube::onNewItemSelectView )
EVT_GRID_CELL_LEFT_CLICK( VCollectionView::onItemClicked )
EVT_BUTTON( VCollectionView::COLLECTION_EDITED, VCollectionView::onCollectionEditorAccept )
EVT_BUTTON( viCollectionEditor::Changes_Accept, VCollectionView::onCollectionEditorAccept )
wxEND_EVENT_TABLE()
VCollectionView::VCollectionView( wxFrame* aParent, wxWindowID aiWID )
: wxPanel(aParent, aiWID)
{
m_mgr.SetManagedWindow( this );
this->GetParent()->SetMinSize( wxSize( 550, 500 ) );
auto pTargetFrame = this->GetParent();
if( pTargetFrame->GetSize().GetWidth() < pTargetFrame->GetMinSize().GetWidth() ||
pTargetFrame->GetSize().GetHeight() < pTargetFrame->GetMinSize().GetHeight() )
{
pTargetFrame->SetSize( pTargetFrame->GetMinSize() );
}
this->GetParent()->Layout();
}
VCollectionView::~VCollectionView()
{
// Don't need to destroy this because wxwidgets will.
//m_ptRenderer->Destroy();
m_mgr.UnInit();
}
void
VCollectionView::SetController( CCollectionView* aptController )
{
m_ptController = aptController;
}
// Takes ownership
void
VCollectionView::SetRenderer( FlexibleGroupRenderer* aptRenderer )
{
m_ptRenderer = aptRenderer;
// TODO: this is ugly;
auto panel = dynamic_cast<wxPanel*>(aptRenderer);
if( panel != nullptr )
{
m_mgr.AddPane( panel,
wxAuiPaneInfo().CenterPane() );
m_mgr.Update();
//GetSizer()->Add( panel, wxSizerFlags( 1 ).Expand() );
//uiPrepareSidePanel();
}
}
void
VCollectionView::Draw( std::vector<CardInterface*> avecItemData )
{
if( m_ptRenderer != nullptr )
{
std::vector<std::shared_ptr<IRendererItem>> vecItems;
for( auto& ptr : avecItemData )
{
vecItems.push_back( std::shared_ptr<IRendererItem>(new RendererItem(ptr) ) );
}
m_ptRenderer->Draw( vecItems );
}
}
void
VCollectionView::Undraw( const wxString & aszDisplay, const wxString & aszUID )
{
auto iter_item = m_ptRenderer->LookupItem( aszDisplay.ToStdString(), aszUID.ToStdString() );
if( iter_item != nullptr )
{
m_ptRenderer->RemoveItem( iter_item );
}
}
void
VCollectionView::Draw( CardInterface* apNew )
{
for( auto& uid : apNew->GetRepresentingUIDs() )
{
Undraw( apNew->GetName(), uid );
}
m_ptRenderer->AddItem( std::shared_ptr<IRendererItem>( new RendererItem( apNew ) ) );
}
void
VCollectionView::ShowCardViewer( IViewFactory* aptViewer )
{
auto view = aptViewer->GetView( this );
m_mgr.AddPane( view,
wxAuiPaneInfo().Right().CaptionVisible( false ).CloseButton( false ).Floatable(false).Fixed().BestSize( view->GetBestSize()) );
m_mgr.Update();
//m_ptSidePanel->GetSizer()->Add( aptViewer->GetView( m_ptSidePanel ), wxSizerFlags( 0 ).Align(wxTOP | wxCenter) );
//this->Layout();
}
void
VCollectionView::ShowCardInventoryViewer( IViewFactory* aptViewer )
{
auto view = aptViewer->GetView( this );
m_mgr.AddPane( view,
wxAuiPaneInfo().Right().CaptionVisible(false).CloseButton(false).Floatable(false).BestSize( view->GetBestSize() ) );
m_mgr.Update();
//m_ptSidePanel->GetSizer()->Add( aptViewer->GetView(m_ptSidePanel), wxSizerFlags( 1 ).Expand() );
//this->Layout();
}
void
VCollectionView::onCollectionEditorAccept( wxCommandEvent& awxEvt )
{
// m_ptController->OnCollectionEdited();
CollectionDelta* delta = dynamic_cast<CollectionDelta*>((CollectionDelta*)awxEvt.GetClientData());
if( delta == nullptr )
{
m_ptController->OnCollectionEdited();
}
else
{
auto myDelta = std::shared_ptr<CollectionDelta>( delta );
// Take ownership of the data.
m_ptController->OnCollectionEdited( myDelta );
}
}
void
VCollectionView::onItemClicked( wxGridEvent& awxEvt )
{
auto pItem = dynamic_cast<RendererItem*>((RendererItem*)awxEvt.GetClientData());
if( pItem != nullptr )
{
m_ptController->ViewItem( pItem->GetBase() );
}
awxEvt.Skip();
}
void
FlexibleGroupRenderer::InitRenderer( std::vector<std::shared_ptr<IRendererItem>> avecItemData )
{
for( auto& item : avecItemData )
{
m_mapLookup.insert( std::make_pair( item->GetName(), item ) );
}
}
std::shared_ptr<IRendererItem>
FlexibleGroupRenderer::LookupItem( const std::string & aszDisplay, const std::string & aszUID )
{
auto pair_item_range = m_mapLookup.equal_range( aszDisplay );
for( auto iter_named = pair_item_range.first;
iter_named != pair_item_range.second;
iter_named++ )
{
if( iter_named->second->RepresentsUID( aszUID ) )
{
return iter_named->second;
}
}
return std::shared_ptr<IRendererItem>();
}
void
FlexibleGroupRenderer::ItemRemoved( std::shared_ptr<IRendererItem> apAdded )
{
auto pair_item_range = m_mapLookup.begin();
for( ;
pair_item_range != m_mapLookup.end();
pair_item_range++ )
{
if( pair_item_range->second == apAdded )
{
m_mapLookup.erase( pair_item_range );
break;
}
}
}
void
FlexibleGroupRenderer::ItemAdded( std::shared_ptr<IRendererItem> apAdded )
{
m_mapLookup.insert( std::make_pair( apAdded->GetName(), apAdded ) );
}
| [
"[email protected]"
] | |
614ec6dfbb9d10d1bef6281d242fc7f1ad2fde26 | b4660cc8fa3ce045508105fa52228a98fa19a87d | /src/gui/post_install_dialog/post_install_dialog.h | efd4222a68f02b55fb045c2c62c83c05e0530280 | [
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-public-domain"
] | permissive | hnakamur/mozc-deb | 81e9b561863e57da73aa9ba90d24ff5d0bca480b | a0d6db21786ae7fc54806714cbeca6c7c74cbd36 | refs/heads/master | 2021-04-15T09:32:03.635220 | 2018-05-04T10:09:23 | 2018-05-04T10:09:23 | 126,575,465 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,616 | h | // Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef MOZC_GUI_POST_INSTALL_DIALOG_H_
#define MOZC_GUI_POST_INSTALL_DIALOG_H_
#include <memory>
#include "base/port.h"
#include "gui/post_install_dialog/ui_post_install_dialog.h"
namespace mozc {
namespace gui {
class SetupUtil;
// Shows additional information to the user after installation.
// This dialog also set Mozc as the default IME if it is closed
// with the check box marekd.
class PostInstallDialog : public QDialog,
private Ui::PostInstallDialog {
Q_OBJECT;
public:
PostInstallDialog();
virtual ~PostInstallDialog();
protected slots:
virtual void OnOk();
virtual void OnsetAsDefaultCheckBoxToggled(int state);
virtual void reject();
private:
// - Sets Mozc as the default IME if the check box on the
// dialog is marked.
// - Imports MS-IME's user dictionary to Mozc' dictionary if
// the checkbox on the dialog is marked.
void ApplySettings();
std::unique_ptr<SetupUtil> setuputil_;
};
} // namespace gui
} // namespace mozc
#endif // MOZC_GUI_POST_INSTALL_DIALOG_H_
| [
"[email protected]"
] | |
d5c39ee96f0ca0d6432b774da2764b04566e8e68 | 965bb5b0652e62900c1c4494ca741d3a1f845b88 | /ObstacleAvoid/LocalizationManager.h | 565b6e3c99e16507e14edc65a051ef54a72d0ba3 | [] | no_license | adielbaz25/ObstacleAvoid | 6c1509d0a37c93b5e117c43def28f9e3bafa6de4 | 789cfd833124d2bf99cae26bf7e045eac69c6ce1 | refs/heads/master | 2021-01-01T20:20:42.002061 | 2017-08-03T22:07:45 | 2017-08-03T22:07:45 | 98,818,989 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,900 | h | #ifndef LOCALIZATIONMANAGER_H_
#define LOCALIZATIONMANAGER_H_
#include "LocalizationParticle.h"
#include <vector>
#include <HamsterAPIClientCPP/Hamster.h>
#include "Constants.h"
#include "Structs.h"
#include "MapMatrix.h"
#define NUM_OF_PARTICALES 350
#define TRY_TO_BACK 20
#define TOP_PARTICALES 80
#define BAD_PARTICALES 80
using namespace std;
using namespace HamsterAPI;
//this class manage all the particals in the map
class LocalizationManager
{
public:
void Update(float deltaX, float deltaY, float deltaYaw, LidarScan* lidarHandler, MapMatrix* map);
LocalizationParticle* BestParticle(LidarScan* lidar, float x, float y);
bool CreateParticle(float xDelta, float yDelta, float yawDelta, float belief);
bool CreateParticle(float xDelta, float yDelta, float yawDelta, float belief, float expansionRadius, float yawRange, int childsCount);
void DuplicateParticle(LocalizationParticle* particle, int childCount, vector<LocalizationParticle*>& childs);
void DuplicateParticle(LocalizationParticle* particle, int childCount, float expansionRadius, float yawRange, vector<LocalizationParticle*>& childs);
void ChildsToParticles(vector<LocalizationParticle*> childs);
vector<LocalizationParticle *> particles;
public:
MapMatrix* map;
Robot* robot;
Hamster *hamster;
//return back the particales which out of the free cells range to free cells range
bool tryReturnBackOutOfRangeParticle(LocalizationParticle *particle);
//update the particale's belief
double updateBelief(LocalizationParticle *particle);
//create a random particale
void createRandomParticle(LocalizationParticle *particle);
//close the bad particale near to a particale with a high belief
void createNeighborParticales(LocalizationParticle *prevP, LocalizationParticle *newP);
void initSourceParticle(positionState * ps);
double randNumberFactor(int level);
double randNumberFactorYaw(int level);
void calculateRealPos(LocalizationParticle* p,
double deltaX,
double deltaY,
double deltaYaw);
void calculateYaw(LocalizationParticle* p, double deltaYaw);
void calculatePositionOnMap(LocalizationParticle* p);
void replaceBadOutOfRangeParticle(LocalizationParticle* p, int size);
double computeBelief(LocalizationParticle *particle, LidarScan& scan);
public:
OccupancyGrid *ogrid;
//constructor
LocalizationManager( OccupancyGrid *ogrid, Hamster *hamster, Robot* amnon, MapMatrix* map);
//getter
vector<LocalizationParticle *>* getParticles();
//print the particale's vector
void printParticles() ;
//create new random particals on the map
void InitParticalesOnMap(positionState * ps);
//move the particales according to the robot's movement
void moveParticales(double deltaX, double deltaY, double deltaYaw);
positionState getPosition();
double getBestBelief();
//distructor
virtual ~LocalizationManager();
};
#endif /* LOCALIZATIONMANAGER_H_ */
| [
"[email protected]"
] | |
561155b40a9c18ece8471d14c539338bbc1ccfe7 | 48db44cdc74f8452b606e78bbbac2ef9eca8b1c1 | /cbz2pdf/cbz2pdf.cpp | a727dfcd78f61d3156d02e68c402d0323f630f6a | [] | no_license | fryn3/cbz2pdf | 92d2f915c3282de6685c056d3612c2ecd32a15ca | 19aeb72844e66fbe3da06f51b7d3b23a6eb79c20 | refs/heads/master | 2023-04-05T01:01:54.248002 | 2021-04-15T16:02:23 | 2021-04-15T16:02:23 | 356,853,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | cpp | #include "cbz2pdf.h"
#include <QDebug>
#include <QEventLoop>
#include <QTimer>
#include <cbz2pdfprivate.h>
Cbz2pdf::Cbz2pdf(QObject *parent)
: QObject(parent),
_worker(new Cbz2pdfWorker()),
_private(new Cbz2pdfPrivate(_worker, this)) {
_worker->moveToThread(&_thread);
connect(&_thread, &QThread::finished, _worker, &QObject::deleteLater);
_thread.start();
}
Cbz2pdf::~Cbz2pdf() {
stop();
QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect( _worker, &Cbz2pdfWorker::stoped, &loop, &QEventLoop::quit );
connect( &timer, &QTimer::timeout, &loop, &QEventLoop::quit );
timer.start(2000);
loop.exec();
if (timer.isActive()) {
_thread.quit();
_thread.wait();
} else {
qDebug() << __PRETTY_FUNCTION__ << "timeout";
_thread.terminate();
}
}
void Cbz2pdf::setK(double k) { _private->setK(k); }
void Cbz2pdf::setDirOrZipName(QString dirOrZipName) { _private->setDirOrZipName(dirOrZipName); }
void Cbz2pdf::start() { _private->start(); }
void Cbz2pdf::stop() { _private->stop(); }
| [
"[email protected]"
] | |
e612362e41aecddbce0e4c097cbc1dccef14f3f2 | e142a836c4c4956004d68eda44168be27ed97e7b | /LeetCodeCNExplore/leetcodeCNmedium/Others/621leastInterval.cpp | 28ae1532b64be815f4b396ba4dfe13f710e1f5fb | [] | no_license | usernamegenerator/leetcode | 966e7e55f098850295886cb89dc9c97a4fa8099a | 7aa47b1f8aad2ccc2f4d9fe83a8a4e1921c22aea | refs/heads/master | 2021-11-17T17:34:55.754554 | 2021-09-10T04:10:04 | 2021-09-10T04:10:04 | 212,457,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | cpp | /*
任务调度器
给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间。
示例 :
输入:tasks = ["A","A","A","B","B","B"], n = 2
输出:8
解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。
提示:
任务的总个数为 [1, 10000]。
n 的取值范围为 [0, 100]。
*/
//https://leetcode-cn.com/problems/task-scheduler/solution/python-xiang-jie-by-jalan/
class Solution
{
public:
int leastInterval(vector<char> &tasks, int n)
{
vector<int> count(26, 0);
for (int i = 0; i < tasks.size(); i++)
{
count[tasks[i] - 'A']++;
}
sort(count.begin(), count.end(), greater);
int total = (count[0] - 1) * (n + 1) + 1;
for (int i = 1; i < count.size(); i++)
{
if (count[i] == count[0])
{
total = total + 1;
}
}
return total > tasks.size() ? total : tasks.size();
}
}; | [
"[email protected]"
] | |
1864bd86b85e71d76929ec0ac108937c8962779e | bd3915c51fb828204db56f61151314dc3fc7cb8e | /appointments_manage/task_management_tool.cpp | da19d50bd38474b347565e4dc6b394afb7ac3f49 | [] | no_license | kayduemre/DataStructurs | 731b5c2fc80a0e5f4745edb8f9ab0444912d6015 | e5554c7e685d0d325f90c9e519d88fef54a2371e | refs/heads/master | 2020-04-12T10:00:15.736845 | 2019-12-09T22:20:42 | 2019-12-09T22:20:42 | 162,415,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,856 | cpp | /* @Author
Student Name: Emre KAYDU
Student ID : 150160552
Date: 4.11.2019 */
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include "task_management_tool.h"
using namespace std;
void WorkPlan::display(bool verbose,bool testing)
{
string inone="***";
if (head!=NULL)
{
Task *pivot =new Task;
Task *compeer =new Task;
pivot=head;
do
{
if(testing)
inone+=" ";
else
cout << pivot->day <<". DAY"<< endl;
compeer=pivot;
while(compeer!=NULL)
{
string PREV= compeer->previous!=NULL?compeer->previous->name:"NULL";
string NEXT=compeer->next!=NULL?compeer->next->name:"NULL";
string CONT=compeer->counterpart!=NULL?compeer->counterpart->name:"NULL";
if (testing)
inone+=compeer->name;
else
if(verbose)
cout<<"\t"<<setw(2)<< compeer->time <<":00\t"<< PREV<<"\t<- "<< compeer->name <<"("<< compeer->priority <<")->\t"<<NEXT <<"\t |_"<<CONT<<endl;
else
cout<<"\t"<<setw(2)<< compeer->time <<":00\t"<< compeer->name <<"("<< compeer->priority <<")"<<endl;
compeer=compeer->counterpart;
}
pivot=pivot->next;
}while(pivot!=head);
if(testing)
{
cout<<inone<<endl;
cout<<"(checking cycled list:";
if (checkCycledList())
cout<<" PASS)"<<endl;
else
cout<<" FAIL)"<<endl;
}
}
else
cout<<"There is no task yet!"<<endl;
}
void WorkPlan::delaytask(int day, int time)
{
Task *oldone=new Task();
Task *newone=new Task();
if (day>0 and time>0)
{
oldone=getTask(day, time);
if (oldone!=NULL)
{
newone->name=new char [strlen(oldone->name)];
newone->name=oldone->name;
newone->priority=oldone->priority;
checkAvailableNextTimesFor(oldone);
cout<<getUsableDay()<<".day and "<<std::setw(2)<<getUsableTime()<<":00 is the first available day and hour for delaying the task "<<oldone->name<<" that is on "<<oldone->day<<".day at "<<std::setw(2)<< oldone->time <<":00"<<endl;
newone->day=getUsableDay();
newone->time=getUsableTime();
remove(oldone);
add(newone);
}
}
else
cout<<"Invalid input!"<<endl;
}
bool WorkPlan::checkavailabletime(Task *receive)
{
Task *traverse;
traverse = receive;
int time = 8;
bool flag = false;
if (traverse->time > 8)
{
usable_time = time;
flag = true;
return flag;
}
while (traverse)
{
if((traverse->time != time) && (time !=17))
{
usable_time = time;
flag = true;
return flag;
}
if( traverse->counterpart == NULL && time !=17)
{
time++;
usable_time = time;
flag = true;
return flag;
}
traverse = traverse->counterpart;
time++;
}
return flag;
}
void WorkPlan::checkavailableday(Task *receive)
{
Task *traverse = receive;
do
{
traverse = traverse->next;
if (checkavailabletime(traverse))
{
usable_day = traverse->day;
return;
}
}while (traverse != traverse->previous);
}
void WorkPlan::make_node(Task *node)
{
Task *newnode = new Task;
*newnode = *node;
newnode->name = new char[strlen(node->name)];
strcpy(newnode->name, node->name);
newnode->next = newnode;
newnode->previous = newnode;
newnode->counterpart = NULL;
head = newnode;
}
void WorkPlan::insertbegin(Task *node)
{
Task *last = head->previous;
Task *newnode = new Task;
*newnode = *node;
newnode->name = new char[strlen(node->name)];
strcpy(newnode->name, node->name);
newnode->next = head;
newnode->previous = last;
last->next = newnode;
head->previous = newnode;
head = newnode;
newnode->counterpart = NULL;
}
void WorkPlan::insertend(Task *node)
{
Task *last = head->previous;
Task *newnode = new Task;
*newnode =*node;
newnode->name = new char[strlen(node->name)];
strcpy(newnode->name, node->name);
newnode->next = head;
head->previous = newnode;
newnode->previous = last;
last->next = newnode;
newnode->counterpart =NULL;
}
int WorkPlan::getUsableDay()
{
return usable_day;
}
int WorkPlan::getUsableTime()
{
return usable_time;
}
void WorkPlan::create()
{
head = NULL;
}
void WorkPlan::close()
{
/*
Task *p, *q;
while (head)
{
p = head;
head = head->next;
q = p->counterpart;
while (q)
{
p->counterpart = p->counterpart->counterpart;
delete q;
q = p->counterpart;
}
delete p;
}
*/
}
void WorkPlan::add(Task *task)
{
Task *last, *begin;
Task *newnode = new Task;
*newnode = *task;
newnode->name = new char[strlen(task->name)];
strcpy(newnode->name, task->name);
newnode->counterpart = NULL;
newnode->next = NULL;
newnode->previous = NULL;
if(head == NULL)
{
make_node(newnode);
return;
}
else if(head->day > newnode->day)
{
insertbegin(newnode);
return;
}
else if(head->previous->day < newnode->day)
{
insertend(newnode);
return;
}
else if (head->day == newnode->day)
{
Task *traverse, *tail;
traverse = head;
tail = head;
begin = traverse;
if ((traverse->time > newnode->time))
{
last = head->previous;
newnode->counterpart = traverse;
traverse = traverse->next;
newnode->next = traverse;
traverse->previous = newnode;
newnode->previous = last;
last->next = newnode;
newnode->counterpart->next = NULL;
newnode->counterpart->previous = NULL;
head = newnode;
return;
}
while (traverse && (traverse->time < newnode->time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if(traverse && (traverse->time > newnode->time))
{
newnode->counterpart = traverse;
tail->counterpart = newnode;
return;
}
if (traverse && (traverse->time == newnode->time))
{
if ((traverse->priority > newnode->priority) || (traverse->priority == newnode->priority))
{
if (checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
else if (traverse->priority < newnode->priority)
{
Task *node = new Task;
node->name = new char[strlen(traverse->name)];
node->name = traverse->name;
node->priority = traverse->priority;
node->time = traverse->time;
traverse->name = new char[strlen(newnode->name)];
traverse->name = newnode->name;
traverse->priority = newnode->priority;
newnode->name = new char[strlen(node->name)];
newnode->name = node->name;
newnode->priority = node->priority;
delete node;
if (checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
}
else
{
tail->counterpart = newnode;
return;
}
}
else
{
Task *traverse, *tail, *last;
traverse = head;
last = head;
while((traverse != last->previous) && (traverse->day < newnode->day))
{
tail = traverse;
traverse = traverse->next;
}
if ((traverse != traverse->previous) && (traverse->day > newnode->day))
{
newnode->next = traverse;
tail->next = newnode;
traverse->previous = newnode;
newnode->previous = tail;
return;
}
if((traverse->day == newnode->day))
{
if ((traverse->time > newnode->time))
{
newnode->counterpart = traverse;
traverse = traverse->next;
newnode->next = traverse;
tail->next = newnode;
traverse->previous = newnode;
newnode->previous = tail;
return;
}
begin = traverse;
while ((traverse) && (traverse->time < newnode->time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if(traverse && (traverse->time > newnode->time))
{
newnode->counterpart = traverse;
tail->counterpart = newnode;
return;
}
if (traverse && (traverse->time == newnode->time))
{
if ((traverse->priority > newnode->priority) || (traverse->priority == newnode->priority) )
{
if(checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
else if(traverse->priority < newnode->priority)
{
Task *node = new Task;
node->name = new char[strlen(traverse->name)];
node->name = traverse->name;
node->priority = traverse->priority;
traverse->name = new char[strlen(newnode->name)];
traverse->name = newnode->name;
traverse->priority = newnode->priority;
newnode->name = new char[strlen(node->name)];
newnode->name = node->name;
newnode->priority = node->priority;
delete node;
if(checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
}
else
{
tail->counterpart = newnode;
return;
}
}
else
{
insertend(newnode);
}
}
}
Task * WorkPlan::getTask(int day, int time)
{
Task *traverse = head, *tail;;
while (traverse)
{
if(traverse->day == day)
{
while (traverse && (traverse->time != time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse)
{
return traverse;
}
else
{
return tail;
}
}
traverse = traverse->next;
}
return traverse;
}
void WorkPlan::last_time(Task *day)
{
Task *traverse = head,*tail;
while (traverse->day != day->day)
{
cout<<traverse->day;
traverse = traverse->next;
}
while (traverse)
{
tail = traverse;
traverse = traverse->counterpart;
}
last_Time = tail->time;
}
void WorkPlan::checkAvailableNextTimesFor(Task *delayed)
{
Task *traverse = head, *node,*checkhead;
node = delayed;
while (traverse->day != node->day)
{
traverse = traverse->next;
}
traverse = traverse->next;
checkhead = traverse->next;
//while (traverse)
//{
// tail = traverse;
// traverse = traverse->counterpart;
//}
//int lasttime = tail->time;
//traverse = checkhead;
int time = 8;
if (traverse->time > 8)
{
usable_time = time;
usable_day = traverse->day;
return;
}
while (traverse)
{
time = 8;
if (traverse->time > 8)
{
usable_time = time;
usable_day = traverse->day;
return;
}
while (traverse)
{
last_time(traverse);
if((traverse->time != time) && (time !=17) && (traverse->time != last_Time))
{
usable_time = time;
usable_day = traverse->day;
return;
}
if( traverse->counterpart == NULL && (time !=17) && (traverse->time != last_Time))
{
usable_time = time;
usable_day = traverse->day;
return;
}
traverse = traverse->counterpart;
time++;
}
traverse = checkhead;
traverse = traverse->next;
}
}
void WorkPlan::delayAllTasksOfDay(int day)
{
Task *traverse = head;
while (traverse->day != day)
{
traverse = traverse->next;
}
while (traverse)
{
int day = traverse->day;
int time = traverse->time;
delaytask(day, time);
traverse = traverse->counterpart;
}
}
void WorkPlan::remove(Task *target)
{
Task *tail, *traverse, *targetnode, *last;
targetnode = new Task;
*targetnode = *target;
traverse = head;
tail = traverse;
last = head->previous;
if ((traverse->day == targetnode->day))
{
if ((traverse->counterpart == NULL))
{
last = traverse->previous;
traverse = traverse->next;
last->next = head;
head->previous = last;
delete traverse;
return;
}
else if (traverse->time == targetnode->time)
{
//Task *del = traverse;
last = head->previous;
traverse = traverse->counterpart;
//delete del;
traverse->next = head->next;
head->next->previous = traverse;
traverse->previous = last;
head = traverse;
last->next = head;
return;
}
else
{
while (traverse && traverse->time !=targetnode->time)
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse->counterpart != NULL)
{
tail->counterpart = traverse->counterpart;
delete traverse;
}
else
{
//Task *del = traverse;
tail->counterpart = NULL;
//delete del;
}
}
}
else if (last->day == targetnode->day)
{
if ((last->counterpart == NULL))
{
Task *temp= last;
last = last->previous;
last->next = head;
head->previous = last;
delete temp;
}
else if (last->time == targetnode->time)
{
Task *temp= last;
Task *tail = last->previous;
last = last->counterpart;
tail->next = last;
last->previous = tail;
last->next = head;
head->previous = last;
delete temp;
}
else
{
traverse = last;
if (traverse->time ==targetnode->time)
{
Task *temp = traverse;
traverse = traverse->counterpart;
traverse->next = temp->next;
temp->next->previous = traverse;
traverse->previous = tail;
tail->next = traverse;
return;
}
while (traverse && traverse->time !=targetnode->time)
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse->counterpart != NULL)
{
tail->counterpart = traverse->counterpart;
delete traverse;
}
else
{
tail->counterpart = NULL;
delete traverse;
}
}
}
else
{
while (traverse->day != targetnode->day)
{
tail = traverse;
traverse = traverse->next;
}
if (traverse->counterpart == NULL)
{
traverse = traverse->next;
tail->next = traverse;
traverse->previous = tail;
//delete temp;
return;
}
if (traverse->time == targetnode->time)
{
Task *temp = traverse;
traverse = traverse->counterpart;
traverse->next = temp->next;
temp->next->previous = traverse;
traverse->previous = tail;
tail->next = traverse;
return;
}
while (traverse && (traverse->time != targetnode->time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse != NULL)
{
tail->counterpart = traverse->counterpart;
return;
//delete traverse;
}
else
{
tail->counterpart = NULL;
//delete traverse;
}
}
}
bool WorkPlan::checkCycledList()
{
Task *pivot=new Task();
pivot=head;
int patient=100;
bool r=false;
while (pivot!=NULL&&patient>0)
{
patient--;
pivot=pivot->previous;
if(pivot==head)
{
r=true;
break;
}
}
cout<<"("<<100-patient<<")";
patient=100;
bool l=false;
while (pivot!=NULL&&patient>0)
{
patient--;
pivot=pivot->next;
if(pivot==head)
{
l=true;
break;
}
}
return r&l;
}
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.