blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6dc2919550f8fe6c0b6a1b8f2030f1e086d1a641 | 01ed846bf5367f391711e3799ba58a40d03df67e | /sem2/hw5/2511/A.cpp | 5ab5f4ab433beee90218cd416ffbf2e00f322f63 | [] | no_license | katyamineeva/learning-algoritms | a540ed4c9a5cd8bfc25d07d67c59baf3a0ab4bc2 | 0ea7e3f15cbed710f975bef14d83ed2102b62878 | refs/heads/master | 2021-06-08T05:59:16.023426 | 2016-12-03T14:43:46 | 2016-12-03T14:43:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,487 | cpp | #include <iostream>
#include <fstream>
#include <utility>
#include <vector>
#include <queue>
using std::vector;
using std::cout;
using std::ifstream;
using std::queue;
using std::pair;
const int NOT_INITIALISED = -2;
const int FIRST_COMPONENT_OF_EQUIVALENCE = -1;
void readData(vector<vector<vector<int>>>& reversedAutomat,
vector<vector<int>>& graph,
int& start,
vector<bool>& isTerminal) {
ifstream fin("input.txt");
int numOfStates = 0;
int sigmaSize = 0;
fin >> numOfStates >> sigmaSize;
vector<int> emptyVect = {};
vector<vector<int>> pattern(sigmaSize, emptyVect);
reversedAutomat.resize(numOfStates, pattern);
graph.resize(numOfStates, {});
isTerminal.resize(numOfStates, false);
int nextState = 0;
for (int curState = 0; curState < numOfStates; ++curState) {
for (int symb = 0; symb < sigmaSize; ++symb) {
fin >> nextState;
reversedAutomat[nextState][symb].push_back(curState);
graph[curState].push_back(nextState);
}
}
int numOfTerminals = 0;
int curTerminal = 0;
fin >> start >> numOfTerminals;
for (int i = 0; i < numOfTerminals; ++i) {
fin >> curTerminal;
isTerminal[curTerminal] = true;
}
fin.close();
}
void findReachable(const vector<vector<int>>& graph,
vector<bool>& used,
int curVertex) {
used[curVertex] = true;
for (int vertex : graph[curVertex]) {
if (!used[vertex]) {
findReachable(graph, used, vertex);
}
}
}
void makeEquivalenceTable(vector<vector<bool>>& marked,
const vector<bool>& isTerminal,
const vector<vector<vector<int>>>& reversedAutomat,
int sigmaSize) {
queue<pair<int, int>> myQueue;
for (int i = 0; i < marked.size(); ++i) {
for (int j = 0; j < marked.size(); ++j) {
if (!marked[i][j] && (isTerminal[i] != isTerminal[j])) {
marked[i][j] = true;
marked[j][i] = true;
myQueue.push({i, j});
}
}
}
int firstState = 0;
int secondState = 0;
while (!myQueue.empty()) {
firstState = myQueue.front().first;
secondState = myQueue.front().second;
myQueue.pop();
for (int symb = 0; symb < sigmaSize; ++symb) {
for (int prevStateFirst : reversedAutomat[firstState][symb]) {
for (int prevStateSecond : reversedAutomat[secondState][symb]) {
if (!marked[prevStateFirst][prevStateSecond]) {
marked[prevStateFirst][prevStateSecond] = true;
marked[prevStateSecond][prevStateFirst] = true;
myQueue.push({prevStateFirst, prevStateSecond});
}
}
}
}
}
}
void minimizeAutomat() {
vector<vector<vector<int>>> reversedAutomat;
vector<vector<int>> graph;
int start = 0;
vector<bool> isTerminal;
readData(reversedAutomat, graph, start, isTerminal);
vector<bool> isReachable(graph.size(), false);
vector<vector<bool>> notEquivalent(graph.size(), isReachable);
findReachable(graph, isReachable, start);
int sigmaSize = reversedAutomat[0].size();
makeEquivalenceTable(notEquivalent, isTerminal, reversedAutomat, sigmaSize);
vector<int> componentOfEquivalence(graph.size(), NOT_INITIALISED);
for (int i = 0; i < graph.size(); ++i) {
if (!notEquivalent[0][i]) {
componentOfEquivalence[i] = FIRST_COMPONENT_OF_EQUIVALENCE;
}
}
int numOfComponents = 0;
for (int stateFirst = 0; stateFirst < graph.size(); ++stateFirst) {
if (!isReachable[stateFirst] || componentOfEquivalence[stateFirst] != NOT_INITIALISED) {
continue;
}
++numOfComponents;
componentOfEquivalence[stateFirst] = numOfComponents;
for (int stateSecond = stateFirst; stateSecond < graph.size(); ++stateSecond) {
if (!notEquivalent[stateFirst][stateSecond]) {
componentOfEquivalence[stateSecond] = componentOfEquivalence[stateFirst];
}
}
}
cout << numOfComponents + 1;
}
int main() {
minimizeAutomat();
return 0;
}
| [
"katya.mineeva96@gmail.com"
] | katya.mineeva96@gmail.com |
01b30535efb556a0f03c914a83d883fe169be41e | 32e15f38217b7bd97af61f359479b6a53a4d17cf | /OGL/source/Objects/Primitives/PyramidObject.hpp | 5b8128ec1ea8015141e9afd8fbba327c93e2e07c | [] | no_license | mkulagowski/AsteroidShooter | 3bcb4fad6bad6a15edc6b6f6317f74593f57e431 | 74d4e0c076f6150ac3346cf7e81ada861a1aeb92 | refs/heads/master | 2016-09-13T02:03:55.001033 | 2016-05-21T22:24:50 | 2016-05-21T22:24:50 | 58,769,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | hpp | #pragma once
#include "Object.hpp"
class PyramidObject : public Object
{
public:
PyramidObject(btVector3 halfSize);
PyramidObject(float halfSizeX, float halfSizeY, float halfSizeZ);
~PyramidObject();
private:
btVector3 mHalfSize;
void AddShape() override;
};
| [
"mk.kulagowski@gmail.com"
] | mk.kulagowski@gmail.com |
2fb93e228d08ce08b9727d00e5045419741c3245 | 4308660d4fd08f2b4daadbc906099d6fd4638e27 | /car/beifen/path_planning5.16/src/rrt_node.cpp | b5cfd42a2c1273a650bac2332b29e49906972774 | [] | no_license | zhang-quanzhe/car | 4ea54f60ee56d81400304c5023f1124436130f9c | 00ea7396404f4d1e29fb624e436fd8b41665c9e3 | refs/heads/master | 2023-06-11T04:01:02.436099 | 2021-07-02T10:09:39 | 2021-07-02T10:09:39 | 382,208,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,461 | cpp | #include <ros/ros.h>
#include <visualization_msgs/Marker.h>
#include <geometry_msgs/Point.h>
#include <path_planning/rrt.h>
#include <path_planning/obstacles.h>
#include <iostream>
#include <cmath>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <vector>
#include <time.h>
#define success false
#define running true
using namespace rrt;
bool status = running;
bool pro_status = running;
void initializeMarkers(visualization_msgs::Marker &sourcePoint,
visualization_msgs::Marker &goalPoint,
visualization_msgs::Marker &randomPoint,
visualization_msgs::Marker &rrtTreeMarker,
visualization_msgs::Marker &finalPath)
{
//init headers
sourcePoint.header.frame_id = goalPoint.header.frame_id = randomPoint.header.frame_id = rrtTreeMarker.header.frame_id = finalPath.header.frame_id = "path_planner";
sourcePoint.header.stamp = goalPoint.header.stamp = randomPoint.header.stamp = rrtTreeMarker.header.stamp = finalPath.header.stamp = ros::Time::now();
sourcePoint.ns = goalPoint.ns = randomPoint.ns = rrtTreeMarker.ns = finalPath.ns = "path_planner";
sourcePoint.action = goalPoint.action = randomPoint.action = rrtTreeMarker.action = finalPath.action = visualization_msgs::Marker::ADD;
sourcePoint.pose.orientation.w = goalPoint.pose.orientation.w = randomPoint.pose.orientation.w = rrtTreeMarker.pose.orientation.w = finalPath.pose.orientation.w = 1.0;
//setting id for each marker
sourcePoint.id = 0;
goalPoint.id = 1;
randomPoint.id = 2;
rrtTreeMarker.id = 3;
finalPath.id = 4;
//defining types
rrtTreeMarker.type = visualization_msgs::Marker::LINE_LIST;
finalPath.type = visualization_msgs::Marker::LINE_STRIP;
sourcePoint.type = goalPoint.type = randomPoint.type = visualization_msgs::Marker::SPHERE;
//setting scale
rrtTreeMarker.scale.x = 0.2;
finalPath.scale.x = 1;
sourcePoint.scale.x = goalPoint.scale.x = randomPoint.scale.x = 2;
sourcePoint.scale.y = goalPoint.scale.y = randomPoint.scale.y = 2;
sourcePoint.scale.z = goalPoint.scale.z = randomPoint.scale.z = 1;
//assigning colors
sourcePoint.color.r = 1.0f;
goalPoint.color.g = 1.0f;
randomPoint.color.b = 1.0f;
rrtTreeMarker.color.r = 0.8f;
rrtTreeMarker.color.g = 0.4f;
finalPath.color.r = 0.2f;
finalPath.color.g = 0.2f;
finalPath.color.b = 1.0f;
sourcePoint.color.a = goalPoint.color.a = randomPoint.color.a = rrtTreeMarker.color.a = finalPath.color.a = 1.0f;
}
vector< vector<geometry_msgs::Point> > getObstacles()
{
obstacles obst;
return obst.getObstacleArray();
}
void addBranchtoRRTTree(visualization_msgs::Marker &rrtTreeMarker, RRT::rrtNode &tempNode, RRT &myRRT)
{
geometry_msgs::Point point;
point.x = tempNode.posX;
point.y = tempNode.posY;
point.z = 0;
rrtTreeMarker.points.push_back(point);
RRT::rrtNode parentNode = myRRT.getParent(tempNode.nodeID);
point.x = parentNode.posX;
point.y = parentNode.posY;
point.z = 0;
rrtTreeMarker.points.push_back(point);
}
bool checkIfInsideBoundary(RRT::rrtNode &tempNode)
{
if(tempNode.posX < 0 || tempNode.posY < 0 || tempNode.posX > 100 || tempNode.posY > 100 ) return false;
else return true;
}
bool checkIfOutsideObstacles(vector< vector<geometry_msgs::Point> > &obstArray, RRT::rrtNode &tempNode)
{
double AB, AD, AMAB, AMAD;
for(int i=0; i<obstArray.size(); i++)
{
//=============================================================================================================
for(int j=0; j<11; j=j+5) //j小于障碍物的数量
{
//=============================================================================================================
AB = (pow(obstArray[i][j].x - obstArray[i][j+1].x,2) + pow(obstArray[i][j].y - obstArray[i][j+1].y,2));
AD = (pow(obstArray[i][j].x - obstArray[i][j+3].x,2) + pow(obstArray[i][j].y - obstArray[i][j+3].y,2));
AMAB = (((tempNode.posX - obstArray[i][j].x) * (obstArray[i][j+1].x - obstArray[i][j].x)) + (( tempNode.posY - obstArray[i][j].y) * (obstArray[i][j+1].y - obstArray[i][j].y)));
AMAD = (((tempNode.posX - obstArray[i][j].x) * (obstArray[i][j+3].x - obstArray[i][j].x)) + (( tempNode.posY - obstArray[i][j].y) * (obstArray[i][j+3].y - obstArray[i][j].y)));
//(0<AM⋅AB<AB⋅AB)∧(0<AM⋅AD<AD⋅AD)
if((0 < AMAB) && (AMAB < AB) && (0 < AMAD) && (AMAD < AD))
{
return false;
}
}
}
return true;
}
void generateTempPoint(RRT::rrtNode &tempNode, int goal_x, int goal_y)
{
int x = rand() % 150 + 1; //产生1-150之间的随机数
int y = rand() % 150 + 1; //产生1-150之间的随机数
//std::cout<<"Random X: "<<x <<endl<<"Random Y: "<<y<<endl;
if(x<20) //13%的概率
{
tempNode.posX = goal_x;
tempNode.posY = goal_y;
}
else
{
tempNode.posX = x;
tempNode.posY = y;
}
}
//判断目标点在分割的地图的哪一部分,假设地图是方的,在地图中心建立直角坐标系
int judge_goalPoint(int bondx, int bondy, int goal_x, int goal_y)
{
int result;
int median_x, median_y;
median_x = bondx/2;
median_y = bondy/2;
if( (goal_x > median_x)&&(goal_y > median_y) )
result = 1;
else if( (goal_x < median_x)&&(goal_y > median_y) )
result = 2;
else if( (goal_x < median_x)&&(goal_y < median_y) )
result = 3;
else if( (goal_x > median_x)&&(goal_y < median_y) )
result = 4;
return result;
}
bool addNewPointtoRRT(RRT &myRRT, RRT::rrtNode &tempNode, int rrtStepSize, vector< vector<geometry_msgs::Point> > &obstArray, int PointWhere)
{
int nearestNodeID = myRRT.getNearestNodeID(tempNode.posX,tempNode.posY);
RRT::rrtNode nearestNode = myRRT.getNode(nearestNodeID);
int nearestPosition;
nearestPosition = judge_goalPoint(100,100,(int)nearestNode.posX,(int)nearestNode.posY);
double theta = atan2(tempNode.posY - nearestNode.posY,tempNode.posX - nearestNode.posX);
if(nearestPosition==PointWhere)
{
tempNode.posX = nearestNode.posX + (rrtStepSize * cos(theta));
tempNode.posY = nearestNode.posY + (rrtStepSize * sin(theta));
}
else
{
tempNode.posX = nearestNode.posX + (8 * cos(theta));
tempNode.posY = nearestNode.posY + (8 * sin(theta));
}
if(checkIfInsideBoundary(tempNode) && checkIfOutsideObstacles(obstArray,tempNode))
{
tempNode.parentID = nearestNodeID;
tempNode.nodeID = myRRT.getTreeSize();
myRRT.addNewNode(tempNode);
return true;
} //检查障碍物========
else
return false;
}
bool checkNodetoGoal(int X, int Y, RRT::rrtNode &tempNode)
{
double distance = sqrt(pow(X-tempNode.posX,2)+pow(Y-tempNode.posY,2));
if(distance < 3)
{
return true;
}
return false;
}
void setFinalPathData(vector< vector<int> > &rrtPaths, RRT &myRRT, int i, visualization_msgs::Marker &finalpath, int goalX, int goalY)
{
RRT::rrtNode tempNode;
geometry_msgs::Point point;
//===========================================================================
//geometry_msgs::Point point_pub;
//===========================================================================
for(int j=0; j<rrtPaths[i].size();j++)
{
tempNode = myRRT.getNode(rrtPaths[i][j]);
point.x = tempNode.posX;
point.y = tempNode.posY;
point.z = 0;
finalpath.points.push_back(point);
//=======================================================================
//point_pub.x = tempNode.posX;
//point_pub.y = tempNode.posY;
//point_pub.z = 0;
//turtle_vel_pub.publish(vel_msg);
//=======================================================================
}
point.x = goalX;
point.y = goalY;
finalpath.points.push_back(point);
}
int main(int argc,char** argv)
{
//initializing ROS
ros::init(argc,argv,"rrt_node");
ros::NodeHandle n;
//defining Publisher
ros::Publisher rrt_publisher = n.advertise<visualization_msgs::Marker>("path_planner_rrt",1);
//====================================================================================================
ros::Publisher points_publisher = n.advertise<geometry_msgs::Point>("/planning_rrt_points", 1);
//====================================================================================================
//====================================================================================================
ros::Publisher obstpoints_publisher = n.advertise<geometry_msgs::Point>("/obstacle_points", 1);
//====================================================================================================
//defining markers
visualization_msgs::Marker sourcePoint;
visualization_msgs::Marker goalPoint;
visualization_msgs::Marker randomPoint;
visualization_msgs::Marker rrtTreeMarker;
visualization_msgs::Marker finalPath;
geometry_msgs::Point obstic_pub;
initializeMarkers(sourcePoint, goalPoint, randomPoint, rrtTreeMarker, finalPath);
//setting source and goal
sourcePoint.pose.position.x = 2;
sourcePoint.pose.position.y = 2;
goalPoint.pose.position.x = 95;
goalPoint.pose.position.y = 95;
rrt_publisher.publish(sourcePoint);
rrt_publisher.publish(goalPoint);
ros::spinOnce();
ros::Duration(0.01).sleep();
srand (time(NULL));
//initialize rrt specific variables
//initializing rrtTree
RRT myRRT(2.0,2.0);
int goalX, goalY;
goalX = goalY = 95;
int rrtStepSize = 3;
vector< vector<int> > rrtPaths;
vector<int> path;
int rrtPathLimit = 1;
int shortestPathLength = 9999;
int shortestPath = -1;
RRT::rrtNode tempNode;
vector< vector<geometry_msgs::Point> > obstacleList = getObstacles();
bool addNodeResult = false, nodeToGoal = false;
obstic_pub.x=0;
obstic_pub.y=0;
obstic_pub.z=0;
obstpoints_publisher.publish(obstic_pub);
usleep(1000000);
for(int i=0;i<15;i++)
{
obstic_pub.x=obstacleList[0][i].x;
obstic_pub.y=obstacleList[0][i].y;
obstic_pub.z=0;
obstpoints_publisher.publish(obstic_pub);
printf("ok!--%d, x:%f y:%f \n", i, obstic_pub.x, obstic_pub.y );
ros::spinOnce();
usleep(1000000);
}
int GoalPointInWhere;
GoalPointInWhere = judge_goalPoint(100,100,goalX,goalY);
while(ros::ok() && status)
{
if(rrtPaths.size() < rrtPathLimit)
{
generateTempPoint(tempNode,goalX,goalY);
//std::cout<<"tempnode generated"<<endl;
addNodeResult = addNewPointtoRRT(myRRT,tempNode,rrtStepSize,obstacleList,GoalPointInWhere);
if(addNodeResult)
{
// std::cout<<"tempnode accepted"<<endl;
addBranchtoRRTTree(rrtTreeMarker,tempNode,myRRT);
// std::cout<<"tempnode printed"<<endl;
nodeToGoal = checkNodetoGoal(goalX, goalY,tempNode);
if(nodeToGoal)
{
path = myRRT.getRootToEndPath(tempNode.nodeID);
rrtPaths.push_back(path);
std::cout<<"New Path Found. Total paths "<<rrtPaths.size()<<endl;
//ros::Duration(10).sleep();
//std::cout<<"got Root Path"<<endl;
}
}
}
else //if(rrtPaths.size() >= rrtPathLimit)
{
status = success;
std::cout<<"Finding Optimal Path"<<endl;
for(int i=0; i<rrtPaths.size();i++)
{
if(rrtPaths[i].size() < shortestPath)
{
shortestPath = i;
shortestPathLength = rrtPaths[i].size();
}
}
setFinalPathData(rrtPaths, myRRT, shortestPath, finalPath, goalX, goalY);
rrt_publisher.publish(finalPath);
//========================================================================================
geometry_msgs::Point point_pub;
for(int j=0; j<rrtPaths[shortestPath].size();j++)
{
tempNode = myRRT.getNode(rrtPaths[shortestPath][j]);
point_pub.x = tempNode.posX;
point_pub.y = tempNode.posY;
point_pub.z = 0;
points_publisher.publish(point_pub);
usleep(100000);
ROS_INFO("No.%d----Publsh:%f-x, %f-y, %f-z",
j,point_pub.x, point_pub.y, point_pub.z);
}
point_pub.x = goalX;
point_pub.y = goalY;
point_pub.z = 0;
points_publisher.publish(point_pub);
ROS_INFO("Publsh:%f-x, %f-y, %f-z \n",
point_pub.x, point_pub.y, point_pub.z);
//========================================================================================
}
rrt_publisher.publish(sourcePoint);
rrt_publisher.publish(goalPoint);
rrt_publisher.publish(rrtTreeMarker);
//rrt_publisher.publish(finalPath);
ros::spinOnce();
ros::Duration(0.01).sleep();
}
return 1;
}
| [
"ustb_zqz@163.com"
] | ustb_zqz@163.com |
70f24f40cb2da90d502a0cd8227b6b4c4c4827d7 | 36a77db57f0a8cb67ca526fb82db1105da095b32 | /P3Lab7_ClaudioHernandez/ClaseHogwarts.cpp | faef8fb20562cfa4a68a3e079812f8d93fe3bf99 | [] | no_license | Claudio-Hernandez/P3Lab7_ClaudioHernandez | 2acf07b1542e1846044380c7701981d5ca478f96 | 4c56ff7fc63664ef2b5beedfc5fcbfa5661c38a3 | refs/heads/main | 2023-05-10T04:56:00.257514 | 2021-06-05T00:01:46 | 2021-06-05T00:01:46 | 373,925,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,513 | cpp | #include "ClaseHogwarts.h"
ClaseHogwarts::ClaseHogwarts(int anio2){
this->anio = anio2;
}
vector<MagoGryffindor*>ClaseHogwarts::getVectorgr(){
return this->magosGryffindor;
}
vector<MagoHufflepuff*>ClaseHogwarts::getVectorhuff(){
return this->magosHuffle;
}
vector<MagoRavenclaw*>ClaseHogwarts::getVectorraven(){
return this->magosRaven;
}
vector<MagoSlytherin*>ClaseHogwarts::getvectorsly(){
return this->magosslyde;
}
void ClaseHogwarts::imprimirCasas(){
cout<<"Casa Gryffindor:\n ";
for(int i =0;i<magosGryffindor.size();i++) {
MagoGryffindor* b = magosGryffindor[i];
b->toString();
}
cout<<"Casa Hufflepuff:\n ";
for(int i =0;i<magosHuffle.size();i++) {
MagoHufflepuff* b = magosHuffle[i];
b->toString();
}
cout<<"Casa Slydering:\n ";
for(int i =0;i<magosslyde.size();i++) {
MagoSlytherin* b = magosslyde[i];
b->toString();
}
cout<<"Casa Ravenclaw:\n ";
for(int i =0;i<magosRaven.size();i++) {
MagoRavenclaw* b = magosRaven[i];
b->toString();
}
}
void ClaseHogwarts::promedioCualidades(){
double nI,nv,nl,nA;
double pg,ps,phu,pr;
double pi,pv,pl,pA;
for(int i =0;i<magosGryffindor.size();i++){
nI+=magosGryffindor[i]->getinteligencia();
nv+=magosGryffindor[i]->getvalentia();
nl+=magosGryffindor[i]->getlealtad();
nA+=magosGryffindor[i]->getastucia();
}
pi = nI/magosGryffindor.size();
pv = nv/magosGryffindor.size();
pl = nl/magosGryffindor.size();
pA = nA/magosGryffindor.size();
cout<<"Promedio de inteligencia en gryffindor:"+to_string(pi);
} | [
"claudio.ahz123@gmail.com"
] | claudio.ahz123@gmail.com |
794e565ae24334d24e941c37b7f0ed5c591f70c4 | b1d641d47810571860f3207bfd836db7f14c212f | /VulkanEngine/FirstPersonCamera.cpp | c15f31bc74bd5786f01b80a346707a679d8e3b75 | [] | no_license | VilRan/VulkanEngine | 953a245ccc0437a9cbaf918f03ae6523b52e4b16 | 54f3eeb82a80c90fce6da2105fa7a2cc179a1e63 | refs/heads/master | 2021-01-20T00:16:39.061037 | 2017-08-07T16:15:02 | 2017-08-07T16:15:02 | 89,107,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,614 | cpp | #include "FirstPersonCamera.h"
#include <glm/gtc/matrix_transform.hpp>
FirstPersonCamera::FirstPersonCamera()
{
Position = glm::vec3(0.0f, 0.0f, 0.0f);
Rotation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f));
Angles = glm::vec2(0.0f, 0.0f);
}
FirstPersonCamera::~FirstPersonCamera()
{
}
glm::mat4 FirstPersonCamera::GetViewProjection(bool invertY)
{
glm::vec3 target = Position + Rotation * glm::vec3(1.0f, 0.0f, 0.0f);
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::mat4 view = glm::lookAt(Position, target, up);
glm::mat4 projection = glm::perspective(glm::radians(FieldOfView), AspectRatio, Near, Far);
if (invertY)
{
projection[1][1] *= -1;
}
return projection * view;
}
void FirstPersonCamera::MoveBy(glm::vec3 delta)
{
Position += delta;
}
void FirstPersonCamera::Rotate(float x, float y)
{
Angles.x += x;
Angles.y += y;
float yLimit = glm::pi<float>() / 3;
if (Angles.y > yLimit)
{
Angles.y = yLimit;
}
else if (Angles.y < -yLimit)
{
Angles.y = -yLimit;
}
glm::quat q1 = glm::angleAxis(Angles.x, glm::vec3(0.0f, 1.0f, 0.0f));
glm::quat q2 = glm::angleAxis(Angles.y, glm::vec3(0.0f, 0.0f, -1.0f));
Rotation = q1 * q2;
}
void FirstPersonCamera::MoveForward(float delta)
{
Position += glm::angleAxis(Angles.x, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec3(delta, 0.0f, 0.0f);
}
void FirstPersonCamera::MoveBackward(float delta)
{
MoveForward(-delta);
}
void FirstPersonCamera::MoveRight(float delta)
{
Position += glm::angleAxis(Angles.x, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec3(0.0f, 0.0f, delta);
}
void FirstPersonCamera::MoveLeft(float delta)
{
MoveRight(-delta);
}
| [
"VilleMattiRantala@gmail.com"
] | VilleMattiRantala@gmail.com |
10f825b34a771bf4a0e7497832b9d98375d718f0 | 740ba734bba1e942a1c4ee011d4436055be8db5c | /lua-icxx/LuaStackSizeChecker.h | 0f35482508e082e230960d8ca535357eef27bf5c | [
"BSD-3-Clause"
] | permissive | ice1k/lua-full | f96c3945eb292d7caa2347e6c8cc22900fd69019 | 60764a084e776126fa1b3a1dbf4d0ee5876d17df | refs/heads/master | 2020-03-26T04:21:50.928581 | 2018-08-03T07:18:36 | 2018-08-03T07:18:36 | 144,500,190 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | h | /*
This file is part of the Lua_icxx library.
Copyright 2010 (c) by Oliver Schoenborn.
License terms in LICENSE.txt.
*/
#pragma once
#include <cassert>
#include <lua/lua.hpp>
/** Checker class to verify that stack size unchanged. It tracks the
stack top when constructed, and asserts that it is the same when
destructed. Use as
\code
{
LuaStackSizeChecker checker(L);
... use Lua C API that manipulates stack...
} // checker destroyed, asserts no change in stack size
// or if you don't want to use C++ block:
LuaStackSizeChecker checker(L);
... use Lua C API that manipulates stack...
checker.checkNow();
\endcode
Note that the check only occurs in a Debug build (if NDEBUG not defined.
*/
class // LUA_ICXX_CPP_API
LuaStackSizeChecker
{
public:
/// capture current stack top level
LuaStackSizeChecker(lua_State* lua)
: mLua(lua), mStackTop( lua_gettop(mLua) ) { assert(mLua); }
/// do the check upon destruction
inline ~LuaStackSizeChecker() { checkNow(); }
/// returns true if stack top currently same as at construction
inline void checkNow() const { assert( mStackTop == lua_gettop(mLua) ); }
private:
lua_State * mLua;
const int mStackTop;
};
| [
"ice1000kotlin@foxmail.com"
] | ice1000kotlin@foxmail.com |
9642e7aff8cb71c4caca66c6ca9cc8cb0d63c3dc | 2d99181d9516fa710a82730b4c69b5c140920b5d | /AI2/HP Model/hp.cpp | 59a178ff8e2b2316ad54c8a38076593de722d306 | [] | no_license | NelsonGomesNeto/Artificial-Intelligence | 7a78249a96253b4de9f651720718fb4cbd0dae11 | 6d160c40a2e99b360b419e9f45687ccfdce91c9c | refs/heads/master | 2021-05-11T05:54:16.112812 | 2019-04-18T21:46:10 | 2019-04-18T21:46:10 | 117,973,475 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,783 | cpp | // #include <bits/stdc++.h>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>
#include <string.h>
using namespace std;
int hpSize; char hp[(int) 1e6]; double baseEnergy = 0, accumulatedEnergy[1000];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}, n, m, si, sj;
char dop[4 + 1] = {'v', '>', '^', '<'}, table[1000][1000];
struct State
{
vector<char> direction;
int i = 0, j = 0;
set<pair<int, int>> hVisited, pVisited;
double value = 0, energy = 0;
bool operator<(const State &b) const { return(value > b.value); }
void insert(pair<int, int> position, char protein) { if (protein == 'P') pVisited.insert(position); else hVisited.insert(position); i = position.first, j = position.second; }
bool has(pair<int, int> position) { return(hVisited.count(position) || pVisited.count(position)); }
};
void fillTable(State &state)
{
int minI = 0, maxI = 0, minJ = 0, maxJ = 0;
int i = 0, j = 0;
for (auto d: state.direction)
{
i += dy[d], j += dx[d];
minI = min(minI, i), maxI = max(maxI, i), minJ = min(minJ, j), maxJ = max(maxJ, j);
}
n = maxI - minI + 1, m = maxJ - minJ + 1;
for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) table[i][j] = '.'; table[i][m] = '\0'; }
i = -minI, j = -minJ; si = i, sj = j; int s = 0;
table[i][j] = hp[s ++];
for (auto d: state.direction)
{
i += dy[d], j += dx[d];
table[i][j] = hp[s ++];
}
}
double stateEnergy(State &state, bool fill)
{
if (fill) fillTable(state);
double energy = baseEnergy;
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++)
if (table[i][j] == 'H')
{
energy -= (i + 1 < n) && table[i + 1][j] == 'H';
energy -= (j + 1 < m) && table[i][j + 1] == 'H';
}
return(energy);
}
void printState(State &state)
{
printf("------------------------------\n");
fillTable(state);
for (int d = 0; d < state.direction.size(); d ++)
printf("%c%c", dop[state.direction[d]], d < state.direction.size() - 1 ? ' ' : '\n');
printf("%dx%d (start: %d, %d) | Energy: %.0lf\n", n, m, si, sj, stateEnergy(state, false));
for (int d = 0; d < n; d ++)
printf("%s\n", table[d]);
printf("------------------------------\n");
}
State bfs()
{
State bestState; bestState.energy = 1e7;
State base; base.insert({0, 0}, hp[0]);
queue<State> q; q.push(base);
while (!q.empty())
{
State u = q.front(); q.pop();
// printState(u);
if (u.direction.size() == hpSize - 1)
{
if (u.energy < bestState.energy) bestState = u;
continue;
}
for (int k = 0; k < 4; k ++)
{
char nextProtein = hp[u.direction.size() + 1];
int ii = u.i + dy[k], jj = u.j + dx[k];
if (!u.has({ii, jj}))
{
State next = u; next.direction.push_back(k);
next.insert({ii, jj}, nextProtein);
if (nextProtein == 'H') if (nextProtein == 'H') for (int kk = 0, prevK = (k + 2) % 4; kk < 4; kk ++) if (prevK != kk) next.energy -= next.hVisited.count({ii + dy[kk], jj + dx[kk]});
q.push(next);
}
}
}
return(bestState);
}
State Astar()
{
int breakCount = 1000;
State bestState; bestState.energy = 1e7;
State base; base.insert({0, 0}, hp[0]);
priority_queue<State> q; q.push(base);
while (!q.empty())
{
State u = q.top(); q.pop();
// printState(u);
if (u.direction.size() == hpSize - 1) // Reached the end
{
if (u.energy < bestState.energy) bestState = u;
else if (u.energy > bestState.energy) breakCount --;
if (breakCount == 0) break;
continue;
}
for (int k = 0; k < 4; k ++) // Adds each possible direction
{
char nextProtein = hp[u.direction.size() + 1];
int ii = u.i + dy[k], jj = u.j + dx[k];
if (!u.has({ii, jj}))
{
State next = u; next.direction.push_back(k);
next.insert({ii, jj}, nextProtein);
if (nextProtein == 'H') for (int kk = 0, prevK = (k + 2) % 4; kk < 4; kk ++) if (prevK != kk) next.energy -= next.hVisited.count({ii + dy[kk], jj + dx[kk]});
next.value = u.value*0 + next.energy / (4*accumulatedEnergy[next.direction.size()]); // Heuristic value
q.push(next);
}
}
}
return(bestState);
}
int main()
{
while (scanf("%s", hp) != EOF)
{
getchar();
baseEnergy = 0;
hpSize = strlen(hp);
accumulatedEnergy[0] = 1;
for (int i = 0; i < hpSize - 1; i ++)
{
baseEnergy += (hp[i] == 'H') && (hp[i + 1] == 'H');
accumulatedEnergy[i + 1] = baseEnergy + 1;
}
accumulatedEnergy[hpSize] = accumulatedEnergy[hpSize - 1];
printf("Sequence of size %d: %s\n", hpSize, hp);
// State best = bfs();
State best = Astar();
printf("Best energy: %.0lf\n", stateEnergy(best, true));
printState(best);
fflush(stdout);
}
return(0);
}
| [
"ngn@ic.ufal.br"
] | ngn@ic.ufal.br |
0c917850a74e24d44ef9debc26b8e886f458949f | c8cc2b12af263730022608bd4e13dbe57423ab08 | /KitStack.h | d58d9b367befb9de2451b2d5e15f3080ba3d3c35 | [] | no_license | Lajjo/ProjectZuma | 6b1a84cbd618c733cbbef88f809597f70fa7a1a6 | 11bb754de1d19ecdc0e4c314ea1fa15ec39a6357 | refs/heads/master | 2021-01-13T01:36:24.959761 | 2013-02-01T16:47:09 | 2013-02-01T16:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | h | #pragma once
#include <SFML\Graphics.hpp>
#include "HealthKit.h"
class KitStack{
public:
void addHealthKit(HealthKit*);
void drawStack(sf::RenderWindow &window);
bool checkIfTouchKit(sf::IntRect playerRect);
private:
typedef std::vector<HealthKit*> Stack;
Stack kitStack;
}; | [
"Lajjo1992@gmail.com"
] | Lajjo1992@gmail.com |
a80e64a77727894147621d3067c92802083e5c2a | bff4518b3089c014e9af2e729d98f5521138073b | /Save_patients.cpp | 8c8cf337bd8f368c245c8f5f6d7125804fd82563 | [] | no_license | Aniganesh/100daysofcode | 3d5e2e6c3d8526938620cf9fac700c69175618ec | 2c11d71a5374be0d845b568ef16009bd3f1718da | refs/heads/master | 2021-05-16T22:58:48.915268 | 2020-07-17T18:18:48 | 2020-07-17T18:18:48 | 250,505,128 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | // https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/practice-problems/algorithm/save-patients/
// 14-05-2020 Very-easy/easy
#include<bits/stdc++.h>
#define MOD % 1000000007
typedef long long ll;
using namespace std;
int main(){
int numVaccines;
cin >> numVaccines;
int vaccineMidichlorian[numVaccines], patientMidichlorian[numVaccines];
for(int i = 0; i < numVaccines; ++i){
cin >> vaccineMidichlorian[i];
}
for(int i = 0; i < numVaccines; ++i){
cin >> patientMidichlorian[i];
}
sort(vaccineMidichlorian, vaccineMidichlorian+numVaccines);
sort(patientMidichlorian, patientMidichlorian+numVaccines);
bool failed = false;
for(int i = 0; i < numVaccines; ++i){
if(patientMidichlorian[i] >= vaccineMidichlorian[i]){
cout << "No"; failed = true; break;
}
}
if(!failed)
cout << "Yes";
} | [
"aniganesh741@gmail.com"
] | aniganesh741@gmail.com |
5432ca64fd344981de60bd64a72f33701354eae2 | e3063fccaaed7d0e9a763c495e4d787a6dbb9056 | /Samples/Scripts/Layout/samples/sample4/Msvc60/CLIENTDL.H | 79061697d0441a3c1ea03a0f1009c144430c206d | [] | no_license | VB6Hobbyst7/PLayouts | dedce6e1ce2f0884c3cbe4a929c39f93dfd3bdc6 | 012d506f20c97948053411c29bdecc4739f8a510 | refs/heads/master | 2021-09-04T20:00:39.905993 | 2017-12-03T03:07:05 | 2017-12-03T03:07:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,698 | h | //////////////////////////////////////////////////////////////////////////////
//
// CLIENTDLG.H : header file
//
//////////////////////////////////////////////////////////////////////////////
// This is a part of the PADS-PowerPCB OLE Automation server SAMPLE2 sample.
// Copyright (C) 2003 Mentor Graphics Corp.
// All rights reserved.
//
// This source code is only intended as a supplement to the PADS-PowerPCB OLE
// Automation Server API Help file.
//////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_CLIENTDLG_H__EFD4272A_D443_11D0_BCBF_444553540000__INCLUDED_)
#define AFX_CLIENTDLG_H__EFD4272A_D443_11D0_BCBF_444553540000__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
class CClientDlgAutoProxy;
/////////////////////////////////////////////////////////////////////////////
// CClientDlg dialog
class IPowerPCBApp;
class CClientDlg : public CDialog
{
DECLARE_DYNAMIC(CClientDlg);
friend class CClientDlgAutoProxy;
// Construction
public:
CClientDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CClientDlg();
void Refresh();
void RefreshGeneralInfos();
void RefreshObjectsInfos();
void RefreshSelectionInfos();
void ProcessException(COleException* e);
void Connect();
void SendSelection();
void ShowObjectInfo();
void Disconnect();
void SafeDisconnect();
// Dialog Data
//{{AFX_DATA(CClientDlg)
enum { IDD = IDD_CLIENT_DIALOG };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CClientDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
CClientDlgAutoProxy* m_pAutoProxy;
HICON m_hIcon;
// Pointer to the PowerPCB server's top level object
IPowerPCBApp *m_pPowerPCBApplication;
PowerPCBSink m_PowerPCBSink;
BOOL SetSink(BOOL bStatus);
DWORD m_dwAppConnectionID;
DWORD m_dwDocConnectionID;
BOOL CanExit();
// Generated message map functions
//{{AFX_MSG(CClientDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnConnect();
afx_msg void OnDisconnect();
afx_msg void OnRefresh();
afx_msg void OnListBoxSelectionChange();
afx_msg void OnListBoxDoubleClick();
afx_msg void OnClose();
virtual void OnOK();
virtual void OnCancel();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CLIENTDLG_H__EFD4272A_D443_11D0_BCBF_444553540000__INCLUDED_)
| [
"matt@aquagps.com"
] | matt@aquagps.com |
9dd18cbc3ebf16c4ff85b1c92f7e87a4420a0e60 | 762d0c7c44687373bf643624c8ac616cb08cd227 | /External Dependencies/FMOD Studio API Windows/api/core/examples/dsp_custom.cpp | ff955009fcc5ab5277c94d170f753a58a701b17a | [
"MIT"
] | permissive | Promethaes/Espresso-Shot-Engine | eba955c95cbbce03cb22051bd055ae89a499d984 | 6dffcbd5e69708af2f8251b701b7052207162e9b | refs/heads/master | 2020-07-17T03:27:23.751072 | 2019-09-10T02:56:06 | 2019-09-10T02:56:06 | 205,931,611 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,836 | cpp | /*==============================================================================
Custom DSP Example
Copyright (c), Firelight Technologies Pty, Ltd 2004-2019.
This example shows how to add a user created DSP callback to process audio
data. The read callback is executed at runtime, and can be added anywhere in
the DSP network.
==============================================================================*/
#include "fmod.hpp"
#include "common.h"
typedef struct
{
float *buffer;
float volume_linear;
int length_samples;
int channels;
} mydsp_data_t;
FMOD_RESULT F_CALLBACK myDSPCallback(FMOD_DSP_STATE *dsp_state, float *inbuffer, float *outbuffer, unsigned int length, int inchannels, int *outchannels)
{
mydsp_data_t *data = (mydsp_data_t *)dsp_state->plugindata;
/*
This loop assumes inchannels = outchannels, which it will be if the DSP is created with '0'
as the number of channels in FMOD_DSP_DESCRIPTION.
Specifying an actual channel count will mean you have to take care of any number of channels coming in,
but outputting the number of channels specified. Generally it is best to keep the channel
count at 0 for maximum compatibility.
*/
for (unsigned int samp = 0; samp < length; samp++)
{
/*
Feel free to unroll this.
*/
for (int chan = 0; chan < *outchannels; chan++)
{
/*
This DSP filter just halves the volume!
Input is modified, and sent to output.
*/
data->buffer[(samp * *outchannels) + chan] = outbuffer[(samp * inchannels) + chan] = inbuffer[(samp * inchannels) + chan] * data->volume_linear;
}
}
data->channels = inchannels;
return FMOD_OK;
}
/*
Callback called when DSP is created. This implementation creates a structure which is attached to the dsp state's 'plugindata' member.
*/
FMOD_RESULT F_CALLBACK myDSPCreateCallback(FMOD_DSP_STATE *dsp_state)
{
unsigned int blocksize;
FMOD_RESULT result;
result = dsp_state->functions->getblocksize(dsp_state, &blocksize);
ERRCHECK(result);
mydsp_data_t *data = (mydsp_data_t *)calloc(sizeof(mydsp_data_t), 1);
if (!data)
{
return FMOD_ERR_MEMORY;
}
dsp_state->plugindata = data;
data->volume_linear = 1.0f;
data->length_samples = blocksize;
data->buffer = (float *)malloc(blocksize * 8 * sizeof(float)); // *8 = maximum size allowing room for 7.1. Could ask dsp_state->functions->getspeakermode for the right speakermode to get real speaker count.
if (!data->buffer)
{
return FMOD_ERR_MEMORY;
}
return FMOD_OK;
}
/*
Callback called when DSP is destroyed. The memory allocated in the create callback can be freed here.
*/
FMOD_RESULT F_CALLBACK myDSPReleaseCallback(FMOD_DSP_STATE *dsp_state)
{
if (dsp_state->plugindata)
{
mydsp_data_t *data = (mydsp_data_t *)dsp_state->plugindata;
if (data->buffer)
{
free(data->buffer);
}
free(data);
}
return FMOD_OK;
}
/*
Callback called when DSP::getParameterData is called. This returns a pointer to the raw floating point PCM data.
We have set up 'parameter 0' to be the data parameter, so it checks to make sure the passed in index is 0, and nothing else.
*/
FMOD_RESULT F_CALLBACK myDSPGetParameterDataCallback(FMOD_DSP_STATE *dsp_state, int index, void **data, unsigned int *length, char *)
{
if (index == 0)
{
unsigned int blocksize;
FMOD_RESULT result;
mydsp_data_t *mydata = (mydsp_data_t *)dsp_state->plugindata;
result = dsp_state->functions->getblocksize(dsp_state, &blocksize);
ERRCHECK(result);
*data = (void *)mydata;
*length = blocksize * 2 * sizeof(float);
return FMOD_OK;
}
return FMOD_ERR_INVALID_PARAM;
}
/*
Callback called when DSP::setParameterFloat is called. This accepts a floating point 0 to 1 volume value, and stores it.
We have set up 'parameter 1' to be the volume parameter, so it checks to make sure the passed in index is 1, and nothing else.
*/
FMOD_RESULT F_CALLBACK myDSPSetParameterFloatCallback(FMOD_DSP_STATE *dsp_state, int index, float value)
{
if (index == 1)
{
mydsp_data_t *mydata = (mydsp_data_t *)dsp_state->plugindata;
mydata->volume_linear = value;
return FMOD_OK;
}
return FMOD_ERR_INVALID_PARAM;
}
/*
Callback called when DSP::getParameterFloat is called. This returns a floating point 0 to 1 volume value.
We have set up 'parameter 1' to be the volume parameter, so it checks to make sure the passed in index is 1, and nothing else.
An alternate way of displaying the data is provided, as a string, so the main app can use it.
*/
FMOD_RESULT F_CALLBACK myDSPGetParameterFloatCallback(FMOD_DSP_STATE *dsp_state, int index, float *value, char *valstr)
{
if (index == 1)
{
mydsp_data_t *mydata = (mydsp_data_t *)dsp_state->plugindata;
*value = mydata->volume_linear;
if (valstr)
{
sprintf(valstr, "%d", (int)((*value * 100.0f)+0.5f));
}
return FMOD_OK;
}
return FMOD_ERR_INVALID_PARAM;
}
int FMOD_Main()
{
FMOD::System *system;
FMOD::Sound *sound;
FMOD::Channel *channel;
FMOD::DSP *mydsp;
FMOD::ChannelGroup *mastergroup;
FMOD_RESULT result;
unsigned int version;
void *extradriverdata = 0;
Common_Init(&extradriverdata);
/*
Create a System object and initialize.
*/
result = FMOD::System_Create(&system);
ERRCHECK(result);
result = system->getVersion(&version);
ERRCHECK(result);
if (version < FMOD_VERSION)
{
Common_Fatal("FMOD lib version %08x doesn't match header version %08x", version, FMOD_VERSION);
}
result = system->init(32, FMOD_INIT_NORMAL, extradriverdata);
ERRCHECK(result);
result = system->createSound(Common_MediaPath("stereo.ogg"), FMOD_LOOP_NORMAL, 0, &sound);
ERRCHECK(result);
result = system->playSound(sound, 0, false, &channel);
ERRCHECK(result);
/*
Create the DSP effect.
*/
{
FMOD_DSP_DESCRIPTION dspdesc;
memset(&dspdesc, 0, sizeof(dspdesc));
FMOD_DSP_PARAMETER_DESC wavedata_desc;
FMOD_DSP_PARAMETER_DESC volume_desc;
FMOD_DSP_PARAMETER_DESC *paramdesc[2] =
{
&wavedata_desc,
&volume_desc
};
FMOD_DSP_INIT_PARAMDESC_DATA(wavedata_desc, "wave data", "", "wave data", FMOD_DSP_PARAMETER_DATA_TYPE_USER);
FMOD_DSP_INIT_PARAMDESC_FLOAT(volume_desc, "volume", "%", "linear volume in percent", 0, 1, 1);
strncpy(dspdesc.name, "My first DSP unit", sizeof(dspdesc.name));
dspdesc.version = 0x00010000;
dspdesc.numinputbuffers = 1;
dspdesc.numoutputbuffers = 1;
dspdesc.read = myDSPCallback;
dspdesc.create = myDSPCreateCallback;
dspdesc.release = myDSPReleaseCallback;
dspdesc.getparameterdata = myDSPGetParameterDataCallback;
dspdesc.setparameterfloat = myDSPSetParameterFloatCallback;
dspdesc.getparameterfloat = myDSPGetParameterFloatCallback;
dspdesc.numparameters = 2;
dspdesc.paramdesc = paramdesc;
result = system->createDSP(&dspdesc, &mydsp);
ERRCHECK(result);
}
result = system->getMasterChannelGroup(&mastergroup);
ERRCHECK(result);
result = mastergroup->addDSP(0, mydsp);
ERRCHECK(result);
/*
Main loop.
*/
do
{
bool bypass;
Common_Update();
result = mydsp->getBypass(&bypass);
ERRCHECK(result);
if (Common_BtnPress(BTN_ACTION1))
{
bypass = !bypass;
result = mydsp->setBypass(bypass);
ERRCHECK(result);
}
if (Common_BtnPress(BTN_ACTION2))
{
float vol;
result = mydsp->getParameterFloat(1, &vol, 0, 0);
ERRCHECK(result);
if (vol > 0.0f)
{
vol -= 0.1f;
}
result = mydsp->setParameterFloat(1, vol);
ERRCHECK(result);
}
if (Common_BtnPress(BTN_ACTION3))
{
float vol;
result = mydsp->getParameterFloat(1, &vol, 0, 0);
ERRCHECK(result);
if (vol < 1.0f)
{
vol += 0.1f;
}
result = mydsp->setParameterFloat(1, vol);
ERRCHECK(result);
}
result = system->update();
ERRCHECK(result);
{
char volstr[32] = { 0 };
FMOD_DSP_PARAMETER_DESC *desc;
mydsp_data_t *data;
result = mydsp->getParameterInfo(1, &desc);
ERRCHECK(result);
result = mydsp->getParameterFloat(1, 0, volstr, 32);
ERRCHECK(result);
result = mydsp->getParameterData(0, (void **)&data, 0, 0, 0);
ERRCHECK(result);
Common_Draw("==================================================");
Common_Draw("Custom DSP Example.");
Common_Draw("Copyright (c) Firelight Technologies 2004-2019.");
Common_Draw("==================================================");
Common_Draw("");
Common_Draw("Press %s to toggle filter bypass", Common_BtnStr(BTN_ACTION1));
Common_Draw("Press %s to decrease volume 10%%", Common_BtnStr(BTN_ACTION2));
Common_Draw("Press %s to increase volume 10%%", Common_BtnStr(BTN_ACTION3));
Common_Draw("Press %s to quit", Common_BtnStr(BTN_QUIT));
Common_Draw("");
Common_Draw("Filter is %s", bypass ? "inactive" : "active");
Common_Draw("Volume is %s%s", volstr, desc->label);
if (data->channels)
{
char display[80] = { 0 };
int channel;
for (channel = 0; channel < data->channels; channel++)
{
int count,level;
float max = 0;
for (count = 0; count < data->length_samples; count++)
{
if (fabsf(data->buffer[(count * data->channels) + channel]) > max)
{
max = fabsf(data->buffer[(count * data->channels) + channel]);
}
}
level = (int)(max * 40.0f);
sprintf(display, "%2d ", channel);
for (count = 0; count < level; count++) display[count + 3] = '=';
Common_Draw(display);
}
}
}
Common_Sleep(50);
} while (!Common_BtnPress(BTN_QUIT));
/*
Shut down
*/
result = sound->release();
ERRCHECK(result);
result = mastergroup->removeDSP(mydsp);
ERRCHECK(result);
result = mydsp->release();
ERRCHECK(result);
result = system->close();
ERRCHECK(result);
result = system->release();
ERRCHECK(result);
Common_Close();
return 0;
}
| [
"anth19800@hotmail.com"
] | anth19800@hotmail.com |
3ce2c2cf610416782e14de081b1212e27a208392 | 163e4861bc8cabd801c72d3db865b553bf1937a8 | /chapter-02/exercise-07/main.cpp | 91248592e9b2020a58580845be0510021368a0de | [] | no_license | hartbit/accelerated-cpp | 9a98b80d259ec9fb5fc29ccfff7eceb9859c47c5 | e9a2d435783bf5ce527535cb6eeff8e7976ae601 | refs/heads/master | 2020-03-11T14:53:43.972407 | 2018-04-28T20:30:01 | 2018-04-28T20:30:01 | 130,068,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103 | cpp | #include <iostream>
int main() {
for (int i = 10; i >= -5; i--) {
std::cout << i << std::endl;
}
} | [
"david@hartbit.com"
] | david@hartbit.com |
e7fad910446719d32141c366e9e610abe7ab8fc4 | dd928db5d8f137ecb0d17a5bb34410e01a1970fd | /object_analytics_node/include/object_analytics_node/segmenter/algorithm_config.hpp | 8ade475b037d9e3767ba5c77043b0413e0c86de2 | [
"Apache-2.0"
] | permissive | TonyGuo236/ros2_object_analytics | cb9fd31bdc4fd6779fbecd94dc765ccab1e40ba1 | 1f5ea31dee5f7d3ca7839a9172f8b9975204ec75 | refs/heads/master | 2020-03-17T16:38:59.132046 | 2018-05-16T07:25:53 | 2018-05-16T07:39:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,551 | hpp | /*
* Copyright (c) 2018 Intel Corporation
*
* 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 OBJECT_ANALYTICS_NODE_SEGMENTER_ALGORITHM_CONFIG_H
#define OBJECT_ANALYTICS_NODE_SEGMENTER_ALGORITHM_CONFIG_H
#include <map>
#include <string>
#include "object_analytics_node/util/file_parser.hpp"
namespace object_analytics_node
{
namespace segmenter
{
/** @class AlorithmConfig
*
* Encapsulate config related operations.
*/
class AlgorithmConfig
{
public:
/**
* Constructor of AlgorithmConfig
*
* @param[in] name Configuration file name
*/
explicit AlgorithmConfig(const std::string& file_name)
{
file_name;
// TODO(Peter Han): Don't want to recreate the wheel.
// To leverage 3rd part library, should get approved.
// Not implement this is totally okay, becasue default value is always provided.
}
/**
* Get value of given key
*
* @param[in] key name of query item
* @param[in] default_val default value used when fail to query
*
* @return value of given key, def_val if failed to query the key
*/
template <typename T>
inline T get(const std::string& key, const T default_val)
{
assert(false);
return default_val;
}
private:
std::map<std::string, std::string> map_;
};
template <>
inline std::string AlgorithmConfig::get<std::string>(const std::string& key, const std::string default_val)
{
try
{
return map_[key];
}
catch (...)
{
}
return default_val;
}
template <>
inline size_t AlgorithmConfig::get<size_t>(const std::string& key, const size_t default_val)
{
try
{
return static_cast<size_t>(std::stoi(map_[key]));
}
catch (...)
{
}
return default_val;
}
template <>
inline float AlgorithmConfig::get<float>(const std::string& key, const float default_val)
{
try
{
return static_cast<float>(std::stof(map_[key]));
}
catch (...)
{
}
return default_val;
}
} // namespace segmenter
} // namespace object_analytics_node
#endif // OBJECT_ANALYTICS_NODE_SEGMENTER_ALGORITHM_CONFIG_H
| [
"peter.han@intel.com"
] | peter.han@intel.com |
700f51dcd67d6ad2d7cee1b365896b0919a0d545 | 1af5cf87e3e749fdc8ae0589156aa85fb54443b1 | /qt/screenshot/main.cpp | 256c72f0d245d962381bb6576a7d91469d53d0d6 | [] | no_license | tangboshi/julia_c | c3fe5974d12005cc7b74f806dccceacaa27c6ea2 | 0a722b4755e3c518a58b395fd39b1a192ad0884e | refs/heads/master | 2020-12-30T14:00:13.902392 | 2017-06-10T22:03:37 | 2017-06-10T22:03:37 | 91,271,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | cpp | #include "window.h"
#include <QApplication>
#include <QStyleFactory>
int main(int argc, char *argv[])
{
QApplication::setDesktopSettingsAware(false);
QApplication a(argc, argv);
window w;
#ifdef __linux__
QStyle* style = QStyleFactory::create("Oxygen");
a.setStyle(style);
#endif
w.show();
return a.exec();
}
| [
"info@alexander-pastor.de"
] | info@alexander-pastor.de |
bf37ef7e8e7601c015e7d28efc2968f64aa8ea2f | e21eddf0d9225ddc07c28e72c510d3b243c3b363 | /baekjoon/basic/graph_bfs/1261/1261.cpp | 5fe26831be9b9dc476d700299af35d73f445bd2f | [] | no_license | Kangwoosun/Algorithm | 5913bc51df2e7573d870ec0e4d544091c8ef1e67 | 7cf6ac9d5c933ffa4255c803295852365400f8cc | refs/heads/master | 2023-03-14T00:26:32.352711 | 2021-03-02T07:23:32 | 2021-03-02T07:23:32 | 280,450,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,637 | cpp | #include <iostream>
#include <queue>
#include <utility>
#include <climits>
using namespace std;
int visit[101][101];
bool v[101][101];
int N, M;
int mx[] = {0,0,-1,1};
int my[] = {1,-1,0,0};
bool isin(int x, int y){
return (1<=x && x<=N && 1<=y && y<=M ? true : false);
}
int bfs(){
queue<pair<int,int>> q;
for(int i =1; i<=N; ++i)
for(int j = 1; j<=M; ++j)
visit[i][j] = INT_MAX;
q.push(make_pair(1,1));
visit[1][1] = 0;
while(!q.empty()){
auto [x,y] = q.front();
q.pop();
if(x == N && y == M)
continue;
for(int i =0; i<4; ++i){
int tmp_x = x + mx[i];
int tmp_y = y + my[i];
if(v[tmp_x][tmp_y]){
if(isin(tmp_x, tmp_y) && visit[tmp_x][tmp_y]>visit[x][y]+1){
q.push(make_pair(tmp_x, tmp_y));
visit[tmp_x][tmp_y] = visit[x][y] + 1;
}
}
else{
if(isin(tmp_x,tmp_y) && visit[tmp_x][tmp_y] > visit[x][y]){
q.push(make_pair(tmp_x,tmp_y));
visit[tmp_x][tmp_y] = visit[x][y];
}
}
}
}
return visit[N][M];
}
int main(){
cin.tie(NULL);
ios::sync_with_stdio(false);
char input;
cin >> M >> N;
for(int i =1; i<= N; ++i){
for(int j=1; j<=M; ++j){
cin >> input;
v[i][j] = '0' - input;
}
}
cout << bfs();
} | [
"kws981924@gmail.com"
] | kws981924@gmail.com |
4fc79168a022d39910cac93eac6493ef2db37859 | ddf03b0ce0bb5f54696aa531f7561a694d2b82df | /rebuild_v0/include/JunDataWriter.hh | ab964ce9ed57c2ff0aacc2eb820a116eedd95143 | [] | no_license | fengjunpku/rebuild_13C | 7f6ff7971ddebd5d3981d17a7c743bf59c25f1b8 | 570c7b85566194adaa1350b94708e9f484865b3a | refs/heads/master | 2021-01-22T21:53:11.637574 | 2017-10-26T08:35:30 | 2017-10-26T08:35:30 | 85,484,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | hh | #ifndef JunDataWriter_HH
#define JunDataWriter_HH
#include <iomanip>
#include <vector>
#include "stdio.h"
#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TString.h>
#include "reDefine.hh"
#include "JunParticle.hh"
using namespace std;
//instance->openfile->gettree->recorde
class JunDataWriter
{
private:
JunDataWriter();
public:
virtual ~JunDataWriter();
static JunDataWriter* Instance();
void Fill();
void Record();
void Clear();
void OpenFile(int runnum);
private:
TTree *otree;
TFile *ofile;
static JunDataWriter* theWriter;
public:
int num;
int numHe4;
int numBe9;
int numT1H;
JunParticle he4;
JunParticle be9;
JunParticle he4t0;
JunParticle he4t1;
JunParticle be9b;//breakup
JunParticle be9r;//recoil
JunParticle t1h;//particle on T1 heavier than alpha
JunParticle im;
JunParticle qim;
JunParticle mm;
JunParticle mix;
JunParticle q;
};
#endif | [
"fengjun2013@pku.edu.cn"
] | fengjun2013@pku.edu.cn |
3f399cf66e47bb803284655f0e50c7150abf75a0 | b7d023db1ceafa805120f529c731d98cc2482719 | /main.cpp | ef7c8c59755e0e996a0f6adf35f41edc4691aeea | [] | no_license | Sudoka/Kingdom | 36a8ec3f91beb021e913ed1013452aa9337d978e | e7e0e3f2532e0fe2500c2642b2c1934a4573013e | refs/heads/master | 2020-04-10T15:00:14.809841 | 2013-06-30T01:44:49 | 2013-07-04T04:01:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,980 | cpp | #include <iostream>
#include "Kingdom.h"
int main()
{
NonDupWarrior ndw;
Warrior* pw;
int choice;
int position;
while(1) {
int archers = 1, knights = 2, spearman = 3;
cout << "\n\n********************************************" << endl;
cout << "\nPlease select your choice of warriors." << endl;
cout << "\n(0)Quit (1)Archers (2)Knights (3)Spearmen: ";
cin >> choice;
if (!choice) {
break;
}
int bWon = 0;
int front = 1, middle = 2, back = 3;
if (choice == archers) {
while(1) {
cout << "\n\nPlease select the position of your Archers" << endl;
cout << "\n(0)Quit (1)FrontLine (2)Middle (3)BackRank: ";
cin >> position;
if (!position) {
break;
}
if (position == 1) {
cout << "\nPlease enter the number of battles that these archers have won: ";
cin >> bWon;
pw = new Archer( bWon, front );
}
else if (position == 2) {
cout << "\nPlease enter the number of battles that these archers have won: ";
cin >> bWon;
pw = new Archer( bWon, middle );
}
else {
cout << "\nPlease enter the number of battles that these archers have won: ";
cin >> bWon;
pw = new Archer( bWon, back );
}
ndw.insert(pw);
} // close while
} // close if
else if (choice == knights) {
while(1) {
cout << "\n\nPlease select the position of your Knights" << endl;
cout << "\n(0)Quit (1)FrontLine (2)Middle (3)BackRank: ";
cin >> position;
if (!position) {
break;
}
if (position == 1) {
cout << "\nPlease enter the number of battles that these knights have won: ";
cin >> bWon;
pw = new Knight( bWon, front );
}
else if (position == 2) {
cout << "\nPlease enter the number of battles that these knights have won: ";
cin >> bWon;
pw = new Knight( bWon, middle );
}
else {
cout << "\nPlease enter the number of battles that these knights have won: ";
cin >> bWon;
pw = new Knight( bWon, back );
}
ndw.insert(pw);
} // close while
} // close else if
else {
while(1) {
cout << "\n\nPlease select the position of your Spearmen" << endl;
cout << "\n(0)Quit (1)FrontLine (2)Middle (3)BackRank: ";
cin >> position;
if (!position) {
break;
}
if (position == 1) {
cout << "\nPlease enter the number of battles that these spearmen have won: ";
cin >> bWon;
pw = new Spearman( bWon, front );
}
else if (position == 2) {
cout << "\nPlease enter the number of battles that these spearmen have won: ";
cin >> bWon;
pw = new Spearman( bWon, middle );
}
else {
cout << "\nPlease enter the number of battles that these spearmen have won: ";
cin >> bWon;
pw = new Spearman( bWon, back );
}
ndw.insert(pw);
} // close while
} // close else
} // close outer while
ndw.showAll();
int exit;
cout << "Please enter any key to exit...";
cin >> exit;
return 0;
}
| [
"yswarovski@ucsd.edu"
] | yswarovski@ucsd.edu |
5e67d7f850c3472a5748aee8cdf78909f0f3bcaf | 9923e30eb99716bfc179ba2bb789dcddc28f45e6 | /openapi-generator/cpp-restbed-server/model/InlineResponse2008.cpp | 8cd5f396e14e0ccd82ea4f52447be8f167c9569d | [] | no_license | silverspace/samsara-sdks | cefcd61458ed3c3753ac5e6bf767229dd8df9485 | c054b91e488ab4266f3b3874e9b8e1c9e2d4d5fa | refs/heads/master | 2020-04-25T13:16:59.137551 | 2019-03-01T05:49:05 | 2019-03-01T05:49:05 | 172,804,041 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,816 | cpp | /**
* Samsara API
* # Introduction Samsara provides API endpoints for interacting with Samsara Cloud, so that you can build powerful applications and custom solutions with sensor data. Samsara has endpoints available to track and analyze sensors, vehicles, and entire fleets. The Samsara Cloud API is a [RESTful API](https://en.wikipedia.org/wiki/Representational_state_transfer) accessed by an [HTTP](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) client such as wget or curl, or HTTP libraries of most modern programming languages including python, ruby, java. We use built-in HTTP features, like HTTP authentication and HTTP verbs, which are understood by off-the-shelf HTTP clients. We allow you to interact securely with our API from a client-side web application (though you should never expose your secret API key). [JSON](http://www.json.org/) is returned by all API responses, including errors. If you’re familiar with what you can build with a REST API, the following API reference guide will be your go-to resource. API access to the Samsara cloud is available to all Samsara administrators. To start developing with Samsara APIs you will need to [obtain your API keys](#section/Authentication) to authenticate your API requests. If you have any questions you can reach out to us on [support@samsara.com](mailto:support@samsara.com) # Endpoints All our APIs can be accessed through HTTP requests to URLs like: ```curl https://api.samsara.com/<version>/<endpoint> ``` All our APIs are [versioned](#section/Versioning). If we intend to make breaking changes to an API which either changes the response format or request parameter, we will increment the version. # Authentication To authenticate your API request you will need to include your secret token. You can manage your API tokens in the [Dashboard](https://cloud.samsara.com). They are visible under `Settings->Organization->API Tokens`. Your API tokens carry many privileges, so be sure to keep them secure. Do not share your secret API tokens in publicly accessible areas such as GitHub, client-side code, and so on. Authentication to the API is performed via [HTTP Basic Auth](https://en.wikipedia.org/wiki/Basic_access_authentication). Provide your API token as the basic access_token value in the URL. You do not need to provide a password. ```curl https://api.samsara.com/<version>/<endpoint>?access_token={access_token} ``` All API requests must be made over [HTTPS](https://en.wikipedia.org/wiki/HTTPS). Calls made over plain HTTP or without authentication will fail. # Request Methods Our API endpoints use [HTTP request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) to specify the desired operation to be performed. The documentation below specified request method supported by each endpoint and the resulting action. ## GET GET requests are typically used for fetching data (like data for a particular driver). ## POST POST requests are typically used for creating or updating a record (like adding new tags to the system). With that being said, a few of our POST requests can be used for fetching data (like current location data of your fleet). ## PUT PUT requests are typically used for updating an existing record (like updating all devices associated with a particular tag). ## PATCH PATCH requests are typically used for modifying an existing record (like modifying a few devices associated with a particular tag). ## DELETE DELETE requests are used for deleting a record (like deleting a tag from the system). # Response Codes All API requests will respond with appropriate [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). Your API client should handle each response class differently. ## 2XX These are successful responses and indicate that the API request returned the expected response. ## 4XX These indicate that there was a problem with the request like a missing parameter or invalid values. Check the response for specific [error details](#section/Error-Responses). Requests that respond with a 4XX status code, should be modified before retrying. ## 5XX These indicate server errors when the server is unreachable or is misconfigured. In this case, you should retry the API request after some delay. # Error Responses In case of a 4XX status code, the body of the response will contain information to briefly explain the error reported. To help debugging the error, you can refer to the following table for understanding the error message. | Status Code | Message | Description | |-------------|----------------|-------------------------------------------------------------------| | 401 | Invalid token | The API token is invalid and could not be authenticated. Please refer to the [authentication section](#section/Authentication). | | 404 | Page not found | The API endpoint being accessed is invalid. | | 400 | Bad request | Default response for an invalid request. Please check the request to make sure it follows the format specified in the documentation. | # Versioning All our APIs are versioned. Our current API version is `v1` and we are continuously working on improving it further and provide additional endpoints. If we intend to make breaking changes to an API which either changes the response format or request parameter, we will increment the version. Thus, you can use our current API version worry free. # FAQs Check out our [responses to FAQs here](https://kb.samsara.com/hc/en-us/sections/360000538054-APIs). Don’t see an answer to your question? Reach out to us on [support@samsara.com](mailto:support@samsara.com).
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Inline_response_200_8.h"
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;
namespace org {
namespace openapitools {
namespace server {
namespace model {
Inline_response_200_8::Inline_response_200_8()
{
}
Inline_response_200_8::~Inline_response_200_8()
{
}
std::string Inline_response_200_8::toJsonString()
{
std::stringstream ss;
ptree pt;
write_json(ss, pt, false);
return ss.str();
}
void Inline_response_200_8::fromJsonString(std::string const& jsonString)
{
std::stringstream ss(jsonString);
ptree pt;
read_json(ss,pt);
}
std::vector<std::shared_ptr<Sensor>> Inline_response_200_8::getSensors() const
{
return m_Sensors;
}
void Inline_response_200_8::setSensors(std::vector<std::shared_ptr<Sensor>> value)
{
m_Sensors = value;
}
}
}
}
}
| [
"greg@samsara.com"
] | greg@samsara.com |
1af32172e5822dc615639bc35d81464268c12fda | c451cb186764b7de60eace0d3b34b27bb3404bd6 | /691B.cpp | d4e34047455a756030dcc39e7046802a143b9754 | [] | no_license | Tsugiru/codeforces | 759f9abd46daa748202f720c6e6003654d553c15 | 3cc16d7cb8b0ae7f9da075c54e39640f00bd73e5 | refs/heads/master | 2021-08-16T21:50:31.625336 | 2021-06-27T11:02:02 | 2021-06-27T11:02:02 | 207,086,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
struct int_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
struct pair_hash {
size_t operator()(pair<int, int> x) const {
return int_hash{}(x.first) ^ (int_hash{}(x.second) << 16);
}
};
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int MOD = 1000000007;
const ll INF = numeric_limits<ll>::max();
const int inf = 1e7;
const int MX = 100001; //check the limits, dummy
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string s; cin >> s;
int n = s.size();
unordered_set<char> gm{'A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y', 'o', 'v', 'w', 'x'};
unordered_map<char, char> mir{ {'p', 'q'}, {'b', 'd'}, {'q', 'p'}, {'d', 'b'} };
bool ok = true;
for(int i = 0; i < n / 2 && ok; i++) {
if(!(s[i] == s[n - i - 1] && gm.count(s[i]) || mir.count(s[i]) && mir[s[i]] == s[n - i - 1]))
ok = false;
}
if (n & 1) ok = ok && gm.count(s[n/2]);
if(ok) cout << "TAK" << endl;
else cout << "NIE" << endl;
} | [
"eliemaamary17@gmail.com"
] | eliemaamary17@gmail.com |
03b78c89a9021e7276155ec37809d5301b89bb47 | 81ca137bb6b204c2aef6d9128dc0bb7a2b4e94b4 | /ivnavigation/src/ivnavigation.cpp | 1685287fcc7d07d922d053172bdd5a13dc2a2b2a | [] | no_license | beamiter/ros_wtf | 29ae642cc86b2388c0d088a51111c313f5114882 | 83f01d40204f2068ea75b10475b142446bda9fa7 | refs/heads/master | 2020-12-01T05:31:23.675761 | 2017-02-08T00:59:53 | 2017-02-08T00:59:53 | 65,908,193 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cpp | #include "ivnav.h"
#include "ivamcl.h"
#include "ivodom.h"
#include <iostream>
int main (int argc, char **argv)
{
ros::init(argc, argv, "ivnavigation");
ros::NodeHandle nh;
//ivnav ivnav(nh);
//ivamcl ivamcl(nh);
ivodom ivodom(nh);
ros::spin();
return 0;
} | [
"beamiter@163.com"
] | beamiter@163.com |
fa29188e1aac4ceb27e7590794ee666b3572bf61 | 0439e7879c557e51e57e4d0bcc3fdeb5ef428ad4 | /NT-HW-I/183D.cpp | b050c191ead5941afa44b4da6ce4c8da6325e5f5 | [] | no_license | zcwwzdjn/OI | f176a5618c8c5528f1af1dfb082d89c97f5872d8 | 710c65923898d39ebf29b609fdc084cf9ebecb15 | refs/heads/master | 2021-01-10T01:42:32.147017 | 2013-06-04T08:35:26 | 2013-06-04T08:35:26 | 8,447,388 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
const double kEps = 1E-12;
const int kMaxN = 3000, kMaxM = 300;
int n, m;
double p[kMaxN][kMaxM];
double dp[2][kMaxN + 1];
vector<double> seq;
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++ i)
for (int j = 0; j < m; ++ j) {
scanf("%lf", &p[i][j]);
p[i][j] /= 1000.0;
}
for (int j = 0; j < m; ++ j) {
int des = 0, src = 1;
for (int i = 0; i <= n; ++ i) dp[des][i] = dp[src][i] = 0.0;
dp[des][0] = 1.0;
double sum = 0.0;
int len = 0;
for (int i = 0; i < n; ++ i) {
des ^= 1, src ^= 1;
dp[des][0] = 1.0;
for (int k = 0; k <= len; ++ k) {
dp[des][k + 1] = p[i][j] * dp[src][k] + (1.0 - p[i][j]) * dp[src][k + 1];
}
if (sum + dp[des][len + 1] < kEps)
sum += dp[des][len + 1];
else
++ len;
}
for (int k = 1; k <= len; ++ k) {
seq.push_back(dp[des][k]);
}
}
double res = 0.0;
sort(seq.begin(), seq.end(), greater<double>());
for (int i = 0; i < n; ++ i) res += seq[i];
printf("%.12lf\n", res);
return 0;
}
| [
"zcwwzdjn@hotmail.com"
] | zcwwzdjn@hotmail.com |
734fa3a0bde45feeda9e83ce9b9adb5fc3a736cc | 9c73501c5a8413753ed5776299fe1f62a0a2659e | /fvm/Equation/LinearTransientTerm.cpp | 0e64148dc696d6942670659bf8feb2472212c40e | [
"MIT"
] | permissive | anymodel/DREAM-1 | 5d1ac63ffc48157f110ef672036d801442a2c917 | eba9fabddfa4ef439737807ef30978a52ab55afb | refs/heads/master | 2023-08-23T05:01:13.867792 | 2021-10-28T19:45:33 | 2021-10-28T19:45:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,022 | cpp | /**
* Implementation of an Euler backward transient term multiplied
* by an arbitrary grid-dependent weight function.
* Evaluation of weights must be implemented in derived classes.
*/
#include <iostream>
#include "FVM/config.h"
#include "FVM/Matrix.hpp"
#include "FVM/Equation/LinearTransientTerm.hpp"
#include "FVM/Grid/Grid.hpp"
using namespace DREAM::FVM;
/**
* Constructor.
*/
LinearTransientTerm::LinearTransientTerm(Grid *grid, const len_t unknownId)
: DiagonalTerm(grid), unknownId(unknownId){}
/**
* Rebuild the transient term.
*
* dt: Length of next time step to take.
*/
void LinearTransientTerm::Rebuild(const real_t, const real_t dt, UnknownQuantityHandler *uqty) {
this->dt = dt;
this->xn = uqty->GetUnknownDataPrevious(this->unknownId);
if(!hasBeenInitialized){
InitializeWeights();
hasBeenInitialized = true;
}
if(TermDependsOnUnknowns())
SetWeights();
}
/**
* Set the matrix elements corresponding to this
* transient term.
*
* This term assumes that the linearized matrix equation
* to solve is of the form
*
* df/dt + Mf = -S
*
* where M is a linear matrix operator represented by 'mat',
* and 'S' is a source term stored in 'rhs'.
*
* mat: Matrix to set elements of.
* rhs: Equation RHS.
*/
void LinearTransientTerm::SetMatrixElements(Matrix *mat, real_t *rhs) {
const len_t N = grid->GetNCells();
for (len_t i = 0; i < N; i++)
mat->SetElement(i, i, weights[i]/this->dt, ADD_VALUES);
if (rhs != nullptr)
for (len_t i = 0; i < N; i++)
rhs[i] -= weights[i]*this->xn[i] / this->dt;
}
/**
* Set the elements in the function vector 'F' (i.e.
* evaluate this term).
*
* vec: Vector containing value of 'F' on return.
* x: Previous solution (unused).
*/
void LinearTransientTerm::SetVectorElements(real_t *vec, const real_t *xnp1) {
const len_t N = grid->GetNCells();
for (len_t i = 0; i < N; i++)
vec[i] += weights[i]*(xnp1[i] - xn[i]) / this->dt;
}
| [
"embreus@chalmers.se"
] | embreus@chalmers.se |
811fb48069e869699a8afd2b2bd87c7db77f27b6 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/beast/test/beast/zlib.cpp | 8b56a8d176c85f249e41d0320e1a82cd272e1b84 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | //
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
// Test that header file is self-contained.
#include <sstd/boost/beast/zlib.hpp>
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
364e7958273d510d69fa6b313b110dfcf528f952 | 91c53b665a8a0d5e0d6fbec989bf84072f910ce2 | /C++ Primer Plus/Chapter 10/stack.h | b94ba1e134db5ad55bfdaf061ba387c4498464a3 | [] | no_license | LONGZR007/StudyC-- | 0dd8fb5aeaa0fe0fda8194c0b8b53bc506fe5d52 | adf22f9d7f2b2465c07e440702284811b0c3955c | refs/heads/master | 2020-07-10T11:19:57.357876 | 2019-09-15T11:45:24 | 2019-09-15T11:45:42 | 204,249,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | h | // stack.h -- class definition for the stack ADT
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack
{
private:
// enum {MAX = 10}; // constant specific to class
Item *items; // holds stack items
Item MAX;
int top; // index for top stack item
public:
Stack(Item max = 1);
~Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item & item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item & item); // pop top into item
};
#endif
| [
"1558193230@qq.com"
] | 1558193230@qq.com |
0720be5f36568927a0612aa136c84eb9da464ec9 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/068/368/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_54e.cpp | a18893330aface6611cc1392b1f199abe944058e | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_54e.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml
Template File: sources-sink-54e.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sink: memcpy
* BadSink : Copy string to data using memcpy
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_54
{
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void badSink_e(char * data)
{
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
memcpy(data, source, 100*sizeof(char));
data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_e(char * data)
{
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
memcpy(data, source, 100*sizeof(char));
data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */
printLine(data);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
80b2043306a4d730c4bac4cee9e9b69e25b80dbb | ffe3bdc5d6135ccec77b372c23a9c63252f41c7e | /build/intermediates/jniLibs/armv7/debug/TgNetWrapper.cpp | 11a689e3afaec47dea31fc65b2df8c123f376bc9 | [] | no_license | DevDoubleDream/StoryShop | 12c4ac34c9560c631c17f859bcb43ef4b85ac0a9 | 41c215976e8a8ed819c25b91706b539db3da254b | refs/heads/master | 2021-01-20T12:03:56.202337 | 2017-03-08T01:53:29 | 2017-03-08T01:53:29 | 82,640,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,078 | cpp | #include <jni.h>
#include "tgnet/ApiScheme.h"
#include "tgnet/BuffersStorage.h"
#include "tgnet/NativeByteBuffer.h"
#include "tgnet/ConnectionsManager.h"
#include "tgnet/MTProtoScheme.h"
#include "tgnet/FileLoadOperation.h"
JavaVM *java;
jclass jclass_RequestDelegateInternal;
jmethodID jclass_RequestDelegateInternal_run;
jclass jclass_QuickAckDelegate;
jmethodID jclass_QuickAckDelegate_run;
jclass jclass_FileLoadOperationDelegate;
jmethodID jclass_FileLoadOperationDelegate_onFinished;
jmethodID jclass_FileLoadOperationDelegate_onFailed;
jmethodID jclass_FileLoadOperationDelegate_onProgressChanged;
jclass jclass_ConnectionsManager;
jmethodID jclass_ConnectionsManager_onUnparsedMessageReceived;
jmethodID jclass_ConnectionsManager_onUpdate;
jmethodID jclass_ConnectionsManager_onSessionCreated;
jmethodID jclass_ConnectionsManager_onLogout;
jmethodID jclass_ConnectionsManager_onConnectionStateChanged;
jmethodID jclass_ConnectionsManager_onInternalPushReceived;
jmethodID jclass_ConnectionsManager_onUpdateConfig;
jint createLoadOpetation(JNIEnv *env, jclass c, jint dc_id, jlong id, jlong volume_id, jlong access_hash, jint local_id, jbyteArray encKey, jbyteArray encIv, jstring extension, jint version, jint size, jstring dest, jstring temp, jobject delegate) {
if (encKey != nullptr && encIv == nullptr || encKey == nullptr && encIv != nullptr || extension == nullptr || dest == nullptr || temp == nullptr) {
return 0;
}
FileLoadOperation *loadOperation = nullptr;
bool error = false;
const char *extensionStr = env->GetStringUTFChars(extension, NULL);
const char *destStr = env->GetStringUTFChars(dest, NULL);
const char *tempStr = env->GetStringUTFChars(temp, NULL);
if (extensionStr == nullptr || destStr == nullptr || tempStr == nullptr) {
error = true;
}
jbyte *keyBuff = nullptr;
jbyte *ivBuff = nullptr;
if (!error && encKey != nullptr) {
keyBuff = env->GetByteArrayElements(encKey, NULL);
ivBuff = env->GetByteArrayElements(encIv, NULL);
if (keyBuff == nullptr || ivBuff == nullptr) {
error = true;
}
}
if (!error) {
if (delegate != nullptr) {
delegate = env->NewGlobalRef(delegate);
}
loadOperation = new FileLoadOperation(dc_id, id, volume_id, access_hash, local_id, (uint8_t *) keyBuff, (uint8_t *) ivBuff, extensionStr, version, size, destStr, tempStr);
loadOperation->setDelegate([delegate](std::string path) {
jstring pathText = jniEnv->NewStringUTF(path.c_str());
if (delegate != nullptr) {
jniEnv->CallVoidMethod(delegate, jclass_FileLoadOperationDelegate_onFinished, pathText);
}
if (pathText != nullptr) {
jniEnv->DeleteLocalRef(pathText);
}
}, [delegate](FileLoadFailReason reason) {
if (delegate != nullptr) {
jniEnv->CallVoidMethod(delegate, jclass_FileLoadOperationDelegate_onFailed, reason);
}
}, [delegate](float progress) {
if (delegate != nullptr) {
jniEnv->CallVoidMethod(delegate, jclass_FileLoadOperationDelegate_onProgressChanged, progress);
}
});
loadOperation->ptr1 = delegate;
}
if (keyBuff != nullptr) {
env->ReleaseByteArrayElements(encKey, keyBuff, JNI_ABORT);
}
if (ivBuff != nullptr) {
env->ReleaseByteArrayElements(encIv, ivBuff, JNI_ABORT);
}
if (extensionStr != nullptr) {
env->ReleaseStringUTFChars(extension, extensionStr);
}
if (destStr != nullptr) {
env->ReleaseStringUTFChars(dest, destStr);
}
if (tempStr != nullptr) {
env->ReleaseStringUTFChars(temp, tempStr);
}
return (jint) loadOperation;
}
void startLoadOperation(JNIEnv *env, jclass c, jint address) {
if (address != 0) {
((FileLoadOperation *) address)->start();
}
}
void cancelLoadOperation(JNIEnv *env, jclass c, jint address) {
if (address != 0) {
((FileLoadOperation *) address)->cancel();
}
}
static const char *FileLoadOperationClassPathName = "kr/wdream/tgnet/FileLoadOperation";
static JNINativeMethod FileLoadOperationMethods[] = {
{"native_createLoadOpetation", "(IJJJI[B[BLjava/lang/String;IILjava/lang/String;Ljava/lang/String;Ljava/lang/Object;)I", (void *) createLoadOpetation},
{"native_startLoadOperation", "(I)V", (void *) startLoadOperation},
{"native_cancelLoadOperation", "(I)V", (void *) cancelLoadOperation}
};
jint getFreeBuffer(JNIEnv *env, jclass c, jint length) {
return (jint) BuffersStorage::getInstance().getFreeBuffer(length);
}
jint limit(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
return buffer->limit();
}
jint position(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
return buffer->position();
}
void reuse(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
buffer->reuse();
}
jobject getJavaByteBuffer(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
return buffer->getJavaByteBuffer();
}
static const char *NativeByteBufferClassPathName = "kr/wdream/tgnet/NativeByteBuffer";
static JNINativeMethod NativeByteBufferMethods[] = {
{"native_getFreeBuffer", "(I)I", (void *) getFreeBuffer},
{"native_limit", "(I)I", (void *) limit},
{"native_position", "(I)I", (void *) position},
{"native_reuse", "(I)V", (void *) reuse},
{"native_getJavaByteBuffer", "(I)Ljava/nio/ByteBuffer;", (void *) getJavaByteBuffer}
};
jlong getCurrentTimeMillis(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getCurrentTimeMillis();
}
jint getCurrentTime(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getCurrentTime();
}
jint getTimeDifference(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getTimeDifference();
}
void sendRequest(JNIEnv *env, jclass c, jint object, jobject onComplete, jobject onQuickAck, jint flags, jint datacenterId, jint connetionType, jboolean immediate, jint token) {
TL_api_request *request = new TL_api_request();
request->request = (NativeByteBuffer *) object;
if (onComplete != nullptr) {
onComplete = env->NewGlobalRef(onComplete);
}
if (onQuickAck != nullptr) {
onQuickAck = env->NewGlobalRef(onQuickAck);
}
ConnectionsManager::getInstance().sendRequest(request, ([onComplete](TLObject *response, TL_error *error) {
TL_api_response *resp = (TL_api_response *) response;
jint ptr = 0;
jint errorCode = 0;
jstring errorText = nullptr;
if (resp != nullptr) {
ptr = (jint) resp->response.get();
} else if (error != nullptr) {
errorCode = error->code;
errorText = jniEnv->NewStringUTF(error->text.c_str());
}
if (onComplete != nullptr) {
jniEnv->CallVoidMethod(onComplete, jclass_RequestDelegateInternal_run, ptr, errorCode, errorText);
}
if (errorText != nullptr) {
jniEnv->DeleteLocalRef(errorText);
}
}), ([onQuickAck] {
if (onQuickAck != nullptr) {
jniEnv->CallVoidMethod(onQuickAck, jclass_QuickAckDelegate_run);
}
}), flags, datacenterId, (ConnectionType) connetionType, immediate, token, onComplete, onQuickAck);
}
void cancelRequest(JNIEnv *env, jclass c, jint token, jboolean notifyServer) {
return ConnectionsManager::getInstance().cancelRequest(token, notifyServer);
}
void cleanUp(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().cleanUp();
}
void cancelRequestsForGuid(JNIEnv *env, jclass c, jint guid) {
return ConnectionsManager::getInstance().cancelRequestsForGuid(guid);
}
void bindRequestToGuid(JNIEnv *env, jclass c, jint requestToken, jint guid) {
return ConnectionsManager::getInstance().bindRequestToGuid(requestToken, guid);
}
void applyDatacenterAddress(JNIEnv *env, jclass c, jint datacenterId, jstring ipAddress, jint port) {
const char *valueStr = env->GetStringUTFChars(ipAddress, 0);
ConnectionsManager::getInstance().applyDatacenterAddress(datacenterId, std::string(valueStr), port);
if (valueStr != 0) {
env->ReleaseStringUTFChars(ipAddress, valueStr);
}
}
jint getConnectionState(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getConnectionState();
}
void setUserId(JNIEnv *env, jclass c, int32_t id) {
ConnectionsManager::getInstance().setUserId(id);
}
void switchBackend(JNIEnv *env, jclass c) {
ConnectionsManager::getInstance().switchBackend();
}
void pauseNetwork(JNIEnv *env, jclass c) {
ConnectionsManager::getInstance().pauseNetwork();
}
void resumeNetwork(JNIEnv *env, jclass c, jboolean partial) {
ConnectionsManager::getInstance().resumeNetwork(partial);
}
void updateDcSettings(JNIEnv *env, jclass c) {
ConnectionsManager::getInstance().updateDcSettings(0);
}
void setUseIpv6(JNIEnv *env, jclass c, bool value) {
ConnectionsManager::getInstance().setUseIpv6(value);
}
void setNetworkAvailable(JNIEnv *env, jclass c, jboolean value) {
ConnectionsManager::getInstance().setNetworkAvailable(value);
}
void setPushConnectionEnabled(JNIEnv *env, jclass c, jboolean value) {
ConnectionsManager::getInstance().setPushConnectionEnabled(value);
}
class Delegate : public ConnectiosManagerDelegate {
void onUpdate() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUpdate);
}
void onSessionCreated() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onSessionCreated);
}
void onConnectionStateChanged(ConnectionState state) {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onConnectionStateChanged, state);
}
void onUnparsedMessageReceived(int64_t reqMessageId, NativeByteBuffer *buffer, ConnectionType connectionType) {
if (connectionType == ConnectionTypeGeneric) {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUnparsedMessageReceived, buffer);
}
}
void onLogout() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onLogout);
}
void onUpdateConfig(TL_config *config) {
NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(config->getObjectSize());
config->serializeToStream(buffer);
buffer->position(0);
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUpdateConfig, buffer);
buffer->reuse();
}
void onInternalPushReceived() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onInternalPushReceived);
}
};
void init(JNIEnv *env, jclass c, jint version, jint layer, jint apiId, jstring deviceModel, jstring systemVersion, jstring appVersion, jstring langCode, jstring configPath, jstring logPath, jint userId, jboolean enablePushConnection) {
const char *deviceModelStr = env->GetStringUTFChars(deviceModel, 0);
const char *systemVersionStr = env->GetStringUTFChars(systemVersion, 0);
const char *appVersionStr = env->GetStringUTFChars(appVersion, 0);
const char *langCodeStr = env->GetStringUTFChars(langCode, 0);
const char *configPathStr = env->GetStringUTFChars(configPath, 0);
const char *logPathStr = env->GetStringUTFChars(logPath, 0);
ConnectionsManager::getInstance().init(version, layer, apiId, std::string(deviceModelStr), std::string(systemVersionStr), std::string(appVersionStr), std::string(langCodeStr), std::string(configPathStr), std::string(logPathStr), userId, true, enablePushConnection);
if (deviceModelStr != 0) {
env->ReleaseStringUTFChars(deviceModel, deviceModelStr);
}
if (systemVersionStr != 0) {
env->ReleaseStringUTFChars(systemVersion, systemVersionStr);
}
if (appVersionStr != 0) {
env->ReleaseStringUTFChars(appVersion, appVersionStr);
}
if (langCodeStr != 0) {
env->ReleaseStringUTFChars(langCode, langCodeStr);
}
if (configPathStr != 0) {
env->ReleaseStringUTFChars(configPath, configPathStr);
}
if (logPathStr != 0) {
env->ReleaseStringUTFChars(logPath, logPathStr);
}
}
void setJava(JNIEnv *env, jclass c, jboolean useJavaByteBuffers) {
ConnectionsManager::useJavaVM(java, useJavaByteBuffers);
ConnectionsManager::getInstance().setDelegate(new Delegate());
}
static const char *ConnectionsManagerClassPathName = "kr/wdream/tgnet/ConnectionsManager";
static JNINativeMethod ConnectionsManagerMethods[] = {
{"native_getCurrentTimeMillis", "()J", (void *) getCurrentTimeMillis},
{"native_getCurrentTime", "()I", (void *) getCurrentTime},
{"native_getTimeDifference", "()I", (void *) getTimeDifference},
{"native_sendRequest", "(ILkr/wdream/tgnet/RequestDelegateInternal;Lkr/wdream/tgnet/QuickAckDelegate;IIIZI)V", (void *) sendRequest},
{"native_cancelRequest", "(IZ)V", (void *) cancelRequest},
{"native_cleanUp", "()V", (void *) cleanUp},
{"native_cancelRequestsForGuid", "(I)V", (void *) cancelRequestsForGuid},
{"native_bindRequestToGuid", "(II)V", (void *) bindRequestToGuid},
{"native_applyDatacenterAddress", "(ILjava/lang/String;I)V", (void *) applyDatacenterAddress},
{"native_getConnectionState", "()I", (void *) getConnectionState},
{"native_setUserId", "(I)V", (void *) setUserId},
{"native_init", "(IIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)V", (void *) init},
{"native_switchBackend", "()V", (void *) switchBackend},
{"native_pauseNetwork", "()V", (void *) pauseNetwork},
{"native_resumeNetwork", "(Z)V", (void *) resumeNetwork},
{"native_updateDcSettings", "()V", (void *) updateDcSettings},
{"native_setUseIpv6", "(Z)V", (void *) setUseIpv6},
{"native_setNetworkAvailable", "(Z)V", (void *) setNetworkAvailable},
{"native_setPushConnectionEnabled", "(Z)V", (void *) setPushConnectionEnabled},
{"native_setJava", "(Z)V", (void *) setJava}
};
inline int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int methodsCount) {
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, methods, methodsCount) < 0) {
return JNI_FALSE;
}
return JNI_TRUE;
}
extern "C" int registerNativeTgNetFunctions(JavaVM *vm, JNIEnv *env) {
java = vm;
if (!registerNativeMethods(env, NativeByteBufferClassPathName, NativeByteBufferMethods, sizeof(NativeByteBufferMethods) / sizeof(NativeByteBufferMethods[0]))) {
return JNI_FALSE;
}
if (!registerNativeMethods(env, FileLoadOperationClassPathName, FileLoadOperationMethods, sizeof(FileLoadOperationMethods) / sizeof(FileLoadOperationMethods[0]))) {
return JNI_FALSE;
}
if (!registerNativeMethods(env, ConnectionsManagerClassPathName, ConnectionsManagerMethods, sizeof(ConnectionsManagerMethods) / sizeof(ConnectionsManagerMethods[0]))) {
return JNI_FALSE;
}
jclass_RequestDelegateInternal = (jclass) env->NewGlobalRef(env->FindClass("kr/wdream/tgnet/RequestDelegateInternal"));
if (jclass_RequestDelegateInternal == 0) {
return JNI_FALSE;
}
jclass_RequestDelegateInternal_run = env->GetMethodID(jclass_RequestDelegateInternal, "run", "(IILjava/lang/String;)V");
if (jclass_RequestDelegateInternal_run == 0) {
return JNI_FALSE;
}
jclass_QuickAckDelegate = (jclass) env->NewGlobalRef(env->FindClass("kr/wdream/tgnet/QuickAckDelegate"));
if (jclass_RequestDelegateInternal == 0) {
return JNI_FALSE;
}
jclass_QuickAckDelegate_run = env->GetMethodID(jclass_QuickAckDelegate, "run", "()V");
if (jclass_QuickAckDelegate_run == 0) {
return JNI_FALSE;
}
jclass_FileLoadOperationDelegate = (jclass) env->NewGlobalRef(env->FindClass("kr/wdream/tgnet/FileLoadOperationDelegate"));
if (jclass_FileLoadOperationDelegate == 0) {
return JNI_FALSE;
}
jclass_FileLoadOperationDelegate_onFinished = env->GetMethodID(jclass_FileLoadOperationDelegate, "onFinished", "(Ljava/lang/String;)V");
if (jclass_FileLoadOperationDelegate_onFinished == 0) {
return JNI_FALSE;
}
jclass_FileLoadOperationDelegate_onFailed = env->GetMethodID(jclass_FileLoadOperationDelegate, "onFailed", "(I)V");
if (jclass_FileLoadOperationDelegate_onFailed == 0) {
return JNI_FALSE;
}
jclass_FileLoadOperationDelegate_onProgressChanged = env->GetMethodID(jclass_FileLoadOperationDelegate, "onProgressChanged", "(F)V");
if (jclass_FileLoadOperationDelegate_onProgressChanged == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager = (jclass) env->NewGlobalRef(env->FindClass("kr/wdream/tgnet/ConnectionsManager"));
if (jclass_ConnectionsManager == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onUnparsedMessageReceived = env->GetStaticMethodID(jclass_ConnectionsManager, "onUnparsedMessageReceived", "(I)V");
if (jclass_ConnectionsManager_onUnparsedMessageReceived == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onUpdate = env->GetStaticMethodID(jclass_ConnectionsManager, "onUpdate", "()V");
if (jclass_ConnectionsManager_onUpdate == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onSessionCreated = env->GetStaticMethodID(jclass_ConnectionsManager, "onSessionCreated", "()V");
if (jclass_ConnectionsManager_onSessionCreated == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onLogout = env->GetStaticMethodID(jclass_ConnectionsManager, "onLogout", "()V");
if (jclass_ConnectionsManager_onLogout == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onConnectionStateChanged = env->GetStaticMethodID(jclass_ConnectionsManager, "onConnectionStateChanged", "(I)V");
if (jclass_ConnectionsManager_onConnectionStateChanged == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onInternalPushReceived = env->GetStaticMethodID(jclass_ConnectionsManager, "onInternalPushReceived", "()V");
if (jclass_ConnectionsManager_onInternalPushReceived == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onUpdateConfig = env->GetStaticMethodID(jclass_ConnectionsManager, "onUpdateConfig", "(I)V");
if (jclass_ConnectionsManager_onUpdateConfig == 0) {
return JNI_FALSE;
}
ConnectionsManager::getInstance().setDelegate(new Delegate());
return JNI_TRUE;
}
| [
"dev.doubledream@gmail.com"
] | dev.doubledream@gmail.com |
f2ae17aff389b1656d993b413edbcaba033efdde | 094a7815d2caf5ea8eb9d7c104665bdeee9801b8 | /FunProject/src/Framework/Window.cpp | c64dba1fac8c38a39acce0f08491d199f6843fdd | [] | no_license | Rodanco/FunProject | da36a95ac842899cee8edd275ecc45f6cf2a2412 | 6fc5c5cde29f069e7f94d9096b708fedeeac9813 | refs/heads/master | 2020-04-23T16:49:55.930687 | 2019-03-22T14:05:52 | 2019-03-22T14:05:52 | 171,311,425 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,125 | cpp | #include "Window.h"
#include <string>
#include "SDL/SDL_log.h"
#include "SDL/SDL_timer.h"
#include "Definitions.h"
Window::Window() : Window(1280, 720)
{
}
Window::Window(Uint32 width, Uint32 height) : Window(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height)
{
}
Window::Window(Uint32 posX, Uint32 posY, Uint32 width, Uint32 height)
: window(nullptr), renderer(nullptr), pos(), currentSize(Vector2i(width, height)), beforeFullscreenSize(Vector2i(width, height)),
isMinimized(false), close(false), hasResize(false), fullscreen(false), windowID(0)
{
window = std::unique_ptr<SDL_Window, std::function<void(SDL_Window*)>>(
SDL_CreateWindow("Test", posX, posY, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE),
SDL_DestroyWindow);
renderer = std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer*)>>(
SDL_CreateRenderer(window.get(), -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED),
SDL_DestroyRenderer);
Vector2i aux;
SDL_GetWindowPosition(window.get(), &aux.x, &aux.y);
windowID.store(SDL_GetWindowID(window.get()), std::memory_order_release);
pos.store(aux, std::memory_order_release);
windowID = SDL_GetWindowID(window.get());
}
void Window::HandleEvents(const SDL_Event & e)
{
if (e.type != SDL_WINDOWEVENT)
return;
const auto& windowEvent = e.window;
if (windowEvent.windowID != windowID)
return;
ONLY_DEBUG(std::string logText = "Window " + std::to_string(SDL_GetWindowID(window.get()));)
switch (windowEvent.event)
{
case SDL_WINDOWEVENT_FOCUS_LOST:
//ONLY_DEBUG(logText += " has lost focus from user";)
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
//ONLY_DEBUG(logText += " has gained focus from user";)
break;
case SDL_WINDOWEVENT_CLOSE:
close.store(true, std::memory_order_release);
LOG("Window %d closed.", SDL_GetWindowID(window.get()));
break;
case SDL_WINDOWEVENT_MINIMIZED:
isMinimized.store(true, std::memory_order_release);
LOG("Window %d minimized.", SDL_GetWindowID(window.get()));
break;
case SDL_WINDOWEVENT_RESTORED:
isMinimized.store(false, std::memory_order_release);
LOG("Window %d restored.", SDL_GetWindowID(window.get()));
break;
case SDL_WINDOWEVENT_RESIZED:
currentSize.store({ windowEvent.data1, windowEvent.data2 }, std::memory_order_release);
hasResize.store(true, std::memory_order_release);
LOG("Window %d resized to %s.", SDL_GetWindowID(window.get()), currentSize.load(std::memory_order_acquire).ToString().data());
break;
case SDL_WINDOWEVENT_MOVED:
pos.store({ windowEvent.data1, windowEvent.data2 }, std::memory_order_release);
LOG("Window %d moved to %s.", SDL_GetWindowID(window.get()), pos.load(std::memory_order_acquire).ToString().data());
break;
}
}
void Window::ClearWindow()
{
hasResize.store(false, std::memory_order_release);
if(!isMinimized)
SDL_RenderClear(renderer.get());
}
void Window::Draw()
{
if (!isMinimized)
SDL_RenderPresent(renderer.get());
}
void Window::ToogleFullscreen()
{
if (!fullscreen.load(std::memory_order_acquire))
{
fullscreen.store(true, std::memory_order_release);
ONLY_DEBUG(
int sucess = SDL_SetWindowFullscreen(window.get(), SDL_WINDOW_FULLSCREEN_DESKTOP);\
if (sucess != 0)\
SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "[ERROR VIDEO] Window %d suffered an error: %s\n", SDL_GetWindowID(window.get()), std::string(SDL_GetError())); \
else\
{\
LOG("Window %d is fullscreen on display %d", SDL_GetWindowID(window.get()), SDL_GetWindowDisplayIndex(window.get())); \
Vector2<int> s; \
SDL_GetWindowSize(window.get(), &s.x, &s.y); \
LOG("Window currentSize: %d, %d", s.x, s.y);
}
)
return;
}
SDL_SetWindowFullscreen(window.get(), 0);
//SDL_RestoreWindow(window.get());
//SDL_SetWindowSize(window.get(), beforeFullscreenSize.x, beforeFullscreenSize.y);
fullscreen.store(false, std::memory_order_release);
}
bool Window::IsToClose() const
{
return close.load(std::memory_order_acquire);
}
bool Window::HasResized(Vector2<int>* newSize) const
{
if (newSize != nullptr)
*newSize = currentSize.load(std::memory_order_acquire);
return hasResize.load(std::memory_order_acquire);
}
| [
"conradofeltrin@gmail.com"
] | conradofeltrin@gmail.com |
95ce47237bd3a1bc5f7e0c45bd1c204eb4130cb5 | b6a39646e8a8b15db4047abaf9dd3fa013aa53f9 | /vs2015/ch17 blending/window2/main.cpp | 850dfcfe7581c6c7cecb99edcfc9854a5f7d4345 | [] | no_license | qxly/LearnOpenGL-qxly | c37393040fbcbb44d3fb272a8d4df28f35a772e4 | b71194648bf5c189d34f209d4712e7a3ede09c73 | refs/heads/master | 2021-01-20T07:29:41.659195 | 2017-05-02T10:04:56 | 2017-05-02T10:04:56 | 90,006,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,215 | cpp | #define GLEW_STATIC
// glew
#include "GL/glew.h"
// glfw
#include "GLFW/glfw3.h"
// SOIL
#include "SOIL/SOIL.h"
//GLM
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#pragma comment(lib, "OpenGL32.lib")
#pragma comment(lib, "../../../dep/lib_x86/debug_static/glew32sd.lib")
#pragma comment(lib, "../../../dep/lib_x86/debug_static/glfw3.lib")
#pragma comment(lib, "../../../dep/lib_x86/debug_static/SOIL.lib")
#include "shader.h"
#include "camera.h"
#include <iostream>
#include <direct.h>
#include <map>
bool keys[1024];
GLfloat deltaTime = 0.0f;
GLfloat lastFrame = 0.0f;
bool firstMouse = true;
GLfloat lastX = 400.0f;
GLfloat lastY = 300.0f;
// camera
Camera camera(glm::vec3(0.0f, 0.0f, 10.0f));
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void do_movement();
GLuint loadTexture(GLchar* path, GLboolean alpha = false);
int main()
{
// init glfw
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// create windows
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr);
if (nullptr == window)
{
std::cout << "fail to create glfw window" << std::endl;
glfwTerminate();
return -1;
}
// set context
glfwMakeContextCurrent(window);
// init glew
glewExperimental = GL_TRUE;
if (GLEW_OK != glewInit())
{
std::cout << "fail to init glew" << std::endl;
return -1;
}
// set viewport
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
// set keycallback
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetScrollCallback(window, scroll_callback);
// game loop
char buf[1000];
_getcwd(buf, 1000);
std::string workDir = buf;
std::string advanced_vs = workDir + "/advanced.vs";
std::string model_frag = workDir + "/advanced.frag";
Shader shader(advanced_vs.c_str(), model_frag.c_str());
// Load models
#pragma region "object_initialization"
// Set the object data (buffers, vertex attributes)
GLfloat cubeVertices[] = {
// Positions // Texture Coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
GLfloat planeVertices[] = {
// Positions // Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat)
5.0f, -0.5f, 5.0f, 2.0f, 0.0f,
-5.0f, -0.5f, 5.0f, 0.0f, 0.0f,
-5.0f, -0.5f, -5.0f, 0.0f, 2.0f,
5.0f, -0.5f, 5.0f, 2.0f, 0.0f,
-5.0f, -0.5f, -5.0f, 0.0f, 2.0f,
5.0f, -0.5f, -5.0f, 2.0f, 2.0f
};
GLfloat windowVertices[] = {
// Positions // Texture Coords (swapped y coordinates because texture is flipped upside down)
0.0f, 0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f, 1.0f,
1.0f, -0.5f, 0.0f, 1.0f, 1.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f,
1.0f, -0.5f, 0.0f, 1.0f, 1.0f,
1.0f, 0.5f, 0.0f, 1.0f, 0.0f
};
std::vector<glm::vec3> windows;
windows.push_back(glm::vec3(-1.5f, 0.0f, -0.48f));
windows.push_back(glm::vec3(1.5f, 0.0f, 0.51f));
windows.push_back(glm::vec3(0.0f, 0.0f, 0.7f));
windows.push_back(glm::vec3(-0.3f, 0.0f, -2.3f));
windows.push_back(glm::vec3(0.5f, 0.0f, -0.6f));
// setup cube VAO
GLuint cubeVAO, cubeVBO;
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &cubeVBO);
glBindVertexArray(cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
// setup plane VAO
GLuint planeVAO, planeVBO;
glGenVertexArrays(1, &planeVAO);
glGenBuffers(1, &planeVBO);
glBindVertexArray(planeVAO);
glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
// setup window
GLuint vegetationVAO, vegetationVBO;
glGenVertexArrays(1, &vegetationVAO);
glGenBuffers(1, &vegetationVBO);
glBindVertexArray(vegetationVAO);
glBindBuffer(GL_ARRAY_BUFFER, vegetationVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(windowVertices), &windowVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
#pragma endregion
GLuint cubeTexture = loadTexture((GLchar*)(workDir + "/marble.jpg").c_str());
GLuint planeTexture = loadTexture((GLchar*)(workDir + "/metal.png").c_str());
GLuint vegetatinTexture = loadTexture((GLchar*)(workDir + "/window.png").c_str(), true);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
while (!glfwWindowShouldClose(window))
{
GLfloat currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// check key or mouse events
glfwPollEvents();
do_movement();
glClearColor(0.2, 0.3, 0.3, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.use();
glm::mat4 model;
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::perspective(camera.Zoom, (float)width / (float)height, 0.1f, 100.0f);
glUniformMatrix4fv(glGetUniformLocation(shader.program, "view"), 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(glGetUniformLocation(shader.program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
// draw cube 1
glBindVertexArray(cubeVAO);
glBindTexture(GL_TEXTURE_2D, cubeTexture);
model = glm::translate(model, glm::vec3(-1.0, 0.0, -1.0));
glUniformMatrix4fv(glGetUniformLocation(shader.program, "model"), 1, GL_FALSE, glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 36);
// draw cube 2
model = glm::mat4();
model = glm::translate(model, glm::vec3(2.0, 0.0, 0.0));
glUniformMatrix4fv(glGetUniformLocation(shader.program, "model"), 1, GL_FALSE, glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 36);
// draw plane
glBindVertexArray(planeVAO);
glBindTexture(GL_TEXTURE_2D, planeTexture);
model = glm::mat4();
glUniformMatrix4fv(glGetUniformLocation(shader.program, "model"), 1, GL_FALSE, glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
// draw window
std::map<float, glm::vec3> sorted;
for (GLuint i = 0; i < windows.size(); i++)
{
GLfloat distance = glm::length(camera.Position - windows[i]);
sorted[distance] = windows[i];
}
glBindVertexArray(vegetationVAO);
glBindTexture(GL_TEXTURE_2D, vegetatinTexture);
for (std::map<float, glm::vec3>::reverse_iterator it = sorted.rbegin(); it != sorted.rend(); ++it)
{
model = glm::mat4();
model = glm::translate(model, it->second);
glUniformMatrix4fv(glGetUniformLocation(shader.program, "model"), 1, GL_FALSE, glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 6);
}
glBindTexture(GL_TEXTURE_2D, 0);
// swap buffer
glfwSwapBuffers(window);
}
glDisable(GL_DEPTH_TEST);
glfwTerminate();
return 0;
}
GLuint loadTexture(GLchar* path, GLboolean alpha)
{
GLuint textureID;
glGenTextures(1, &textureID);
int width, height;
unsigned char* image = SOIL_load_image(path, &width, &height, 0, alpha ? SOIL_LOAD_RGBA : SOIL_LOAD_RGB);
if (nullptr == image)
{
return textureID;
}
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, alpha ? GL_RGBA : GL_RGB, width, height, 0, alpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
SOIL_free_image_data(image);
return textureID;
}
// key callback function
void key_callback(GLFWwindow* window, int key, int scancode, int acion, int mode)
{
if (key == GLFW_KEY_ESCAPE && acion == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (key >= 0 && key <= 1024)
{
if (acion == GLFW_PRESS)
{
keys[key] = true;
}
else if (acion == GLFW_RELEASE)
{
keys[key] = false;
}
}
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
GLfloat xoffset = xpos - lastX;
GLfloat yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset, GL_TRUE);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
void do_movement()
{
if (keys[GLFW_KEY_W])
{
camera.ProcessKeyboard(FORWARD, deltaTime);
}
if (keys[GLFW_KEY_S])
{
camera.ProcessKeyboard(BACKWARD, deltaTime);
}
if (keys[GLFW_KEY_A])
{
camera.ProcessKeyboard(LEFT, deltaTime);
}
if (keys[GLFW_KEY_D])
{
camera.ProcessKeyboard(RIGHT, deltaTime);
}
} | [
"qxly_q@qq.com"
] | qxly_q@qq.com |
63eea75b13ebac36d614cd1370066cfa6c2ccfba | a1ad2a60c5a67dc7f3275e287f0de6c15e452aa6 | /core/menu/menu.cpp | 68a0371afe594028cba76324eaf43c84fd2f0150 | [] | no_license | ChoZenTime/LegitInternalSource | 95cc3277242058c4314ea2a9ea641a9d19dc81d7 | ce2be8d10b4c7c9847313679916bda0acb0fd986 | refs/heads/master | 2022-10-07T00:47:44.642527 | 2020-06-11T13:27:38 | 2020-06-11T13:27:38 | 271,831,208 | 0 | 1 | null | 2020-06-12T15:29:13 | 2020-06-12T15:29:12 | null | UTF-8 | C++ | false | false | 5,350 | cpp | #include "menu.hpp"
//todo auto elements positioning
auto do_frame = [&](std::int32_t x, std::int32_t y, std::int32_t w, std::int32_t h, color bg, color header_text, color header_line, const std::string& name) {
render::draw_filled_rect(x, y, w, h, bg);
render::draw_filled_rect(x, y, w, 30, header_text);
render::draw_filled_rect(x, y + 30, w, 2, header_line);
render::draw_text_string(x + 10, y + 8, render::fonts::watermark_font, name, false, color::white());
};
void menu::render() {
if (!variables::menu::opened)
return;
do_frame(variables::menu::x, variables::menu::y, variables::menu::w, variables::menu::h, color(255, 128, 0, 255), color(255, 153, 51, 255), color(255, 128, 0, 255), "ClemInternal");
menu_framework::group_box(variables::menu::x + 5, variables::menu::y + 35, variables::menu::w - 10, 80, render::fonts::watermark_font, "tabs", false); {
menu_framework::tab(variables::menu::x + variables::menu::w / 3 - 35, variables::menu::y + 55, 100, 30, render::fonts::watermark_font, "legitbot", menu::current_tab, 0, false);
menu_framework::tab(variables::menu::x + variables::menu::w / 2 - 35, variables::menu::y + 55, 100, 30, render::fonts::watermark_font, "visuals", menu::current_tab, 1, false);
menu_framework::tab(variables::menu::x + variables::menu::w - variables::menu::w / 3 - 35, variables::menu::y + 55, 100, 30, render::fonts::watermark_font, "misc", menu::current_tab, 2, false);
}
switch (current_tab) {
case 0:
menu_framework::group_box(variables::menu::x + 5, variables::menu::y + 125, variables::menu::w - 10, 320, render::fonts::watermark_font, "legitbot", false); {
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 135, variables::menu::x + 575, render::fonts::watermark_font, "AimBot", variables::aimbot);
menu_framework::slider(variables::menu::x + 10, variables::menu::y + 150, 125, render::fonts::watermark_font, "AimBot Fov", variables::aimbot_fov, 0.f, 10.f);
menu_framework::slider(variables::menu::x + 10, variables::menu::y + 165, 125, render::fonts::watermark_font, "AimBot Smoothing", variables::aimbot_smoothing, 1.f, 5.f);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 180, variables::menu::x + 575, render::fonts::watermark_font, "Only enemy is visible", variables::aimbot_isvisiblecheck);
}
break;
case 1:
menu_framework::group_box(variables::menu::x + 5, variables::menu::y + 125, variables::menu::w - 10, 320, render::fonts::watermark_font, "visuals", false); {
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 135, variables::menu::x + 575, render::fonts::watermark_font, "Team ESP", variables::showteamesp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 150, variables::menu::x + 575, render::fonts::watermark_font, "Box ESP", variables::boxesp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 165, variables::menu::x + 575, render::fonts::watermark_font, "Name ESP", variables::nameesp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 180, variables::menu::x + 575, render::fonts::watermark_font, "Health ESP", variables::healthesp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 195, variables::menu::x + 575, render::fonts::watermark_font, "Armor ESP", variables::armoresp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 210, variables::menu::x + 575, render::fonts::watermark_font, "Glow ESP", variables::glowesp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 225, variables::menu::x + 575, render::fonts::watermark_font, "Bone ESP", variables::boneesp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 240, variables::menu::x + 575, render::fonts::watermark_font, "Snapline ESP", variables::snaplineesp);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 255, variables::menu::x + 575, render::fonts::watermark_font, "C4 Timer and ESP", variables::drawc4);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 270, variables::menu::x + 575, render::fonts::watermark_font, "Draw Backtrack", variables::drawbacktrack);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 285, variables::menu::x + 575, render::fonts::watermark_font, "Draw Aimbot FOV", variables::drawfov);
}
break;
case 2:
menu_framework::group_box(variables::menu::x + 5, variables::menu::y + 125, variables::menu::w - 10, 320, render::fonts::watermark_font, "misc", false); {
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 135, variables::menu::x + 575, render::fonts::watermark_font, "WaterMark", variables::watermark);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 150, variables::menu::x + 575, render::fonts::watermark_font, "BunnyHop", variables::bhop);
menu_framework::check_box(variables::menu::x + 10, variables::menu::y + 165, variables::menu::x + 575, render::fonts::watermark_font, "Backtracking", variables::backtrack);
}
break;
}
menu_framework::menu_movement(variables::menu::x, variables::menu::y, variables::menu::w, 30);
}
void menu::toggle() {
if (GetAsyncKeyState(VK_INSERT) & 1)
variables::menu::opened = !variables::menu::opened;
} | [
"65666375+clem45@users.noreply.github.com"
] | 65666375+clem45@users.noreply.github.com |
ecb9a87a090102cc247fc3260f4a8933b83a7f38 | 4e7ec3b0c599efd987ecaf31de329558b13ca7ee | /src/AlarmWatch.h | 5d0d24f7fa3f7dc702ff9bd7a1dc2375ca46d4b9 | [] | no_license | GitMatti/ArduAlarmWatchSample | 0000b6af7430a8a7f94b4b7dbbcafb7d79c3717e | 8b4024e1b883f45ed6f08c4fbede677233ee3a3e | refs/heads/main | 2023-03-30T04:11:16.261003 | 2021-04-05T17:24:42 | 2021-04-05T17:24:42 | 354,902,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 800 | h | #include "WeekTime.h"
#include "AlarmChannel.h"
/// Einfacher Wecker mit bis zu 4 Alarmkanälen
class AlarmWatch
{
private:
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal *lcd;
unsigned long offset;
int channelCount;
AlarmChannel *alarmChannels[4];
public:
/// Erzeugt einen Wecker, der Mo 00:00 Uhr startet
AlarmWatch();
/// Erzeugt einen Wecker mir der angegebenen Wochenstartzeit
AlarmWatch(WeekTime startTime);
/// Fügt dem Wecker einen Alarm hinzu
void AddAlarmChannel(AlarmChannel *alarm);
/// Anzeigen der Wochenzeit und prüfen auf Alarmzustände
void Display(WeekTime weekTime);
/// Anzeigen der Wochenzeit (berechnet aus abgelaufener Zeit und Startzeit) und prüfen auf Alarmzustände
void Display(unsigned long relativSeconds);
}; | [
"matthias.richter@gradient.de"
] | matthias.richter@gradient.de |
8ed715183d36bfba5fbfb75cc5b2e4ccbe129996 | cb5136307affe2d714877fc02076d1f1802f0a84 | /flame/httpssession.cpp | 1a9b98a6c28ffe2b5750bf1c0c5d72ac81d20cd5 | [
"Apache-2.0"
] | permissive | jwijenbergh/flamethrower | 21f5019e3521c2a79ad2d6cc13c376c00e5d7ec3 | 7be159ff28d8bf0ccc037ae6ef9814d286066b4f | refs/heads/master | 2021-07-18T23:35:54.559316 | 2020-07-16T15:01:33 | 2020-07-16T15:04:57 | 197,210,551 | 0 | 1 | Apache-2.0 | 2019-07-16T14:32:42 | 2019-07-16T14:32:41 | null | UTF-8 | C++ | false | false | 12,659 | cpp | #include <algorithm>
#include <cstring>
#include <iostream>
#include "httpssession.h"
static ssize_t gnutls_pull_trampoline(gnutls_transport_ptr_t h, void *buf, size_t len)
{
auto session = static_cast<HTTPSSession *>(h);
return session->gnutls_pull(buf, len);
}
static ssize_t gnutls_push_trampoline(gnutls_transport_ptr_t h, const void *buf, size_t len)
{
auto session = static_cast<HTTPSSession *>(h);
return session->gnutls_push(buf, len);
}
HTTPSSession::HTTPSSession(std::shared_ptr<uvw::TcpHandle> handle,
TCPSession::malformed_data_cb malformed_data_handler,
TCPSession::got_dns_msg_cb got_dns_msg_handler,
TCPSession::connection_ready_cb connection_ready_handler,
handshake_error_cb handshake_error_handler,
Target target,
HTTPMethod method)
: TCPSession(handle, malformed_data_handler, got_dns_msg_handler, connection_ready_handler)
, http2_state{STATE_HTTP2::WAIT_SETTINGS}
, _malformed_data{malformed_data_handler}
, _got_dns_msg{got_dns_msg_handler}
, _handle{handle}
, _tls_state{LinkState::HANDSHAKE}
, _handshake_error{handshake_error_handler}
, _target{target}
, _method{method}
{
}
HTTPSSession::~HTTPSSession()
{
gnutls_certificate_free_credentials(_gnutls_cert_credentials);
gnutls_deinit(_gnutls_session);
nghttp2_session_del(_current_session);
}
std::unique_ptr<http2_stream_data> HTTPSSession::create_http2_stream_data(std::unique_ptr<char[]> data, size_t len)
{
std::string uri = _target.uri;
struct http_parser_url *u = _target.parsed;
std::string scheme(&uri[u->field_data[UF_SCHEMA].off], u->field_data[UF_SCHEMA].len);
std::string authority(&uri[u->field_data[UF_HOST].off], u->field_data[UF_HOST].len);
std::string path(&uri[u->field_data[UF_PATH].off], u->field_data[UF_PATH].len);
int32_t stream_id = -1;
if (_method == HTTPMethod::GET) {
path.append("?dns=");
path.append(data.get(), len);
}
std::string streamData(data.get(), len);
auto root = std::make_unique<http2_stream_data>(scheme, authority, path, stream_id, streamData);
return root;
}
#define ARRLEN(x) (sizeof(x) / sizeof(x[0]))
static ssize_t send_callback(nghttp2_session *session, const uint8_t *data, size_t length, int flags, void *user_data)
{
auto class_session = static_cast<HTTPSSession *>(user_data);
class_session->send_tls((void *)data, length);
return (ssize_t)length;
}
void HTTPSSession::destroy_session()
{
gnutls_certificate_free_credentials(_gnutls_cert_credentials);
gnutls_deinit(_gnutls_session);
nghttp2_session_del(_current_session);
}
void HTTPSSession::process_receive(const uint8_t *data, size_t len)
{
const size_t MIN_DNS_QUERY_SIZE = 17;
const size_t MAX_DNS_QUERY_SIZE = 512;
if (len < MIN_DNS_QUERY_SIZE || len > MAX_DNS_QUERY_SIZE) {
std::cerr << "malformed data" << std::endl;
_malformed_data();
return;
}
auto buf = std::make_unique<char[]>(len);
memcpy(buf.get(), (const char *)data, len);
_got_dns_msg(std::move(buf), len);
}
static int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags,
int32_t stream_id, const uint8_t *data,
size_t len, void *user_data)
{
auto class_session = static_cast<HTTPSSession *>(user_data);
auto req = nghttp2_session_get_stream_user_data(session, stream_id);
if (!req) {
std::cerr << "No stream data on data chunk" << std::endl;
return 0;
}
class_session->process_receive(data, len);
return 0;
}
static int on_stream_close_callback(nghttp2_session *session, int32_t stream_id, uint32_t error_code, void *user_data)
{
auto stream_data = static_cast<http2_stream_data *>(nghttp2_session_get_stream_user_data(session, stream_id));
if (!stream_data) {
std::cerr << "No stream data on stream close" << std::endl;
return 0;
}
nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR);
return 0;
}
int on_frame_recv_callback(nghttp2_session *session,
const nghttp2_frame *frame, void *user_data)
{
auto class_session = static_cast<HTTPSSession *>(user_data);
switch (frame->hd.type) {
case NGHTTP2_SETTINGS:
class_session->settings_received();
break;
}
return 0;
}
void HTTPSSession::init_nghttp2()
{
nghttp2_session_callbacks *callbacks;
nghttp2_session_callbacks_new(&callbacks);
nghttp2_session_callbacks_set_send_callback(callbacks, send_callback);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(callbacks, on_data_chunk_recv_callback);
nghttp2_session_callbacks_set_on_stream_close_callback(callbacks, on_stream_close_callback);
nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks, on_frame_recv_callback);
nghttp2_session_client_new(&_current_session, callbacks, this);
nghttp2_session_callbacks_del(callbacks);
}
bool HTTPSSession::setup()
{
int ret;
ret = gnutls_init(&_gnutls_session, GNUTLS_CLIENT | GNUTLS_NONBLOCK);
if (ret != GNUTLS_E_SUCCESS) {
std::cerr << "GNUTLS init failed: " << gnutls_strerror(ret) << std::endl;
return false;
}
ret = gnutls_set_default_priority(_gnutls_session);
if (ret != GNUTLS_E_SUCCESS) {
std::cerr << "GNUTLS failed to set default priority: " << gnutls_strerror(ret) << std::endl;
return false;
}
ret = gnutls_certificate_allocate_credentials(&_gnutls_cert_credentials);
if (ret < 0) {
std::cerr << "GNUTLS failed to allocate credentials: " << gnutls_strerror(ret) << std::endl;
return false;
}
ret = gnutls_certificate_set_x509_system_trust(_gnutls_cert_credentials);
if (ret < 0) {
std::cerr << "GNUTLS failed to set system trust: " << gnutls_strerror(ret) << std::endl;
return false;
}
ret = gnutls_credentials_set(_gnutls_session, GNUTLS_CRD_CERTIFICATE,
_gnutls_cert_credentials);
if (ret < 0) {
std::cerr << "GNUTLS failed to set system credentials" << gnutls_strerror(ret) << std::endl;
return false;
}
gnutls_datum_t alpn;
alpn.data = (unsigned char *)"h2";
alpn.size = 2;
ret = gnutls_alpn_set_protocols(_gnutls_session, &alpn, 1, GNUTLS_ALPN_MANDATORY);
if (ret != GNUTLS_E_SUCCESS) {
std::cerr << "GNUTLS failed to set ALPN: " << gnutls_strerror(ret) << std::endl;
return false;
}
gnutls_transport_set_pull_function(_gnutls_session, gnutls_pull_trampoline);
gnutls_transport_set_push_function(_gnutls_session, gnutls_push_trampoline);
gnutls_handshake_set_timeout(_gnutls_session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
gnutls_transport_set_ptr(_gnutls_session, this);
return true;
}
void HTTPSSession::send_settings()
{
nghttp2_settings_entry settings[1] = {{NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, (1U << 31) - 1}};
int val;
val = nghttp2_submit_settings(_current_session, NGHTTP2_FLAG_NONE, settings, ARRLEN(settings));
if (val != 0) {
std::cerr << "Could not submit SETTINGS frame: " << nghttp2_strerror(val) << std::endl;
}
}
void HTTPSSession::settings_received()
{
if (http2_state == STATE_HTTP2::WAIT_SETTINGS) {
TCPSession::on_connect_event();
http2_state = STATE_HTTP2::SENDING_DATA;
}
}
void HTTPSSession::receive_response(const char data[], size_t len)
{
ssize_t stream_id = nghttp2_session_mem_recv(_current_session, (const uint8_t *)data, len);
if (stream_id < 0) {
std::cerr << "Could not get HTTP2 request: " << nghttp2_strerror(stream_id);
close();
return;
}
}
int HTTPSSession::session_send()
{
int rv;
rv = nghttp2_session_send(_current_session);
if (rv != 0) {
std::cerr << "HTTP2 fatal error: " << nghttp2_strerror(rv);
return -1;
}
return 0;
}
void HTTPSSession::on_connect_event()
{
_current_session = {};
do_handshake();
}
void HTTPSSession::close()
{
_tls_state = LinkState::CLOSE;
gnutls_bye(_gnutls_session, GNUTLS_SHUT_WR);
TCPSession::close();
}
static ssize_t post_data(nghttp2_session *session, int32_t stream_id, uint8_t *buf, size_t length, uint32_t *data_flags, nghttp2_data_source *source, void *user_data)
{
auto stream_data = static_cast<http2_stream_data *>(nghttp2_session_get_stream_user_data(session, stream_id));
size_t nread = std::min(stream_data->data.size(), length);
memcpy(buf, stream_data->data.c_str(), nread);
*data_flags = NGHTTP2_DATA_FLAG_EOF;
return nread;
}
#define HDR_S(NAME, VALUE) \
{ \
(uint8_t *)NAME, (uint8_t *)VALUE.c_str(), sizeof(NAME) - 1, VALUE.size(), \
NGHTTP2_NV_FLAG_NONE \
}
void HTTPSSession::write(std::unique_ptr<char[]> data, size_t len)
{
int32_t stream_id;
auto stream_data = create_http2_stream_data(std::move(data), len);
nghttp2_data_provider provider = {};
std::string method = _method == HTTPMethod::GET ? "GET" : "POST";
std::string content = "application/dns-message";
std::vector<nghttp2_nv> hdrs{
HDR_S(":method", method),
HDR_S(":scheme", stream_data->scheme),
HDR_S(":authority", stream_data->authority),
HDR_S(":path", stream_data->path),
HDR_S("accept", content)};
if (_method == HTTPMethod::POST) {
hdrs.push_back(HDR_S("content-type", content));
hdrs.push_back(HDR_S("content-length", std::to_string(len)));
provider.read_callback = post_data;
}
stream_id = nghttp2_submit_request(_current_session, NULL, hdrs.data(), hdrs.size(), &provider, stream_data.get());
if (stream_id < 0) {
std::cerr << "Could not submit HTTP request: " << nghttp2_strerror(stream_id);
}
stream_data->id = stream_id;
if (session_send() != 0) {
std::cerr << "HTTP2 failed to send" << std::endl;
}
}
void HTTPSSession::receive_data(const char data[], size_t _len)
{
_pull_buffer.append(data, _len);
switch (_tls_state) {
case LinkState::HANDSHAKE:
do_handshake();
break;
case LinkState::DATA:
char buf[2048];
for (;;) {
ssize_t len = gnutls_record_recv(_gnutls_session, buf, sizeof(buf));
if (len > 0) {
receive_response(buf, len);
} else {
if (len == GNUTLS_E_AGAIN) {
// Check if we don't have any data left to read
if (_pull_buffer.empty()) {
break;
}
continue;
} else if (len == GNUTLS_E_INTERRUPTED) {
continue;
}
break;
}
}
break;
case LinkState::CLOSE:
break;
}
}
void HTTPSSession::send_tls(void *data, size_t len)
{
ssize_t sent = gnutls_record_send(_gnutls_session, data, len);
if (sent <= 0) {
std::cerr << "HTTP2 failed in sending data" << std::endl;
}
}
void HTTPSSession::do_handshake()
{
int err = gnutls_handshake(_gnutls_session);
if (err == GNUTLS_E_SUCCESS) {
gnutls_datum_t alpn;
alpn.data = (unsigned char *)"h2";
alpn.size = 2;
int ret = gnutls_alpn_get_selected_protocol(_gnutls_session, &alpn);
if (ret != GNUTLS_E_SUCCESS) {
std::cerr << "Cannot get alpn" << std::endl;
close();
}
init_nghttp2();
send_settings();
if (session_send() != 0) {
std::cerr << "Cannot submit settings frame" << std::endl;
}
_tls_state = LinkState::DATA;
} else if (err < 0 && gnutls_error_is_fatal(err)) {
std::cerr << "Handshake failed: " << gnutls_strerror(err) << std::endl;
_handshake_error();
} else if (err != GNUTLS_E_AGAIN && err != GNUTLS_E_INTERRUPTED) {
std::cout << "Handshake " << gnutls_strerror(err) << std::endl;
}
}
int HTTPSSession::gnutls_pull(void *buf, size_t len)
{
if (!_pull_buffer.empty()) {
len = std::min(len, _pull_buffer.size());
std::memcpy(buf, _pull_buffer.data(), len);
_pull_buffer.erase(0, len);
return len;
}
errno = EAGAIN;
return -1;
}
int HTTPSSession::gnutls_push(const void *buf, size_t len)
{
auto data = std::make_unique<char[]>(len);
memcpy(data.get(), const_cast<char *>(reinterpret_cast<const char *>(buf)), len);
TCPSession::write(std::move(data), len);
return len;
}
| [
"jeroenwijenbergh@protonmail.com"
] | jeroenwijenbergh@protonmail.com |
556ff1d6391b7b6b36239a1a8a0fcadc3ce8477d | c14356d4bd1cb3535545e87beac368d35a2d97ed | /FSM/TypeElem.h | 539e328eaeca9e0b553ca76f9f97a15ec59a80dc | [] | no_license | AllenWang0217/UseDSLToImplementASimpleFSM | 1b1695c8feede83f92dc05d41168955f7fbbe0cf | af660af39e355dded05b792bd3b2c3bd173db1a6 | refs/heads/master | 2021-01-20T14:36:07.870835 | 2017-06-07T15:08:34 | 2017-06-07T16:07:53 | 90,636,378 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | h | #pragma once
template<typename H, typename T>
struct TypeElem
{
using Head = H;
using Tail = T;
};
#define __type_elem(...) TypeElem<__VA_ARGS__> | [
"allen_wang0217@sina.com"
] | allen_wang0217@sina.com |
41cdaddd7e6566214fcd2d59476c040c045f3873 | 0b64e7d44ab3dce171cb3b7cb0063b6b40e34dd1 | /SLinkedList.h | 70a097b131469f744d123ba79a5f00eab528e2e7 | [] | no_license | wahibkamran/Stack-Queue-SinglyLinkedList | 8b691f8c12e89d90ff37530cab99d366f2fed173 | bcc644b6fe1ba3603d5667f32583f1dc808106d2 | refs/heads/master | 2020-04-19T05:03:18.463675 | 2019-01-28T15:29:31 | 2019-01-28T15:29:31 | 167,977,292 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | h | #ifndef SLINKEDLIST_H_INCLUDED
#define SLINKEDLIST_H_INCLUDED
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
class SNode
{
private:
SNode* next;
int data;
friend class SLinkedList;
public:
SNode(int val) {data=val;}
};
class SLinkedList
{
private:
SNode* head;
friend class Stack;
public:
SLinkedList() {head=NULL;}
void AddFront(int val);
int RemoveFront();
void display();
};
#endif
| [
"wahibkamran@nyu.edu"
] | wahibkamran@nyu.edu |
5bed93bee9161e7a1a6dd2eae4dbb7cf7d6c9794 | 219c496b4269879763a9cbb2f67bb07f923c2027 | /imgprocess/shell/ui/hotkeytabledialog.cpp | 5bb94bd2c1dffdaafff9aa825f83ddabd8299af9 | [] | no_license | wuyougongzi/imgProcess | cb670e6738d1c39654aeb5ab47bcfce4c5b88699 | 9a8ac006239c12b1b46578150013191821becef7 | refs/heads/master | 2020-12-29T02:24:59.952265 | 2017-12-02T13:23:22 | 2017-12-02T13:23:22 | 35,098,933 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 766 | cpp | #include "hotkeytabledialog.h"
#include "ui_hotkeytabledialog.h"
#include <Windows.h>
HotKeyTableDialog::HotKeyTableDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::HotKeyTableDialog)
{
ui->setupUi(this);
}
HotKeyTableDialog::~HotKeyTableDialog()
{
delete ui;
}
bool HotKeyTableDialog::winEvent(MSG *message, long *result)
{
//这里拿到消息后设置到里面的hotkeyLineEdit
switch(message->message)
{
case WM_KEYDOWN:
{
//todo:
}
break;
case WM_CHAR:
{
//todo:
}
break;
case WM_SYSKEYDOWN:
{
}
break;
case WM_SYSCHAR:
{
}
break;
}
return QWidget::winEvent(message, result);
} | [
"1211385701@qq.com"
] | 1211385701@qq.com |
c8b80a3875f6fd6edf4c87fe8fb582cef0de44c0 | 864c2d9c3cf67666ba1ed0d7ad08b316fb10fea6 | /d02/ex01/Fixed.cpp | 2e44e05069292aa489c9f23f097d4aeb22a04f92 | [] | no_license | VolodymyrShkykavyi/cpp_piscine | 14669be4d8c3798f660f91760883e2b70bca6616 | ff0b9397877ba0eb0434380643c23d66d5a87b93 | refs/heads/master | 2020-03-20T23:44:23.999475 | 2018-10-13T12:33:49 | 2018-10-13T12:33:49 | 137,860,605 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,137 | cpp | #include "Fixed.hpp"
Fixed::Fixed()
{
std::cout << "Default constructor called" << std::endl;
this->_value = 0;
}
Fixed::Fixed(Fixed const &number)
{
std::cout << "Copy constructor called" << std::endl;
*this = number;
}
Fixed::Fixed(int const number): _value(number << Fixed::_fract)
{
std::cout << "Int constructor called" << std::endl;
}
Fixed::Fixed(float const number): _value(roundf(number * (1 << Fixed::_fract)))
{
std::cout << "Float constructor called" << std::endl;
}
Fixed::~Fixed()
{
std::cout << "Destructor called" << std::endl;
}
Fixed &Fixed::operator=(Fixed const &number)
{
std::cout << "Assignation operator called" << std::endl;
this->_value = number.getRawBits();
return *this;
}
int Fixed::getRawBits() const
{
return this->_value;
}
void Fixed::setRawBits(int const raw)
{
this->_value = raw;
}
float Fixed::toFloat( void ) const
{
return this->_value / (float)(1 << Fixed::_fract);
}
int Fixed::toInt( void ) const
{
return this->_value / (1 << Fixed::_fract);
}
std::ostream &operator<<(std::ostream& stream, Fixed const &number){
stream << number.toFloat();
return stream;
}
| [
"volodymyr.shkykavyi@gmail.com"
] | volodymyr.shkykavyi@gmail.com |
cf013186be8e955c00dedeb24d26ee57c7245341 | 8c45d7267931d8a6869041053e5d232b5c258187 | /Implementação/Companhia.h | d80f5d4e53ab314a46e2f7bcd8eb25cd9d967f09 | [
"MIT"
] | permissive | carlosmccosta/Airport-Management-System | 92566ead23fac020015a393f6e6c55768a690fec | bdeecdec8cc077ce7d8e8fda4298345ba5f0d47f | refs/heads/master | 2021-01-10T13:27:09.187911 | 2015-10-11T16:37:11 | 2015-10-11T16:37:11 | 44,049,529 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,968 | h | /**\file Companhia.h
* \brief Classe que contém informação associada a uma Companhia.
*
* PROJECTO: Projecto 2 - Gestão do embarque dos passageiros num aeroporto (check-in/embarque) \n
* FICHEIRO: Companhia.cpp \n
* DESCRIÇÃO: Classe que contém informação associada a uma Companhia Aérea. \n
*
* TURMA / GRUPO: 2MIEIC1 / 4 \n
* AUTORES:
* - Carlos Miguel Correia da Costa
* - Daniela Filipa Neves Cardeano
* - Vítor Amálio Maia Martins Moreira
*/
#ifndef COMPANHIA_H_
#define COMPANHIA_H_
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <utility>
#include <functional>
#include <sstream>
#include "Aviao.h"
#include "Tripulante.h"
#include "DataHora.h"
#include "Voo.h"
#include "TipoAviao.h"
#include "Exceptions.h"
#include "utils.h"
#include "Comandos.h"
#include "TipoAviaoDB.h"
using std::vector;
using std::string;
using std::endl;
using std::find_if;
using std::bind2nd;
using std::equal_to;
using std::find;
using std::stringstream;
using std::flush;
using std::pow;
extern TipoAviaoDB tipoaviaoDB;
///Classe que armazena informação acerca de uma Companhia de um dado Aeroporto.
class Companhia {
private:
string _sigla; ///<Ex: TAP
string _nome; ///<Ex: TAP Portugal
unsigned _taxa_balcoes;
vector <Aviao*> _avioes;
vector <Tripulante*> _tripulacao;
vector <Voo*> _voos;
//É um vector de apontadores porque o mesmo tipo de avião pode estar associado a aviões de companhias diferentes (evita duplicação de dados)
vector <TipoAviao*> _frota;
bool _can_delete_values;
public:
Companhia(): _taxa_balcoes(0), _avioes(), _tripulacao(), _voos(), _frota(), _can_delete_values(false) {}
Companhia(string sigla, string nome, unsigned taxa_balcoes): _sigla(sigla), _nome(nome), _taxa_balcoes(taxa_balcoes),
_avioes(), _tripulacao(), _voos(), _frota(), _can_delete_values(true) {}
virtual ~Companhia();
string getSigla() const { return _sigla; }
string getNome() const { return _nome; }
unsigned getTaxaBalcoes() const { return _taxa_balcoes; }
vector <Aviao*> getAvioes() const { return _avioes; }
//Variante dos gets para os vectores, usadas em iteradores constantes
const vector <Aviao*>& getConstRefAvioes() const { return _avioes; }
//Variante do get do vector que permite alterá-lo através da referência que é dada
vector <Aviao*>& getRefAvioes() { return _avioes; }
vector <Tripulante*> getTripulacao() const { return _tripulacao; }
const vector <Tripulante*>& getConstRefTripulacao() const { return _tripulacao; }
vector <Tripulante*>& getRefTripulacao() { return _tripulacao; }
vector <Voo*> getVoos() const { return _voos; }
const vector <Voo*>& getConstRefVoos() const { return _voos; }
vector <Voo*>& getRefVoos() { return _voos; }
vector <TipoAviao*> getFrota() const { return _frota; }
const vector <TipoAviao*>& getConstRefFrota() const { return _frota; }
vector <TipoAviao*>& getRefFrota() { return _frota; }
void setSigla(string sigla) { _sigla = sigla; }
void setNome(string nome) { _nome = nome; }
void setTaxaBalcoes(unsigned taxa_balcoes) { _taxa_balcoes = taxa_balcoes; }
void setAvioes(vector <Aviao*> avioes) { _avioes = avioes; }
void setTripulacao(vector <Tripulante*> tripulacao) { _tripulacao = tripulacao; }
void setVoos(vector <Voo*> voos) { _voos = voos; }
void setFrota(vector <TipoAviao*> frota) { _frota = frota; }
///Operador que permite comparar se duas Companhias têm a mesma sigla e nome.
bool operator==(const Companhia &companhia) const;
///Operador que permite verificar se o nome de uma companhia é "menor" que o de outra. Se forem iguais compara a sigla.
bool operator<(const Companhia &companhia) const;
/**
* \brief Função que pede ao utilizador uma nova matrícula para um avião, verificando se ela já está atribuída.
* \details Caso esteja, continua a pedir para introduzir uma nova matrícula.
* @param mensagem Mesagem a ser mostrada ao utilizador antes de pedir a matrícula.
* @return Uma matricula, que é unica naquela companhia.
*/
string getMatriculaAviaoCin(const char* mensagem);
/**
* \brief Função que pede ao utilizador um BI.
* @param mensagem Mesagem a ser mostrada ao utilizador antes de pedir o BI.
* @return Um BI que é único naquela companhia.
*/
unsigned getBICin(const char* mensagem);
/**
* \brief Função que pede ao utilizador um número (ID) para um tripulante.
* @param mensagem Mensagem a ser mostrada ao utilizador antes de pedir o número.
* @return Um ID para um tripulante que é único na companhia.
*/
unsigned getNumeroTripulanteCin(const char* mensagem);
/**
* \brief Função que pede ao utilizador um número de voo e verifica se esse número (ID), é único na companhia em questão.
* @param mensagem Mensagem a ser mostrada ao utilizador antes de se pedir o número.
* @return O número de um voo único na companhia.
*/
unsigned getNumeroVooCin(const char *mensagem);
};
#endif
| [
"carloscosta.cmcc@gmail.com"
] | carloscosta.cmcc@gmail.com |
b725333593842fe0c8910c5881c5d06cc1d5608c | 855a0e6571af91a2f5605dbd0f9d8d64479b2cad | /common/SEServiceHelper.cpp | 9bab511845de4d517fffd1faa8f425a090a93d95 | [
"Apache-2.0"
] | permissive | tizenorg/framework.system.smartcard-service | fa39c03eca390905d84dae7dc1869795380dbcef | 2414320e7b8eb504dda28a8216d34174bcbeefb1 | refs/heads/master | 2016-09-12T12:53:15.142628 | 2012-08-22T12:36:29 | 2012-08-22T12:36:29 | 56,109,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,250 | cpp | /*
* Copyright (c) 2012 Samsung Electronics Co., Ltd 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.
*/
/* standard library header */
#include <stdio.h>
/* SLP library header */
/* local header */
#include "SEServiceHelper.h"
namespace smartcard_service_api
{
SEServiceHelper::SEServiceHelper()
{
connected = false;
}
SEServiceHelper::~SEServiceHelper()
{
shutdown();
}
vector<ReaderHelper *> SEServiceHelper::getReaders()
{
return readers;
}
bool SEServiceHelper::isConnected()
{
return (readers.size() > 0);
}
void SEServiceHelper::shutdown()
{
uint32_t i;
for (i = 0; i < readers.size(); i++)
{
readers[i]->closeSessions();
}
readers.clear();
}
} /* namespace smartcard_service_api */
| [
"neueziel.lim"
] | neueziel.lim |
28335a4e717b00f7f120520df43621c608bb1cc7 | 350ae5f1f96a9f281811dc57f4d2436603f489f1 | /Portage.cpp | cb41daf3d1bdf4cf474c5086de0b7451c89db4cb | [] | no_license | cjwijtmans/Qentoo | 36e9ff64fa3ddb8ab26d804ae0a3d1d4e7e18f96 | d340423d32c8c4d1d0eedee43974f65e24fc3f49 | refs/heads/master | 2021-01-10T13:06:52.844760 | 2013-07-18T12:16:22 | 2013-07-18T12:16:22 | 8,506,204 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | cpp | #include "Portage.hpp"
#include <QDebug>
#include <QProcess>
Portage::Portage()
{
PortageParser::Repositories repositories = m_Parser.getRepositories();
for(PortageParser::Repositories::const_iterator iter = repositories.constBegin(); iter != repositories.constEnd(); ++iter)
{
Repository repository(*iter, &m_Repositories);
m_Repositories.insert(repository.getName(), repository);
}
}
Portage::Categories Portage::getCategories() const
{
Categories categories;
for(Repositories::const_iterator iter = m_Repositories.constBegin(); iter != m_Repositories.constEnd(); ++iter)
categories.unite(iter->getParser().getCategories());
return categories;
}
Portage::EnvironmentalVariables Portage::getEnvironmentalVariables() const
{
return m_Parser.getEnvironmentalVariables();
}
const Portage::Repositories& Portage::getRepositories() const
{
return m_Repositories;
}
Repository Portage::getRepository(const QString& name) const
{
return m_Repositories.value(name);
}
| [
"cj.wijtmans@gmail.com"
] | cj.wijtmans@gmail.com |
92284fa972d52ea6e3654beb799128a0f1aae29e | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/pdfium/core/fpdfapi/cmaps/CNS1/B5pc-V_0.cpp | b7a17a522cd4aa298c940cf6ec5fa50797970ab9 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 661 | cpp | // Copyright 2014 The PDFium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/cmaps/CNS1/cmaps_cns1.h"
namespace fxcmap {
const uint16_t kB5pc_V_0[12 * 3] = {
0xA14B, 0xA14B, 0x354E, 0xA15A, 0xA15A, 0x35AF, 0xA15C, 0xA15C, 0x35B1,
0xA15D, 0xA15E, 0x0082, 0xA161, 0xA162, 0x0086, 0xA165, 0xA166, 0x008A,
0xA169, 0xA16A, 0x008E, 0xA16D, 0xA16E, 0x0092, 0xA171, 0xA172, 0x0096,
0xA175, 0xA176, 0x009A, 0xA179, 0xA17A, 0x009E, 0xA1E3, 0xA1E3, 0x354F,
};
} // namespace fxcmap
| [
"jengelh@inai.de"
] | jengelh@inai.de |
d5387ef555a0103d0193fc25b02a330b8473dd8d | 1e7bf8d43d8cb417cd32492a7f32701df896dad9 | /src/Epidemic.cpp | 962716c4c747e7f46b8eea686473c4073947b30a | [] | no_license | sheeco/sim | 7ca6d1284fb8240d78c41e5812a04623509a71fd | 58cd9127d1bedcc7518cb575604babd8986c77ed | refs/heads/master | 2021-01-19T21:58:11.286846 | 2018-06-10T17:34:19 | 2018-06-10T17:34:19 | 45,496,887 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 11,988 | cpp | #include "Epidemic.h"
#include "Global.h"
#include "Configuration.h"
#include "Node.h"
#include "Sink.h"
#include "SMac.h"
#include "HDC.h"
#include "PrintHelper.h"
// //在特定时槽上发送数据
// //注意:必须在调用UpdateNodeStatus之后调用此函数
// static void SendData(int now);
CEpidemic::CEpidemic()
{
}
CEpidemic::~CEpidemic()
{
}
vector<CPacket*> CEpidemic::receivePackets(CGeneralNode & gToNode, CGeneralNode & gFromNode, vector<CPacket*> packets, int now)
{
vector<CPacket*> packetsToSend;
if( typeid( gToNode ) == typeid( CSink ) )
{
CSink* toSink = dynamic_cast< CSink* >( &gToNode );
/*********************************************** Sink <- Node *******************************************************/
if( typeid( gFromNode ) == typeid( CNode ) )
{
CNode* fromNode = dynamic_cast<CNode*>( &gFromNode );
packetsToSend = CEpidemic::receivePackets(toSink, fromNode, packets, now);
}
}
else if( typeid( gToNode ) == typeid( CNode ) )
{
CNode* node = dynamic_cast<CNode*>( &gToNode );
/*********************************************** Node <- Sink *******************************************************/
if( typeid( gFromNode ) == typeid( CSink ) )
{
CSink* fromSink = dynamic_cast< CSink* >( &gFromNode );
packetsToSend = CEpidemic::receivePackets(node, fromSink, packets, now);
}
/*********************************************** Node <- Node *******************************************************/
else if( typeid( gFromNode ) == typeid( CNode ) )
{
CNode* fromNode = dynamic_cast<CNode*>( &gFromNode );
packetsToSend = CEpidemic::receivePackets(node, fromNode, packets, now);
}
}
return packetsToSend;
}
vector<CPacket*> CEpidemic::receivePackets(CNode* node, CSink* sink, vector<CPacket*> packets, int now)
{
vector<CPacket*> packetsToSend;
CCtrl* ctrlToSend = nullptr;
CCtrl* indexToSend = nullptr;
CCtrl* nodataToSend = nullptr; //NODATA包代表缓存为空,没有适合传输的数据
vector<CData> dataToSend; //空vector代表拒绝传输数据
bool waitForResponse = false;
for( vector<CPacket*>::iterator ipacket = packets.begin(); ipacket != packets.end(); )
{
/***************************************** rcv Ctrl Message *****************************************/
if( typeid( **ipacket ) == typeid( CCtrl ) )
{
CCtrl* ctrl = dynamic_cast<CCtrl*>( *ipacket );
switch( ctrl->getType() )
{
/*************************************** rcv RTS **************************************/
case CCtrl::_rts:
if( !node->hasData() )
{
return packetsToSend;
}
//CTS
ctrlToSend = new CCtrl(node->getID(), now, CCtrl::_cts);
// + DATA
dataToSend = node->getDataForTrans(INVALID);
waitForResponse = true;
// TODO: mark skipRTS ?
// TODO: connection established ?
break;
case CCtrl::_cts:
break;
case CCtrl::_capacity:
break;
case CCtrl::_index:
break;
case CCtrl::_no_data:
break;
/*************************************** rcv ACK **************************************/
case CCtrl::_ack:
node->startDiscovering();
//收到空的ACK时,结束本次数据传输
if( ctrl->getACK().empty() )
return packetsToSend;
//clear data with ack
else
node->dropDataByAck(ctrl->getACK());
CPrintHelper::PrintCommunication(now, node->getName(), sink->getName(), ctrl->getACK().size());
return packetsToSend;
break;
default:
break;
}
++ipacket;
}
else
{
++ipacket;
}
}
/********************************** wrap ***********************************/
if( ctrlToSend != nullptr )
{
packetsToSend.push_back(ctrlToSend);
}
if( indexToSend != nullptr )
{
packetsToSend.push_back(indexToSend);
}
if( nodataToSend != nullptr )
{
packetsToSend.push_back(nodataToSend);
}
if( !dataToSend.empty() )
{
for( auto idata = dataToSend.begin(); idata != dataToSend.end(); ++idata )
packetsToSend.push_back(new CData(*idata));
}
if( waitForResponse )
{
int timeDelay = CMacProtocol::getTransmissionDelay(packetsToSend);
node->delaySleep(timeDelay);
}
return packetsToSend;
}
vector<CPacket*> CEpidemic::receivePackets(CSink* sink, CNode* fromNode, vector<CPacket*> packets, int now)
{
vector<CPacket*> packetsToSend;
CCtrl* ctrlToSend = nullptr;
CCtrl* ackToSend = nullptr;
for( vector<CPacket*>::iterator ipacket = packets.begin(); ipacket != packets.end(); )
{
if( typeid( **ipacket ) == typeid( CCtrl ) )
{
CCtrl* ctrl = dynamic_cast<CCtrl*>( *ipacket );
switch( ctrl->getType() )
{
case CCtrl::_rts:
break;
case CCtrl::_cts:
break;
case CCtrl::_capacity:
break;
case CCtrl::_index:
break;
case CCtrl::_ack:
break;
case CCtrl::_no_data:
break;
default:
break;
}
++ipacket;
}
else if( typeid( **ipacket ) == typeid( CData ) )
{
//extract data packet
vector<CData> datas;
do
{
datas.push_back(*dynamic_cast<CData*>( *ipacket ));
++ipacket;
} while( ipacket != packets.end() );
//accept data into buffer
vector<CData> ack = CSink::bufferData(now, datas);
//ACK(如果收到的数据全部被丢弃,发送空的ACK)
ackToSend = new CCtrl(CSink::getSink()->getID(), ack, now, CCtrl::_ack);
}
}
/********************************** wrap ***********************************/
if( ctrlToSend != nullptr )
packetsToSend.push_back(ctrlToSend);
if( ackToSend != nullptr )
packetsToSend.push_back(ackToSend);
return packetsToSend;
}
//TODO: test
vector<CPacket*> CEpidemic::receivePackets(CNode* node, CNode* fromNode, vector<CPacket*> packets, int now)
{
vector<CPacket*> packetsToSend;
CCtrl* ctrlToSend = nullptr;
CCtrl* capacityToSend = nullptr;
CCtrl* indexToSend = nullptr;
CCtrl* nodataToSend = nullptr; //NODATA包代表缓存为空,没有适合传输的数据
CCtrl* ackToSend = nullptr;
vector<CData> dataToSend; //空vector代表拒绝传输数据
int capacity = INVALID;
bool waitForResponse = false;
for( vector<CPacket*>::iterator ipacket = packets.begin(); ipacket != packets.end(); )
{
/***************************************** rcv Ctrl Message *****************************************/
if( typeid( **ipacket ) == typeid( CCtrl ) )
{
CCtrl* ctrl = dynamic_cast<CCtrl*>( *ipacket );
switch( ctrl->getType() )
{
/*************************************** rcv RTS **************************************/
case CCtrl::_rts:
//skip if has spoken recently
if( node->hasCommunicatedRecently(fromNode->getID(), now) )
{
CPrintHelper::PrintCommunicationSkipped(now, node->getName(), fromNode->getName());
return packetsToSend;
}
//rcv RTS from node
else
{
//CTS
ctrlToSend = new CCtrl(node->getID(), now, CCtrl::_cts);
// + Capacity
capacityToSend = new CCtrl(node->getID(), node->getBufferVacancy(), now, CCtrl::_capacity);
// + Index
indexToSend = new CCtrl(node->getID(), now, CCtrl::_index);
}
// TODO: mark skipRTS ?
// TODO: connection established ?
break;
/*************************************** rcv CTS **************************************/
case CCtrl::_cts:
// TODO: connection established ?
break;
/************************************* rcv capacity ***********************************/
case CCtrl::_capacity:
capacity = ctrl->getCapacity();
break;
/****************************** rcv Data Index ( dp / sv ) ****************************/
case CCtrl::_index:
dataToSend = node->getDataForTrans(fromNode->getBufferHistory(), capacity);
if( dataToSend.empty() )
nodataToSend = new CCtrl(node->getID(), now, CCtrl::_no_data);
else
waitForResponse = true;
break;
/*************************************** rcv ACK **************************************/
case CCtrl::_ack:
//加入最近邻居列表
node->updateCommunicationHistory(fromNode->getID(), now);
node->startDiscovering();
//收到空的ACK时,结束本次数据传输
if( !ctrl->getACK().empty() )
{
CPrintHelper::PrintCommunication(now, node->getName(), fromNode->getName(), ctrl->getACK().size());
}
break;
case CCtrl::_no_data:
//CTS
if( ctrlToSend == nullptr )
ctrlToSend = new CCtrl(node->getID(), now, CCtrl::_cts);
//收到NODATA,也将回复一个空的ACK,即,也将被认为数据传输成功
//空的ACK
ackToSend = new CCtrl(node->getID(), vector<CData>(), now, CCtrl::_ack);
//加入最近邻居列表
node->updateCommunicationHistory(fromNode->getID(), now);
node->startDiscovering();
break;
default:
break;
}
++ipacket;
}
/******************************************* rcv Data *******************************************/
else if( typeid( **ipacket ) == typeid( CData ) )
{
//CTS
if( ctrlToSend == nullptr )
ctrlToSend = new CCtrl(node->getID(), now, CCtrl::_cts);
//extract data packet
vector<CData> datas;
do
{
datas.push_back(*dynamic_cast<CData*>( *ipacket ));
++ipacket;
} while( ipacket != packets.end() );
//accept data into buffer
vector<CData> ack;
//存入收到的数据并发送ACK
ack = node->bufferData(now, datas);
ackToSend = new CCtrl(node->getID(), ack, now, CCtrl::_ack);
//加入最近邻居列表
node->updateCommunicationHistory(fromNode->getID(), now);
node->startDiscovering();
}
}
/********************************** wrap ***********************************/
if( ctrlToSend != nullptr )
{
packetsToSend.push_back(ctrlToSend);
}
if( capacityToSend != nullptr )
{
packetsToSend.push_back(capacityToSend);
}
if( indexToSend != nullptr )
{
packetsToSend.push_back(indexToSend);
}
if( ackToSend != nullptr )
{
packetsToSend.push_back(ackToSend);
}
if( nodataToSend != nullptr )
{
packetsToSend.push_back(nodataToSend);
}
if( !dataToSend.empty() )
{
for( auto idata = dataToSend.begin(); idata != dataToSend.end(); ++idata )
packetsToSend.push_back(new CData(*idata));
}
if( waitForResponse )
{
int timeDelay = CMacProtocol::getTransmissionDelay(packetsToSend);
node->delaySleep(timeDelay);
}
return packetsToSend;
}
void CEpidemic::CommunicateBetweenNeighbors(int now)
{
if( now % getConfig<int>("log", "slot_log") == 0 )
{
if( now > 0 )
{
CPrintHelper::PrintPercentage("Delivery Ratio", CData::getDeliveryRatio());
}
CPrintHelper::PrintNewLine();
CPrintHelper::PrintHeading(now, "DATA DELIVERY");
}
// Prophet: sink => nodes
CSink* sink = CSink::getSink();
//use default neighbor pool (only sensor nodes)
CMacProtocol::transmitFrame(*sink, sink->sendRTS(now), now, receivePackets);
vector<CNode*> nodes = CNode::getAllNodes();
for( vector<CNode*>::iterator srcNode = nodes.begin(); srcNode != nodes.end(); ++srcNode )
{
if( ( *srcNode )->isDiscovering() )
{
CMacProtocol::transmitFrame(**srcNode, ( *srcNode )->sendRTSWithCapacityAndIndex(now), now, receivePackets);
( *srcNode )->finishDiscovering();
}
}
}
bool CEpidemic::Init(int now)
{
if( getConfig<config::EnumMacProtocolScheme>("simulation", "mac_protocol") == config::_hdc )
CHDC::Init();
else if( getConfig<config::EnumMacProtocolScheme>("simulation", "mac_protocol") == config::_smac )
CSMac::Init();
return true;
}
bool CEpidemic::Operate(int now)
{
if( getConfig<config::EnumMacProtocolScheme>("simulation", "mac_protocol") == config::_hdc )
CHDC::Prepare(now);
else if( getConfig<config::EnumMacProtocolScheme>("simulation", "mac_protocol") == config::_smac )
CSMac::Prepare(now);
if( !CNode::UpdateNodeStatus(now) )
return false;
if( now < getConfig<int>("simulation", "runtime") )
CommunicateBetweenNeighbors(now);
PrintInfo(now);
return true;
}
| [
"sheeco@live.com"
] | sheeco@live.com |
2c63e9dd7f19594cad70ecf8b73e6bad1f1a7bc0 | dcab97ae22c4b935191dabc56024c657ab0a56e9 | /python code/find_face_landmarks-master/sfl_viewer/sfl_viewer_states.cpp | 1de81fb52829acb4599e152b77a9b81dd10c28a9 | [] | no_license | AkashSrivastava/PoseInvariantFaceRecognition | c2654bb006122b779172ad2f980040f443361497 | ad1acb6d08812c14284a50f449d5356eb8a4b126 | refs/heads/master | 2021-05-15T11:20:27.904135 | 2020-04-04T09:33:04 | 2020-04-04T09:33:04 | 108,314,331 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,706 | cpp | #include "sfl_viewer_states.h"
#include "sfl_viewer.h"
#include <iostream>//
// Boost
#include <boost/filesystem.hpp>
// Qt
#include <QTimer>
#include <QMessageBox>
using namespace boost::filesystem;
namespace sfl
{
ViewerSM::ViewerSM(Viewer * _viewer) : viewer(_viewer)
{
}
Inactive::Inactive(my_context ctx) : my_base(ctx), viewer(nullptr)
{
viewer = context<ViewerSM>().viewer;
}
void Inactive::onUpdate(const EvUpdate & event)
{
// Render to display
viewer->display->setPixmap(QPixmap::fromImage(viewer->render_image->rgbSwapped()));
viewer->display->update();
}
sc::result Inactive::react(const EvStart &)
{
if (viewer->vs == nullptr || viewer->sfl == nullptr)
{
QMessageBox msgBox;
msgBox.setText("Failed to open sequence sources.");
msgBox.exec();
return discard_event();
}
return transit< Active >();
}
Active::Active(my_context ctx) : my_base(ctx), viewer(nullptr)
{
viewer = context<ViewerSM>().viewer;
post_event(EvStart());
}
void Active::onSeek(const EvSeek & event)
{
if (event.i < 0 || event.i >= viewer->total_frames) return;
viewer->vs->seek(event.i);
if (viewer->vs->read())
{
viewer->curr_frame_pos = event.i;
viewer->frame_slider->setValue(viewer->curr_frame_pos);
viewer->curr_frame_lbl->setText(std::to_string(viewer->curr_frame_pos).c_str());
viewer->frame = viewer->vs->getFrame();
post_event(EvUpdate());
}
}
void Active::onStart(const EvStart & event)
{
// Reshape window
viewer->display->setMinimumSize(viewer->vs->getWidth(), viewer->vs->getHeight());
viewer->adjustSize();
// Read first video frame
viewer->curr_frame_pos = 0;
viewer->total_frames = viewer->vs->size();
viewer->fps = viewer->vs->getFPS();
if (viewer->fps < 1.0) viewer->fps = 30.0;
viewer->vs->seek(viewer->curr_frame_pos);
if (viewer->vs->read())
viewer->frame = viewer->vs->getFrame();
// Initialize render frame
QSize displaySize = viewer->display->size();
viewer->render_frame = cv::Mat::zeros(displaySize.height(), displaySize.width(), CV_8UC3);
// Get sfl frames
const std::list<std::unique_ptr<Frame>>& sfl_frames_list = viewer->sfl->getSequence();
viewer->sfl_frames.clear();
viewer->sfl_frames.reserve(sfl_frames_list.size());
for (auto& frame : sfl_frames_list)
viewer->sfl_frames.push_back(frame.get());
// Initialize widgets
path title(path(viewer->sequence_path).filename() += path(" / ") +=
path(viewer->landmarks_path).filename() += path(" - SFL Viewer"));
viewer->setWindowTitle(title.string().c_str());
viewer->frame_slider->setMinimum(0);
viewer->frame_slider->setMaximum(viewer->total_frames - 1);
viewer->frame_slider->setValue(viewer->curr_frame_pos);
viewer->curr_frame_lbl->setText(std::to_string(viewer->curr_frame_pos).c_str());
viewer->max_frame_lbl->setText(std::to_string(viewer->total_frames - 1).c_str());
viewer->frame_slider->setEnabled(true);
}
Paused::Paused(my_context ctx) : my_base(ctx), viewer(nullptr)
{
viewer = context<Active>().viewer;
viewer->actionPlay->setIcon(
QIcon::fromTheme(QStringLiteral(":/images/play.png")));
}
void Paused::onUpdate(const EvUpdate& event)
{
viewer->render();
}
Playing::Playing(my_context ctx) : my_base(ctx), viewer(nullptr)
{
viewer = context<Active>().viewer;
viewer->actionPlay->setIcon(
QIcon::fromTheme(QStringLiteral(":/images/pause.png")));
// Start timer
timer_id = viewer->startTimer((int)std::round(1000.0 / viewer->fps));
}
Playing::~Playing()
{
viewer->killTimer(timer_id);
}
void Playing::onUpdate(const EvUpdate& event)
{
viewer->render();
}
void Playing::onTimerTick(const EvTimerTick& event)
{
if (viewer->curr_frame_pos >= (viewer->total_frames - 1))
{
post_event(EvPlayPause());
return;
}
if (viewer->vs->read())
{
viewer->frame_slider->setValue(++viewer->curr_frame_pos);
viewer->curr_frame_lbl->setText(std::to_string(viewer->curr_frame_pos).c_str());
viewer->frame = viewer->vs->getFrame();
post_event(EvUpdate());
}
}
} // namespace sfl
| [
"akashsrivastava436@gmail.com"
] | akashsrivastava436@gmail.com |
147f642790d2324db2a40741c609e8b59b912558 | 7fa4b0bbe1fb3f52027ebcbe82679df39c1a3da9 | /src/wbem/logic/LayoutStep.h | ad5e78b8b7198348d2f081f8e15b921acf132df6 | [
"BSD-3-Clause"
] | permissive | nkothapa/IXPDIMMSW | 1c0f985cbae8709c2a3d8dcbbaed1341ed2be704 | 3fd90f97425b0efe767ae8f4ba2c14df8dca1e47 | refs/heads/master | 2021-01-14T10:52:16.837065 | 2016-05-10T10:46:04 | 2016-05-10T10:46:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,845 | h | /*
* Copyright (c) 2015 2016, Intel Corporation
*
* 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 Intel Corporation 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.
*/
/*
* Base class for memory allocation layout steps.
*/
#ifndef _WBEM_LOGIC_LAYOUTSTEP_H_
#define _WBEM_LOGIC_LAYOUTSTEP_H_
#include "MemoryAllocationTypes.h"
namespace wbem
{
namespace logic
{
class NVM_API LayoutStep
{
public:
virtual ~LayoutStep() {}
virtual void execute(const MemoryAllocationRequest &request, MemoryAllocationLayout &layout) = 0;
virtual bool isRemainingStep(const MemoryAllocationRequest &request);
protected:
NVM_UINT64 getDimmUnallocatedBytes(
const NVM_UINT64 &dimmCapacity,
const struct config_goal &dimmGoal);
NVM_UINT64 getDimmUnallocatedGiBAlignedBytes(
const NVM_UINT64 &dimmCapacity,
const struct config_goal &dimmGoal);
NVM_UINT64 getCountOfDimmsWithUnallocatedCapacity(
const std::vector<Dimm> &dimms,
std::map<std::string, struct config_goal> &goals);
NVM_UINT64 getLargestPerDimmSymmetricalBytes(
const std::vector<Dimm> &dimms,
std::map<std::string, struct config_goal> &goals,
const NVM_UINT64 &requestedCapacity,
std::vector<Dimm> &dimmsIncluded);
NVM_UINT64 getRemainingBytesFromRequestedDimms(
const struct MemoryAllocationRequest& request,
MemoryAllocationLayout& layout);
};
} /* namespace logic */
} /* namespace wbem */
#endif /* _WBEM_LOGIC_LAYOUTSTEP_H_ */
| [
"nicholas.w.moulin@intel.com"
] | nicholas.w.moulin@intel.com |
d434f3bf3809789c789f8e6a677c63626e567dc3 | 1fd33efcea837bb2ffcd32fcdceee78e246e1414 | /mediatek/platform/mt6572/hardware/camera/core/featureio/pipe/aaa/isp_tuning/paramctrl/paramctrl_lifetime.cpp | b0653e1250cdb8460faf8929cb7acff5f2dc846b | [] | no_license | rock12/android_kernel_xbasic | cda1c5a956cf8afdc6b9440cefd84644e4bfd7b5 | 38d09253ba7ef2e7e4ba2ee7f448a04457159ddb | refs/heads/master | 2021-01-17T08:38:46.441103 | 2016-07-01T19:36:39 | 2016-07-01T19:36:39 | 62,417,176 | 2 | 0 | null | 2016-07-01T20:07:19 | 2016-07-01T20:07:19 | null | UTF-8 | C++ | false | false | 9,953 | cpp | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/********************************************************************************************
* LEGAL DISCLAIMER
*
* (Header of MediaTek Software/Firmware Release or Documentation)
*
* BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED
* FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS
* ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
* A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY
* WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK
* ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION
* OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH
* RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION,
TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE
* FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS
* OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES.
************************************************************************************************/
#define LOG_TAG "paramctrl_lifetime"
#ifndef ENABLE_MY_LOG
#define ENABLE_MY_LOG (1)
#endif
#include <cutils/properties.h>
#include <aaa_types.h>
#include <aaa_error_code.h>
#include <aaa_log.h>
#include <camera_custom_nvram.h>
#include <awb_param.h>
#include <ae_param.h>
#include <af_param.h>
#include <flash_param.h>
#include <isp_tuning.h>
#include <camera_feature.h>
#include <isp_tuning_cam_info.h>
#include <isp_tuning_idx.h>
#include <isp_tuning_custom.h>
#include <nvram_drv_mgr.h>
#include <ispdrv_mgr.h>
#include <isp_mgr.h>
#include <isp_mgr_helper.h>
#include <tdri_mgr.h>
#include <pca_mgr.h>
#include <dynamic_ccm.h>
#include <ccm_mgr.h>
#include <lsc_mgr.h>
#include <dbg_isp_param.h>
#include <sensor_hal.h>
#include "paramctrl_if.h"
#include "paramctrl.h"
using namespace NSIspTuning;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
IParamctrl*
IParamctrl::createInstance(ESensorDev_T const eSensorDev)
{
return Paramctrl::getInstance(eSensorDev);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Paramctrl*
Paramctrl::
getInstance(ESensorDev_T const eSensorDev)
{
Paramctrl* pParamctrl = MNULL;
NVRAM_CAMERA_ISP_PARAM_STRUCT* pNvram_Isp = MNULL;
SensorHal* pSensorHal = MNULL;
MY_LOG("%s(): eSensorDev = %d\n", __FUNCTION__, eSensorDev);
// ISP NVRAM
if (MERR_OK != NvramDrvMgr::getInstance().init(eSensorDev))
{
goto lbExit;
}
NvramDrvMgr::getInstance().getRefBuf(pNvram_Isp);
if (! pNvram_Isp)
{
MY_ERR("[createInstance] (pNvram_Isp) = (%p)", pNvram_Isp);
goto lbExit;
}
#if 0
MY_LOG("sizeof(pNvram_Isp->Version) = %d\n", sizeof(pNvram_Isp->Version));
MY_LOG("sizeof(pNvram_Isp->SensorId) = %d\n", sizeof(pNvram_Isp->SensorId));
MY_LOG("sizeof(pNvram_Isp->ISPComm) = %d\n", sizeof(pNvram_Isp->ISPComm));
MY_LOG("sizeof(pNvram_Isp->ISPPca) = %d\n", sizeof(pNvram_Isp->ISPPca));
MY_LOG("sizeof(pNvram_Isp->ISPRegs) = %d\n", sizeof(pNvram_Isp->ISPRegs));
MY_LOG("sizeof(pNvram_Isp->ISPMfbMixer) = %d\n", sizeof(pNvram_Isp->ISPMfbMixer));
MY_LOG("sizeof(pNvram_Isp->ISPCcmPoly22) = %d\n", sizeof(pNvram_Isp->ISPCcmPoly22));
MY_LOG("sizeof(pNvram_Isp) = %d\n", sizeof(NVRAM_CAMERA_ISP_PARAM_STRUCT));
#endif
// Sensor ID
pSensorHal = SensorHal::createInstance();
if ( ! pSensorHal )
{
MY_ERR("Cannot create Sensor driver");
goto lbExit;
}
// Query sensor ID
MUINT32 u4SensorID;
switch ( eSensorDev )
{
case ESensorDev_Main:
pSensorHal->sendCommand(SENSOR_DEV_MAIN, SENSOR_CMD_GET_SENSOR_ID, reinterpret_cast<MINT32>(&u4SensorID), 0, 0);
break;
case ESensorDev_Sub:
pSensorHal->sendCommand(SENSOR_DEV_SUB, SENSOR_CMD_GET_SENSOR_ID, reinterpret_cast<MINT32>(&u4SensorID), 0, 0);
break;
case ESensorDev_MainSecond:
pSensorHal->sendCommand(SENSOR_DEV_MAIN_2, SENSOR_CMD_GET_SENSOR_ID, reinterpret_cast<MINT32>(&u4SensorID), 0, 0);
break;
default: // Shouldn't happen.
MY_ERR("Invalid sensor device: %d", eSensorDev);
goto lbExit;
}
// Here, pIspParam must be legal.
pParamctrl = new Paramctrl(
eSensorDev, u4SensorID, pNvram_Isp
);
lbExit:
NvramDrvMgr::getInstance().uninit();
if ( pSensorHal )
pSensorHal->destroyInstance();
return pParamctrl;
}
void
Paramctrl::
destroyInstance()
{
delete this;
}
Paramctrl::
Paramctrl(
ESensorDev_T const eSensorDev,
MUINT32 const u4SensorID,
NVRAM_CAMERA_ISP_PARAM_STRUCT*const pNvram_Isp
)
: IParamctrl(eSensorDev)
, m_u4ParamChangeCount(0)
, m_fgDynamicTuning(MTRUE)
, m_fgDynamicBypass(MFALSE)
, m_fgDynamicCCM(MTRUE)
, m_eIdx_Effect(MEFFECT_OFF)
, m_eSensorDev(eSensorDev)
, m_eOperMode(EOperMode_Normal)
, m_eSensorMode(ESensorMode_Capture)
, m_rIspExifDebugInfo()
, m_IspUsrSelectLevel()
, m_rIspCamInfo()
, m_pIspTuningCustom(IspTuningCustom::createInstance(eSensorDev, u4SensorID))
, m_rIspParam(*pNvram_Isp)
, m_rIspComm(m_rIspParam.ISPComm)
, m_IspNvramMgr(&m_rIspParam.ISPRegs)
, m_pPcaMgr(PcaMgr::createInstance(eSensorDev, m_rIspParam.ISPPca))
, m_pCcmMgr(CcmMgr::createInstance(eSensorDev, m_rIspParam.ISPRegs, m_rIspParam.ISPCcmPoly22, m_pIspTuningCustom))
, m_pLscMgr(LscMgr::createInstance(eSensorDev, m_rIspParam.ISPRegs))
, m_Lock()
, m_bDebugEnable(MFALSE)
{
}
Paramctrl::
~Paramctrl()
{
}
MERROR_ENUM
Paramctrl::
init()
{
MERROR_ENUM err = MERR_OK;
char value[32] = {'\0'};
property_get("debug.paramctrl.enable", value, "0");
m_bDebugEnable = atoi(value);
// (1) Force to assume all params have chagned and different.
m_u4ParamChangeCount = 1;
// (2) Init ISP/T driver manager.
IspDrvMgr::getInstance().init();
TdriMgr::getInstance().init();
LscMgr::getInstance()->init();
// (3) validateFrameless() is invoked
// when init() or status change, like Camera Mode.
err = validateFrameless();
if ( MERR_OK != err )
{
goto lbExit;
}
// (4) however, is it needed to invoke validatePerFrame() in init()?
// or just invoke it only when a frame comes.
err = validatePerFrame(MTRUE);
if ( MERR_OK != err )
{
goto lbExit;
}
lbExit:
if ( MERR_OK != err )
{
uninit();
}
MY_LOG("[-ParamctrlRAW::init]err(%X)", err);
return err;
}
MERROR_ENUM
Paramctrl::
uninit()
{
MY_LOG("[+uninit]");
// Uninit ISP driver manager.
IspDrvMgr::getInstance().uninit();
TdriMgr::getInstance().uninit();
LscMgr::getInstance()->uninit();
return MERR_OK;
}
| [
"yugers@gmail.com"
] | yugers@gmail.com |
bbfb497cfbb389d81aa0e818308f641657d4a58d | ba065a9c2f6d4f187c0c6ae772ae171b5edcc3eb | /sketch_apr12a/sketch_apr12a.ino | c921a9217ef334ecdcea3d0f767705b05464c9ab | [] | no_license | hjh010501/dimigo-microprocessing | 8db07154052493b1548ec7c19ab37012bb0add8b | 894102ee6bbebabb32b868e30d0399d7c21481a4 | refs/heads/master | 2020-05-17T05:32:43.988007 | 2019-04-26T01:49:47 | 2019-04-26T01:49:47 | 183,537,146 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,352 | ino | int p = 5;
int sw = 3;
int led1 = 9;
int led2 = 10;
int led3 = 11;
void setup() {
// put your setup code here, to run once:
pinMode(p, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(sw, INPUT_PULLUP);
}
void loop() {
// put your main code here, to run repeatedly:
if(digitalRead(sw) == LOW) {
digitalWrite(led1, HIGH);
delay(1000);
digitalWrite(led2, HIGH);
delay(1000);
digitalWrite(led3, HIGH);
delay(1000);
tone(p, 391, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 440, 200);
delay(400);
tone(p, 440, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 329, 400);
delay(1000);
tone(p, 391, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 329, 200);
delay(400);
tone(p, 329, 200);
delay(400);
tone(p, 294, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 440, 200);
delay(400);
tone(p, 440, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 391, 200);
delay(400);
tone(p, 329, 400);
delay(1000);
tone(p, 440, 200);
delay(400);
tone(p, 329, 400);
delay(1000);
digitalWrite(led3, LOW);
delay(1000);
digitalWrite(led2, LOW);
delay(1000);
digitalWrite(led1, LOW);
delay(1000);
}
}
| [
"hjh010501@naver.com"
] | hjh010501@naver.com |
a1fdf7849e1464c40e6f71a94f51f47517d92bfa | cd527908c157b027e41cb16b17f0426b4367bb2a | /depthview2/src/version.cpp | aaf6d2b3863d1a41fba42dc5608f451547136f05 | [
"MIT"
] | permissive | chipgw/depthview2 | 69f0a6f5d7c019cf35e91833f0cc38133ec25b9b | 444e1af861143447d99d887c8aeb6cf326b0f503 | refs/heads/master | 2020-04-12T08:48:44.060425 | 2019-03-13T17:57:03 | 2019-03-13T18:20:04 | 40,026,162 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 959 | cpp | #include "version.hpp"
namespace version {
const QVersionNumber number = QVersionNumber::fromString(VERSION);
#ifdef NDEBUG
const char* build_type = "Release";
#else
const char* build_type = "Debug";
#endif
#if defined(__clang__)
const char* compiler = "Clang/LLVM";
#elif defined(__ICC) || defined(__INTEL_COMPILER)
const char* compiler = "Intel ICC/ICPC";
#elif defined(__GNUC__) || defined(__GNUG__)
const char* compiler = "GNU GCC/G++";
#elif defined(__HP_cc) || defined(__HP_aCC)
const char* compiler = "Hewlett-Packard C/aC++";
#elif defined(__IBMC__) || defined(__IBMCPP__)
const char* compiler = "IBM XL C/C++";
#elif defined(_MSC_VER)
const char* compiler = "Microsoft Visual Studio";
#elif defined(__PGI)
const char* compiler = "Portland Group PGCC/PGCPP";
#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
const char* compiler = "Oracle Solaris Studio";
#else
const char* compiler = "Unknown";
#endif
const char* git_version = GIT_VERSION;
}
| [
"gw.chip.gw@gmail.com"
] | gw.chip.gw@gmail.com |
ab9249e598235b659923252ec5db914b2775c5c2 | 48da3cf76d6932e643824e8538bfad5529cf335a | /branches/20180201/center_server/country/country_common.hpp | 13df46abc044f29619f6c6bea175384d6975a7da | [] | no_license | daxingyou/sg_server | 932c84317210f7096b97f06c837e9e15e73809bd | 2bd0a812f0baeb31dc09192d0e88d47fde916a2b | refs/heads/master | 2021-09-19T16:01:37.630704 | 2018-07-28T09:27:09 | 2018-07-28T09:27:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 263 | hpp | #ifndef __CENTER_COUNTRY_COMMON_H__
#define __CENTER_COUNTRY_COMMON_H__
#include <map>
#include "macros.hpp"
#include "common.pb.h"
enum EM_BID_STATE
{
EM_BID_STATE_NONE = 0, // 没开始竞价
EM_BID_STATE_BIDING = 1, // 正在竞价
};
#endif | [
"major@fun2"
] | major@fun2 |
a4ab5a8d0f23cfc344b928c3f7397534e6d7660d | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /v8_4_8/src/elements.cc | 7eafe9bfaf4a40b2ae275e3c29f56d85ababf739 | [
"Apache-2.0"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 100,003 | cc | // Copyright 2012 the V8 project 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 "src/elements.h"
#include "src/arguments.h"
#include "src/conversions.h"
#include "src/factory.h"
#include "src/messages.h"
#include "src/objects-inl.h"
#include "src/utils.h"
// Each concrete ElementsAccessor can handle exactly one ElementsKind,
// several abstract ElementsAccessor classes are used to allow sharing
// common code.
//
// Inheritance hierarchy:
// - ElementsAccessorBase (abstract)
// - FastElementsAccessor (abstract)
// - FastSmiOrObjectElementsAccessor
// - FastPackedSmiElementsAccessor
// - FastHoleySmiElementsAccessor
// - FastPackedObjectElementsAccessor
// - FastHoleyObjectElementsAccessor
// - FastDoubleElementsAccessor
// - FastPackedDoubleElementsAccessor
// - FastHoleyDoubleElementsAccessor
// - TypedElementsAccessor: template, with instantiations:
// - FixedUint8ElementsAccessor
// - FixedInt8ElementsAccessor
// - FixedUint16ElementsAccessor
// - FixedInt16ElementsAccessor
// - FixedUint32ElementsAccessor
// - FixedInt32ElementsAccessor
// - FixedFloat32ElementsAccessor
// - FixedFloat64ElementsAccessor
// - FixedUint8ClampedElementsAccessor
// - DictionaryElementsAccessor
// - SloppyArgumentsElementsAccessor
// - FastSloppyArgumentsElementsAccessor
// - SlowSloppyArgumentsElementsAccessor
namespace v8 {
namespace internal {
namespace {
static const int kPackedSizeNotKnown = -1;
enum Where { AT_START, AT_END };
// First argument in list is the accessor class, the second argument is the
// accessor ElementsKind, and the third is the backing store class. Use the
// fast element handler for smi-only arrays. The implementation is currently
// identical. Note that the order must match that of the ElementsKind enum for
// the |accessor_array[]| below to work.
#define ELEMENTS_LIST(V) \
V(FastPackedSmiElementsAccessor, FAST_SMI_ELEMENTS, FixedArray) \
V(FastHoleySmiElementsAccessor, FAST_HOLEY_SMI_ELEMENTS, FixedArray) \
V(FastPackedObjectElementsAccessor, FAST_ELEMENTS, FixedArray) \
V(FastHoleyObjectElementsAccessor, FAST_HOLEY_ELEMENTS, FixedArray) \
V(FastPackedDoubleElementsAccessor, FAST_DOUBLE_ELEMENTS, FixedDoubleArray) \
V(FastHoleyDoubleElementsAccessor, FAST_HOLEY_DOUBLE_ELEMENTS, \
FixedDoubleArray) \
V(DictionaryElementsAccessor, DICTIONARY_ELEMENTS, SeededNumberDictionary) \
V(FastSloppyArgumentsElementsAccessor, FAST_SLOPPY_ARGUMENTS_ELEMENTS, \
FixedArray) \
V(SlowSloppyArgumentsElementsAccessor, SLOW_SLOPPY_ARGUMENTS_ELEMENTS, \
FixedArray) \
V(FixedUint8ElementsAccessor, UINT8_ELEMENTS, FixedUint8Array) \
V(FixedInt8ElementsAccessor, INT8_ELEMENTS, FixedInt8Array) \
V(FixedUint16ElementsAccessor, UINT16_ELEMENTS, FixedUint16Array) \
V(FixedInt16ElementsAccessor, INT16_ELEMENTS, FixedInt16Array) \
V(FixedUint32ElementsAccessor, UINT32_ELEMENTS, FixedUint32Array) \
V(FixedInt32ElementsAccessor, INT32_ELEMENTS, FixedInt32Array) \
V(FixedFloat32ElementsAccessor, FLOAT32_ELEMENTS, FixedFloat32Array) \
V(FixedFloat64ElementsAccessor, FLOAT64_ELEMENTS, FixedFloat64Array) \
V(FixedUint8ClampedElementsAccessor, UINT8_CLAMPED_ELEMENTS, \
FixedUint8ClampedArray)
template<ElementsKind Kind> class ElementsKindTraits {
public:
typedef FixedArrayBase BackingStore;
};
#define ELEMENTS_TRAITS(Class, KindParam, Store) \
template<> class ElementsKindTraits<KindParam> { \
public: /* NOLINT */ \
static const ElementsKind Kind = KindParam; \
typedef Store BackingStore; \
};
ELEMENTS_LIST(ELEMENTS_TRAITS)
#undef ELEMENTS_TRAITS
MUST_USE_RESULT
MaybeHandle<Object> ThrowArrayLengthRangeError(Isolate* isolate) {
THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kInvalidArrayLength),
Object);
}
void CopyObjectToObjectElements(FixedArrayBase* from_base,
ElementsKind from_kind, uint32_t from_start,
FixedArrayBase* to_base, ElementsKind to_kind,
uint32_t to_start, int raw_copy_size) {
DCHECK(to_base->map() !=
from_base->GetIsolate()->heap()->fixed_cow_array_map());
DisallowHeapAllocation no_allocation;
int copy_size = raw_copy_size;
if (raw_copy_size < 0) {
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = Min(from_base->length() - from_start,
to_base->length() - to_start);
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
int start = to_start + copy_size;
int length = to_base->length() - start;
if (length > 0) {
Heap* heap = from_base->GetHeap();
MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
heap->the_hole_value(), length);
}
}
}
DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
(copy_size + static_cast<int>(from_start)) <= from_base->length());
if (copy_size == 0) return;
FixedArray* from = FixedArray::cast(from_base);
FixedArray* to = FixedArray::cast(to_base);
DCHECK(IsFastSmiOrObjectElementsKind(from_kind));
DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
Address to_address = to->address() + FixedArray::kHeaderSize;
Address from_address = from->address() + FixedArray::kHeaderSize;
CopyWords(reinterpret_cast<Object**>(to_address) + to_start,
reinterpret_cast<Object**>(from_address) + from_start,
static_cast<size_t>(copy_size));
if (IsFastObjectElementsKind(from_kind) &&
IsFastObjectElementsKind(to_kind)) {
Heap* heap = from->GetHeap();
if (!heap->InNewSpace(to)) {
heap->RecordWrites(to->address(),
to->OffsetOfElementAt(to_start),
copy_size);
}
heap->incremental_marking()->RecordWrites(to);
}
}
static void CopyDictionaryToObjectElements(
FixedArrayBase* from_base, uint32_t from_start, FixedArrayBase* to_base,
ElementsKind to_kind, uint32_t to_start, int raw_copy_size) {
DisallowHeapAllocation no_allocation;
SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
int copy_size = raw_copy_size;
Heap* heap = from->GetHeap();
if (raw_copy_size < 0) {
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = from->max_number_key() + 1 - from_start;
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
int start = to_start + copy_size;
int length = to_base->length() - start;
if (length > 0) {
Heap* heap = from->GetHeap();
MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
heap->the_hole_value(), length);
}
}
}
DCHECK(to_base != from_base);
DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
if (copy_size == 0) return;
FixedArray* to = FixedArray::cast(to_base);
uint32_t to_length = to->length();
if (to_start + copy_size > to_length) {
copy_size = to_length - to_start;
}
for (int i = 0; i < copy_size; i++) {
int entry = from->FindEntry(i + from_start);
if (entry != SeededNumberDictionary::kNotFound) {
Object* value = from->ValueAt(entry);
DCHECK(!value->IsTheHole());
to->set(i + to_start, value, SKIP_WRITE_BARRIER);
} else {
to->set_the_hole(i + to_start);
}
}
if (IsFastObjectElementsKind(to_kind)) {
if (!heap->InNewSpace(to)) {
heap->RecordWrites(to->address(),
to->OffsetOfElementAt(to_start),
copy_size);
}
heap->incremental_marking()->RecordWrites(to);
}
}
// NOTE: this method violates the handlified function signature convention:
// raw pointer parameters in the function that allocates.
// See ElementsAccessorBase::CopyElements() for details.
static void CopyDoubleToObjectElements(FixedArrayBase* from_base,
uint32_t from_start,
FixedArrayBase* to_base,
uint32_t to_start, int raw_copy_size) {
int copy_size = raw_copy_size;
if (raw_copy_size < 0) {
DisallowHeapAllocation no_allocation;
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = Min(from_base->length() - from_start,
to_base->length() - to_start);
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
// Also initialize the area that will be copied over since HeapNumber
// allocation below can cause an incremental marking step, requiring all
// existing heap objects to be propertly initialized.
int start = to_start;
int length = to_base->length() - start;
if (length > 0) {
Heap* heap = from_base->GetHeap();
MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
heap->the_hole_value(), length);
}
}
}
DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
(copy_size + static_cast<int>(from_start)) <= from_base->length());
if (copy_size == 0) return;
// From here on, the code below could actually allocate. Therefore the raw
// values are wrapped into handles.
Isolate* isolate = from_base->GetIsolate();
Handle<FixedDoubleArray> from(FixedDoubleArray::cast(from_base), isolate);
Handle<FixedArray> to(FixedArray::cast(to_base), isolate);
// create an outer loop to not waste too much time on creating HandleScopes
// on the other hand we might overflow a single handle scope depending on
// the copy_size
int offset = 0;
while (offset < copy_size) {
HandleScope scope(isolate);
offset += 100;
for (int i = offset - 100; i < offset && i < copy_size; ++i) {
Handle<Object> value = FixedDoubleArray::get(from, i + from_start);
to->set(i + to_start, *value, UPDATE_WRITE_BARRIER);
}
}
}
static void CopyDoubleToDoubleElements(FixedArrayBase* from_base,
uint32_t from_start,
FixedArrayBase* to_base,
uint32_t to_start, int raw_copy_size) {
DisallowHeapAllocation no_allocation;
int copy_size = raw_copy_size;
if (raw_copy_size < 0) {
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = Min(from_base->length() - from_start,
to_base->length() - to_start);
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
for (int i = to_start + copy_size; i < to_base->length(); ++i) {
FixedDoubleArray::cast(to_base)->set_the_hole(i);
}
}
}
DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
(copy_size + static_cast<int>(from_start)) <= from_base->length());
if (copy_size == 0) return;
FixedDoubleArray* from = FixedDoubleArray::cast(from_base);
FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
Address to_address = to->address() + FixedDoubleArray::kHeaderSize;
Address from_address = from->address() + FixedDoubleArray::kHeaderSize;
to_address += kDoubleSize * to_start;
from_address += kDoubleSize * from_start;
int words_per_double = (kDoubleSize / kPointerSize);
CopyWords(reinterpret_cast<Object**>(to_address),
reinterpret_cast<Object**>(from_address),
static_cast<size_t>(words_per_double * copy_size));
}
static void CopySmiToDoubleElements(FixedArrayBase* from_base,
uint32_t from_start,
FixedArrayBase* to_base, uint32_t to_start,
int raw_copy_size) {
DisallowHeapAllocation no_allocation;
int copy_size = raw_copy_size;
if (raw_copy_size < 0) {
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = from_base->length() - from_start;
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
for (int i = to_start + copy_size; i < to_base->length(); ++i) {
FixedDoubleArray::cast(to_base)->set_the_hole(i);
}
}
}
DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
(copy_size + static_cast<int>(from_start)) <= from_base->length());
if (copy_size == 0) return;
FixedArray* from = FixedArray::cast(from_base);
FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
Object* the_hole = from->GetHeap()->the_hole_value();
for (uint32_t from_end = from_start + static_cast<uint32_t>(copy_size);
from_start < from_end; from_start++, to_start++) {
Object* hole_or_smi = from->get(from_start);
if (hole_or_smi == the_hole) {
to->set_the_hole(to_start);
} else {
to->set(to_start, Smi::cast(hole_or_smi)->value());
}
}
}
static void CopyPackedSmiToDoubleElements(FixedArrayBase* from_base,
uint32_t from_start,
FixedArrayBase* to_base,
uint32_t to_start, int packed_size,
int raw_copy_size) {
DisallowHeapAllocation no_allocation;
int copy_size = raw_copy_size;
uint32_t to_end;
if (raw_copy_size < 0) {
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = packed_size - from_start;
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
to_end = to_base->length();
for (uint32_t i = to_start + copy_size; i < to_end; ++i) {
FixedDoubleArray::cast(to_base)->set_the_hole(i);
}
} else {
to_end = to_start + static_cast<uint32_t>(copy_size);
}
} else {
to_end = to_start + static_cast<uint32_t>(copy_size);
}
DCHECK(static_cast<int>(to_end) <= to_base->length());
DCHECK(packed_size >= 0 && packed_size <= copy_size);
DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
(copy_size + static_cast<int>(from_start)) <= from_base->length());
if (copy_size == 0) return;
FixedArray* from = FixedArray::cast(from_base);
FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
for (uint32_t from_end = from_start + static_cast<uint32_t>(packed_size);
from_start < from_end; from_start++, to_start++) {
Object* smi = from->get(from_start);
DCHECK(!smi->IsTheHole());
to->set(to_start, Smi::cast(smi)->value());
}
}
static void CopyObjectToDoubleElements(FixedArrayBase* from_base,
uint32_t from_start,
FixedArrayBase* to_base,
uint32_t to_start, int raw_copy_size) {
DisallowHeapAllocation no_allocation;
int copy_size = raw_copy_size;
if (raw_copy_size < 0) {
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = from_base->length() - from_start;
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
for (int i = to_start + copy_size; i < to_base->length(); ++i) {
FixedDoubleArray::cast(to_base)->set_the_hole(i);
}
}
}
DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
(copy_size + static_cast<int>(from_start)) <= from_base->length());
if (copy_size == 0) return;
FixedArray* from = FixedArray::cast(from_base);
FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
Object* the_hole = from->GetHeap()->the_hole_value();
for (uint32_t from_end = from_start + copy_size;
from_start < from_end; from_start++, to_start++) {
Object* hole_or_object = from->get(from_start);
if (hole_or_object == the_hole) {
to->set_the_hole(to_start);
} else {
to->set(to_start, hole_or_object->Number());
}
}
}
static void CopyDictionaryToDoubleElements(FixedArrayBase* from_base,
uint32_t from_start,
FixedArrayBase* to_base,
uint32_t to_start,
int raw_copy_size) {
DisallowHeapAllocation no_allocation;
SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
int copy_size = raw_copy_size;
if (copy_size < 0) {
DCHECK(copy_size == ElementsAccessor::kCopyToEnd ||
copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = from->max_number_key() + 1 - from_start;
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
for (int i = to_start + copy_size; i < to_base->length(); ++i) {
FixedDoubleArray::cast(to_base)->set_the_hole(i);
}
}
}
if (copy_size == 0) return;
FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
uint32_t to_length = to->length();
if (to_start + copy_size > to_length) {
copy_size = to_length - to_start;
}
for (int i = 0; i < copy_size; i++) {
int entry = from->FindEntry(i + from_start);
if (entry != SeededNumberDictionary::kNotFound) {
to->set(i + to_start, from->ValueAt(entry)->Number());
} else {
to->set_the_hole(i + to_start);
}
}
}
static void TraceTopFrame(Isolate* isolate) {
StackFrameIterator it(isolate);
if (it.done()) {
PrintF("unknown location (no JavaScript frames present)");
return;
}
StackFrame* raw_frame = it.frame();
if (raw_frame->is_internal()) {
Code* apply_builtin = isolate->builtins()->builtin(
Builtins::kFunctionApply);
if (raw_frame->unchecked_code() == apply_builtin) {
PrintF("apply from ");
it.Advance();
raw_frame = it.frame();
}
}
JavaScriptFrame::PrintTop(isolate, stdout, false, true);
}
// Base class for element handler implementations. Contains the
// the common logic for objects with different ElementsKinds.
// Subclasses must specialize method for which the element
// implementation differs from the base class implementation.
//
// This class is intended to be used in the following way:
//
// class SomeElementsAccessor :
// public ElementsAccessorBase<SomeElementsAccessor,
// BackingStoreClass> {
// ...
// }
//
// This is an example of the Curiously Recurring Template Pattern (see
// http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern). We use
// CRTP to guarantee aggressive compile time optimizations (i.e. inlining and
// specialization of SomeElementsAccessor methods).
template <typename ElementsAccessorSubclass,
typename ElementsTraitsParam>
class ElementsAccessorBase : public ElementsAccessor {
public:
explicit ElementsAccessorBase(const char* name)
: ElementsAccessor(name) { }
typedef ElementsTraitsParam ElementsTraits;
typedef typename ElementsTraitsParam::BackingStore BackingStore;
static ElementsKind kind() { return ElementsTraits::Kind; }
static void ValidateContents(Handle<JSObject> holder, int length) {
}
static void ValidateImpl(Handle<JSObject> holder) {
Handle<FixedArrayBase> fixed_array_base(holder->elements());
if (!fixed_array_base->IsHeapObject()) return;
// Arrays that have been shifted in place can't be verified.
if (fixed_array_base->IsFiller()) return;
int length = 0;
if (holder->IsJSArray()) {
Object* length_obj = Handle<JSArray>::cast(holder)->length();
if (length_obj->IsSmi()) {
length = Smi::cast(length_obj)->value();
}
} else {
length = fixed_array_base->length();
}
ElementsAccessorSubclass::ValidateContents(holder, length);
}
void Validate(Handle<JSObject> holder) final {
DisallowHeapAllocation no_gc;
ElementsAccessorSubclass::ValidateImpl(holder);
}
bool IsPacked(Handle<JSObject> holder, Handle<FixedArrayBase> backing_store,
uint32_t start, uint32_t end) final {
return ElementsAccessorSubclass::IsPackedImpl(holder, backing_store, start,
end);
}
static bool IsPackedImpl(Handle<JSObject> holder,
Handle<FixedArrayBase> backing_store, uint32_t start,
uint32_t end) {
if (IsFastPackedElementsKind(kind())) return true;
for (uint32_t i = start; i < end; i++) {
if (!ElementsAccessorSubclass::HasElementImpl(holder, i, backing_store,
NONE)) {
return false;
}
}
return true;
}
static void TryTransitionResultArrayToPacked(Handle<JSArray> array) {
if (!IsHoleyElementsKind(kind())) return;
int length = Smi::cast(array->length())->value();
Handle<FixedArrayBase> backing_store(array->elements());
if (!ElementsAccessorSubclass::IsPackedImpl(array, backing_store, 0,
length)) {
return;
}
ElementsKind packed_kind = GetPackedElementsKind(kind());
Handle<Map> new_map =
JSObject::GetElementsTransitionMap(array, packed_kind);
JSObject::MigrateToMap(array, new_map);
if (FLAG_trace_elements_transitions) {
JSObject::PrintElementsTransition(stdout, array, kind(), backing_store,
packed_kind, backing_store);
}
}
bool HasElement(Handle<JSObject> holder, uint32_t index,
Handle<FixedArrayBase> backing_store,
PropertyAttributes filter) final {
return ElementsAccessorSubclass::HasElementImpl(holder, index,
backing_store, filter);
}
static bool HasElementImpl(Handle<JSObject> holder, uint32_t index,
Handle<FixedArrayBase> backing_store,
PropertyAttributes filter) {
return ElementsAccessorSubclass::GetEntryForIndexImpl(
*holder, *backing_store, index, filter) != kMaxUInt32;
}
Handle<Object> Get(Handle<FixedArrayBase> backing_store,
uint32_t entry) final {
return ElementsAccessorSubclass::GetImpl(backing_store, entry);
}
static Handle<Object> GetImpl(Handle<FixedArrayBase> backing_store,
uint32_t entry) {
uint32_t index = GetIndexForEntryImpl(*backing_store, entry);
return BackingStore::get(Handle<BackingStore>::cast(backing_store), index);
}
void Set(FixedArrayBase* backing_store, uint32_t entry, Object* value) final {
ElementsAccessorSubclass::SetImpl(backing_store, entry, value);
}
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value) {
UNREACHABLE();
}
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value, WriteBarrierMode mode) {
UNREACHABLE();
}
void Reconfigure(Handle<JSObject> object, Handle<FixedArrayBase> store,
uint32_t entry, Handle<Object> value,
PropertyAttributes attributes) final {
ElementsAccessorSubclass::ReconfigureImpl(object, store, entry, value,
attributes);
}
static void ReconfigureImpl(Handle<JSObject> object,
Handle<FixedArrayBase> store, uint32_t entry,
Handle<Object> value,
PropertyAttributes attributes) {
UNREACHABLE();
}
void Add(Handle<JSObject> object, uint32_t index, Handle<Object> value,
PropertyAttributes attributes, uint32_t new_capacity) final {
ElementsAccessorSubclass::AddImpl(object, index, value, attributes,
new_capacity);
}
static void AddImpl(Handle<JSObject> object, uint32_t index,
Handle<Object> value, PropertyAttributes attributes,
uint32_t new_capacity) {
UNREACHABLE();
}
uint32_t Push(Handle<JSArray> receiver, Handle<FixedArrayBase> backing_store,
Arguments* args, uint32_t push_size) final {
return ElementsAccessorSubclass::PushImpl(receiver, backing_store, args,
push_size);
}
static uint32_t PushImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> elms_obj, Arguments* args,
uint32_t push_sized) {
UNREACHABLE();
return 0;
}
uint32_t Unshift(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store, Arguments* args,
uint32_t unshift_size) final {
return ElementsAccessorSubclass::UnshiftImpl(receiver, backing_store, args,
unshift_size);
}
static uint32_t UnshiftImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> elms_obj, Arguments* args,
uint32_t unshift_size) {
UNREACHABLE();
return 0;
}
Handle<JSArray> Slice(Handle<JSObject> receiver,
Handle<FixedArrayBase> backing_store, uint32_t start,
uint32_t end) final {
return ElementsAccessorSubclass::SliceImpl(receiver, backing_store, start,
end);
}
static Handle<JSArray> SliceImpl(Handle<JSObject> receiver,
Handle<FixedArrayBase> backing_store,
uint32_t start, uint32_t end) {
UNREACHABLE();
return Handle<JSArray>();
}
Handle<JSArray> Splice(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store, uint32_t start,
uint32_t delete_count, Arguments* args,
uint32_t add_count) final {
return ElementsAccessorSubclass::SpliceImpl(receiver, backing_store, start,
delete_count, args, add_count);
}
static Handle<JSArray> SpliceImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store,
uint32_t start, uint32_t delete_count,
Arguments* args, uint32_t add_count) {
UNREACHABLE();
return Handle<JSArray>();
}
Handle<Object> Pop(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store) final {
return ElementsAccessorSubclass::PopImpl(receiver, backing_store);
}
static Handle<Object> PopImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store) {
UNREACHABLE();
return Handle<Object>();
}
Handle<Object> Shift(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store) final {
return ElementsAccessorSubclass::ShiftImpl(receiver, backing_store);
}
static Handle<Object> ShiftImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store) {
UNREACHABLE();
return Handle<Object>();
}
void SetLength(Handle<JSArray> array, uint32_t length) final {
ElementsAccessorSubclass::SetLengthImpl(array->GetIsolate(), array, length,
handle(array->elements()));
}
static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
uint32_t length,
Handle<FixedArrayBase> backing_store) {
DCHECK(!array->SetLengthWouldNormalize(length));
DCHECK(IsFastElementsKind(array->GetElementsKind()));
uint32_t old_length = 0;
CHECK(array->length()->ToArrayIndex(&old_length));
if (old_length < length) {
ElementsKind kind = array->GetElementsKind();
if (!IsFastHoleyElementsKind(kind)) {
kind = GetHoleyElementsKind(kind);
JSObject::TransitionElementsKind(array, kind);
}
}
// Check whether the backing store should be shrunk.
uint32_t capacity = backing_store->length();
old_length = Min(old_length, capacity);
if (length == 0) {
array->initialize_elements();
} else if (length <= capacity) {
if (array->HasFastSmiOrObjectElements()) {
backing_store = JSObject::EnsureWritableFastElements(array);
}
if (2 * length <= capacity) {
// If more than half the elements won't be used, trim the array.
isolate->heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
*backing_store, capacity - length);
} else {
// Otherwise, fill the unused tail with holes.
for (uint32_t i = length; i < old_length; i++) {
BackingStore::cast(*backing_store)->set_the_hole(i);
}
}
} else {
// Check whether the backing store should be expanded.
capacity = Max(length, JSObject::NewElementsCapacity(capacity));
ElementsAccessorSubclass::GrowCapacityAndConvertImpl(array, capacity);
}
array->set_length(Smi::FromInt(length));
JSObject::ValidateElements(array);
}
static Handle<FixedArrayBase> ConvertElementsWithCapacity(
Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
ElementsKind from_kind, uint32_t capacity) {
return ConvertElementsWithCapacity(
object, old_elements, from_kind, capacity, 0, 0,
ElementsAccessor::kCopyToEndAndInitializeToHole);
}
static Handle<FixedArrayBase> ConvertElementsWithCapacity(
Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
ElementsKind from_kind, uint32_t capacity, int copy_size) {
return ConvertElementsWithCapacity(object, old_elements, from_kind,
capacity, 0, 0, copy_size);
}
static Handle<FixedArrayBase> ConvertElementsWithCapacity(
Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
ElementsKind from_kind, uint32_t capacity, uint32_t src_index,
uint32_t dst_index, int copy_size) {
Isolate* isolate = object->GetIsolate();
Handle<FixedArrayBase> new_elements;
if (IsFastDoubleElementsKind(kind())) {
new_elements = isolate->factory()->NewFixedDoubleArray(capacity);
} else {
new_elements = isolate->factory()->NewUninitializedFixedArray(capacity);
}
int packed_size = kPackedSizeNotKnown;
if (IsFastPackedElementsKind(from_kind) && object->IsJSArray()) {
packed_size = Smi::cast(JSArray::cast(*object)->length())->value();
}
ElementsAccessorSubclass::CopyElementsImpl(
*old_elements, src_index, *new_elements, from_kind, dst_index,
packed_size, copy_size);
return new_elements;
}
static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
uint32_t capacity) {
ElementsKind from_kind = object->GetElementsKind();
if (IsFastSmiOrObjectElementsKind(from_kind)) {
// Array optimizations rely on the prototype lookups of Array objects
// always returning undefined. If there is a store to the initial
// prototype object, make sure all of these optimizations are invalidated.
object->GetIsolate()->UpdateArrayProtectorOnSetLength(object);
}
Handle<FixedArrayBase> old_elements(object->elements());
// This method should only be called if there's a reason to update the
// elements.
DCHECK(IsFastDoubleElementsKind(from_kind) !=
IsFastDoubleElementsKind(kind()) ||
IsDictionaryElementsKind(from_kind) ||
static_cast<uint32_t>(old_elements->length()) < capacity);
Handle<FixedArrayBase> elements =
ConvertElementsWithCapacity(object, old_elements, from_kind, capacity);
ElementsKind to_kind = kind();
if (IsHoleyElementsKind(from_kind)) to_kind = GetHoleyElementsKind(to_kind);
Handle<Map> new_map = JSObject::GetElementsTransitionMap(object, to_kind);
JSObject::SetMapAndElements(object, new_map, elements);
// Transition through the allocation site as well if present.
JSObject::UpdateAllocationSite(object, to_kind);
if (FLAG_trace_elements_transitions) {
JSObject::PrintElementsTransition(stdout, object, from_kind, old_elements,
to_kind, elements);
}
}
void GrowCapacityAndConvert(Handle<JSObject> object,
uint32_t capacity) final {
ElementsAccessorSubclass::GrowCapacityAndConvertImpl(object, capacity);
}
void Delete(Handle<JSObject> obj, uint32_t entry) final {
ElementsAccessorSubclass::DeleteImpl(obj, entry);
}
static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
FixedArrayBase* to, ElementsKind from_kind,
uint32_t to_start, int packed_size,
int copy_size) {
UNREACHABLE();
}
void CopyElements(Handle<FixedArrayBase> from, uint32_t from_start,
ElementsKind from_kind, Handle<FixedArrayBase> to,
uint32_t to_start, int copy_size) final {
DCHECK(!from.is_null());
// NOTE: the ElementsAccessorSubclass::CopyElementsImpl() methods
// violate the handlified function signature convention:
// raw pointer parameters in the function that allocates. This is done
// intentionally to avoid ArrayConcat() builtin performance degradation.
// See the comment in another ElementsAccessorBase::CopyElements() for
// details.
ElementsAccessorSubclass::CopyElementsImpl(*from, from_start, *to,
from_kind, to_start,
kPackedSizeNotKnown, copy_size);
}
void CopyElements(JSObject* from_holder, uint32_t from_start,
ElementsKind from_kind, Handle<FixedArrayBase> to,
uint32_t to_start, int copy_size) final {
int packed_size = kPackedSizeNotKnown;
bool is_packed = IsFastPackedElementsKind(from_kind) &&
from_holder->IsJSArray();
if (is_packed) {
packed_size =
Smi::cast(JSArray::cast(from_holder)->length())->value();
if (copy_size >= 0 && packed_size > copy_size) {
packed_size = copy_size;
}
}
FixedArrayBase* from = from_holder->elements();
// NOTE: the ElementsAccessorSubclass::CopyElementsImpl() methods
// violate the handlified function signature convention:
// raw pointer parameters in the function that allocates. This is done
// intentionally to avoid ArrayConcat() builtin performance degradation.
//
// Details: The idea is that allocations actually happen only in case of
// copying from object with fast double elements to object with object
// elements. In all the other cases there are no allocations performed and
// handle creation causes noticeable performance degradation of the builtin.
ElementsAccessorSubclass::CopyElementsImpl(
from, from_start, *to, from_kind, to_start, packed_size, copy_size);
}
static void CollectElementIndicesImpl(Handle<JSObject> object,
Handle<FixedArrayBase> backing_store,
KeyAccumulator* keys, uint32_t range,
PropertyAttributes filter,
uint32_t offset) {
uint32_t length = 0;
if (object->IsJSArray()) {
length = Smi::cast(JSArray::cast(*object)->length())->value();
} else {
length =
ElementsAccessorSubclass::GetCapacityImpl(*object, *backing_store);
}
if (range < length) length = range;
for (uint32_t i = offset; i < length; i++) {
if (!ElementsAccessorSubclass::HasElementImpl(object, i, backing_store,
filter))
continue;
keys->AddKey(i);
}
}
void CollectElementIndices(Handle<JSObject> object,
Handle<FixedArrayBase> backing_store,
KeyAccumulator* keys, uint32_t range,
PropertyAttributes filter, uint32_t offset) final {
ElementsAccessorSubclass::CollectElementIndicesImpl(
object, backing_store, keys, range, filter, offset);
};
void AddElementsToKeyAccumulator(Handle<JSObject> receiver,
KeyAccumulator* accumulator,
AddKeyConversion convert) final {
Handle<FixedArrayBase> from(receiver->elements());
uint32_t add_length =
ElementsAccessorSubclass::GetCapacityImpl(*receiver, *from);
if (add_length == 0) return;
for (uint32_t i = 0; i < add_length; i++) {
if (!ElementsAccessorSubclass::HasEntryImpl(*from, i)) continue;
Handle<Object> value = ElementsAccessorSubclass::GetImpl(from, i);
DCHECK(!value->IsTheHole());
DCHECK(!value->IsAccessorPair());
DCHECK(!value->IsExecutableAccessorInfo());
accumulator->AddKey(value, convert);
}
}
static uint32_t GetCapacityImpl(JSObject* holder,
FixedArrayBase* backing_store) {
return backing_store->length();
}
uint32_t GetCapacity(JSObject* holder, FixedArrayBase* backing_store) final {
return ElementsAccessorSubclass::GetCapacityImpl(holder, backing_store);
}
static bool HasEntryImpl(FixedArrayBase* backing_store, uint32_t entry) {
return true;
}
static uint32_t GetIndexForEntryImpl(FixedArrayBase* backing_store,
uint32_t entry) {
return entry;
}
static uint32_t GetEntryForIndexImpl(JSObject* holder,
FixedArrayBase* backing_store,
uint32_t index,
PropertyAttributes filter) {
if (IsHoleyElementsKind(kind())) {
return index < ElementsAccessorSubclass::GetCapacityImpl(holder,
backing_store) &&
!BackingStore::cast(backing_store)->is_the_hole(index)
? index
: kMaxUInt32;
} else {
Smi* smi_length = Smi::cast(JSArray::cast(holder)->length());
uint32_t length = static_cast<uint32_t>(smi_length->value());
return index < length ? index : kMaxUInt32;
}
}
uint32_t GetEntryForIndex(JSObject* holder, FixedArrayBase* backing_store,
uint32_t index) final {
return ElementsAccessorSubclass::GetEntryForIndexImpl(holder, backing_store,
index, NONE);
}
static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
uint32_t entry) {
return PropertyDetails(NONE, DATA, 0, PropertyCellType::kNoCell);
}
PropertyDetails GetDetails(FixedArrayBase* backing_store,
uint32_t entry) final {
return ElementsAccessorSubclass::GetDetailsImpl(backing_store, entry);
}
private:
DISALLOW_COPY_AND_ASSIGN(ElementsAccessorBase);
};
class DictionaryElementsAccessor
: public ElementsAccessorBase<DictionaryElementsAccessor,
ElementsKindTraits<DICTIONARY_ELEMENTS> > {
public:
explicit DictionaryElementsAccessor(const char* name)
: ElementsAccessorBase<DictionaryElementsAccessor,
ElementsKindTraits<DICTIONARY_ELEMENTS> >(name) {}
static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
uint32_t length,
Handle<FixedArrayBase> backing_store) {
Handle<SeededNumberDictionary> dict =
Handle<SeededNumberDictionary>::cast(backing_store);
int capacity = dict->Capacity();
uint32_t old_length = 0;
CHECK(array->length()->ToArrayLength(&old_length));
if (length < old_length) {
if (dict->requires_slow_elements()) {
// Find last non-deletable element in range of elements to be
// deleted and adjust range accordingly.
for (int entry = 0; entry < capacity; entry++) {
DisallowHeapAllocation no_gc;
Object* index = dict->KeyAt(entry);
if (index->IsNumber()) {
uint32_t number = static_cast<uint32_t>(index->Number());
if (length <= number && number < old_length) {
PropertyDetails details = dict->DetailsAt(entry);
if (!details.IsConfigurable()) length = number + 1;
}
}
}
}
if (length == 0) {
// Flush the backing store.
JSObject::ResetElements(array);
} else {
DisallowHeapAllocation no_gc;
// Remove elements that should be deleted.
int removed_entries = 0;
Handle<Object> the_hole_value = isolate->factory()->the_hole_value();
for (int entry = 0; entry < capacity; entry++) {
Object* index = dict->KeyAt(entry);
if (index->IsNumber()) {
uint32_t number = static_cast<uint32_t>(index->Number());
if (length <= number && number < old_length) {
dict->SetEntry(entry, the_hole_value, the_hole_value);
removed_entries++;
}
}
}
// Update the number of elements.
dict->ElementsRemoved(removed_entries);
}
}
Handle<Object> length_obj = isolate->factory()->NewNumberFromUint(length);
array->set_length(*length_obj);
}
static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
FixedArrayBase* to, ElementsKind from_kind,
uint32_t to_start, int packed_size,
int copy_size) {
UNREACHABLE();
}
static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
// TODO(verwaest): Remove reliance on index in Shrink.
Handle<SeededNumberDictionary> dict(
SeededNumberDictionary::cast(obj->elements()));
uint32_t index = GetIndexForEntryImpl(*dict, entry);
Handle<Object> result = SeededNumberDictionary::DeleteProperty(dict, entry);
USE(result);
DCHECK(result->IsTrue());
Handle<FixedArray> new_elements =
SeededNumberDictionary::Shrink(dict, index);
obj->set_elements(*new_elements);
}
static Object* GetRaw(FixedArrayBase* store, uint32_t entry) {
SeededNumberDictionary* backing_store = SeededNumberDictionary::cast(store);
return backing_store->ValueAt(entry);
}
static Handle<Object> GetImpl(Handle<FixedArrayBase> store, uint32_t entry) {
Isolate* isolate = store->GetIsolate();
return handle(GetRaw(*store, entry), isolate);
}
static inline void SetImpl(FixedArrayBase* store, uint32_t entry,
Object* value) {
SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(store);
dictionary->ValueAtPut(entry, value);
}
static void ReconfigureImpl(Handle<JSObject> object,
Handle<FixedArrayBase> store, uint32_t entry,
Handle<Object> value,
PropertyAttributes attributes) {
SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(*store);
if (attributes != NONE) object->RequireSlowElements(dictionary);
dictionary->ValueAtPut(entry, *value);
PropertyDetails details = dictionary->DetailsAt(entry);
details = PropertyDetails(attributes, DATA, details.dictionary_index(),
PropertyCellType::kNoCell);
dictionary->DetailsAtPut(entry, details);
}
static void AddImpl(Handle<JSObject> object, uint32_t index,
Handle<Object> value, PropertyAttributes attributes,
uint32_t new_capacity) {
PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
Handle<SeededNumberDictionary> dictionary =
object->HasFastElements()
? JSObject::NormalizeElements(object)
: handle(SeededNumberDictionary::cast(object->elements()));
Handle<SeededNumberDictionary> new_dictionary =
SeededNumberDictionary::AddNumberEntry(
dictionary, index, value, details,
object->map()->is_prototype_map());
if (attributes != NONE) object->RequireSlowElements(*new_dictionary);
if (dictionary.is_identical_to(new_dictionary)) return;
object->set_elements(*new_dictionary);
}
static bool HasEntryImpl(FixedArrayBase* store, uint32_t entry) {
DisallowHeapAllocation no_gc;
SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
Object* index = dict->KeyAt(entry);
return !index->IsTheHole();
}
static uint32_t GetIndexForEntryImpl(FixedArrayBase* store, uint32_t entry) {
DisallowHeapAllocation no_gc;
SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
uint32_t result = 0;
CHECK(dict->KeyAt(entry)->ToArrayIndex(&result));
return result;
}
static uint32_t GetEntryForIndexImpl(JSObject* holder, FixedArrayBase* store,
uint32_t index,
PropertyAttributes filter) {
DisallowHeapAllocation no_gc;
SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(store);
int entry = dictionary->FindEntry(index);
if (entry == SeededNumberDictionary::kNotFound) return kMaxUInt32;
if (filter != NONE) {
PropertyDetails details = dictionary->DetailsAt(entry);
PropertyAttributes attr = details.attributes();
if ((attr & filter) != 0) return kMaxUInt32;
}
return static_cast<uint32_t>(entry);
}
static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
uint32_t entry) {
return SeededNumberDictionary::cast(backing_store)->DetailsAt(entry);
}
static void CollectElementIndicesImpl(Handle<JSObject> object,
Handle<FixedArrayBase> backing_store,
KeyAccumulator* keys, uint32_t range,
PropertyAttributes filter,
uint32_t offset) {
Handle<SeededNumberDictionary> dictionary =
Handle<SeededNumberDictionary>::cast(backing_store);
int capacity = dictionary->Capacity();
for (int i = 0; i < capacity; i++) {
Object* k = dictionary->KeyAt(i);
if (!dictionary->IsKey(k)) continue;
if (k->FilterKey(filter)) continue;
if (dictionary->IsDeleted(i)) continue;
DCHECK(k->IsNumber());
DCHECK_LE(k->Number(), kMaxUInt32);
uint32_t index = static_cast<uint32_t>(k->Number());
if (index < offset) continue;
PropertyDetails details = dictionary->DetailsAt(i);
PropertyAttributes attr = details.attributes();
if ((attr & filter) != 0) continue;
keys->AddKey(index);
}
keys->SortCurrentElementsList();
}
};
// Super class for all fast element arrays.
template<typename FastElementsAccessorSubclass,
typename KindTraits>
class FastElementsAccessor
: public ElementsAccessorBase<FastElementsAccessorSubclass, KindTraits> {
public:
explicit FastElementsAccessor(const char* name)
: ElementsAccessorBase<FastElementsAccessorSubclass,
KindTraits>(name) {}
typedef typename KindTraits::BackingStore BackingStore;
static void DeleteAtEnd(Handle<JSObject> obj,
Handle<BackingStore> backing_store, uint32_t entry) {
uint32_t length = static_cast<uint32_t>(backing_store->length());
Heap* heap = obj->GetHeap();
for (; entry > 0; entry--) {
if (!backing_store->is_the_hole(entry - 1)) break;
}
if (entry == 0) {
FixedArray* empty = heap->empty_fixed_array();
if (obj->HasFastArgumentsElements()) {
FixedArray::cast(obj->elements())->set(1, empty);
} else {
obj->set_elements(empty);
}
return;
}
heap->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(*backing_store,
length - entry);
}
static void DeleteCommon(Handle<JSObject> obj, uint32_t entry,
Handle<FixedArrayBase> store) {
DCHECK(obj->HasFastSmiOrObjectElements() ||
obj->HasFastDoubleElements() ||
obj->HasFastArgumentsElements());
Handle<BackingStore> backing_store = Handle<BackingStore>::cast(store);
if (!obj->IsJSArray() &&
entry == static_cast<uint32_t>(store->length()) - 1) {
DeleteAtEnd(obj, backing_store, entry);
return;
}
backing_store->set_the_hole(entry);
// TODO(verwaest): Move this out of elements.cc.
// If an old space backing store is larger than a certain size and
// has too few used values, normalize it.
// To avoid doing the check on every delete we require at least
// one adjacent hole to the value being deleted.
const int kMinLengthForSparsenessCheck = 64;
if (backing_store->length() < kMinLengthForSparsenessCheck) return;
if (backing_store->GetHeap()->InNewSpace(*backing_store)) return;
uint32_t length = 0;
if (obj->IsJSArray()) {
JSArray::cast(*obj)->length()->ToArrayLength(&length);
} else {
length = static_cast<uint32_t>(store->length());
}
if ((entry > 0 && backing_store->is_the_hole(entry - 1)) ||
(entry + 1 < length && backing_store->is_the_hole(entry + 1))) {
if (!obj->IsJSArray()) {
uint32_t i;
for (i = entry + 1; i < length; i++) {
if (!backing_store->is_the_hole(i)) break;
}
if (i == length) {
DeleteAtEnd(obj, backing_store, entry);
return;
}
}
int num_used = 0;
for (int i = 0; i < backing_store->length(); ++i) {
if (!backing_store->is_the_hole(i)) {
++num_used;
// Bail out if a number dictionary wouldn't be able to save at least
// 75% space.
if (4 * SeededNumberDictionary::ComputeCapacity(num_used) *
SeededNumberDictionary::kEntrySize >
backing_store->length()) {
return;
}
}
}
JSObject::NormalizeElements(obj);
}
}
static void ReconfigureImpl(Handle<JSObject> object,
Handle<FixedArrayBase> store, uint32_t entry,
Handle<Object> value,
PropertyAttributes attributes) {
Handle<SeededNumberDictionary> dictionary =
JSObject::NormalizeElements(object);
entry = dictionary->FindEntry(entry);
DictionaryElementsAccessor::ReconfigureImpl(object, dictionary, entry,
value, attributes);
}
static void AddImpl(Handle<JSObject> object, uint32_t index,
Handle<Object> value, PropertyAttributes attributes,
uint32_t new_capacity) {
DCHECK_EQ(NONE, attributes);
ElementsKind from_kind = object->GetElementsKind();
ElementsKind to_kind = FastElementsAccessorSubclass::kind();
if (IsDictionaryElementsKind(from_kind) ||
IsFastDoubleElementsKind(from_kind) !=
IsFastDoubleElementsKind(to_kind) ||
FastElementsAccessorSubclass::GetCapacityImpl(
*object, object->elements()) != new_capacity) {
FastElementsAccessorSubclass::GrowCapacityAndConvertImpl(object,
new_capacity);
} else {
if (from_kind != to_kind) {
JSObject::TransitionElementsKind(object, to_kind);
}
if (IsFastSmiOrObjectElementsKind(from_kind)) {
DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
JSObject::EnsureWritableFastElements(object);
}
}
FastElementsAccessorSubclass::SetImpl(object->elements(), index, *value);
}
static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
ElementsKind kind = KindTraits::Kind;
if (IsFastPackedElementsKind(kind)) {
JSObject::TransitionElementsKind(obj, GetHoleyElementsKind(kind));
}
if (IsFastSmiOrObjectElementsKind(KindTraits::Kind)) {
JSObject::EnsureWritableFastElements(obj);
}
DeleteCommon(obj, entry, handle(obj->elements()));
}
static bool HasEntryImpl(FixedArrayBase* backing_store, uint32_t entry) {
return !BackingStore::cast(backing_store)->is_the_hole(entry);
}
static void ValidateContents(Handle<JSObject> holder, int length) {
#if DEBUG
Isolate* isolate = holder->GetIsolate();
HandleScope scope(isolate);
Handle<FixedArrayBase> elements(holder->elements(), isolate);
Map* map = elements->map();
DCHECK((IsFastSmiOrObjectElementsKind(KindTraits::Kind) &&
(map == isolate->heap()->fixed_array_map() ||
map == isolate->heap()->fixed_cow_array_map())) ||
(IsFastDoubleElementsKind(KindTraits::Kind) ==
((map == isolate->heap()->fixed_array_map() && length == 0) ||
map == isolate->heap()->fixed_double_array_map())));
if (length == 0) return; // nothing to do!
DisallowHeapAllocation no_gc;
Handle<BackingStore> backing_store = Handle<BackingStore>::cast(elements);
if (IsFastSmiElementsKind(KindTraits::Kind)) {
for (int i = 0; i < length; i++) {
DCHECK(BackingStore::get(backing_store, i)->IsSmi() ||
(IsFastHoleyElementsKind(KindTraits::Kind) &&
backing_store->is_the_hole(i)));
}
}
#endif
}
static Handle<Object> PopImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store) {
return FastElementsAccessorSubclass::RemoveElement(receiver, backing_store,
AT_END);
}
static Handle<Object> ShiftImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store) {
return FastElementsAccessorSubclass::RemoveElement(receiver, backing_store,
AT_START);
}
static uint32_t PushImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store,
Arguments* args, uint32_t push_size) {
return FastElementsAccessorSubclass::AddArguments(receiver, backing_store,
args, push_size, AT_END);
}
static uint32_t UnshiftImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store,
Arguments* args, uint32_t unshift_size) {
return FastElementsAccessorSubclass::AddArguments(
receiver, backing_store, args, unshift_size, AT_START);
}
static void MoveElements(Isolate* isolate, Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store, int dst_index,
int src_index, int len, int hole_start,
int hole_end) {
UNREACHABLE();
}
static Handle<JSArray> SliceImpl(Handle<JSObject> receiver,
Handle<FixedArrayBase> backing_store,
uint32_t start, uint32_t end) {
DCHECK(start < end);
Isolate* isolate = receiver->GetIsolate();
int result_len = end - start;
Handle<JSArray> result_array = isolate->factory()->NewJSArray(
KindTraits::Kind, result_len, result_len);
DisallowHeapAllocation no_gc;
FastElementsAccessorSubclass::CopyElementsImpl(
*backing_store, start, result_array->elements(), KindTraits::Kind, 0,
kPackedSizeNotKnown, result_len);
FastElementsAccessorSubclass::TryTransitionResultArrayToPacked(
result_array);
return result_array;
}
static Handle<JSArray> SpliceImpl(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store,
uint32_t start, uint32_t delete_count,
Arguments* args, uint32_t add_count) {
Isolate* isolate = receiver->GetIsolate();
Heap* heap = isolate->heap();
uint32_t length = Smi::cast(receiver->length())->value();
uint32_t new_length = length - delete_count + add_count;
if (new_length == 0) {
receiver->set_elements(heap->empty_fixed_array());
receiver->set_length(Smi::FromInt(0));
return isolate->factory()->NewJSArrayWithElements(
backing_store, KindTraits::Kind, delete_count);
}
// Construct the result array which holds the deleted elements.
Handle<JSArray> deleted_elements = isolate->factory()->NewJSArray(
KindTraits::Kind, delete_count, delete_count);
if (delete_count > 0) {
DisallowHeapAllocation no_gc;
FastElementsAccessorSubclass::CopyElementsImpl(
*backing_store, start, deleted_elements->elements(), KindTraits::Kind,
0, kPackedSizeNotKnown, delete_count);
}
// Delete and move elements to make space for add_count new elements.
if (add_count < delete_count) {
FastElementsAccessorSubclass::SpliceShrinkStep(
isolate, receiver, backing_store, start, delete_count, add_count,
length, new_length);
} else if (add_count > delete_count) {
backing_store = FastElementsAccessorSubclass::SpliceGrowStep(
isolate, receiver, backing_store, start, delete_count, add_count,
length, new_length);
}
// Copy over the arguments.
FastElementsAccessorSubclass::CopyArguments(args, backing_store, add_count,
3, start);
receiver->set_length(Smi::FromInt(new_length));
FastElementsAccessorSubclass::TryTransitionResultArrayToPacked(
deleted_elements);
return deleted_elements;
}
private:
// SpliceShrinkStep might modify the backing_store.
static void SpliceShrinkStep(Isolate* isolate, Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store,
uint32_t start, uint32_t delete_count,
uint32_t add_count, uint32_t len,
uint32_t new_length) {
const int move_left_count = len - delete_count - start;
const int move_left_dst_index = start + add_count;
FastElementsAccessorSubclass::MoveElements(
isolate, receiver, backing_store, move_left_dst_index,
start + delete_count, move_left_count, new_length, len);
}
// SpliceGrowStep might modify the backing_store.
static Handle<FixedArrayBase> SpliceGrowStep(
Isolate* isolate, Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store, uint32_t start,
uint32_t delete_count, uint32_t add_count, uint32_t length,
uint32_t new_length) {
// Check we do not overflow the new_length.
DCHECK((add_count - delete_count) <= (Smi::kMaxValue - length));
// Check if backing_store is big enough.
if (new_length <= static_cast<uint32_t>(backing_store->length())) {
FastElementsAccessorSubclass::MoveElements(
isolate, receiver, backing_store, start + add_count,
start + delete_count, (length - delete_count - start), 0, 0);
// MoveElements updates the backing_store in-place.
return backing_store;
}
// New backing storage is needed.
int capacity = JSObject::NewElementsCapacity(new_length);
// Partially copy all elements up to start.
Handle<FixedArrayBase> new_elms =
FastElementsAccessorSubclass::ConvertElementsWithCapacity(
receiver, backing_store, KindTraits::Kind, capacity, start);
// Copy the trailing elements after start + delete_count
FastElementsAccessorSubclass::CopyElementsImpl(
*backing_store, start + delete_count, *new_elms, KindTraits::Kind,
start + add_count, kPackedSizeNotKnown,
ElementsAccessor::kCopyToEndAndInitializeToHole);
receiver->set_elements(*new_elms);
return new_elms;
}
static Handle<Object> RemoveElement(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store,
Where remove_position) {
Isolate* isolate = receiver->GetIsolate();
uint32_t length =
static_cast<uint32_t>(Smi::cast(receiver->length())->value());
DCHECK(length > 0);
int new_length = length - 1;
int remove_index = remove_position == AT_START ? 0 : new_length;
Handle<Object> result =
FastElementsAccessorSubclass::GetImpl(backing_store, remove_index);
if (remove_position == AT_START) {
FastElementsAccessorSubclass::MoveElements(
isolate, receiver, backing_store, 0, 1, new_length, 0, 0);
}
FastElementsAccessorSubclass::SetLengthImpl(isolate, receiver, new_length,
backing_store);
if (IsHoleyElementsKind(KindTraits::Kind) && result->IsTheHole()) {
return receiver->GetIsolate()->factory()->undefined_value();
}
return result;
}
static uint32_t AddArguments(Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store,
Arguments* args, uint32_t add_size,
Where remove_position) {
uint32_t length = Smi::cast(receiver->length())->value();
DCHECK(add_size > 0);
uint32_t elms_len = backing_store->length();
// Check we do not overflow the new_length.
DCHECK(add_size <= static_cast<uint32_t>(Smi::kMaxValue - length));
uint32_t new_length = length + add_size;
if (new_length > elms_len) {
// New backing storage is needed.
uint32_t capacity = JSObject::NewElementsCapacity(new_length);
// If we add arguments to the start we have to shift the existing objects.
int copy_dst_index = remove_position == AT_START ? add_size : 0;
// Copy over all objects to a new backing_store.
backing_store = FastElementsAccessorSubclass::ConvertElementsWithCapacity(
receiver, backing_store, KindTraits::Kind, capacity, 0,
copy_dst_index, ElementsAccessor::kCopyToEndAndInitializeToHole);
receiver->set_elements(*backing_store);
} else if (remove_position == AT_START) {
// If the backing store has enough capacity and we add elements to the
// start we have to shift the existing objects.
Isolate* isolate = receiver->GetIsolate();
FastElementsAccessorSubclass::MoveElements(
isolate, receiver, backing_store, add_size, 0, length, 0, 0);
}
int insertion_index = remove_position == AT_START ? 0 : length;
// Copy the arguments to the start.
FastElementsAccessorSubclass::CopyArguments(args, backing_store, add_size,
1, insertion_index);
// Set the length.
receiver->set_length(Smi::FromInt(new_length));
return new_length;
}
static void CopyArguments(Arguments* args, Handle<FixedArrayBase> dst_store,
uint32_t copy_size, uint32_t src_index,
uint32_t dst_index) {
// Add the provided values.
DisallowHeapAllocation no_gc;
FixedArrayBase* raw_backing_store = *dst_store;
WriteBarrierMode mode = raw_backing_store->GetWriteBarrierMode(no_gc);
for (uint32_t i = 0; i < copy_size; i++) {
Object* argument = (*args)[i + src_index];
FastElementsAccessorSubclass::SetImpl(raw_backing_store, i + dst_index,
argument, mode);
}
}
};
template<typename FastElementsAccessorSubclass,
typename KindTraits>
class FastSmiOrObjectElementsAccessor
: public FastElementsAccessor<FastElementsAccessorSubclass, KindTraits> {
public:
explicit FastSmiOrObjectElementsAccessor(const char* name)
: FastElementsAccessor<FastElementsAccessorSubclass,
KindTraits>(name) {}
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value) {
FixedArray::cast(backing_store)->set(entry, value);
}
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value, WriteBarrierMode mode) {
FixedArray::cast(backing_store)->set(entry, value, mode);
}
static Object* GetRaw(FixedArray* backing_store, uint32_t entry) {
uint32_t index = FastElementsAccessorSubclass::GetIndexForEntryImpl(
backing_store, entry);
return backing_store->get(index);
}
static void MoveElements(Isolate* isolate, Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store, int dst_index,
int src_index, int len, int hole_start,
int hole_end) {
Heap* heap = isolate->heap();
Handle<FixedArray> dst_elms = Handle<FixedArray>::cast(backing_store);
if (heap->CanMoveObjectStart(*dst_elms) && dst_index == 0) {
// Update all the copies of this backing_store handle.
*dst_elms.location() =
FixedArray::cast(heap->LeftTrimFixedArray(*dst_elms, src_index));
receiver->set_elements(*dst_elms);
// Adjust the hole offset as the array has been shrunk.
hole_end -= src_index;
DCHECK_LE(hole_start, backing_store->length());
DCHECK_LE(hole_end, backing_store->length());
} else if (len != 0) {
DisallowHeapAllocation no_gc;
heap->MoveElements(*dst_elms, dst_index, src_index, len);
}
if (hole_start != hole_end) {
dst_elms->FillWithHoles(hole_start, hole_end);
}
}
// NOTE: this method violates the handlified function signature convention:
// raw pointer parameters in the function that allocates.
// See ElementsAccessor::CopyElements() for details.
// This method could actually allocate if copying from double elements to
// object elements.
static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
FixedArrayBase* to, ElementsKind from_kind,
uint32_t to_start, int packed_size,
int copy_size) {
DisallowHeapAllocation no_gc;
ElementsKind to_kind = KindTraits::Kind;
switch (from_kind) {
case FAST_SMI_ELEMENTS:
case FAST_HOLEY_SMI_ELEMENTS:
case FAST_ELEMENTS:
case FAST_HOLEY_ELEMENTS:
CopyObjectToObjectElements(from, from_kind, from_start, to, to_kind,
to_start, copy_size);
break;
case FAST_DOUBLE_ELEMENTS:
case FAST_HOLEY_DOUBLE_ELEMENTS: {
AllowHeapAllocation allow_allocation;
DCHECK(IsFastObjectElementsKind(to_kind));
CopyDoubleToObjectElements(from, from_start, to, to_start, copy_size);
break;
}
case DICTIONARY_ELEMENTS:
CopyDictionaryToObjectElements(from, from_start, to, to_kind, to_start,
copy_size);
break;
case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
UNREACHABLE();
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
case TYPE##_ELEMENTS: \
UNREACHABLE();
TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
}
}
};
class FastPackedSmiElementsAccessor
: public FastSmiOrObjectElementsAccessor<
FastPackedSmiElementsAccessor,
ElementsKindTraits<FAST_SMI_ELEMENTS> > {
public:
explicit FastPackedSmiElementsAccessor(const char* name)
: FastSmiOrObjectElementsAccessor<
FastPackedSmiElementsAccessor,
ElementsKindTraits<FAST_SMI_ELEMENTS> >(name) {}
};
class FastHoleySmiElementsAccessor
: public FastSmiOrObjectElementsAccessor<
FastHoleySmiElementsAccessor,
ElementsKindTraits<FAST_HOLEY_SMI_ELEMENTS> > {
public:
explicit FastHoleySmiElementsAccessor(const char* name)
: FastSmiOrObjectElementsAccessor<
FastHoleySmiElementsAccessor,
ElementsKindTraits<FAST_HOLEY_SMI_ELEMENTS> >(name) {}
};
class FastPackedObjectElementsAccessor
: public FastSmiOrObjectElementsAccessor<
FastPackedObjectElementsAccessor,
ElementsKindTraits<FAST_ELEMENTS> > {
public:
explicit FastPackedObjectElementsAccessor(const char* name)
: FastSmiOrObjectElementsAccessor<
FastPackedObjectElementsAccessor,
ElementsKindTraits<FAST_ELEMENTS> >(name) {}
};
class FastHoleyObjectElementsAccessor
: public FastSmiOrObjectElementsAccessor<
FastHoleyObjectElementsAccessor,
ElementsKindTraits<FAST_HOLEY_ELEMENTS> > {
public:
explicit FastHoleyObjectElementsAccessor(const char* name)
: FastSmiOrObjectElementsAccessor<
FastHoleyObjectElementsAccessor,
ElementsKindTraits<FAST_HOLEY_ELEMENTS> >(name) {}
};
template<typename FastElementsAccessorSubclass,
typename KindTraits>
class FastDoubleElementsAccessor
: public FastElementsAccessor<FastElementsAccessorSubclass, KindTraits> {
public:
explicit FastDoubleElementsAccessor(const char* name)
: FastElementsAccessor<FastElementsAccessorSubclass,
KindTraits>(name) {}
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value) {
FixedDoubleArray::cast(backing_store)->set(entry, value->Number());
}
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value, WriteBarrierMode mode) {
FixedDoubleArray::cast(backing_store)->set(entry, value->Number());
}
static void MoveElements(Isolate* isolate, Handle<JSArray> receiver,
Handle<FixedArrayBase> backing_store, int dst_index,
int src_index, int len, int hole_start,
int hole_end) {
Heap* heap = isolate->heap();
Handle<FixedDoubleArray> dst_elms =
Handle<FixedDoubleArray>::cast(backing_store);
if (heap->CanMoveObjectStart(*dst_elms) && dst_index == 0) {
// Update all the copies of this backing_store handle.
*dst_elms.location() = FixedDoubleArray::cast(
heap->LeftTrimFixedArray(*dst_elms, src_index));
receiver->set_elements(*dst_elms);
// Adjust the hole offset as the array has been shrunk.
hole_end -= src_index;
DCHECK_LE(hole_start, backing_store->length());
DCHECK_LE(hole_end, backing_store->length());
} else if (len != 0) {
MemMove(dst_elms->data_start() + dst_index,
dst_elms->data_start() + src_index, len * kDoubleSize);
}
if (hole_start != hole_end) {
dst_elms->FillWithHoles(hole_start, hole_end);
}
}
static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
FixedArrayBase* to, ElementsKind from_kind,
uint32_t to_start, int packed_size,
int copy_size) {
DisallowHeapAllocation no_allocation;
switch (from_kind) {
case FAST_SMI_ELEMENTS:
CopyPackedSmiToDoubleElements(from, from_start, to, to_start,
packed_size, copy_size);
break;
case FAST_HOLEY_SMI_ELEMENTS:
CopySmiToDoubleElements(from, from_start, to, to_start, copy_size);
break;
case FAST_DOUBLE_ELEMENTS:
case FAST_HOLEY_DOUBLE_ELEMENTS:
CopyDoubleToDoubleElements(from, from_start, to, to_start, copy_size);
break;
case FAST_ELEMENTS:
case FAST_HOLEY_ELEMENTS:
CopyObjectToDoubleElements(from, from_start, to, to_start, copy_size);
break;
case DICTIONARY_ELEMENTS:
CopyDictionaryToDoubleElements(from, from_start, to, to_start,
copy_size);
break;
case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
UNREACHABLE();
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
case TYPE##_ELEMENTS: \
UNREACHABLE();
TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
}
}
};
class FastPackedDoubleElementsAccessor
: public FastDoubleElementsAccessor<
FastPackedDoubleElementsAccessor,
ElementsKindTraits<FAST_DOUBLE_ELEMENTS> > {
public:
explicit FastPackedDoubleElementsAccessor(const char* name)
: FastDoubleElementsAccessor<
FastPackedDoubleElementsAccessor,
ElementsKindTraits<FAST_DOUBLE_ELEMENTS> >(name) {}
};
class FastHoleyDoubleElementsAccessor
: public FastDoubleElementsAccessor<
FastHoleyDoubleElementsAccessor,
ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> > {
public:
explicit FastHoleyDoubleElementsAccessor(const char* name)
: FastDoubleElementsAccessor<
FastHoleyDoubleElementsAccessor,
ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> >(name) {}
};
// Super class for all external element arrays.
template<ElementsKind Kind>
class TypedElementsAccessor
: public ElementsAccessorBase<TypedElementsAccessor<Kind>,
ElementsKindTraits<Kind> > {
public:
explicit TypedElementsAccessor(const char* name)
: ElementsAccessorBase<AccessorClass,
ElementsKindTraits<Kind> >(name) {}
typedef typename ElementsKindTraits<Kind>::BackingStore BackingStore;
typedef TypedElementsAccessor<Kind> AccessorClass;
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value) {
BackingStore::cast(backing_store)->SetValue(entry, value);
}
static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value, WriteBarrierMode mode) {
BackingStore::cast(backing_store)->SetValue(entry, value);
}
static Handle<Object> GetImpl(Handle<FixedArrayBase> backing_store,
uint32_t entry) {
uint32_t index = GetIndexForEntryImpl(*backing_store, entry);
return BackingStore::get(Handle<BackingStore>::cast(backing_store), index);
}
static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
uint32_t entry) {
return PropertyDetails(DONT_DELETE, DATA, 0, PropertyCellType::kNoCell);
}
static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
uint32_t length,
Handle<FixedArrayBase> backing_store) {
// External arrays do not support changing their length.
UNREACHABLE();
}
static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
UNREACHABLE();
}
static uint32_t GetIndexForEntryImpl(FixedArrayBase* backing_store,
uint32_t entry) {
return entry;
}
static uint32_t GetEntryForIndexImpl(JSObject* holder,
FixedArrayBase* backing_store,
uint32_t index,
PropertyAttributes filter) {
return index < AccessorClass::GetCapacityImpl(holder, backing_store)
? index
: kMaxUInt32;
}
static uint32_t GetCapacityImpl(JSObject* holder,
FixedArrayBase* backing_store) {
JSArrayBufferView* view = JSArrayBufferView::cast(holder);
if (view->WasNeutered()) return 0;
return backing_store->length();
}
};
#define FIXED_ELEMENTS_ACCESSOR(Type, type, TYPE, ctype, size) \
typedef TypedElementsAccessor<TYPE##_ELEMENTS > \
Fixed##Type##ElementsAccessor;
TYPED_ARRAYS(FIXED_ELEMENTS_ACCESSOR)
#undef FIXED_ELEMENTS_ACCESSOR
template <typename SloppyArgumentsElementsAccessorSubclass,
typename ArgumentsAccessor, typename KindTraits>
class SloppyArgumentsElementsAccessor
: public ElementsAccessorBase<SloppyArgumentsElementsAccessorSubclass,
KindTraits> {
public:
explicit SloppyArgumentsElementsAccessor(const char* name)
: ElementsAccessorBase<SloppyArgumentsElementsAccessorSubclass,
KindTraits>(name) {
USE(KindTraits::Kind);
}
static Handle<Object> GetImpl(Handle<FixedArrayBase> parameters,
uint32_t entry) {
Isolate* isolate = parameters->GetIsolate();
Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(parameters);
uint32_t length = parameter_map->length() - 2;
if (entry < length) {
DisallowHeapAllocation no_gc;
Object* probe = parameter_map->get(entry + 2);
Context* context = Context::cast(parameter_map->get(0));
int context_entry = Smi::cast(probe)->value();
DCHECK(!context->get(context_entry)->IsTheHole());
return handle(context->get(context_entry), isolate);
} else {
// Object is not mapped, defer to the arguments.
Handle<FixedArray> arguments(FixedArray::cast(parameter_map->get(1)),
isolate);
Handle<Object> result =
ArgumentsAccessor::GetImpl(arguments, entry - length);
// Elements of the arguments object in slow mode might be slow aliases.
if (result->IsAliasedArgumentsEntry()) {
DisallowHeapAllocation no_gc;
AliasedArgumentsEntry* alias = AliasedArgumentsEntry::cast(*result);
Context* context = Context::cast(parameter_map->get(0));
int context_entry = alias->aliased_context_slot();
DCHECK(!context->get(context_entry)->IsTheHole());
return handle(context->get(context_entry), isolate);
}
return result;
}
}
static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
uint32_t capacity) {
UNREACHABLE();
}
static inline void SetImpl(FixedArrayBase* store, uint32_t entry,
Object* value) {
FixedArray* parameter_map = FixedArray::cast(store);
uint32_t length = parameter_map->length() - 2;
if (entry < length) {
Object* probe = parameter_map->get(entry + 2);
Context* context = Context::cast(parameter_map->get(0));
int context_entry = Smi::cast(probe)->value();
DCHECK(!context->get(context_entry)->IsTheHole());
context->set(context_entry, value);
} else {
FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
Object* current = ArgumentsAccessor::GetRaw(arguments, entry - length);
if (current->IsAliasedArgumentsEntry()) {
AliasedArgumentsEntry* alias = AliasedArgumentsEntry::cast(current);
Context* context = Context::cast(parameter_map->get(0));
int context_entry = alias->aliased_context_slot();
DCHECK(!context->get(context_entry)->IsTheHole());
context->set(context_entry, value);
} else {
ArgumentsAccessor::SetImpl(arguments, entry - length, value);
}
}
}
static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
uint32_t length,
Handle<FixedArrayBase> parameter_map) {
// Sloppy arguments objects are not arrays.
UNREACHABLE();
}
static uint32_t GetCapacityImpl(JSObject* holder,
FixedArrayBase* backing_store) {
FixedArray* parameter_map = FixedArray::cast(backing_store);
FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
return parameter_map->length() - 2 +
ArgumentsAccessor::GetCapacityImpl(holder, arguments);
}
static bool HasEntryImpl(FixedArrayBase* parameters, uint32_t entry) {
FixedArray* parameter_map = FixedArray::cast(parameters);
uint32_t length = parameter_map->length() - 2;
if (entry < length) {
return !GetParameterMapArg(parameter_map, entry)->IsTheHole();
}
FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
return ArgumentsAccessor::HasEntryImpl(arguments, entry - length);
}
static uint32_t GetIndexForEntryImpl(FixedArrayBase* parameters,
uint32_t entry) {
FixedArray* parameter_map = FixedArray::cast(parameters);
uint32_t length = parameter_map->length() - 2;
if (entry < length) return entry;
FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
return ArgumentsAccessor::GetIndexForEntryImpl(arguments, entry - length);
}
static uint32_t GetEntryForIndexImpl(JSObject* holder,
FixedArrayBase* parameters,
uint32_t index,
PropertyAttributes filter) {
FixedArray* parameter_map = FixedArray::cast(parameters);
Object* probe = GetParameterMapArg(parameter_map, index);
if (!probe->IsTheHole()) return index;
FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
uint32_t entry = ArgumentsAccessor::GetEntryForIndexImpl(holder, arguments,
index, filter);
if (entry == kMaxUInt32) return entry;
return (parameter_map->length() - 2) + entry;
}
static PropertyDetails GetDetailsImpl(FixedArrayBase* parameters,
uint32_t entry) {
FixedArray* parameter_map = FixedArray::cast(parameters);
uint32_t length = parameter_map->length() - 2;
if (entry < length) {
return PropertyDetails(NONE, DATA, 0, PropertyCellType::kNoCell);
}
FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
return ArgumentsAccessor::GetDetailsImpl(arguments, entry - length);
}
static Object* GetParameterMapArg(FixedArray* parameter_map, uint32_t index) {
uint32_t length = parameter_map->length() - 2;
return index < length
? parameter_map->get(index + 2)
: Object::cast(parameter_map->GetHeap()->the_hole_value());
}
static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
FixedArray* parameter_map = FixedArray::cast(obj->elements());
uint32_t length = static_cast<uint32_t>(parameter_map->length()) - 2;
if (entry < length) {
// TODO(kmillikin): We could check if this was the last aliased
// parameter, and revert to normal elements in that case. That
// would enable GC of the context.
parameter_map->set_the_hole(entry + 2);
} else {
SloppyArgumentsElementsAccessorSubclass::DeleteFromArguments(
obj, entry - length);
}
}
};
class SlowSloppyArgumentsElementsAccessor
: public SloppyArgumentsElementsAccessor<
SlowSloppyArgumentsElementsAccessor, DictionaryElementsAccessor,
ElementsKindTraits<SLOW_SLOPPY_ARGUMENTS_ELEMENTS> > {
public:
explicit SlowSloppyArgumentsElementsAccessor(const char* name)
: SloppyArgumentsElementsAccessor<
SlowSloppyArgumentsElementsAccessor, DictionaryElementsAccessor,
ElementsKindTraits<SLOW_SLOPPY_ARGUMENTS_ELEMENTS> >(name) {}
static void DeleteFromArguments(Handle<JSObject> obj, uint32_t entry) {
Handle<FixedArray> parameter_map(FixedArray::cast(obj->elements()));
Handle<SeededNumberDictionary> dict(
SeededNumberDictionary::cast(parameter_map->get(1)));
// TODO(verwaest): Remove reliance on index in Shrink.
uint32_t index = GetIndexForEntryImpl(*dict, entry);
Handle<Object> result = SeededNumberDictionary::DeleteProperty(dict, entry);
USE(result);
DCHECK(result->IsTrue());
Handle<FixedArray> new_elements =
SeededNumberDictionary::Shrink(dict, index);
parameter_map->set(1, *new_elements);
}
static void AddImpl(Handle<JSObject> object, uint32_t index,
Handle<Object> value, PropertyAttributes attributes,
uint32_t new_capacity) {
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()));
Handle<FixedArrayBase> old_elements(
FixedArrayBase::cast(parameter_map->get(1)));
Handle<SeededNumberDictionary> dictionary =
old_elements->IsSeededNumberDictionary()
? Handle<SeededNumberDictionary>::cast(old_elements)
: JSObject::NormalizeElements(object);
PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
Handle<SeededNumberDictionary> new_dictionary =
SeededNumberDictionary::AddNumberEntry(
dictionary, index, value, details,
object->map()->is_prototype_map());
if (attributes != NONE) object->RequireSlowElements(*new_dictionary);
if (*dictionary != *new_dictionary) {
FixedArray::cast(object->elements())->set(1, *new_dictionary);
}
}
static void ReconfigureImpl(Handle<JSObject> object,
Handle<FixedArrayBase> store, uint32_t entry,
Handle<Object> value,
PropertyAttributes attributes) {
Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(store);
uint32_t length = parameter_map->length() - 2;
if (entry < length) {
Object* probe = parameter_map->get(entry + 2);
DCHECK(!probe->IsTheHole());
Context* context = Context::cast(parameter_map->get(0));
int context_entry = Smi::cast(probe)->value();
DCHECK(!context->get(context_entry)->IsTheHole());
context->set(context_entry, *value);
// Redefining attributes of an aliased element destroys fast aliasing.
parameter_map->set_the_hole(entry + 2);
// For elements that are still writable we re-establish slow aliasing.
if ((attributes & READ_ONLY) == 0) {
Isolate* isolate = store->GetIsolate();
value = isolate->factory()->NewAliasedArgumentsEntry(context_entry);
}
PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
Handle<SeededNumberDictionary> arguments(
SeededNumberDictionary::cast(parameter_map->get(1)));
arguments = SeededNumberDictionary::AddNumberEntry(
arguments, entry, value, details, object->map()->is_prototype_map());
// If the attributes were NONE, we would have called set rather than
// reconfigure.
DCHECK_NE(NONE, attributes);
object->RequireSlowElements(*arguments);
parameter_map->set(1, *arguments);
} else {
Handle<FixedArrayBase> arguments(
FixedArrayBase::cast(parameter_map->get(1)));
DictionaryElementsAccessor::ReconfigureImpl(
object, arguments, entry - length, value, attributes);
}
}
};
class FastSloppyArgumentsElementsAccessor
: public SloppyArgumentsElementsAccessor<
FastSloppyArgumentsElementsAccessor, FastHoleyObjectElementsAccessor,
ElementsKindTraits<FAST_SLOPPY_ARGUMENTS_ELEMENTS> > {
public:
explicit FastSloppyArgumentsElementsAccessor(const char* name)
: SloppyArgumentsElementsAccessor<
FastSloppyArgumentsElementsAccessor,
FastHoleyObjectElementsAccessor,
ElementsKindTraits<FAST_SLOPPY_ARGUMENTS_ELEMENTS> >(name) {}
static void DeleteFromArguments(Handle<JSObject> obj, uint32_t entry) {
FixedArray* parameter_map = FixedArray::cast(obj->elements());
Handle<FixedArray> arguments(FixedArray::cast(parameter_map->get(1)));
FastHoleyObjectElementsAccessor::DeleteCommon(obj, entry, arguments);
}
static void AddImpl(Handle<JSObject> object, uint32_t index,
Handle<Object> value, PropertyAttributes attributes,
uint32_t new_capacity) {
DCHECK_EQ(NONE, attributes);
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()));
Handle<FixedArrayBase> old_elements(
FixedArrayBase::cast(parameter_map->get(1)));
if (old_elements->IsSeededNumberDictionary() ||
static_cast<uint32_t>(old_elements->length()) < new_capacity) {
GrowCapacityAndConvertImpl(object, new_capacity);
}
FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
// For fast holey objects, the entry equals the index. The code above made
// sure that there's enough space to store the value. We cannot convert
// index to entry explicitly since the slot still contains the hole, so the
// current EntryForIndex would indicate that it is "absent" by returning
// kMaxUInt32.
FastHoleyObjectElementsAccessor::SetImpl(arguments, index, *value);
}
static void ReconfigureImpl(Handle<JSObject> object,
Handle<FixedArrayBase> store, uint32_t entry,
Handle<Object> value,
PropertyAttributes attributes) {
Handle<SeededNumberDictionary> dictionary =
JSObject::NormalizeElements(object);
FixedArray::cast(*store)->set(1, *dictionary);
uint32_t length = static_cast<uint32_t>(store->length()) - 2;
if (entry >= length) {
entry = dictionary->FindEntry(entry - length) + length;
}
SlowSloppyArgumentsElementsAccessor::ReconfigureImpl(object, store, entry,
value, attributes);
}
static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
FixedArrayBase* to, ElementsKind from_kind,
uint32_t to_start, int packed_size,
int copy_size) {
DCHECK(!to->IsDictionary());
if (from_kind == SLOW_SLOPPY_ARGUMENTS_ELEMENTS) {
CopyDictionaryToObjectElements(from, from_start, to, FAST_HOLEY_ELEMENTS,
to_start, copy_size);
} else {
DCHECK_EQ(FAST_SLOPPY_ARGUMENTS_ELEMENTS, from_kind);
CopyObjectToObjectElements(from, FAST_HOLEY_ELEMENTS, from_start, to,
FAST_HOLEY_ELEMENTS, to_start, copy_size);
}
}
static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
uint32_t capacity) {
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()));
Handle<FixedArray> old_elements(FixedArray::cast(parameter_map->get(1)));
ElementsKind from_kind = object->GetElementsKind();
// This method should only be called if there's a reason to update the
// elements.
DCHECK(from_kind == SLOW_SLOPPY_ARGUMENTS_ELEMENTS ||
static_cast<uint32_t>(old_elements->length()) < capacity);
Handle<FixedArrayBase> elements =
ConvertElementsWithCapacity(object, old_elements, from_kind, capacity);
Handle<Map> new_map = JSObject::GetElementsTransitionMap(
object, FAST_SLOPPY_ARGUMENTS_ELEMENTS);
JSObject::MigrateToMap(object, new_map);
parameter_map->set(1, *elements);
JSObject::ValidateElements(object);
}
};
} // namespace
void CheckArrayAbuse(Handle<JSObject> obj, const char* op, uint32_t index,
bool allow_appending) {
DisallowHeapAllocation no_allocation;
Object* raw_length = NULL;
const char* elements_type = "array";
if (obj->IsJSArray()) {
JSArray* array = JSArray::cast(*obj);
raw_length = array->length();
} else {
raw_length = Smi::FromInt(obj->elements()->length());
elements_type = "object";
}
if (raw_length->IsNumber()) {
double n = raw_length->Number();
if (FastI2D(FastD2UI(n)) == n) {
int32_t int32_length = DoubleToInt32(n);
uint32_t compare_length = static_cast<uint32_t>(int32_length);
if (allow_appending) compare_length++;
if (index >= compare_length) {
PrintF("[OOB %s %s (%s length = %d, element accessed = %d) in ",
elements_type, op, elements_type, static_cast<int>(int32_length),
static_cast<int>(index));
TraceTopFrame(obj->GetIsolate());
PrintF("]\n");
}
} else {
PrintF("[%s elements length not integer value in ", elements_type);
TraceTopFrame(obj->GetIsolate());
PrintF("]\n");
}
} else {
PrintF("[%s elements length not a number in ", elements_type);
TraceTopFrame(obj->GetIsolate());
PrintF("]\n");
}
}
MaybeHandle<Object> ArrayConstructInitializeElements(Handle<JSArray> array,
Arguments* args) {
if (args->length() == 0) {
// Optimize the case where there are no parameters passed.
JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
return array;
} else if (args->length() == 1 && args->at<Object>(0)->IsNumber()) {
uint32_t length;
if (!args->at<Object>(0)->ToArrayLength(&length)) {
return ThrowArrayLengthRangeError(array->GetIsolate());
}
// Optimize the case where there is one argument and the argument is a small
// smi.
if (length > 0 && length < JSArray::kInitialMaxFastElementArray) {
ElementsKind elements_kind = array->GetElementsKind();
JSArray::Initialize(array, length, length);
if (!IsFastHoleyElementsKind(elements_kind)) {
elements_kind = GetHoleyElementsKind(elements_kind);
JSObject::TransitionElementsKind(array, elements_kind);
}
} else if (length == 0) {
JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
} else {
// Take the argument as the length.
JSArray::Initialize(array, 0);
JSArray::SetLength(array, length);
}
return array;
}
Factory* factory = array->GetIsolate()->factory();
// Set length and elements on the array.
int number_of_elements = args->length();
JSObject::EnsureCanContainElements(
array, args, 0, number_of_elements, ALLOW_CONVERTED_DOUBLE_ELEMENTS);
// Allocate an appropriately typed elements array.
ElementsKind elements_kind = array->GetElementsKind();
Handle<FixedArrayBase> elms;
if (IsFastDoubleElementsKind(elements_kind)) {
elms = Handle<FixedArrayBase>::cast(
factory->NewFixedDoubleArray(number_of_elements));
} else {
elms = Handle<FixedArrayBase>::cast(
factory->NewFixedArrayWithHoles(number_of_elements));
}
// Fill in the content
switch (array->GetElementsKind()) {
case FAST_HOLEY_SMI_ELEMENTS:
case FAST_SMI_ELEMENTS: {
Handle<FixedArray> smi_elms = Handle<FixedArray>::cast(elms);
for (int entry = 0; entry < number_of_elements; entry++) {
smi_elms->set(entry, (*args)[entry], SKIP_WRITE_BARRIER);
}
break;
}
case FAST_HOLEY_ELEMENTS:
case FAST_ELEMENTS: {
DisallowHeapAllocation no_gc;
WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
Handle<FixedArray> object_elms = Handle<FixedArray>::cast(elms);
for (int entry = 0; entry < number_of_elements; entry++) {
object_elms->set(entry, (*args)[entry], mode);
}
break;
}
case FAST_HOLEY_DOUBLE_ELEMENTS:
case FAST_DOUBLE_ELEMENTS: {
Handle<FixedDoubleArray> double_elms =
Handle<FixedDoubleArray>::cast(elms);
for (int entry = 0; entry < number_of_elements; entry++) {
double_elms->set(entry, (*args)[entry]->Number());
}
break;
}
default:
UNREACHABLE();
break;
}
array->set_elements(*elms);
array->set_length(Smi::FromInt(number_of_elements));
return array;
}
void ElementsAccessor::InitializeOncePerProcess() {
static ElementsAccessor* accessor_array[] = {
#define ACCESSOR_ARRAY(Class, Kind, Store) new Class(#Kind),
ELEMENTS_LIST(ACCESSOR_ARRAY)
#undef ACCESSOR_ARRAY
};
STATIC_ASSERT((sizeof(accessor_array) / sizeof(*accessor_array)) ==
kElementsKindCount);
elements_accessors_ = accessor_array;
}
void ElementsAccessor::TearDown() {
if (elements_accessors_ == NULL) return;
#define ACCESSOR_DELETE(Class, Kind, Store) delete elements_accessors_[Kind];
ELEMENTS_LIST(ACCESSOR_DELETE)
#undef ACCESSOR_DELETE
elements_accessors_ = NULL;
}
Handle<JSArray> ElementsAccessor::Concat(Isolate* isolate, Arguments* args,
uint32_t concat_size) {
int result_len = 0;
ElementsKind elements_kind = GetInitialFastElementsKind();
bool has_double = false;
{
DisallowHeapAllocation no_gc;
// Iterate through all the arguments performing checks
// and calculating total length.
bool is_holey = false;
for (uint32_t i = 0; i < concat_size; i++) {
Object* arg = (*args)[i];
int len = Smi::cast(JSArray::cast(arg)->length())->value();
// We shouldn't overflow when adding another len.
const int kHalfOfMaxInt = 1 << (kBitsPerInt - 2);
STATIC_ASSERT(FixedArray::kMaxLength < kHalfOfMaxInt);
USE(kHalfOfMaxInt);
result_len += len;
DCHECK(0 <= result_len);
DCHECK(result_len <= FixedDoubleArray::kMaxLength);
ElementsKind arg_kind = JSArray::cast(arg)->map()->elements_kind();
has_double = has_double || IsFastDoubleElementsKind(arg_kind);
is_holey = is_holey || IsFastHoleyElementsKind(arg_kind);
elements_kind = GetMoreGeneralElementsKind(elements_kind, arg_kind);
}
if (is_holey) {
elements_kind = GetHoleyElementsKind(elements_kind);
}
}
// If a double array is concatted into a fast elements array, the fast
// elements array needs to be initialized to contain proper holes, since
// boxing doubles may cause incremental marking.
ArrayStorageAllocationMode mode =
has_double && IsFastObjectElementsKind(elements_kind)
? INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
: DONT_INITIALIZE_ARRAY_ELEMENTS;
Handle<JSArray> result_array = isolate->factory()->NewJSArray(
elements_kind, result_len, result_len, Strength::WEAK, mode);
if (result_len == 0) return result_array;
int j = 0;
Handle<FixedArrayBase> storage(result_array->elements(), isolate);
ElementsAccessor* accessor = ElementsAccessor::ForKind(elements_kind);
for (uint32_t i = 0; i < concat_size; i++) {
// It is crucial to keep |array| in a raw pointer form to avoid
// performance degradation.
JSArray* array = JSArray::cast((*args)[i]);
int len = Smi::cast(array->length())->value();
if (len > 0) {
ElementsKind from_kind = array->GetElementsKind();
accessor->CopyElements(array, 0, from_kind, storage, j, len);
j += len;
}
}
DCHECK(j == result_len);
return result_array;
}
ElementsAccessor** ElementsAccessor::elements_accessors_ = NULL;
} // namespace internal
} // namespace v8
| [
"22249030@qq.com"
] | 22249030@qq.com |
7b1656ae65474729beac3df9e1ff1cf19e4d6f7d | aab7eafab5efae62cb06c3a2b6c26fe08eea0137 | /weeeksall/week12oct/doublemisidanalysis/pionpionsample/trynonegpion.cc | 0a9917808c4b783730b1bb43a593f6379e4fad7b | [] | no_license | Sally27/B23MuNu_backup | 397737f58722d40e2a1007649d508834c1acf501 | bad208492559f5820ed8c1899320136406b78037 | refs/heads/master | 2020-04-09T18:12:43.308589 | 2018-12-09T14:16:25 | 2018-12-09T14:16:25 | 160,504,958 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,723 | cc | #include<iostream>
#include<algorithm>
#include "TH1F.h"
#include "TH3F.h"
#include "TCanvas.h"
#include "TFile.h"
#include "TTree.h"
#include "TLorentzVector.h"
#include "TVector3.h"
#include "TBranch.h"
#include "TRandom.h"
#include "TBranch.h"
#include "TString.h"
using namespace std;
class DataSample {
public:
DataSample(std::string filename) : _filename(filename), f(NULL)
{ this->open(); }
~DataSample() { this->close(); }
TString _filename;
TFile *f;
void open();
void close();
};
void DataSample::open()
{
f = new TFile(_filename);
}
void DataSample::close()
{
if (f)
if (f->IsOpen())
f->Close();
delete f;
}
bool myfn(int i, int j) { return i<j; }
struct myclass {
bool operator() (int i,int j) { return i<j; }
} myobj;
void eff()
{
Double_t mu1_P;
Int_t nTracks;
Double_t mu1_ETA;
UInt_t runNumber;
Short_t Polarity;
Double_t newcount [288];
Double_t nTracksArr[5] = {0.0};
Double_t EtaArr[5] = {0.0};
Double_t PArr[19] = {0.0};
EtaArr[0]=1.5;
PArr[0]=3000.0;
PArr[1]=9600.0;
PArr[2]=15600.0;
PArr[3]=19000.0;
nTracksArr[0]=0.0;
nTracksArr[1]=50.0;
nTracksArr[2]=200.0;
nTracksArr[3]=300.0;
nTracksArr[4]=500.0;
const int p = 18;
const int eta = 4;
const int ntracks = 4;
//for(int j(1); j<5; ++j)
// {
// nTracksArr[j] = nTracksArr[j-1] + 50.0;
// cout<<"nTracks: "<<nTracksArr[j]<<endl;
// }
for(int j(1); j<(eta+1); ++j)
{
EtaArr[j] = EtaArr[j-1] + 0.875;
// cout<<"Eta: "<<EtaArr[j]<<endl;
}
for(int j(4); j<(p+1); ++j)
{
PArr[j] = PArr[j-1] + 5400.0;
// cout<<"P: "<<PArr[j]<<endl;
}
/*This is binning that is taken*/
cout<<"P binning: ";
for(int j(0); j<(p+1); ++j)
{
cout<<" "<<PArr[j]<<",";
}
cout<<"."<<endl;
cout<<"Eta binning: ";
for(int j(0); j<(eta+1); ++j)
{
cout<<" "<<EtaArr[j]<<",";
}
cout<<"."<<endl;
cout<<"nTracks Binning: ";
for(int j(0); j<(ntracks+1); ++j)
{
cout<<" "<<nTracksArr[j]<<",";
}
cout<<"."<<endl;
TFile* f = new TFile("doublemisidsmallsamplePionvetoJpsi.root");
TTree* t = (TTree*)f->Get("DecayTree");
t->SetBranchAddress("mu1_P", &mu1_P);
t->SetBranchAddress("mu1_ETA", &mu1_ETA);
t->SetBranchAddress("nTracks", &nTracks);
t->SetBranchAddress("runNumber", &runNumber);
t->SetBranchAddress("Polarity", &Polarity);
Int_t numTracks(0);
Int_t numEta(0);
Int_t numP(0);
const int count = 800000;
Double_t maxParr [count] = {};
Double_t maxEtaarr [count] = {};
Double_t maxnTracksarr [count] = {};
int out0(0);
int out1(0);
int out2(0);
int out3(0);
int out4(0);
int out5(0);
int out6(0);
int out7(0);
int out8(0);
int out9(0);
int out10(0);
int out11(0);
int out12(0);
int out13(0);
int out14(0);
for(int b(0); b < t->GetEntries(); ++b)
{
t->GetEntry(b);
maxParr[b] = mu1_P;
maxEtaarr[b] = mu1_ETA;
maxnTracksarr[b] = nTracks;
if (mu1_P<3000.0)
{
out0++;
if (mu1_ETA<1.5)
{
out5++;
if (nTracks>=500.0)
{
out9++;
}
}
if (mu1_ETA>=5.0)
{
out6++;
if (nTracks>=500.0)
{
out10++;
}
}
if (nTracks>=500.0)
{
out13++;
}
}
if (mu1_P>=100000.0)
{
out1++;
if (mu1_ETA<1.5)
{
out7++;
if (nTracks>=500.0)
{
out11++;
}
}
if (mu1_ETA>=5.0)
{
out8++;
if (nTracks>=500.0)
{
out12++;
}
}
if (nTracks>=500.0)
{
out14++;
}
}
if (mu1_ETA<1.5)
{
out2++;
}
if (mu1_ETA>=5.0)
{
out3++;
}
if (nTracks>=500.0)
{
out4++;
}
}
std::cout << "The smallest element in P is " << *std::min_element(maxParr,maxParr+count) << '\n';
std::cout << "The largest element in P is " << *std::max_element(maxParr,maxParr+count) << '\n';
std::cout << "The smallest element in eta is " << *std::min_element(maxEtaarr,maxEtaarr+count) << '\n';
std::cout << "The largest element in eta is " << *std::max_element(maxEtaarr,maxEtaarr+count) << '\n';
std::cout << "The smallest element in nTracks is " << *std::min_element(maxnTracksarr,maxnTracksarr+count) << '\n';
std::cout << "The largest element in nTracks is " << *std::max_element(maxnTracksarr,maxnTracksarr+count) << '\n';
cout<<"This is number of events with mu1_P < 3000.0: "<<out0<<endl;
cout<<"This is number of evetns with mu1_P >= 100000.0: "<<out1<<endl;
cout<<"This is number of events with mu1_ETA < 1.5 "<<out2<<endl;
cout<<"This is number of events with mu1_ETA >= 5.0: "<<out3<<endl;
cout<<"This is number of events with mu1_nTracks >= 500: "<<out4<<endl;
cout<<"This is number of events with mu1_P<3000.0 and mu1_ETA < 1.5: "<<out5<<endl;
cout<<"This is number of events with mu1_P<3000.0 and mu1_ETA >= 5.0: "<<out6<<endl;
cout<<"This is number of events with mu1_P>=10000.0 and mu1_ETA < 1.5: "<<out7<<endl;
cout<<"This is number of events with mu1_P>=10000.0 and mu1_ETA >= 5.0: "<<out8<<endl;
cout<<"This is number of events with mu1_P<3000.0 and mu1_ETA < 1.5 and ntracks >=500: "<<out9<<endl;
cout<<"This is number of events with mu1_P<3000.0 and mu1_ETA >= 5.0 and ntracks >= 500: "<<out10<<endl;
cout<<"This is number of events with mu1_P>=10000.0 and mu1_ETA < 1.5 and ntracks >= 500: "<<out11<<endl;
cout<<"This is number of events with mu1_P>=10000.0 and mu1_ETA >= 5.0 and ntracks >= 500: "<<out12<<endl;
cout<<"This is number of events with mu1_P<3000.0 and ntracks >= 500: "<<out13<<endl;
cout<<"This is number of events with mu1_P>=10000.0 and ntracks >= 500: "<<out14<<endl;
// maxP =
// maxEta =
maxnTracks = *std::max_element(maxnTracksarr,maxnTracksarr+count);
const int p = 18;
const int eta = 4;
const int ntracks = 4;
Double_t MultiArr [p][eta][ntracks]={0.0,0.0,0.0};
for(int b(0); b < t->GetEntries(); ++b)
{
t->GetEntry(b);
cout<<"Event: "<<b<<" This is mu1_P: "<<mu1_P<<" This is mu1_ETA: "<<mu1_ETA<<" This is nTracks: "<<nTracks<<endl;
// cout<<"This is mu1_P: "<<mu1_P<<endl;
// cout<<"This is mu1_ETA: "<<mu1_ETA<<endl;
// cout<<"This is nTracks: "<<nTracks<<endl;
// cout<<"This is runNumber: "<<runNumber<<endl;
// cout<<"This is Polarity: "<<Polarity<<endl;
for (int i=0; i<p; i++) {
if((mu1_P >= PArr[i]) && (mu1_P < PArr[i+1]))
{
for (int j=0; j<eta; j++) {
if((mu1_ETA >= EtaArr[j]) && (mu1_ETA < EtaArr[j+1]))
{
for (int k=0; k<ntracks; k++) {
if((nTracks >= nTracksArr[k]) && (nTracks < nTracksArr[k+1]))
{
// cout<<"Number of events in the bin before allocation: " << MultiArr[i][j][k] <<endl;
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
// cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
// cout<< "Multiarr: "<< i << " "<< j << " " << k << " :" << MultiArr[i][j][k]<<endl;
}
else
{
if ((k==(ntracks-1)) && (nTracks >= nTracksArr[k+1]))
{
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
cout<<"Special case when ntracks>500 "<<endl;
cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
}
}
}
}
else
{
if ((j==(eta-1)) && (mu1_ETA >= EtaArr[j+1]))
{
for (int k=0; k<ntracks; k++) {
if((nTracks >= nTracksArr[k]) && (nTracks < nTracksArr[k+1]))
{
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
cout<<"Special case when eta>5.0 "<<endl;
cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
}
else
{
if ((k==(ntracks-1)) && (nTracks >= nTracksArr[k+1]))
{
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
cout<<"Special case when ntracks>500 eta>5.0 "<<endl;
cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
}
}
}
}
}
}
}
else{
if ((i==(p-1)) && (mu1_P >= PArr[i+1]))
{
for (int j=0; j<(eta); j++) {
if((mu1_ETA >= EtaArr[j]) && (mu1_ETA < EtaArr[j+1]))
{
for (int k=0; k<ntracks; k++) {
if((nTracks >= nTracksArr[k]) && (nTracks < nTracksArr[k+1]))
{
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
cout<<"Special case when P>100000.0 "<<endl;
cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
}
else
{
if ((k==(ntracks-1)) && (nTracks >= nTracksArr[k+1]))
{
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
cout<<"Special case when ntracks>500 and P>100000.0 "<<endl;
cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
}
}
}
}
else
{
if ((j==(eta-1)) && (mu1_ETA >= EtaArr[j+1]))
{
for (int k=0; k<ntracks; k++) {
if((nTracks >= nTracksArr[k]) && (nTracks < nTracksArr[k+1]))
{
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
cout<<"Special case when P>100000.0 and eta>5.0 "<<endl;
cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
}
else
{
if ((k==(ntracks-1)) && (nTracks >= nTracksArr[k+1]))
{
MultiArr[i][j][k]=MultiArr[i][j][k]+1.0;
cout<<"Special case when P>100000.0 and eta>5.0 and ntracks > 500.0 "<<endl;
cout<<"Allocated to bin: "<< i << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[i][j][k] <<endl;
}
}
}
}
}
}
}
if ((i==(p-1)) && (mu1_P < PArr[0]))
{
for (int j=0; j<eta; j++) {
if((mu1_ETA >= EtaArr[j]) && (mu1_ETA < EtaArr[j+1]))
{
for (int k=0; k<ntracks; k++) {
if((nTracks >= nTracksArr[k]) && (nTracks < nTracksArr[k+1]))
{
cout<< "Multiarr i before: "<< i << " "<< j << " " << k << " :" << MultiArr[i][j][k]<<endl;
cout<< "Multiarr 0 before: "<< "0" << " "<< j << " " << k << " :" << MultiArr[0][j][k]<<endl;
MultiArr[0][j][k]=MultiArr[0][j][k]+1.0;
cout<<"Special case when P<3000.0 "<< endl;
cout<<"Allocated to bin: "<< "0" << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[0][j][k] <<endl;
}
else
{
if ((k==(ntracks-1)) && (nTracks >= nTracksArr[k+1]))
{
MultiArr[0][j][k]=MultiArr[0][j][k]+1.0;
cout<<"Special case when P<3000.0 and ntracks>500 "<<endl;
cout<<"Allocated to bin: "<< "0" << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[0][j][k] <<endl;
}
}
}
}
else
{
if ((j==(eta-1)) && (mu1_ETA >= EtaArr[j+1]))
{
for (int k=0; k<ntracks; k++) {
if((nTracks >= nTracksArr[k]) && (nTracks < nTracksArr[k+1]))
{
MultiArr[0][j][k]=MultiArr[0][j][k]+1.0;
cout<<"Special case when P<3000.0 and eta>5.0 "<<endl;
cout<<"Allocated to bin: "<< "0" << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[0][j][k] <<endl;
}
else
{
if ((k==(ntracks-1)) && (nTracks >= nTracksArr[k+1]))
{
MultiArr[0][j][k]=MultiArr[0][j][k]+1.0;
cout<<"Special case when P<3000.0 and ntracks>500 and eta>5.0 "<<endl;
cout<<"Allocated to bin: "<< "0" << " "<< j << " " << k << " . Number of events in this bin" << MultiArr[0][j][k] <<endl;
}
}
}
}
}
}
}
}
}
}
const int numofbins = p*eta*ntracks;
// TFile s("KisMuonDLLmumorethanzeroDLLmuminusKmorethanzero/PerfHists_K_Strip20_MagDown_P_ETA_nTracks.root");
// TH3F *hname =(TH3F*)s.Get("K_(IsMuon==1.0) && (DLLmu > 0.0) && ((DLLmu - DLLK) > 0.0)_All");
TFile s("../../../week20july/PIDefficiencies/newpidsample/PisMuonDLLmumorethanzeroDLLmuminusKmorethanzero/PerfHists_Pi_Strip20_MagDown_P_ETA_nTracks.root");
TH3F *hname =(TH3F*)s.Get("Pi_(IsMuon==1.0) && (DLLmu > 0.0) && ((DLLmu - DLLK) > 0.0)_All");
Double_t effi [numofbins];
Double_t myaverage(0);
Int_t z(0);
for (int i=1; i<(p+1); i++) {
for (int j=1; j<(eta+1); j++) {
for (int k=1; k<(ntracks+1); k++) {
effi[z] = hname->GetBinContent(i,j,k);
cout<<" Efficiency: " << effi[z] << " in a bin i , j , k:" << i << " " << j << " "<< k << " "<< endl;
myaverage+=effi[z];
if (effi[z]<0)
{
cout<<"Alarm!!!!: efficiency: "<< effi[z] <<endl;
effi[z]=0.0000001;
cout<<"Changed efficiency: "<< effi[z] << endl;
}
z++;
}
}
}
Double_t average;
average = (myaverage/numofbins);
cout<<"This is the average efficiency of the mis-id sample:"<<average<<endl;
// TFile s2("KisnotMuonDLLKmorethanzeroDLLpKlessthanfive/PerfHists_K_Strip20_MagDown_P_ETA_nTracks.root");
// TH3F *hname2 =(TH3F*)s2.Get("K_IsMuon==0.0 && DLLK > 0.0 && DLLpK < 5.0_All");
TFile s2("../../../week20july/PIDefficiencies/PisnotMuonDLLKlessthanzeroDLLplessthanfive/PerfHists_Pi_Strip20_MagDown_P_ETA_nTracks.root");
TH3F *hname2 =(TH3F*)s2.Get("Pi_IsMuon==0.0 && DLLK < 0.0 && DLLp < 5.0_All");
Double_t effi2 [numofbins];
Double_t myaverage2(0);
Int_t z2(0);
for (int i=1; i<(p+1); i++) {
for (int j=1; j<(eta+1); j++) {
for (int k=1; k<(ntracks+1); k++) {
effi2[z2] = hname2->GetBinContent(i,j,k);
cout<<" Efficiency: " << effi2[z2] << " in a bin i , j , k:" << i << " " << j << " "<< k << " "<< endl;
myaverage2+=effi2[z2];
if (effi2[z2]<0)
{
cout<<"Alarm!!!!: efficiency: "<< effi2[z2] <<endl;
effi2[z2]=0.0000001;
cout<<"Changed efficiency: "<< effi2[z2] << endl;
}
z2++;
}
}
}
Double_t average2;
average2 = (myaverage2/numofbins);
cout<<"This is the average efficiency of the id sample:"<<average2<<endl;
Int_t c=0;
for (int i=0; i<p; i++) {
for (int j=0; j<eta; j++) {
for (int k=0; k<ntracks; k++) {
newcount[c]=MultiArr[i][j][k];
c++;
// cout<<MultiArr[i][j][k]<< " "<< newcount[c-1]<<endl;
}
}
}
cout << effi[0] << " eff0" << endl;
cout << effi[1] << "eff1" << endl;
cout << effi[5] << "eff5" << endl;
cout << effi[287] << " eff 287" << endl;
cout << effi[288] << " eff 288" << endl;
cout << average << " my final average " << endl;
Double_t myeff(0);
Double_t finalmyeff(0);
Double_t accumulate(0);
Double_t myeff2(0);
Double_t finalmyeff2(0);
Double_t accumulate2(0);
Double_t newcount2(0);
for (int g=0; g<numofbins; g++)
{
finalmyeff = finalmyeff + (newcount[g]*double(effi[g]));
accumulate += newcount[g];
myeff = finalmyeff/accumulate;
cout<< " Number of events expected: " << finalmyeff << " Average cummulated efficiency: " << myeff << " Number of events in a given bin: " << newcount[g] << " Efficiency in a given bin: " << effi[g] << " Num of events processed: " << accumulate << " " <<endl;
}
for (int h=0; h<numofbins; h++)
{
finalmyeff2 = finalmyeff2 + ((newcount[h]*double(effi[h]))/double(effi2[h]));
accumulate2 += newcount[h];
myeff2 = finalmyeff2/accumulate2;
cout<< " Number of events expected: " << finalmyeff2 << " Average cummulated efficiency: " << myeff2 << " Number of events in a given bin: " << newcount[h] << " Efficiency in a given bin: " << effi2[h] << " Num of events processed: " << accumulate2 << " " <<endl;
}
TCanvas* m3p = new TCanvas("m3p", "m3p", 600, 600);
hname->Draw();
m3p->SaveAs("test.pdf");
delete m3p;
return;
}
| [
"ss4314@ss4314-laptop.hep.ph.ic.ac.uk"
] | ss4314@ss4314-laptop.hep.ph.ic.ac.uk |
babcbebe04135d534812880f8e2b0db8bbfd19d2 | 8380b5eb12e24692e97480bfa8939a199d067bce | /Carberp Botnet/source - absource/pro/all source/BlackJoeWhiteJoe/include/rdf/nsIRDFInMemoryDataSource.h | 56b187b116d2696c167d0401c28bd3f20056f8e2 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | RamadhanAmizudin/malware | 788ee745b5bb23b980005c2af08f6cb8763981c2 | 62d0035db6bc9aa279b7c60250d439825ae65e41 | refs/heads/master | 2023-02-05T13:37:18.909646 | 2023-01-26T08:43:18 | 2023-01-26T08:43:18 | 53,407,812 | 873 | 291 | null | 2023-01-26T08:43:19 | 2016-03-08T11:44:21 | C++ | UTF-8 | C++ | false | false | 3,039 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/rdf/base/idl/nsIRDFInMemoryDataSource.idl
*/
#ifndef __gen_nsIRDFInMemoryDataSource_h__
#define __gen_nsIRDFInMemoryDataSource_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
#ifndef __gen_nsIRDFResource_h__
#include "nsIRDFResource.h"
#endif
#ifndef __gen_nsIRDFNode_h__
#include "nsIRDFNode.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIRDFInMemoryDataSource */
#define NS_IRDFINMEMORYDATASOURCE_IID_STR "17c4e0aa-1dd2-11b2-8029-bf6f668de500"
#define NS_IRDFINMEMORYDATASOURCE_IID \
{0x17c4e0aa, 0x1dd2, 0x11b2, \
{ 0x80, 0x29, 0xbf, 0x6f, 0x66, 0x8d, 0xe5, 0x00 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIRDFInMemoryDataSource : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IRDFINMEMORYDATASOURCE_IID)
/* void EnsureFastContainment (in nsIRDFResource aSource); */
NS_SCRIPTABLE NS_IMETHOD EnsureFastContainment(nsIRDFResource *aSource) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIRDFInMemoryDataSource, NS_IRDFINMEMORYDATASOURCE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIRDFINMEMORYDATASOURCE \
NS_SCRIPTABLE NS_IMETHOD EnsureFastContainment(nsIRDFResource *aSource);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIRDFINMEMORYDATASOURCE(_to) \
NS_SCRIPTABLE NS_IMETHOD EnsureFastContainment(nsIRDFResource *aSource) { return _to EnsureFastContainment(aSource); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIRDFINMEMORYDATASOURCE(_to) \
NS_SCRIPTABLE NS_IMETHOD EnsureFastContainment(nsIRDFResource *aSource) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnsureFastContainment(aSource); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsRDFInMemoryDataSource : public nsIRDFInMemoryDataSource
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIRDFINMEMORYDATASOURCE
nsRDFInMemoryDataSource();
private:
~nsRDFInMemoryDataSource();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsRDFInMemoryDataSource, nsIRDFInMemoryDataSource)
nsRDFInMemoryDataSource::nsRDFInMemoryDataSource()
{
/* member initializers and constructor code */
}
nsRDFInMemoryDataSource::~nsRDFInMemoryDataSource()
{
/* destructor code */
}
/* void EnsureFastContainment (in nsIRDFResource aSource); */
NS_IMETHODIMP nsRDFInMemoryDataSource::EnsureFastContainment(nsIRDFResource *aSource)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIRDFInMemoryDataSource_h__ */
| [
"fdiskyou@users.noreply.github.com"
] | fdiskyou@users.noreply.github.com |
ffef25e449d6f600551748b4342ae34db88e26ca | 782014bdfa4c2ccc3497bddf1c36a529a131e064 | /Report/17-09-14_SpecBasedTesting/21360040/Practice/StateTransitionTest/testframework/swut/swut_main.cpp | b27fcbb5162124604cfc095d2e8e1668e6fff61c | [] | no_license | kwonyulchoi/yc_2017_swtesting | 0106409b3dbb6f9f0d13bb93d96ab07463304612 | ac589aa4f0d844f7102a95867587916eff55401d | refs/heads/master | 2021-01-21T00:05:41.072312 | 2017-11-09T08:09:40 | 2017-11-09T08:09:40 | 101,859,626 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,434 | cpp | #include <gtest/gtest.h>
#include "libmodule.h"
#include "fsm.h"
#include "fsm_turnsteel.h"
// 스테이트 생성
// 잠김상태 ; state_locked
State state_locked(&on_locked_enter, &on_locked_exit);
// 풀림상태 ; state_unlocked
State state_unlocked(&on_unlocked_enter, &on_unlocked_exit);
class FSMTest : public testing::Test {
protected:
virtual void SetUp() {
// Init stuff
// 상태기계를 생성한다 ; 시작 상태는 state_locked - 잠김상태
m_pFsm= new Fsm(&state_locked);
// 상태 전이를 추가한다
// 잠김상태에서 EVT_COIN(동전삽입) 이벤트 발생하면
// 풀림상태로 전이하고 전이함수 on_trans_locked_unlocked 호출
m_pFsm->add_transition(&state_locked, &state_unlocked,
EVT_COIN,
&on_trans_locked_unlocked,NULL);
// 풀림상태에서 EVT_PUSH(밀기) 이벤트 발생하면
// 잠김상태로 전이하고 전이함수 on_trans_unlocked_locked 호출
m_pFsm->add_transition(&state_unlocked, &state_locked,
EVT_PUSH,
&on_trans_unlocked_locked,NULL);
}
virtual void TearDown() {
// Uninit stuff
delete m_pFsm;
m_pFsm = NULL;
}
Fsm* m_pFsm;
};
TEST_F(FSMTest, state_coverage_00) {
// 현재 상태 확인 --> 잠김상태
EXPECT_EQ(&state_locked,m_pFsm->get_CurState());
// 동전삽입 발생 시키기
m_pFsm->trigger(EVT_COIN,(void*)NULL);
// 현재 상태 확인 --> 풀림상태
EXPECT_EQ(&state_unlocked,m_pFsm->get_CurState());
// 밀기 이벤트 발생 시키기
m_pFsm->trigger(EVT_PUSH,(void*)NULL);
// 현재 상태 확인 --> 잠김상태
EXPECT_EQ(&state_locked,m_pFsm->get_CurState());
}
TEST_F(FSMTest, state_transition_coverage_00) {
// Write Here
// 복사했음
//////////////////////////////////////////////////////////////////////////////
// 현재 상태 확인 --> 잠김상태
EXPECT_EQ(&state_locked,m_pFsm->get_CurState());
// locked 밀기 이벤트를 발생시켰지만 그래도 locked 인지 검증
// 밀기 이벤트 발생 시키기
m_pFsm->trigger(EVT_PUSH,(void*)NULL);
//////////////////////////////////////////////////////////////////////////////
// 동전삽입 발생 시키기
m_pFsm->trigger(EVT_COIN,(void*)NULL);
// 현재 상태 확인 --> 풀림상태
EXPECT_EQ(&state_unlocked,m_pFsm->get_CurState());
// 일부러 에러 발생 시켜본다
// 현재 상태 확인 --> 풀림상태
//EXPECT_EQ(&state_locked,m_pFsm->get_CurState());
//////////////////////////////////////////////////////////////////////////////
// 풀림 상태에서 동전삽입 발생 시키기
m_pFsm->trigger(EVT_COIN,(void*)NULL);
// 현재 상태 확인 --> 풀림상태
EXPECT_EQ(&state_unlocked,m_pFsm->get_CurState());
///////////////////////////////////////////////////////////////////////////////
// 밀기 이벤트 발생 시키기
m_pFsm->trigger(EVT_PUSH,(void*)NULL);
// 현재 상태 확인 --> 잠김상태
EXPECT_EQ(&state_locked,m_pFsm->get_CurState());
}
int main(int argc, char *argv[])
{
char bus_addr[1024] ={ 0 , };
char cmd[2048] ={ 0 , };
int custom_argc=2;
char* pArgv[2];
char* pCmd1 =(char*)"--gtest_output=xml:swut_report.xml";
pArgv[1] = pCmd1;
::testing::InitGoogleTest(&custom_argc,(char**)pArgv);
return RUN_ALL_TESTS();
}
| [
"jk620815@gmail.com"
] | jk620815@gmail.com |
cfa0f973a3bb30730569fc7e2accbf4aa5be729e | 2e33d336e376c5013842ab16350a73df3e4da39c | /src/trophic_chains.cpp | 6d97ec958157f5f62f90885981d46db107c928f8 | [] | no_license | dsfernandez/cheddar | d0ceb6229278b50bc03a264e4815d740aba7d12e | f9090d4df4df10fc1a64fc8c995668c432474bf4 | refs/heads/master | 2021-04-15T05:09:32.210059 | 2017-04-21T14:25:39 | 2017-04-21T14:25:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,574 | cpp | // visit unique chains in food webs.
#include <R.h>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include "cheddar_exception.h"
typedef std::vector<int> IntVector;
// Define DEBUG_TC to get lots of debug output
//#define DEBUG_TC
#ifdef DEBUG_TC
#define DEBUG(X) { X; }
#else
#define DEBUG(X)
#endif
std::vector<IntVector> Adjacency(const int *adjacency, int node_count)
{
// Returns a C++ representation of the adjacency list in R matrix form
std::vector<IntVector> adj;
for(int node=0; node<node_count; ++node)
{
IntVector l;
const int len = adjacency[node];
for(int v=1; v<=len; ++v)
{
l.push_back(adjacency[node + v*node_count]);
}
adj.push_back(l);
}
return (adj);
}
template <typename Visitor> class TrophicChains
{
// Enumerates every unique chain in a food web, using a breadth-first search.
// A visitor is shown each unique chain. Visitors must implement a method:
// void chain(const IntVector &);
// Algorithm and first implemention by Rob Emerson.
// Converted to use C++ and integrated into R by Lawrence Hudson.
// TODO Stop when queue larger than a threshold
// TODO Respect CTRL+C
private:
const std::vector<IntVector> &adjacency_;
const IntVector &is_basal_;
typedef std::queue<IntVector> Queue;
Queue::size_type max_queue_;
private:
#ifdef DEBUG_TC
void print_adjacency() const
{
for(int i=0; i<adjacency_.size(); ++i)
{
Rprintf("[%d] has [%d] consumers ->", i, adjacency_[i].size());
for(int j=0; j<adjacency_[i].size(); ++j)
Rprintf(" %d", adjacency_[i][j]);
Rprintf("\n");
}
}
void print_path(const char *text, const IntVector &path) const
{
Rprintf("%s:", text);
for(IntVector::const_iterator j=path.begin(); j!=path.end(); ++j)
Rprintf(" %d", *j);
Rprintf("\n");
}
#endif
public:
TrophicChains(const std::vector<IntVector> &adjacency,
const IntVector &is_basal,
Queue::size_type max_queue) :
adjacency_(adjacency),
is_basal_(is_basal),
max_queue_(max_queue)
{
}
void visit(Visitor &visitor) const
{
// Visits unique trophic chains the network represented by adjancency.
DEBUG(Rprintf("DUMP GRAPH\n"));
DEBUG(print_adjacency());
bool queue_warning = false;
for(int n = 0; n < adjacency_.size(); ++n)
{
if(adjacency_[n].size() == 0) continue; // Node n has no out-edges, it
// cannot start a chain
if(is_basal_[n] == 0) continue; // Node n has in-edges, so it cannot
// start a chain
IntVector path(1, n);
DEBUG(print_path("INITIAL PATH", path));
Queue queue;
queue.push(path);
while(!queue.empty())
{
path = queue.front();
queue.pop();
R_ProcessEvents();
if(max_queue_>0 && !queue_warning && queue.size()>max_queue_/2)
{
REprintf("This network has a lot of paths, possibly too many to "
"compute\n");
queue_warning = true;
}
else if(max_queue_>0 && queue.size()>max_queue_)
{
throw CheddarException("Unable to compute paths - see the help for "
"TrophicChains for more information.");
}
int m = path.back();
DEBUG(Rprintf("AT NODE [%d]\n", m));
if(adjacency_[m].size() == 0)
{
DEBUG(print_path("", path));
visitor.chain(path);
}
else
{
bool cycle = true;
for(int j=0; j<adjacency_[m].size(); ++j)
{
bool found = false;
for(IntVector::const_iterator k=path.begin(); k!=path.end(); ++k)
{
if(*k == adjacency_[m][j])
{
found = true;
break;
}
}
if(!found)
{
path.push_back(adjacency_[m][j]);
DEBUG(print_path("EXTEND PATH", path));
queue.push(path);
path.pop_back();
cycle = false;
}
}
if(cycle)
{
DEBUG(print_path("", path));
visitor.chain(path);
}
}
}
}
}
};
class CollectChainsVisitor
{
// Collects chains
private:
int *chains_; // An array of ncols_ * nrows_
int ncols_;
int nrows_;
int n_chains_found_;
public:
CollectChainsVisitor(int *chains, int ncols, int nrows) :
chains_(chains),
ncols_(ncols),
nrows_(nrows),
n_chains_found_(0)
{
}
void chain(const IntVector &path)
{
if(n_chains_found_ <= ncols_ && path.size()<=IntVector::size_type(nrows_))
{
const IntVector::size_type path_length(path.size());
std::memcpy(chains_ + n_chains_found_ * nrows_, &path[0],
path_length*sizeof(IntVector::value_type));
n_chains_found_ += 1;
}
else
{
DEBUG(Rprintf("Chains storage space exceeded\n"));
DEBUG(Rprintf("nrows [%d] ncols [%d]\n", nrows_, ncols_));
DEBUG(Rprintf("n_chains_found_ [%d]\n", n_chains_found_));
DEBUG(Rprintf("path length [%d]\n", path.size()));
throw CheddarException("Chains storage space exceeded");
}
}
};
class PrintChainsVisitor
{
// Prints chains to stdout in the same format as Rob's solution8
public:
void chain(const IntVector &path)
{
// Rprintf is an order of magnitude slower that printf (on my Mac, at
// least) and isn't relevant in this case but we have no choice but to use
// it because of R CMD check
Rprintf(":");
for(IntVector::size_type j=0; j<path.size(); ++j)
Rprintf(" %d", 1+path[j]);
Rprintf("\n");
}
};
class CollectChainLengthsVisitor
{
// Records the number of chains and the length of the longest chain.
public:
int longest_;
int n_chains_;
public:
CollectChainLengthsVisitor(bool test_overflow=false) : longest_(0),
n_chains_(0)
{
if(test_overflow)
{
n_chains_ = INT_MAX;
}
}
void chain(const IntVector &path)
{
longest_ = std::max(longest_, int(path.size()));
if(INT_MAX>n_chains_)
{
n_chains_ += 1;
}
else
{
throw CheddarException("Too many chains to count without overflow");
}
}
};
class ChainStatsVisitor
{
// Records the length of each chains and the number of times that each node
// appears in a position in a chain.
public:
typedef std::vector<IntVector> CountVector;
CountVector counts_;
IntVector chain_lengths_; // A vector of chain lengths
public:
ChainStatsVisitor(int nodes, int longest) : counts_(nodes)
{
for(CountVector::iterator it=counts_.begin(); it!=counts_.end(); ++it)
{
it->resize(longest);
}
}
void chain(const IntVector &path)
{
chain_lengths_.push_back(path.size()-1);
for(IntVector::size_type position=0; position<path.size(); ++position)
{
IntVector::const_reference node = path[position];
counts_[node][position] += 1;
}
}
#ifdef DEBUG_TC
void print() const
{
Rprintf("Chain position counts\n");
for(CountVector::size_type node=0; node<counts_.size(); ++node)
{
CountVector::const_reference v = counts_[node];
Rprintf("[%d] ", node);
for(CountVector::value_type::size_type pos=0; pos!=v.size(); ++pos)
{
Rprintf("%d:%lu, ", pos, v[pos]);
}
Rprintf("\n");
}
}
#endif
};
extern "C"
{
void trophic_chains_size(const int *adjacency,
const int *adjacency_length,
const int *is_basal,
const int *node_count,
const int *test_overflow,
const int *max_queue,
int *n_chains,
int *longest,
int *status)
{
/* WARNING: Nested returns */
/* Enumerates every unique trophic path in a directed graph. Output is
written to chains.
In params:
adjacency: a matrix of node_count rows. First column is the number of
consumers of that row. Subsequent columns are ids of
consumers.
adjacency_length: the number of ints in adjacency
is_basal: an array of length node_count. 1 for nodes that have no
resources, 0 otherwise. Chains start only with nodes which
have a 1 in is_basal.
node_count: the number of nodes in the network.
test_overflow: if non-zero then check the overflow case for counting chains.
max_queue: the maximum alowabe size of the queue used to compute chains.
0 indicates no limit.
Out params:
n_chains: the number of unique chains found.
longest: the number of nodes in the longest chain found.
status: -1 - unexpected error.
0 - normal exit.
1 - problem with one of the parameters.
*/
/* Quick and dirty parameter checks */
if(0==adjacency || 0==adjacency_length || *adjacency_length<1 ||
0==is_basal || 0==node_count || *node_count<1 || 0==test_overflow ||
0==max_queue || *max_queue<0 ||
0==n_chains || 0==longest || 0==status)
{
if(0!=status)
{
*status = 1;
}
/* WARNING: Nested return */
return;
}
*status = -1; // Default to an error status code
try
{
std::vector<IntVector> adj = Adjacency(adjacency, *node_count);
IntVector basal(is_basal, is_basal + *node_count);
TrophicChains<CollectChainLengthsVisitor> worker(adj, basal, *max_queue);
CollectChainLengthsVisitor visitor(0!=*test_overflow);
worker.visit(visitor);
*n_chains = visitor.n_chains_;
*longest = visitor.longest_;
// Normal exit
*status = 0;
}
catch(const std::exception &e)
{
REprintf("Unexpected error in trophic_chains_size [%s]\n", e.what());
}
catch(...)
{
REprintf("Unexpected error in trophic_chains_size\n");
}
}
void print_chains(const int *adjacency,
const int *adjacency_length,
const int *is_basal,
const int *node_count,
const int *max_queue,
int *status)
{
/* WARNING: Nested returns */
/* Enumerates every unique trophic path in a directed graph. Output is
written to chains.
In params:
adjacency: a matrix of node_count rows. First column is the number of
consumers of that row. Subsequent columns are ids of
consumers.
adjacency_length: the number of ints in adjacency
is_basal: an array of length node_count. 1 for nodes that have no
resources, 0 otherwise. Chains start only with nodes which
have a 1 in is_basal.
node_count: the number of nodes in the network.
ncols: the number of columns in chains.
nrows: the number of rows in chains.
max_queue: the maximum alowabe size of the queue used to compute chains.
0 indicates no limit.
Out params:
status: -1 - unexpected error.
0 - normal exit.
1 - problem with one of the parameters.
*/
/* Quick and dirty parameter checks */
if(0==adjacency || 0==adjacency_length || *adjacency_length<1 ||
0==is_basal || 0==node_count || 0==max_queue || *max_queue<0 ||
0==status)
{
if(0!=status)
{
*status = 1;
}
/* WARNING: Nested return */
return;
}
*status = -1; // Default to an error status code
try
{
std::vector<IntVector> adj = Adjacency(adjacency, *node_count);
IntVector basal(is_basal, is_basal + *node_count);
TrophicChains<PrintChainsVisitor> worker(adj, basal, *max_queue);
PrintChainsVisitor visitor;
worker.visit(visitor);
// Normal exit
*status = 0;
}
catch(const std::exception &e)
{
REprintf("Unexpected error in print_chains[%s]\n", e.what());
}
catch(...)
{
REprintf("Unexpected error in print_chains\n");
}
}
void trophic_chains(const int *adjacency,
const int *adjacency_length,
const int *is_basal,
const int *node_count,
const int *ncols,
const int *nrows,
const int *max_queue,
int *chains,
int *status)
{
/* WARNING: Nested returns */
/* Enumerates every unique trophic path in a directed graph. Output is
written to chains.
In params:
adjacency: a matrix of node_count rows. First column is the number of
consumers of that row. Subsequent columns are ids of
consumers.
adjacency_length: the number of ints in adjacency
is_basal: an array of length node_count. 1 for nodes that have no
resources, 0 otherwise. Chains start only with nodes which
have a 1 in is_basal.
node_count: the number of nodes in the network.
ncols: the number of columns in chains.
nrows: the number of rows in chains.
max_queue: the maximum alowabe size of the queue used to compute chains.
0 indicates no limit.
Out params:
chains: a matrix of node_count rows and max_chains columns. Each
unique chain will be written to this matrix.
status: -1 - unexpected error.
0 - normal exit.
1 - problem with one of the parameters.
*/
/* Quick and dirty parameter checks */
if(0==adjacency || 0==adjacency_length || *adjacency_length<1 ||
0==is_basal || 0==node_count || *node_count<1 ||
0==max_queue || *max_queue<0 ||
0==chains || 0==ncols || *ncols<1 ||
0==nrows || *nrows<1 || 0==status)
{
if(0!=status)
{
*status = 1;
}
/* WARNING: Nested return */
return;
}
*status = -1; // Default to an error status code
try
{
std::vector<IntVector> adj = Adjacency(adjacency, *node_count);
IntVector basal(is_basal, is_basal + *node_count);
TrophicChains<CollectChainsVisitor> worker(adj, basal, *max_queue);
CollectChainsVisitor visitor(chains, *ncols, *nrows);
worker.visit(visitor);
// Normal exit
*status = 0;
}
catch(const std::exception &e)
{
REprintf("Unexpected error in trophic_chains[%s]\n", e.what());
}
catch(...)
{
REprintf("Unexpected error in trophic_chains\n");
}
}
void trophic_chains_stats(const int *adjacency,
const int *adjacency_length,
const int *is_basal,
const int *node_count,
const int *n_chains,
const int *longest,
const int *max_queue,
int *node_pos_counts,
int *chain_lengths,
int *status)
{
/* WARNING: Nested returns */
/* Enumerates every unique trophic path in a directed graph. Outputs are the
mean, minimum and maximum position of each node in every chain.
In params:
adjacency: a matrix of node_count rows. First column is the number of
consumers of that row. Subsequent columns are ids of
consumers.
adjacency_length: the number of ints in adjacency
is_basal: an array of length node_count. 1 for nodes that have no
resources, 0 otherwise. Chains start only with nodes which
have a 1 in is_basal.
node_count: the number of nodes in the network.
n_chains: the number of chains.
longest: the number of nodes in the longest chain.
max_queue: the maximum alowabe size of the queue used to compute chains.
0 indicates no limit.
Out params:
node_pos_counts: an array of n_chains * longest integers. Will contain
counts of the number of times each node appears at a given
position in the chain.
chain_lengths: an array of n_chains integers. Will contain the length of
each chain.
status: -1 - unexpected error.
0 - normal exit.
1 - problem with one of the parameters.
*/
/* Quick and dirty parameter checks */
if(0==adjacency || 0==adjacency_length || *adjacency_length<1 ||
0==is_basal || 0==node_count || *node_count<1 ||
0==n_chains || *n_chains<1 || 0==longest || *longest<1 ||
0==max_queue || *max_queue<0 ||
0==node_pos_counts || 0==chain_lengths || 0==status)
{
if(0!=status)
{
*status = 1;
}
/* WARNING: Nested return */
return;
}
*status = -1; // Default to an error status code
try
{
std::vector<IntVector> adj = Adjacency(adjacency, *node_count);
IntVector basal(is_basal, is_basal + *node_count);
TrophicChains<ChainStatsVisitor> worker(adj, basal, *max_queue);
ChainStatsVisitor visitor(*node_count, *longest);
worker.visit(visitor);
if(sizeof(IntVector::value_type)!=sizeof(*chain_lengths) ||
sizeof(IntVector::value_type)!=sizeof(*node_pos_counts))
{
throw CheddarException("Unexpected type size");
}
else if(visitor.chain_lengths_.size()!=IntVector::size_type(*n_chains))
{
throw CheddarException("Unexpected number of chains");
}
else if(visitor.counts_.size()!=IntVector::size_type(*node_count))
{
throw CheddarException("Unexpected number of nodes");
}
else
{
std::memcpy(chain_lengths, &visitor.chain_lengths_[0], sizeof(int) * *n_chains);
for(ChainStatsVisitor::CountVector::size_type node=0;
node<visitor.counts_.size(); ++node)
{
ChainStatsVisitor::CountVector::const_reference v = visitor.counts_[node];
if(v.size()!=ChainStatsVisitor::CountVector::value_type::size_type(*longest))
{
throw CheddarException("Unexpected number of node position counts");
}
else
{
std::memcpy(node_pos_counts + node * *longest, &v[0],
sizeof(int) * *longest);
}
}
}
// Normal exit
*status = 0;
}
catch(const std::exception &e)
{
REprintf("Unexpected error in trophic_chains_stats [%s]\n", e.what());
}
catch(...)
{
REprintf("Unexpected error in trophic_chains_stats\n");
}
}
} // extern "c" | [
"quicklizard@googlemail.com"
] | quicklizard@googlemail.com |
35a8393e8ece08176e51a5bec1160f8809bc2e81 | 768316ed72470715e641fda62a9166b610b27350 | /03-CodeChef-Medium/349--Coin Partition.cpp | 1ba6e55698d68a32584d956da820ddf6a1f78e46 | [] | no_license | dhnesh12/codechef-solutions | 41113bb5922156888d9e57fdc35df89246e194f7 | 55bc7a69f76306bc0c3694180195c149cf951fb6 | refs/heads/master | 2023-03-31T15:42:04.649785 | 2021-04-06T05:38:38 | 2021-04-06T05:38:38 | 355,063,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | cpp | #include <bits/stdc++.h>
using namespace std;
const int md=(int)1e9+123;
inline void add(int &a,int b){
a+=b;
if(a>=md)
a-=md;
}
inline void sub(int &a,int b){
a-=b;
if(a<0)
a+=md;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int tt;cin>>tt;
while(tt--){
int n;cin>>n;
vector<int> a(n);
int sum=0;
for(int i=0;i<n;i++){
cin>>a[i];
sum+=a[i];
}
vector<int> dp(sum+1,0);
dp[0]=1;
for(int x:a){
for(int i=sum-x;i>=0;i--){
add(dp[i+x],dp[i]);
}
}
int ans=-1,aid=-1;
for(int id=0;id<n;id++){
int x=a[id];
for(int i=0;i<=sum-x;i++){
sub(dp[i+x],dp[i]);
}
int rm=sum-x;
for(int i=rm/2;i>=0;i--){
if(dp[i]>0){
int cur=i+x;
if(cur>ans){
ans=cur;
aid=id;
}
}
}
for(int i=sum-x;i>=0;i--){
add(dp[i+x],dp[i]);
}
}
const int N=500*500+10;
vector<bitset<N>> aux(1);
aux[0][0]=1;
for(int i=0;i<n;i++){
aux.push_back(aux.back());
if(i!=aid){
aux[i+1]|=(aux[i]<<a[i]);
}
}
int j=ans-a[aid];
vector<int> mine;
vector<int> his;
for(int i=n;i>0;i--){
if(i-1==aid){
continue;
}
if(aux[i-1][j]==1){
his.push_back(i-1);
}else{
mine.push_back(i-1);
j-=a[i-1];
}
}
assert(j==0);
mine.push_back(aid);
vector<int> my_start(mine.size());
vector<int> his_start(his.size());
for(int i=0;i<(int)mine.size();i++){
my_start[i]=(i==0?0:my_start[i-1]+a[mine[i-1]]);
}
for(int i=0;i<(int)his.size();i++){
his_start[i]=(i==0?0:his_start[i-1]+a[his[i-1]]);
}
vector<int> res;
int pm=0,ph=0;
while(pm<(int)mine.size()||ph<(int)his.size()){
if(ph==(int)his.size()||(pm< (int) mine.size()&& my_start[pm]<=his_start[ph])){
res.push_back(mine[pm++]);
}
else{
res.push_back(his[ph++]);
}
}
assert((int)res.size()==n);
for(int i=0;i<n;i++){
if(i>0){
cout<<" ";
}
cout<<res[i]+1;
}
cout<<'\n';
}
return 0;
} | [
"dhneshwod@gmail.com"
] | dhneshwod@gmail.com |
f2ad253479e3c1f7d9ca58acc72cc9eb6005ffb8 | b5975f01e42ba02b676bcdd9cbc5449b5087acaf | /src/load_plugin.cpp | 528901f96ac05c73e680a01327309a7040850d0e | [
"BSL-1.0"
] | permissive | satyaki3794/hpx_scheduler_plugin | 806185a1545313351f43445821a11e6fee0c9c62 | 06e576de2fc0c57937c818214be6635d0f15c34e | refs/heads/master | 2020-04-01T17:47:16.996673 | 2016-06-30T06:23:14 | 2016-06-30T06:23:14 | 60,599,197 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,307 | cpp | // Copyright (c) 2016 Hartmut Kaiser, Satyaki Upadhyay
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// This executable dynamically loads a shared library and asks it to create
// one instance for each of the factory types it supports. It then uses each of
// the factories to create a corresponding plugin instance. The plugin is
// used to perform some plugin-specific task.
//
// Note that this executable has no knowledge about what plugin types are
// exposed by the loaded shared library. All of this information is dynamically
// discovered at runtime.
#include <hpx/hpx_main.hpp>
#include <hpx/hpx.hpp>
#include "scheduler_plugin_factory_base.hpp"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/tokenizer.hpp>
#include <memory>
#include <string>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
bool load_plugins(hpx::util::section& ini)
{
// load all components as described in the configuration information
if (!ini.has_section("hpx.plugins"))
{
std::cout << "No plugins found/loaded." << std::endl;
return true; // no plugins to load
}
// each shared library containing plugins may have an ini section
//
// # mandatory section describing the component module
// [hpx.plugins.instance_name]
// name = ... # the name of this component module
// path = ... # the path where to find this component module
// enabled = false # optional (default is assumed to be true)
//
// # optional section defining additional properties for this module
// [hpx.plugins.instance_name.settings]
// key = value
//
hpx::util::section* sec = ini.get_section("hpx.plugins");
if (NULL == sec)
{
std::cout << "NULL section found" << std::endl;
return false; // something bad happened
}
hpx::util::section::section_map const& s = (*sec).get_sections();
typedef hpx::util::section::section_map::const_iterator iterator;
iterator end = s.end();
for (iterator i = s.begin (); i != end; ++i)
{
// the section name is the instance name of the component
hpx::util::section const& sect = i->second;
std::string instance (sect.get_name());
std::string component;
if (i->second.has_entry("name"))
component = sect.get_entry("name");
else
component = instance;
if (sect.has_entry("enabled"))
{
std::string tmp = sect.get_entry("enabled");
boost::algorithm::to_lower(tmp);
if (tmp == "no" || tmp == "false" || tmp == "0")
{
std::cout << "plugin factory disabled: " << instance << std::endl;
continue; // this plugin has been disabled
}
}
// initialize the factory instance using the preferences from the
// ini files
hpx::util::section const* glob_ini = NULL;
if (ini.has_section("settings"))
glob_ini = ini.get_section("settings");
hpx::util::section const* plugin_ini = NULL;
std::string plugin_section("hpx.plugins." + instance);
if (ini.has_section(plugin_section))
plugin_ini = ini.get_section(plugin_section);
boost::filesystem::path lib_path;
std::string component_path = sect.get_entry("path");
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(HPX_INI_PATH_DELIMITER);
tokenizer tokens(component_path, sep);
boost::system::error_code fsec;
for(tokenizer::iterator it = tokens.begin(); it != tokens.end(); ++it)
{
boost::filesystem::path dir = boost::filesystem::path(*it);
lib_path = dir / std::string(HPX_MAKE_DLL_STRING(component));
if(boost::filesystem::exists(lib_path, fsec))
{
break;
}
lib_path.clear();
}
if (lib_path.string().empty())
continue; // didn't find this plugin
hpx::util::plugin::dll module(lib_path.string(), HPX_MANGLE_STRING(component));
// get the factory
typedef hpx::threads::policies::scheduler_plugin_factory_base fb;
hpx::util::plugin::plugin_factory<fb> pf(module, "scheduler_factory");
try {
// create the plugin factory object, if not disabled
std::shared_ptr<fb> factory (
pf.create(instance, glob_ini, plugin_ini, true));
// use factory to create an instance of the plugin
std::shared_ptr<hpx::threads::policies::scheduler_base
> plugin(factory->create());
// now use plugin to do something useful
plugin->test_scheduler();
}
catch(...) {
// different type of factory (not "example_factory"), ignore here
}
}
return true;
}
int main(int argc, char* argv[])
{
// load plugins based on registry and configuration information
load_plugins(hpx::get_runtime().get_config());
return 0;
}
| [
"satyaki3794@gmail.com"
] | satyaki3794@gmail.com |
a0f2efb538a1020f744b8925a04cb26b5a0ed919 | 40c0d5aab8e6479193b1892a0d2c0a52c6c073e4 | /LTC6804/LTSketchbook/LTSketchbook/libraries/LT_SMBUS/LT_SMBusARA.h | b62e977cbf7c3145495d54fe08cfb853288f7ed5 | [] | no_license | edewit2/SunstangBPS | 090ccba0ee96d56a3ed74cce8088a4cd081ad2a3 | e03d23110c805801b67535920344bdc4055d5f31 | refs/heads/master | 2021-01-22T19:41:33.914177 | 2017-04-04T02:10:22 | 2017-04-04T02:10:22 | 85,222,657 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,295 | h | /*!
LTC PSM ARA Handling
@verbatim
Representation of a device and its capabilities.
@endverbatim
REVISION HISTORY
$Revision: 3845 $
$Date: 2015-08-24 14:11:21 -0600 (Mon, 24 Aug 2015) $
Copyright (c) 2014, Linear Technology Corp.(LTC)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of Linear Technology Corp.
The Linear Technology Linduino is not affiliated with the official Arduino team.
However, the Linduino is only possible because of the Arduino team's commitment
to the open-source community. Please, visit http://www.arduino.cc and
http://store.arduino.cc , and consider a purchase that will help fund their
ongoing work.
*/
//! @defgroup LT_SMBusAra LT_SMBusAra: Implementation of Device Alert
/*! @file
@ingroup LT_SMBusAra
Library Header File for LT_SMBusAlert
*/
#ifndef LT_SMBusARA_H_
#define LT_SMBusARA_H_
#include <stdint.h>
#include <LT_PMBus.h>
#include <LT_SMBusARA.h>
#include <LT_PMBusDevice.h>
class LT_SMBusARA
{
protected:
LT_SMBus *smbus_;
public:
LT_SMBusARA(LT_SMBus *smbus):smbus_(smbus)
{
}
virtual ~LT_SMBusARA() {}
//! Get the ARA addresses (user must free)
//! @return addresses
uint8_t *getAddresses (
)
{
uint8_t *addresses;
uint16_t count = 0;
uint8_t address = 0xFF;
addresses = (uint8_t *) malloc (sizeof(uint8_t));
do
{
address = smbus_->readAlert();
addresses[count++] = address;
delay(1);
addresses = (uint8_t *) realloc(addresses, (count + 1) * sizeof(uint8_t));
}
while (address != 0);
addresses[count] = 0;
return addresses;
}
//! Get all the ARA devices.
//! @return a list of devices (call must free list, but not devices in list)
LT_PMBusDevice **getDevices(LT_PMBusDevice **devices //!< A list of known devices //!< The number of devices in the list
)
{
uint8_t *addresses;
uint8_t *address;
LT_PMBusDevice **device;
LT_PMBusDevice **matchingDevices;
LT_PMBusDevice **matchingDevice;
int devCount;
devCount = 0;
device = devices;
while ((*device) != 0)
{
device++;
devCount++;
}
addresses = getAddresses();
matchingDevice = (matchingDevices = (LT_PMBusDevice **) calloc(devCount + 1, sizeof(LT_PMBusDevice *)));
// Bad algorithm lies here and needs replacing
address = addresses;
while (*address != 0)
{
device = devices;
while ((*device) != 0)
{
if ((*address) == (*device)->getAddress())
{
*matchingDevice = *device;
matchingDevice++;
}
device++;
}
address++;
}
free (addresses);
return matchingDevices;
}
};
#endif /* LT_SMBusDevice_H_ */
| [
"edewit2@uwo.ca"
] | edewit2@uwo.ca |
6b5d77b23fc7af18cd1e606db77ee88595a05114 | 97ba2181ee73759139b56676d9372946a52715ae | /src/object/C4Object.cpp | 8b7f9bc167a4d6d2b0ab9cdc6bb9533950b5e944 | [
"ISC",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | notprathap/openclonk-5.4.1-src | 18dd847e3432dce72c7c6b2eeb083487139f08c5 | 49f63f9b832cef617ef815552bf37536bc22574b | refs/heads/master | 2020-03-30T10:24:14.015343 | 2014-11-24T12:19:22 | 2014-11-24T12:19:22 | 27,074,589 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 153,092 | cpp | /*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 1998-2000, Matthes Bender
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de/
* Copyright (c) 2009-2013, The OpenClonk Team and contributors
*
* Distributed under the terms of the ISC license; see accompanying file
* "COPYING" for details.
*
* "Clonk" is a registered trademark of Matthes Bender, used with permission.
* See accompanying file "TRADEMARK" for details.
*
* To redistribute this file separately, substitute the full license texts
* for the above references.
*/
/* That which fills the world with life */
#include <C4Include.h>
#include <C4Object.h>
#include <C4DefList.h>
#include <C4Effect.h>
#include <C4ObjectInfo.h>
#include <C4Physics.h>
#include <C4ObjectCom.h>
#include <C4Command.h>
#include <C4Viewport.h>
#include <C4MaterialList.h>
#include <C4Record.h>
#include <C4SolidMask.h>
#include <C4Random.h>
#include <C4Log.h>
#include <C4Player.h>
#include <C4ObjectMenu.h>
#include <C4RankSystem.h>
#include <C4GameMessage.h>
#include <C4GraphicsResource.h>
#include <C4GraphicsSystem.h>
#include <C4Game.h>
#include <C4PlayerList.h>
#include <C4GameObjects.h>
#include <C4Record.h>
#include <C4MeshAnimation.h>
namespace
{
const StdMeshInstance::AttachedMesh::DenumeratorFactoryFunc C4MeshDenumeratorFactory = StdMeshInstance::AttachedMesh::DenumeratorFactory<C4MeshDenumerator>;
}
void C4MeshDenumerator::CompileFunc(StdCompiler* pComp, StdMeshInstance::AttachedMesh* attach)
{
if(pComp->isCompiler())
{
int32_t def;
pComp->Value(mkNamingCountAdapt(def, "ChildInstance"));
if(def)
{
C4DefGraphics* pGfx = NULL;
pComp->Value(mkNamingAdapt(C4DefGraphicsAdapt(pGfx), "ChildMesh"));
Def = pGfx->pDef;
if(pGfx->Type != C4DefGraphics::TYPE_Mesh)
pComp->excCorrupt("ChildMesh points to non-mesh graphics");
assert(!attach->Child);
pComp->Value(mkParAdapt(mkNamingContextPtrAdapt(attach->Child, *pGfx->Mesh, "ChildInstance"), C4MeshDenumeratorFactory));
assert(attach->Child != NULL);
attach->OwnChild = true; // Delete the newly allocated child instance when the parent instance is gone
// TODO: Do we leak pGfx?
}
else
{
pComp->Value(mkNamingAdapt(Object, "ChildObject"));
attach->OwnChild = false; // Keep child instance when parent instance is gone since it belongs to a different object
}
}
else
{
int32_t def = 0;
if(Def) ++def;
pComp->Value(mkNamingCountAdapt(def, "ChildInstance"));
if(Def)
{
assert(attach->OwnChild);
C4DefGraphics* pGfx = &Def->Graphics;
assert(pGfx->Type == C4DefGraphics::TYPE_Mesh);
pComp->Value(mkNamingAdapt(C4DefGraphicsAdapt(pGfx), "ChildMesh"));
pComp->Value(mkParAdapt(mkNamingContextPtrAdapt(attach->Child, *pGfx->Mesh, "ChildInstance"), C4MeshDenumeratorFactory));
}
else
{
assert(!attach->OwnChild);
pComp->Value(mkNamingAdapt(Object, "ChildObject"));
}
}
}
void C4MeshDenumerator::DenumeratePointers(StdMeshInstance::AttachedMesh* attach)
{
Object.DenumeratePointers();
// Set child instance of attach after denumeration
if(Object)
{
assert(!attach->OwnChild);
assert(!attach->Child || attach->Child == Object->pMeshInstance);
if(!attach->Child)
attach->Child = Object->pMeshInstance;
}
}
bool C4MeshDenumerator::ClearPointers(C4Object* pObj)
{
if(Object == pObj)
{
Object = NULL;
// Return false causes the attached mesh to be deleted by StdMeshInstance
return false;
}
return true;
}
static void DrawVertex(C4Facet &cgo, float tx, float ty, int32_t col, int32_t contact)
{
if (Inside<int32_t>(tx,cgo.X,cgo.X+cgo.Wdt) && Inside<int32_t>(ty,cgo.Y,cgo.Y+cgo.Hgt))
{
pDraw->DrawLineDw(cgo.Surface, tx - 1, ty, tx + 1, ty, col, 0.5f);
pDraw->DrawLineDw(cgo.Surface, tx, ty - 1, tx, ty + 1, col, 0.5f);
if (contact) pDraw->DrawFrameDw(cgo.Surface,tx-1.5,ty-1.5,tx+1.5,ty+1.5,C4RGB(0xff, 0xff, 0xff));
}
}
void C4Action::SetBridgeData(int32_t iBridgeTime, bool fMoveClonk, bool fWall, int32_t iBridgeMaterial)
{
// validity
iBridgeMaterial = Min<int32_t>(iBridgeMaterial, ::MaterialMap.Num-1);
if (iBridgeMaterial < 0) iBridgeMaterial = 0xff;
iBridgeTime = BoundBy<int32_t>(iBridgeTime, 0, 0xffff);
// mask in this->Data
Data = (uint32_t(iBridgeTime) << 16) + (uint32_t(fMoveClonk) << 8) + (uint32_t(fWall) << 9) + iBridgeMaterial;
}
void C4Action::GetBridgeData(int32_t &riBridgeTime, bool &rfMoveClonk, bool &rfWall, int32_t &riBridgeMaterial)
{
// mask from this->Data
uint32_t uiData = Data;
riBridgeTime = (uint32_t(uiData) >> 16);
rfMoveClonk = !!(uiData & 0x100);
rfWall = !!(uiData & 0x200);
riBridgeMaterial = (uiData & 0xff);
if (riBridgeMaterial == 0xff) riBridgeMaterial = -1;
}
C4Object::C4Object()
{
FrontParticles = BackParticles = 0;
Default();
}
void C4Object::Default()
{
id=C4ID::None;
nInfo.Clear();
RemovalDelay=0;
Owner=NO_OWNER;
Controller=NO_OWNER;
LastEnergyLossCausePlayer=NO_OWNER;
Category=0;
NoCollectDelay=0;
Con=0;
Mass=OwnMass=0;
Damage=0;
Energy=0;
Alive=0;
Breath=0;
InMat=MNone;
Color=0;
PlrViewRange=0;
fix_x=fix_y=fix_r=0;
xdir=ydir=rdir=0;
Mobile=0;
Unsorted=false;
Initializing=false;
OnFire=0;
InLiquid=0;
EntranceStatus=0;
Audible=0;
t_contact=0;
OCF=0;
Action.Default();
Shape.Default();
fOwnVertices=0;
Contents.Default();
Component.Default();
SolidMask.Default();
PictureRect.Default();
Def=NULL;
Info=NULL;
Command=NULL;
Contained=NULL;
TopFace.Default();
Menu=NULL;
MaterialContents=NULL;
Marker=0;
ColorMod=0xffffffff;
BlitMode=0;
CrewDisabled=false;
Layer=NULL;
pSolidMaskData=NULL;
pGraphics=NULL;
pMeshInstance=NULL;
pDrawTransform=NULL;
pEffects=NULL;
pGfxOverlay=NULL;
iLastAttachMovementFrame=-1;
ClearParticleLists();
}
bool C4Object::Init(C4PropList *pDef, C4Object *pCreator,
int32_t iOwner, C4ObjectInfo *pInfo,
int32_t nx, int32_t ny, int32_t nr,
C4Real nxdir, C4Real nydir, C4Real nrdir, int32_t iController)
{
C4PropListNumbered::AcquireNumber();
// currently initializing
Initializing=true;
// Def & basics
Owner=iOwner;
if (iController > NO_OWNER) Controller = iController; else Controller=iOwner;
LastEnergyLossCausePlayer=NO_OWNER;
Info=pInfo;
Def=pDef->GetDef(); assert(Def);
SetProperty(P_Prototype, C4VPropList(pDef));
id=Def->id;
if (Info) SetName(pInfo->Name);
Category=Def->Category;
Plane = Def->GetPlane(); assert(Plane);
Def->Count++;
if (pCreator) Layer=pCreator->Layer;
// graphics
pGraphics = &Def->Graphics;
if (pGraphics->Type == C4DefGraphics::TYPE_Mesh)
{
pMeshInstance = new StdMeshInstance(*pGraphics->Mesh, Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
pMeshInstance->SetFaceOrderingForClrModulation(ColorMod);
}
else
{
pMeshInstance = NULL;
}
BlitMode = Def->BlitMode;
// Position
if (!Def->Rotateable) { nr=0; nrdir=0; }
fix_x=itofix(nx);
fix_y=itofix(ny);
fix_r=itofix(nr);
xdir=nxdir; ydir=nydir; rdir=nrdir;
// Initial mobility
if (!!xdir || !!ydir || !!rdir)
Mobile=1;
// Mass
Mass=Max<int32_t>(Def->Mass*Con/FullCon,1);
// Life, energy, breath
if (Category & C4D_Living) Alive=1;
if (Alive) Energy=GetPropertyInt(P_MaxEnergy);
Breath=GetPropertyInt(P_MaxBreath);
// Components
Component=Def->Component;
ComponentConCutoff();
// Color
if (Def->ColorByOwner)
{
if (ValidPlr(Owner))
Color=::Players.Get(Owner)->ColorDw;
else
Color=0xff; // no-owner color: blue
}
// Shape & face
Shape=Def->Shape;
SolidMask=Def->SolidMask;
CheckSolidMaskRect();
UpdateGraphics(false);
UpdateFace(true);
// Initial audibility
Audible=::Viewports.GetAudibility(GetX(), GetY(), &AudiblePan);
// Initial OCF
SetOCF();
// finished initializing
Initializing=false;
return true;
}
C4Object::~C4Object()
{
Clear();
#if defined(_DEBUG)
// debug: mustn't be listed in any list now
::Objects.Sectors.AssertObjectNotInList(this);
#endif
}
void C4Object::ClearParticleLists()
{
if (FrontParticles != 0)
Particles.ReleaseParticleList(FrontParticles);
if (BackParticles != 0)
Particles.ReleaseParticleList(BackParticles);
FrontParticles = BackParticles = 0;
}
void C4Object::AssignRemoval(bool fExitContents)
{
// check status
if (!Status) return;
if (Config.General.DebugRec)
{
C4RCCreateObj rc;
memset(&rc, '\0', sizeof(rc));
rc.oei=Number;
if (Def && Def->GetName()) strncpy(rc.id, Def->GetName(), 32+1);
rc.x=GetX(); rc.y=GetY(); rc.ownr=Owner;
AddDbgRec(RCT_DsObj, &rc, sizeof(rc));
}
// Destruction call in container
if (Contained)
{
C4AulParSet pars(C4VObj(this));
Contained->Call(PSF_ContentsDestruction, &pars);
if (!Status) return;
}
// Destruction call
Call(PSF_Destruction);
// Destruction-callback might have deleted the object already
if (!Status) return;
// remove all effects (extinguishes as well)
if (pEffects)
{
pEffects->ClearAll(this, C4FxCall_RemoveClear);
// Effect-callback might actually have deleted the object already
if (!Status) return;
}
// remove particles
ClearParticleLists();
// Action idle
SetAction(0);
// Object system operation
if (Status == C4OS_INACTIVE)
{
// object was inactive: activate first, then delete
::Objects.InactiveObjects.Remove(this);
Status = C4OS_NORMAL;
::Objects.Add(this);
}
Status=0;
// count decrease
Def->Count--;
// Kill contents
C4Object *cobj; C4ObjectLink *clnk,*next;
for (clnk=Contents.First; clnk && (cobj=clnk->Obj); clnk=next)
{
next=clnk->Next;
if (fExitContents)
cobj->Exit(GetX(), GetY());
else
{
Contents.Remove(cobj);
cobj->AssignRemoval();
}
}
// remove from container *after* contents have been removed!
C4Object *pCont;
if ((pCont=Contained))
{
pCont->Contents.Remove(this);
pCont->UpdateMass();
pCont->SetOCF();
Contained=NULL;
}
// Object info
if (Info) Info->Retire();
Info = NULL;
// Object system operation
ClearRefs();
Game.ClearPointers(this);
ClearCommands();
if (pSolidMaskData)
{
delete pSolidMaskData;
pSolidMaskData = NULL;
}
SolidMask.Wdt = 0;
RemovalDelay=2;
}
void C4Object::UpdateShape(bool bUpdateVertices)
{
// Line shape independent
if (Def->Line) return;
// Copy shape from def
Shape.CopyFrom(Def->Shape, bUpdateVertices, !!fOwnVertices);
// Construction zoom
if (Con!=FullCon)
{
if (Def->GrowthType)
Shape.Stretch(Con, bUpdateVertices);
else
Shape.Jolt(Con, bUpdateVertices);
}
// Rotation
if (Def->Rotateable)
if (fix_r != Fix0)
Shape.Rotate(fix_r, bUpdateVertices);
// covered area changed? to be on the save side, update pos
UpdatePos();
}
void C4Object::UpdatePos()
{
// get new area covered
// do *NOT* do this while initializing, because object cannot be sorted by main list
if (!Initializing && Status == C4OS_NORMAL)
::Objects.UpdatePos(this);
}
void C4Object::UpdateFace(bool bUpdateShape, bool fTemp)
{
// Update shape - NOT for temp call, because temnp calls are done in drawing routine
// must not change sync relevant data here (although the shape and pos *should* be updated at that time anyway,
// because a runtime join would desync otherwise)
if (!fTemp) { if (bUpdateShape) UpdateShape(); else UpdatePos(); }
// SolidMask
if (!fTemp) UpdateSolidMask(false);
// Null defaults
TopFace.Default();
// newgfx: TopFace only
if (Con>=FullCon || Def->GrowthType)
if (!Def->Rotateable || (fix_r == Fix0))
if (Def->TopFace.Wdt>0) // Fullcon & no rotation
TopFace.Set(GetGraphics()->GetBitmap(Color),
Def->TopFace.x,Def->TopFace.y,
Def->TopFace.Wdt,Def->TopFace.Hgt);
// Active face
UpdateActionFace();
}
void C4Object::UpdateGraphics(bool fGraphicsChanged, bool fTemp)
{
// check color
if (!fTemp) if (!pGraphics->IsColorByOwner()) Color=0;
// new grafics: update face
if (fGraphicsChanged)
{
// Keep mesh instance if it uses the same underlying mesh
if(!pMeshInstance || pGraphics->Type != C4DefGraphics::TYPE_Mesh ||
&pMeshInstance->GetMesh() != pGraphics->Mesh)
{
// If this mesh is attached somewhere, detach it before deletion
if(pMeshInstance && pMeshInstance->GetAttachParent() != NULL)
{
// TODO: If the new mesh has a bone with the same name, we could try updating...
StdMeshInstance::AttachedMesh* attach_parent = pMeshInstance->GetAttachParent();
attach_parent->Parent->DetachMesh(attach_parent->Number);
}
delete pMeshInstance;
if (pGraphics->Type == C4DefGraphics::TYPE_Mesh)
{
pMeshInstance = new StdMeshInstance(*pGraphics->Mesh, Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
pMeshInstance->SetFaceOrderingForClrModulation(ColorMod);
}
else
{
pMeshInstance = NULL;
}
}
// update face - this also puts any SolidMask
UpdateFace(false);
}
}
void C4Object::UpdateFlipDir()
{
int32_t iFlipDir;
// We're active
C4PropList* pActionDef = GetAction();
if (pActionDef)
// Get flipdir value from action
if ((iFlipDir = pActionDef->GetPropertyInt(P_FlipDir)))
// Action dir is in flipdir range
if (Action.Dir >= iFlipDir)
{
// Calculate flipped drawing dir (from the flipdir direction going backwards)
Action.DrawDir = (iFlipDir - 1 - (Action.Dir - iFlipDir));
// Set draw transform, creating one if necessary
if (pDrawTransform)
pDrawTransform->SetFlipDir(-1);
else
pDrawTransform = new C4DrawTransform(-1);
// Done setting flipdir
return;
}
// No flipdir necessary
Action.DrawDir = Action.Dir;
// Draw transform present?
if (pDrawTransform)
{
// reset flip dir
pDrawTransform->SetFlipDir(1);
// if it's identity now, remove the matrix
if (pDrawTransform->IsIdentity())
{
delete pDrawTransform;
pDrawTransform=NULL;
}
}
}
void C4Object::DrawFaceImpl(C4TargetFacet &cgo, bool action, float fx, float fy, float fwdt, float fhgt, float tx, float ty, float twdt, float thgt, C4DrawTransform* transform) const
{
C4Surface* sfc;
switch (GetGraphics()->Type)
{
case C4DefGraphics::TYPE_Bitmap:
sfc = action ? Action.Facet.Surface : GetGraphics()->GetBitmap(Color);
pDraw->Blit(sfc,
fx, fy, fwdt, fhgt,
cgo.Surface, tx, ty, twdt, thgt,
true, transform);
break;
case C4DefGraphics::TYPE_Mesh:
C4Value value;
GetProperty(P_MeshTransformation, &value);
StdMeshMatrix matrix;
if (!C4ValueToMatrix(value, &matrix))
matrix = StdMeshMatrix::Identity();
if(twdt != fwdt || thgt != fhgt)
{
// Also scale Z so that the mesh is not totally distorted and
// so that normals halfway keep pointing into sensible directions.
// We don't have a better guess so use the geometric mean for Z scale.
matrix = StdMeshMatrix::Scale(twdt/fwdt,thgt/fhgt,std::sqrt(twdt*thgt/(fwdt*fhgt))) * matrix;
}
pDraw->SetMeshTransform(&matrix);
pDraw->RenderMesh(*pMeshInstance, cgo.Surface, tx, ty, twdt, thgt, Color, transform);
pDraw->SetMeshTransform(NULL);
break;
}
}
void C4Object::DrawFace(C4TargetFacet &cgo, float offX, float offY, int32_t iPhaseX, int32_t iPhaseY) const
{
const float swdt = float(Def->Shape.Wdt);
const float shgt = float(Def->Shape.Hgt);
// Grow Type Display
float fx = float(swdt * iPhaseX);
float fy = float(shgt * iPhaseY);
float fwdt = float(swdt);
float fhgt = float(shgt);
float stretch_factor = static_cast<float>(Con) / FullCon;
float tx = offX + Def->Shape.GetX() * stretch_factor;
float ty = offY + Def->Shape.GetY() * stretch_factor;
float twdt = swdt * stretch_factor;
float thgt = shgt * stretch_factor;
// Construction Type Display
if (!Def->GrowthType)
{
tx = offX + Def->Shape.GetX();
twdt = swdt;
fy += fhgt - thgt;
fhgt = thgt;
}
// Straight
if ((!Def->Rotateable || (fix_r == Fix0)) && !pDrawTransform)
{
DrawFaceImpl(cgo, false, fx, fy, fwdt, fhgt, tx, ty, twdt, thgt, NULL);
/* pDraw->Blit(GetGraphics()->GetBitmap(Color),
fx, fy, fwdt, fhgt,
cgo.Surface, tx, ty, twdt, thgt,
true, NULL);*/
}
// Rotated or transformed
else
{
C4DrawTransform rot;
if (pDrawTransform)
{
rot.SetTransformAt(*pDrawTransform, offX, offY);
if (fix_r != Fix0) rot.Rotate(fixtof(fix_r), offX, offY);
}
else
{
rot.SetRotate(fixtof(fix_r), offX, offY);
}
DrawFaceImpl(cgo, false, fx, fy, fwdt, fhgt, tx, ty, twdt, thgt, &rot);
/* pDraw->Blit(GetGraphics()->GetBitmap(Color),
fx, fy, fwdt, fhgt,
cgo.Surface, tx, ty, twdt, thgt,
true, &rot);*/
}
}
void C4Object::DrawActionFace(C4TargetFacet &cgo, float offX, float offY) const
{
// This should not be called for meshes since Facet has no meaning
// for them. Only use DrawFace() with meshes!
assert(GetGraphics()->Type == C4DefGraphics::TYPE_Bitmap);
C4PropList* pActionDef = GetAction();
// Regular action facet
const float swdt = float(Action.Facet.Wdt);
const float shgt = float(Action.Facet.Hgt);
int32_t iPhase = Action.Phase;
if (pActionDef->GetPropertyInt(P_Reverse)) iPhase = pActionDef->GetPropertyInt(P_Length) - 1 - Action.Phase;
// Grow Type Display
float fx = float(Action.Facet.X + swdt * iPhase);
float fy = float(Action.Facet.Y + shgt * Action.DrawDir);
float fwdt = float(swdt);
float fhgt = float(shgt);
// draw stretched towards shape center with transform
float stretch_factor = static_cast<float>(Con) / FullCon;
float tx = (Def->Shape.GetX() + Action.FacetX) * stretch_factor + offX;
float ty = (Def->Shape.GetY() + Action.FacetY) * stretch_factor + offY;
float twdt = swdt * stretch_factor;
float thgt = shgt * stretch_factor;
// Construction Type Display
if (!Def->GrowthType)
{
// FIXME
if (Con != FullCon)
{
// incomplete constructions do not show actions
DrawFace(cgo, offX, offY);
return;
}
tx = Def->Shape.GetX() + Action.FacetX + offX;
twdt = swdt;
float offset_from_top = shgt * Max<float>(float(FullCon - Con), 0) / FullCon;
fy += offset_from_top;
fhgt -= offset_from_top;
}
// Straight
if ((!Def->Rotateable || (fix_r == Fix0)) && !pDrawTransform)
{
DrawFaceImpl(cgo, true, fx, fy, fwdt, fhgt, tx, ty, twdt, thgt, NULL);
/*pDraw->Blit(Action.Facet.Surface,
fx, fy, fwdt, fhgt,
cgo.Surface, tx, ty, twdt, thgt,
true, NULL);*/
}
// Rotated or transformed
else
{
// rotate midpoint of action facet around center of shape
// combine with existing transform if necessary
C4DrawTransform rot;
if (pDrawTransform)
{
rot.SetTransformAt(*pDrawTransform, offX, offY);
if (fix_r != Fix0) rot.Rotate(fixtof(fix_r), offX, offY);
}
else
{
rot.SetRotate(fixtof(fix_r), offX, offY);
}
DrawFaceImpl(cgo, true, fx, fy, fwdt, fhgt, tx, ty, twdt, thgt, &rot);
/* pDraw->Blit(Action.Facet.Surface,
fx, fy, fwdt, fhgt,
cgo.Surface, tx, ty, twdt, thgt,
true, &rot);*/
}
}
void C4Object::UpdateMass()
{
Mass=Max<int32_t>((Def->Mass+OwnMass)*Con/FullCon,1);
if (!Def->NoComponentMass) Mass+=Contents.Mass;
if (Contained)
{
Contained->Contents.MassCount();
Contained->UpdateMass();
}
}
void C4Object::ComponentConCutoff()
{
// this is not ideal, since it does not know about custom builder components
int32_t cnt;
for (cnt=0; Component.GetID(cnt); cnt++)
Component.SetCount(cnt,
Min<int32_t>(Component.GetCount(cnt),Def->Component.GetCount(cnt)*Con/FullCon));
}
void C4Object::ComponentConGain()
{
// this is not ideal, since it does not know about custom builder components
int32_t cnt;
for (cnt=0; Component.GetID(cnt); cnt++)
Component.SetCount(cnt,
Max<int32_t>(Component.GetCount(cnt),Def->Component.GetCount(cnt)*Con/FullCon));
}
void C4Object::UpdateInMat()
{
// get new mat
int32_t newmat;
if (Contained)
newmat = Contained->Def->ClosedContainer ? MNone : Contained->InMat;
else
newmat = GBackMat(GetX(), GetY());
// mat changed?
if (newmat != InMat)
{
Call(PSF_OnMaterialChanged,&C4AulParSet(C4VInt(newmat),C4VInt(InMat)));
InMat = newmat;
}
}
void C4Object::SetOCF()
{
C4PropList* pActionDef = GetAction();
#ifdef DEBUGREC_OCF
uint32_t dwOCFOld = OCF;
#endif
// Update the object character flag according to the object's current situation
C4Real cspeed=GetSpeed();
#ifdef _DEBUG
if (Contained && !C4PropListNumbered::CheckPropList(Contained))
{ LogF("Warning: contained in wild object %p!", static_cast<void*>(Contained)); }
else if (Contained && !Contained->Status)
{ LogF("Warning: contained in deleted object (#%d) (%s)!", Contained->Number, Contained->GetName()); }
#endif
// OCF_Normal: The OCF is never zero
OCF=OCF_Normal;
// OCF_Construct: Can be built outside
if (Def->Constructable && (Con<FullCon)
&& (fix_r==Fix0) && !OnFire)
OCF|=OCF_Construct;
// OCF_Grab: Can be pushed
if (GetPropertyInt(P_Touchable))
OCF|=OCF_Grab;
// OCF_Carryable: Can be picked up
if (GetPropertyInt(P_Collectible))
OCF|=OCF_Carryable;
// OCF_OnFire: Is burning
if (OnFire)
OCF|=OCF_OnFire;
// OCF_Inflammable: Is not burning and is inflammable
if (!OnFire && GetPropertyInt(P_ContactIncinerate) > 0)
OCF|=OCF_Inflammable;
// OCF_FullCon: Is fully completed/grown
if (Con>=FullCon)
OCF|=OCF_FullCon;
// OCF_Rotate: Can be rotated
if (Def->Rotateable)
// Don't rotate minimum (invisible) construction sites
if (Con>100)
OCF|=OCF_Rotate;
// OCF_Exclusive: No action through this, no construction in front of this
if (Def->Exclusive)
OCF|=OCF_Exclusive;
// OCF_Entrance: Can currently be entered/activated
if ((Def->Entrance.Wdt>0) && (Def->Entrance.Hgt>0))
if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (GetR() <= Def->RotatedEntrance)))
OCF|=OCF_Entrance;
// HitSpeeds
if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1;
if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2;
if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3;
if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4;
// OCF_Collection
if ((OCF & OCF_FullCon) || Def->IncompleteActivity)
if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0))
if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled)))
if (NoCollectDelay==0)
OCF|=OCF_Collection;
// OCF_Alive
if (Alive) OCF|=OCF_Alive;
// OCF_CrewMember
if (Def->CrewMember)
if (Alive)
OCF|=OCF_CrewMember;
// OCF_AttractLightning
if (Def->AttractLightning)
if (OCF & OCF_FullCon)
OCF|=OCF_AttractLightning;
// OCF_NotContained
if (!Contained)
OCF|=OCF_NotContained;
// OCF_InLiquid
if (InLiquid)
if (!Contained)
OCF|=OCF_InLiquid;
// OCF_InSolid
if (!Contained)
if (GBackSolid(GetX(), GetY()))
OCF|=OCF_InSolid;
// OCF_InFree
if (!Contained)
if (!GBackSemiSolid(GetX(), GetY()-1))
OCF|=OCF_InFree;
// OCF_Available
if (!Contained || (Contained->Def->GrabPutGet & C4D_Grab_Get) || (Contained->OCF & OCF_Entrance))
if (!GBackSemiSolid(GetX(), GetY()-1) || (!GBackSolid(GetX(), GetY()-1) && !GBackSemiSolid(GetX(), GetY()-8)))
OCF|=OCF_Available;
// OCF_Container
if ((Def->GrabPutGet & C4D_Grab_Put) || (Def->GrabPutGet & C4D_Grab_Get) || (OCF & OCF_Entrance))
OCF|=OCF_Container;
#ifdef DEBUGREC_OCF
if (Config.General.DebugRec)
{
C4RCOCF rc = { dwOCFOld, OCF, false };
AddDbgRec(RCT_OCF, &rc, sizeof(rc));
}
#endif
}
void C4Object::UpdateOCF()
{
C4PropList* pActionDef = GetAction();
#ifdef DEBUGREC_OCF
uint32_t dwOCFOld = OCF;
#endif
// Update the object character flag according to the object's current situation
C4Real cspeed=GetSpeed();
#ifdef _DEBUG
if (Contained && !C4PropListNumbered::CheckPropList(Contained))
{ LogF("Warning: contained in wild object %p!", static_cast<void*>(Contained)); }
else if (Contained && !Contained->Status)
{ LogF("Warning: contained in deleted object %p (%s)!", static_cast<void*>(Contained), Contained->GetName()); }
#endif
// Keep the bits that only have to be updated with SetOCF (def, category, con, alive, onfire)
OCF=OCF & (OCF_Normal | OCF_Exclusive | OCF_Grab | OCF_FullCon | OCF_Rotate | OCF_OnFire
| OCF_Inflammable | OCF_Alive | OCF_CrewMember | OCF_AttractLightning);
// OCF_Carryable: Can be picked up
if (GetPropertyInt(P_Collectible))
OCF|=OCF_Carryable;
// OCF_Construct: Can be built outside
if (Def->Constructable && (Con<FullCon)
&& (fix_r == Fix0) && !OnFire)
OCF|=OCF_Construct;
// OCF_Entrance: Can currently be entered/activated
if ((Def->Entrance.Wdt>0) && (Def->Entrance.Hgt>0))
if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (GetR() <= Def->RotatedEntrance)))
OCF|=OCF_Entrance;
// HitSpeeds
if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1;
if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2;
if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3;
if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4;
// OCF_Collection
if ((OCF & OCF_FullCon) || Def->IncompleteActivity)
if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0))
if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled)))
if (NoCollectDelay==0)
OCF|=OCF_Collection;
// OCF_NotContained
if (!Contained)
OCF|=OCF_NotContained;
// OCF_InLiquid
if (InLiquid)
if (!Contained)
OCF|=OCF_InLiquid;
// OCF_InSolid
if (!Contained)
if (GBackSolid(GetX(), GetY()))
OCF|=OCF_InSolid;
// OCF_InFree
if (!Contained)
if (!GBackSemiSolid(GetX(), GetY()-1))
OCF|=OCF_InFree;
// OCF_Available
if (!Contained || (Contained->Def->GrabPutGet & C4D_Grab_Get) || (Contained->OCF & OCF_Entrance))
if (!GBackSemiSolid(GetX(), GetY()-1) || (!GBackSolid(GetX(), GetY()-1) && !GBackSemiSolid(GetX(), GetY()-8)))
OCF|=OCF_Available;
// OCF_Container
if ((Def->GrabPutGet & C4D_Grab_Put) || (Def->GrabPutGet & C4D_Grab_Get) || (OCF & OCF_Entrance))
OCF|=OCF_Container;
#ifdef DEBUGREC_OCF
if (Config.General.DebugRec)
{
C4RCOCF rc = { dwOCFOld, OCF, true };
AddDbgRec(RCT_OCF, &rc, sizeof(rc));
}
#endif
#ifdef _DEBUG
DEBUGREC_OFF
uint32_t updateOCF = OCF;
SetOCF();
assert (updateOCF == OCF);
DEBUGREC_ON
#endif
}
bool C4Object::ExecLife()
{
// Breathing
if (!::Game.iTick5)
if (Alive && !Def->NoBreath)
{
// Supply check
bool Breathe=false;
// Forcefields are breathable.
if (GBackMat(GetX(), GetY()+Shape.GetY()/2)==MVehic)
{ Breathe=true; }
else if (GetPropertyInt(P_BreatheWater))
{ if (GBackMat(GetX(), GetY())==MWater) Breathe=true; }
else
{ if (!GBackSemiSolid(GetX(), GetY()+Shape.GetY()/2)) Breathe=true; }
if (Contained) Breathe=true;
// No supply
if (!Breathe)
{
// Reduce breath, then energy, bubble
if (Breath > 0) DoBreath(-5);
else DoEnergy(-1,false,C4FxCall_EngAsphyxiation, NO_OWNER);
}
// Supply
else
{
// Take breath
int32_t takebreath = GetPropertyInt(P_MaxBreath) - Breath;
if (takebreath > 0) DoBreath(takebreath);
}
}
// Corrosion energy loss
if (!::Game.iTick10)
if (Alive)
if (InMat!=MNone)
if (::MaterialMap.Map[InMat].Corrosive)
if (!GetPropertyInt(P_CorrosionResist))
DoEnergy(-::MaterialMap.Map[InMat].Corrosive/15,false,C4FxCall_EngCorrosion, NO_OWNER);
// InMat incineration
if (!::Game.iTick10)
if (InMat!=MNone)
if (::MaterialMap.Map[InMat].Incindiary)
if (GetPropertyInt(P_ContactIncinerate) > 0)
{
C4AulFunc *pCallFunc = GetFunc(PSF_OnInIncendiaryMaterial);
if (pCallFunc)
{
pCallFunc->Exec(this, &C4AulParSet());
}
}
// birthday
if (!::Game.iTick255)
if (Alive)
if (Info)
{
int32_t iPlayingTime = Info->TotalPlayingTime + (Game.Time - Info->InActionTime);
int32_t iNewAge = iPlayingTime / 3600 / 5;
if (Info->Age != iNewAge && Info->Age)
{
// message
GameMsgObject(FormatString(LoadResStr("IDS_OBJ_BIRTHDAY"),GetName (), Info->TotalPlayingTime / 3600 / 5).getData(),this);
StartSoundEffect("Trumpet",false,100,this);
}
Info->Age = iNewAge;
}
return true;
}
void C4Object::Execute()
{
if (Config.General.DebugRec)
{
// record debug
C4RCExecObj rc;
rc.Number=Number;
rc.fx=fix_x;
rc.fy=fix_y;
rc.fr=fix_r;
AddDbgRec(RCT_ExecObj, &rc, sizeof(rc));
}
// OCF
UpdateOCF();
// Command
ExecuteCommand();
// Action
// need not check status, because dead objects have lost their action
ExecAction();
// commands and actions are likely to have removed the object, and movement
// *must not* be executed for dead objects (SolidMask-errors)
if (!Status) return;
// Movement
ExecMovement();
if (!Status) return;
// effects
if (pEffects)
{
pEffects->Execute(this);
if (!Status) return;
}
// Life
ExecLife();
// Animation. If the mesh is attached, then don't execute animation here but let the parent object do it to make sure it is only executed once a frame.
if (pMeshInstance && !pMeshInstance->GetAttachParent())
pMeshInstance->ExecuteAnimation(1.0f/37.0f /* play smoothly at 37 FPS */);
// Menu
if (Menu) Menu->Execute();
}
bool C4Object::At(int32_t ctx, int32_t cty) const
{
if (Status) if (!Contained) if (Def)
if (Inside<int32_t>(cty - (GetY() + Shape.GetY() - addtop()), 0, Shape.Hgt - 1 + addtop()))
if (Inside<int32_t>(ctx - (GetX() + Shape.GetX()), 0, Shape.Wdt - 1))
return true;
return false;
}
bool C4Object::At(int32_t ctx, int32_t cty, DWORD &ocf) const
{
if (Status) if (!Contained) if (Def)
if (OCF & ocf)
if (Inside<int32_t>(cty - (GetY() + Shape.GetY() - addtop()), 0, Shape.Hgt - 1 + addtop()))
if (Inside<int32_t>(ctx - (GetX() + Shape.GetX()), 0, Shape.Wdt - 1))
{
// Set ocf return value
GetOCFForPos(ctx, cty, ocf);
return true;
}
return false;
}
void C4Object::GetOCFForPos(int32_t ctx, int32_t cty, DWORD &ocf) const
{
DWORD rocf=OCF;
// Verify entrance area OCF return
if (rocf & OCF_Entrance)
if (!Inside<int32_t>(cty - (GetY() + Def->Entrance.y), 0, Def->Entrance.Hgt - 1)
|| !Inside<int32_t>(ctx - (GetX() + Def->Entrance.x), 0, Def->Entrance.Wdt - 1))
rocf &= (~OCF_Entrance);
// Verify collection area OCF return
if (rocf & OCF_Collection)
if (!Inside<int32_t>(cty - (GetY() + Def->Collection.y), 0, Def->Collection.Hgt - 1)
|| !Inside<int32_t>(ctx - (GetX() + Def->Collection.x), 0, Def->Collection.Wdt - 1))
rocf &= (~OCF_Collection);
ocf=rocf;
}
void C4Object::AssignDeath(bool fForced)
{
C4Object *thing;
// Alive objects only
if (!Alive) return;
// clear all effects
// do not delete effects afterwards, because they might have denied removal
// set alive-flag before, so objects know what's up
// and prevent recursive death-calls this way
// get death causing player before doing effect calls, because those might meddle around with the flags
int32_t iDeathCausingPlayer = LastEnergyLossCausePlayer;
Alive=0;
if (pEffects) pEffects->ClearAll(this, C4FxCall_RemoveDeath);
// if the object is alive again, abort here if the kill is not forced
if (Alive && !fForced) return;
// Action
SetActionByName("Dead");
// Values
Alive=0;
ClearCommands();
C4ObjectInfo * pInfo = Info;
if (Info)
{
Info->HasDied=true;
++Info->DeathCount;
Info->Retire();
}
// Lose contents
while ((thing=Contents.GetObject())) thing->Exit(thing->GetX(),thing->GetY());
// Remove from crew/cursor/view
C4Player *pPlr = ::Players.Get(Owner);
if (pPlr) pPlr->ClearPointers(this, true);
// ensure objects that won't be affected by dead-plrview-decay are handled properly
if (!pPlr || !(Category & C4D_Living) || !pPlr->FoWViewObjs.IsContained(this))
SetPlrViewRange(0);
// Engine script call
C4AulParSet pars(C4VInt(iDeathCausingPlayer));
Call(PSF_Death, &pars);
// Update OCF. Done here because previously it would have been done in the next frame
// Whats worse: Having the OCF change because of some unrelated script-call like
// SetCategory, or slightly breaking compatibility?
SetOCF();
// Engine broadcast: relaunch player (in CR, this was called from clonk script.
// Now, it is done for every crew member)
if(pPlr)
if(!pPlr->Crew.ObjectCount())
::GameScript.GRBroadcast(PSF_RelaunchPlayer,
&C4AulParSet(C4VInt(Owner),C4VInt(iDeathCausingPlayer)));
if (pInfo)
pInfo->HasDied = false;
}
bool C4Object::ChangeDef(C4ID idNew)
{
// Get new definition
C4Def *pDef=C4Id2Def(idNew);
if (!pDef) return false;
// Containment storage
C4Object *pContainer=Contained;
// Exit container (no Ejection/Departure)
if (Contained) Exit(0,0,0,Fix0,Fix0,Fix0,false);
// Pre change resets
SetAction(0);
ResetProperty(&Strings.P[P_Action]); // Enforce ActIdle because SetAction may have failed due to NoOtherAction
SetDir(0); // will drop any outdated flipdir
if (pSolidMaskData) { delete pSolidMaskData; pSolidMaskData=NULL; }
Def->Count--;
// Def change
Def=pDef;
SetProperty(P_Prototype, C4VPropList(pDef));
id=pDef->id;
Def->Count++;
// new def: Needs to be resorted
Unsorted=true;
// graphics change
pGraphics = &pDef->Graphics;
// blit mode adjustment
if (!(BlitMode & C4GFXBLIT_CUSTOM)) BlitMode = Def->BlitMode;
// an object may have newly become an ColorByOwner-object
// if it had been ColorByOwner, but is not now, this will be caught in UpdateGraphics()
if (!Color && ValidPlr(Owner))
Color=::Players.Get(Owner)->ColorDw;
if (!Def->Rotateable) { fix_r=rdir=Fix0; }
// Reset solid mask
SolidMask=Def->SolidMask;
// Post change updates
UpdateGraphics(true);
UpdateMass();
UpdateFace(true);
SetOCF();
// Any effect callbacks to this object might need to reinitialize their target functions
// This is ugly, because every effect there is must be updated...
if (Game.pGlobalEffects) Game.pGlobalEffects->OnObjectChangedDef(this);
for (C4ObjectLink *pLnk = ::Objects.First; pLnk; pLnk = pLnk->Next)
if (pLnk->Obj->pEffects) pLnk->Obj->pEffects->OnObjectChangedDef(this);
// Containment (no Entrance)
if (pContainer) Enter(pContainer,false);
// Done
return true;
}
void C4Object::DoDamage(int32_t iChange, int32_t iCausedBy, int32_t iCause)
{
// non-living: ask effects first
if (pEffects && !Alive)
{
pEffects->DoDamage(this, iChange, iCause, iCausedBy);
if (!iChange) return;
}
// Change value
Damage = Max<int32_t>( Damage+iChange, 0 );
// Engine script call
Call(PSF_Damage,&C4AulParSet(C4VInt(iChange), C4VInt(iCause), C4VInt(iCausedBy)));
}
void C4Object::DoEnergy(int32_t iChange, bool fExact, int32_t iCause, int32_t iCausedByPlr)
{
// iChange 100% = Physical 100000
if (!fExact) iChange=iChange*C4MaxPhysical/100;
// Was zero?
bool fWasZero=(Energy==0);
// Mark last damage causing player to trace kills
if (iChange < 0) UpdatLastEnergyLossCause(iCausedByPlr);
// Living things: ask effects for change first
if (pEffects && Alive)
pEffects->DoDamage(this, iChange, iCause, iCausedByPlr);
// Do change
iChange = BoundBy<int32_t>(iChange, -Energy, GetPropertyInt(P_MaxEnergy) - Energy);
Energy += iChange;
// call to object
Call(PSF_EnergyChange,&C4AulParSet(C4VInt(iChange), C4VInt(iCause), C4VInt(iCausedByPlr)));
// Alive and energy reduced to zero: death
if (Alive) if (Energy==0) if (!fWasZero) AssignDeath(false);
}
void C4Object::UpdatLastEnergyLossCause(int32_t iNewCausePlr)
{
// Mark last damage causing player to trace kills
// do not regard self-administered damage if there was a previous damage causing player, because that would steal kills
// if people tumble themselves via stop-stop-(left/right)-throw while falling into teh abyss
if (iNewCausePlr != Controller || LastEnergyLossCausePlayer < 0)
{
LastEnergyLossCausePlayer = iNewCausePlr;
}
}
void C4Object::DoBreath(int32_t iChange)
{
// Do change
iChange = BoundBy<int32_t>(iChange, -Breath, GetPropertyInt(P_MaxBreath) - Breath);
Breath += iChange;
// call to object
Call(PSF_BreathChange,&C4AulParSet(C4VInt(iChange)));
}
void C4Object::DoCon(int32_t iChange)
{
C4Real strgt_con_b = fix_y + Shape.GetBottom();
bool fWasFull = (Con>=FullCon);
// Change con
if (Def->Oversize)
Con=Max<int32_t>(Con+iChange,0);
else
Con=BoundBy<int32_t>(Con+iChange,0,FullCon);
// Update OCF
SetOCF();
// Mass
UpdateMass();
// shape and position
UpdateShape();
// make the bottom-most vertex stay in place
fix_y = strgt_con_b - Shape.GetBottom();
// Face (except for the shape)
UpdateFace(false);
// component update
// Decay: reduce components
if (iChange<0)
ComponentConCutoff();
// Growth: gain components
else
ComponentConGain();
// Unfullcon
if (fWasFull && (Con<FullCon))
{
// Lose contents
if (!Def->IncompleteActivity)
{
C4Object *cobj;
while ((cobj=Contents.GetObject()))
if (Contained) cobj->Enter(Contained);
else cobj->Exit(cobj->GetX(),cobj->GetY());
SetAction(0);
}
}
// Completion
if (!fWasFull && (Con>=FullCon))
Call(PSF_Initialize);
// Con Zero Removal
if (Con<=0)
AssignRemoval();
// Mesh Graphics Update
else if(pMeshInstance)
pMeshInstance->SetCompletion(Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
}
void C4Object::DoExperience(int32_t change)
{
const int32_t MaxExperience = 100000000;
if (!Info) return;
Info->Experience=BoundBy<int32_t>(Info->Experience+change,0,MaxExperience);
// Promotion check
if (Info->Experience<MaxExperience)
if (Info->Experience>=::DefaultRanks.Experience(Info->Rank+1))
Promote(Info->Rank+1, false, false);
}
bool C4Object::Exit(int32_t iX, int32_t iY, int32_t iR, C4Real iXDir, C4Real iYDir, C4Real iRDir, bool fCalls)
{
// 1. Exit the current container.
// 2. Update Contents of container object and set Contained to NULL.
// 3. Set offset position/motion if desired.
// 4. Call Ejection for container and Departure for object.
// Not contained
C4Object *pContainer=Contained;
if (!pContainer) return false;
// Remove object from container
pContainer->Contents.Remove(this);
pContainer->UpdateMass();
pContainer->SetOCF();
// No container
Contained=NULL;
// Position/motion
fix_x=itofix(iX); fix_y=itofix(iY);
fix_r=itofix(iR);
BoundsCheck(fix_x, fix_y);
xdir=iXDir; ydir=iYDir; rdir=iRDir;
// Misc updates
Mobile=1;
InLiquid=0;
CloseMenu(true);
UpdateFace(true);
SetOCF();
// Engine calls
if (fCalls) pContainer->Call(PSF_Ejection,&C4AulParSet(C4VObj(this)));
if (fCalls) Call(PSF_Departure,&C4AulParSet(C4VObj(pContainer)));
// Success (if the obj wasn't "re-entered" by script)
return !Contained;
}
bool C4Object::Enter(C4Object *pTarget, bool fCalls, bool fCopyMotion, bool *pfRejectCollect)
{
// 0. Query entrance and collection
// 1. Exit if contained.
// 2. Set new container.
// 3. Update Contents and mass of the new container.
// 4. Call collection for container
// 5. Call entrance for object.
// No target or target is self
if (!pTarget || (pTarget==this)) return false;
// check if entrance is allowed
if (!! Call(PSF_RejectEntrance, &C4AulParSet(C4VObj(pTarget)))) return false;
// check if we end up in an endless container-recursion
for (C4Object *pCnt=pTarget->Contained; pCnt; pCnt=pCnt->Contained)
if (pCnt==this) return false;
// Check RejectCollect, if desired
if (pfRejectCollect)
{
if (!!pTarget->Call(PSF_RejectCollection,&C4AulParSet(C4VPropList(Def), C4VObj(this))))
{
*pfRejectCollect = true;
return false;
}
*pfRejectCollect = false;
}
// Exit if contained
if (Contained) if (!Exit(GetX(),GetY())) return false;
if (Contained || !Status || !pTarget->Status) return false;
// Failsafe updates
CloseMenu(true);
SetOCF();
// Set container
Contained=pTarget;
// Enter
if (!Contained->Contents.Add(this, C4ObjectList::stContents))
{
Contained=NULL;
return false;
}
// Assume that the new container controls this object, if it cannot control itself (i.e.: Alive)
// So it can be traced back who caused the damage, if a projectile hits its target
if (!Alive)
Controller = pTarget->Controller;
// Misc updates
// motion must be copied immediately, so the position will be correct when OCF is set, and
// OCF_Available will be set for newly bought items, even if 50/50 is solid in the landscape
// however, the motion must be preserved sometimes to keep flags like OCF_HitSpeed upon collection
if (fCopyMotion)
{
// remove any solidmask before copying the motion...
UpdateSolidMask(false);
CopyMotion(Contained);
}
SetOCF();
UpdateFace(true);
// Update container
Contained->UpdateMass();
Contained->SetOCF();
// Collection call
if (fCalls) pTarget->Call(PSF_Collection2,&C4AulParSet(C4VObj(this)));
if (!Contained || !Contained->Status || !pTarget->Status) return true;
// Entrance call
if (fCalls) Call(PSF_Entrance,&C4AulParSet(C4VObj(Contained)));
if (!Contained || !Contained->Status || !pTarget->Status) return true;
// Success
return true;
}
void C4Object::Fling(C4Real txdir, C4Real tydir, bool fAddSpeed)
{
if (fAddSpeed) { txdir+=xdir/2; tydir+=ydir/2; }
if (!ObjectActionTumble(this,(txdir<0),txdir,tydir))
if (!ObjectActionJump(this,txdir,tydir,false))
{
xdir=txdir; ydir=tydir;
Mobile=1;
Action.t_attach&=~CNAT_Bottom;
}
}
bool C4Object::ActivateEntrance(int32_t by_plr, C4Object *by_obj)
{
// Try entrance activation
if (OCF & OCF_Entrance)
if (!! Call(PSF_ActivateEntrance,&C4AulParSet(C4VObj(by_obj))))
return true;
// Failure
return false;
}
bool C4Object::Push(C4Real txdir, C4Real dforce, bool fStraighten)
{
// Valid check
if (!Status || !Def || Contained || !(OCF & OCF_Grab)) return false;
// Grabbing okay, no pushing
if (GetPropertyInt(P_Touchable)==2) return true;
// Mobilization check (pre-mobilization zero)
if (!Mobile)
{ xdir=ydir=Fix0; }
// General pushing force vs. object mass
dforce=dforce*100/Mass;
// Set dir
if (xdir<0) SetDir(DIR_Left);
if (xdir>0) SetDir(DIR_Right);
// Work towards txdir
if (Abs(xdir-txdir)<=dforce) // Close-enough-set
{ xdir=txdir; }
else // Work towards
{
if (xdir<txdir) xdir+=dforce;
if (xdir>txdir) xdir-=dforce;
}
// Straighten
if (fStraighten)
{
if (Inside<int32_t>(GetR(),-StableRange,+StableRange))
{
rdir=0; // cheap way out
}
else
{
if (fix_r > Fix0) { if (rdir>-RotateAccel) rdir-=dforce; }
else { if (rdir<+RotateAccel) rdir+=dforce; }
}
}
// Mobilization check
if (!!xdir || !!ydir || !!rdir) Mobile=1;
// Stuck check
if (!::Game.iTick35) if (txdir) if (!Def->NoHorizontalMove)
if (ContactCheck(GetX(), GetY())) // Resets t_contact
{
GameMsgObjectError(FormatString(LoadResStr("IDS_OBJ_STUCK"),GetName()).getData(),this);
Call(PSF_Stuck);
}
return true;
}
bool C4Object::Lift(C4Real tydir, C4Real dforce)
{
// Valid check
if (!Status || !Def || Contained) return false;
// Mobilization check
if (!Mobile)
{ xdir=ydir=Fix0; Mobile=1; }
// General pushing force vs. object mass
dforce=dforce*100/Mass;
// If close enough, set tydir
if (Abs(tydir-ydir)<=Abs(dforce))
ydir=tydir;
else // Work towards tydir
{
if (ydir<tydir) ydir+=dforce;
if (ydir>tydir) ydir-=dforce;
}
// Stuck check
if (tydir != -GravAccel)
if (ContactCheck(GetX(), GetY())) // Resets t_contact
{
GameMsgObjectError(FormatString(LoadResStr("IDS_OBJ_STUCK"),GetName()).getData(),this);
Call(PSF_Stuck);
}
return true;
}
C4Object* C4Object::CreateContents(C4PropList * PropList)
{
C4Object *nobj;
if (!(nobj=Game.CreateObject(PropList,this,Owner))) return NULL;
if (!nobj->Enter(this)) { nobj->AssignRemoval(); return NULL; }
return nobj;
}
bool C4Object::CreateContentsByList(C4IDList &idlist)
{
int32_t cnt,cnt2;
for (cnt=0; idlist.GetID(cnt); cnt++)
for (cnt2=0; cnt2<idlist.GetCount(cnt); cnt2++)
if (!CreateContents(C4Id2Def(idlist.GetID(cnt))))
return false;
return true;
}
static void DrawMenuSymbol(int32_t iMenu, C4Facet &cgo, int32_t iOwner)
{
C4Facet ccgo;
DWORD dwColor=0;
if (ValidPlr(iOwner)) dwColor=::Players.Get(iOwner)->ColorDw;
switch (iMenu)
{
case C4MN_Buy:
::GraphicsResource.fctFlagClr.DrawClr(ccgo = cgo.GetFraction(75, 75), true, dwColor);
::GraphicsResource.fctWealth.Draw(ccgo = cgo.GetFraction(100, 50, C4FCT_Left, C4FCT_Bottom));
::GraphicsResource.fctArrow.Draw(ccgo = cgo.GetFraction(70, 70, C4FCT_Right, C4FCT_Center), false, 0);
break;
case C4MN_Sell:
::GraphicsResource.fctFlagClr.DrawClr(ccgo = cgo.GetFraction(75, 75), true, dwColor);
::GraphicsResource.fctWealth.Draw(ccgo = cgo.GetFraction(100, 50, C4FCT_Left, C4FCT_Bottom));
::GraphicsResource.fctArrow.Draw(ccgo = cgo.GetFraction(70, 70, C4FCT_Right, C4FCT_Center), false, 1);
break;
}
}
bool C4Object::ActivateMenu(int32_t iMenu, int32_t iMenuSelect,
int32_t iMenuData, int32_t iMenuPosition,
C4Object *pTarget)
{
// Variables
C4FacetSurface fctSymbol;
C4IDList ListItems;
// Close any other menu
//CloseMenu(true);
if (Menu && Menu->IsActive()) if (!Menu->TryClose(true, false)) return false;
// Create menu
if (!Menu) Menu = new C4ObjectMenu; else Menu->ClearItems();
// Open menu
switch (iMenu)
{
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case C4MN_Activate:
// No target specified: use own container as target
if (!pTarget) if (!(pTarget=Contained)) break;
// Opening contents menu blocked by RejectContents
if (!!pTarget->Call(PSF_RejectContents)) return false;
// Create symbol
fctSymbol.Create(C4SymbolSize,C4SymbolSize);
pTarget->Def->Draw(fctSymbol,false,pTarget->Color,pTarget);
// Init
Menu->Init(fctSymbol,FormatString(LoadResStr("IDS_OBJ_EMPTY"),pTarget->GetName()).getData(),this,C4MN_Extra_None,0,iMenu);
Menu->SetPermanent(true);
Menu->SetRefillObject(pTarget);
// Success
return true;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case C4MN_Buy:
// No target specified: container is base
if (!pTarget) if (!(pTarget=Contained)) break;
// Create symbol
fctSymbol.Create(C4SymbolSize,C4SymbolSize);
//pTarget->Def->Draw(fctSymbol,false,pTarget->Color,pTarget);
DrawMenuSymbol(C4MN_Buy, fctSymbol, pTarget->Owner);
// Init menu
Menu->Init(fctSymbol,LoadResStr("IDS_PLR_NOBUY"),this,C4MN_Extra_Value,0,iMenu);
Menu->SetPermanent(true);
Menu->SetRefillObject(pTarget);
// Success
return true;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case C4MN_Sell:
// No target specified: container is base
if (!pTarget) if (!(pTarget=Contained)) break;
// Create symbol & init
fctSymbol.Create(C4SymbolSize,C4SymbolSize);
//pTarget->Def->Draw(fctSymbol,false,pTarget->Color,pTarget);
DrawMenuSymbol(C4MN_Sell, fctSymbol, pTarget->Owner);
Menu->Init(fctSymbol,FormatString(LoadResStr("IDS_OBJ_EMPTY"),pTarget->GetName()).getData(),this,C4MN_Extra_Value,0,iMenu);
Menu->SetPermanent(true);
Menu->SetRefillObject(pTarget);
// Success
return true;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case C4MN_Get:
case C4MN_Contents:
// No target specified
if (!pTarget) break;
// Opening contents menu blocked by RejectContents
if (!!pTarget->Call(PSF_RejectContents)) return false;
// Create symbol & init
fctSymbol.Create(C4SymbolSize,C4SymbolSize);
pTarget->Def->Draw(fctSymbol,false,pTarget->Color,pTarget);
Menu->Init(fctSymbol,FormatString(LoadResStr("IDS_OBJ_EMPTY"),pTarget->GetName()).getData(),this,C4MN_Extra_None,0,iMenu);
Menu->SetPermanent(true);
Menu->SetRefillObject(pTarget);
// Success
return true;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case C4MN_Info:
// Target by parameter
if (!pTarget) break;
// Create symbol & init menu
fctSymbol.Create(C4SymbolSize, C4SymbolSize); GfxR->fctOKCancel.Draw(fctSymbol,true,0,1);
Menu->Init(fctSymbol, pTarget->GetName(), this, C4MN_Extra_None, 0, iMenu, C4MN_Style_Info);
Menu->SetPermanent(true);
Menu->SetAlignment(C4MN_Align_Free);
C4Viewport *pViewport = ::Viewports.GetViewport(Controller); // Hackhackhack!!!
if (pViewport) Menu->SetLocation((pTarget->GetX() + pTarget->Shape.GetX() + pTarget->Shape.Wdt + 10 - pViewport->ViewX) * pViewport->GetZoom(),
(pTarget->GetY() + pTarget->Shape.GetY() - pViewport->ViewY) * pViewport->GetZoom());
// Add info item
fctSymbol.Create(C4PictureSize, C4PictureSize); pTarget->Def->Draw(fctSymbol, false, pTarget->Color, pTarget);
Menu->Add(pTarget->GetName(), fctSymbol, "", C4MN_Item_NoCount, NULL, pTarget->GetInfoString().getData());
fctSymbol.Default();
// Success
return true;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}
// Invalid menu identification
CloseMenu(true);
return false;
}
bool C4Object::CloseMenu(bool fForce)
{
if (Menu)
{
if (Menu->IsActive()) if (!Menu->TryClose(fForce, false)) return false;
if (!Menu->IsCloseQuerying()) { delete Menu; Menu=NULL; } // protect menu deletion from recursive menu operation calls
}
return true;
}
BYTE C4Object::GetArea(int32_t &aX, int32_t &aY, int32_t &aWdt, int32_t &aHgt) const
{
if (!Status || !Def) return 0;
aX = GetX() + Shape.GetX(); aY = GetY() + Shape.GetY();
aWdt=Shape.Wdt; aHgt=Shape.Hgt;
return 1;
}
BYTE C4Object::GetEntranceArea(int32_t &aX, int32_t &aY, int32_t &aWdt, int32_t &aHgt) const
{
if (!Status || !Def) return 0;
// Return actual entrance
if (OCF & OCF_Entrance)
{
aX=GetX() + Def->Entrance.x;
aY=GetY() + Def->Entrance.y;
aWdt=Def->Entrance.Wdt;
aHgt=Def->Entrance.Hgt;
}
// Return object center
else
{
aX=GetX(); aY=GetY();
aWdt=0; aHgt=0;
}
// Done
return 1;
}
BYTE C4Object::GetMomentum(C4Real &rxdir, C4Real &rydir) const
{
rxdir=rydir=0;
if (!Status || !Def) return 0;
rxdir=xdir; rydir=ydir;
return 1;
}
C4Real C4Object::GetSpeed() const
{
C4Real cobjspd=Fix0;
if (xdir<0) cobjspd-=xdir; else cobjspd+=xdir;
if (ydir<0) cobjspd-=ydir; else cobjspd+=ydir;
return cobjspd;
}
StdStrBuf C4Object::GetDataString()
{
StdStrBuf Output;
// Type
Output.AppendFormat(LoadResStr("IDS_CNS_TYPE"),GetName(),Def->id.ToString());
// Owner
if (ValidPlr(Owner))
{
Output.Append(LineFeed);
Output.AppendFormat(LoadResStr("IDS_CNS_OWNER"),::Players.Get(Owner)->GetName());
}
// Contents
if (Contents.ObjectCount())
{
Output.Append(LineFeed);
Output.Append(LoadResStr("IDS_CNS_CONTENTS"));
Output.Append(Contents.GetNameList(::Definitions));
}
// Action
if (GetAction())
{
Output.Append(LineFeed);
Output.Append(LoadResStr("IDS_CNS_ACTION"));
Output.Append(GetAction()->GetName());
}
// Properties
Output.Append(LineFeed);
Output.Append(LoadResStr("IDS_CNS_PROPERTIES"));
Output.Append(LineFeed " ");
AppendDataString(&Output, LineFeed " ");
// Effects
if (pEffects)
{
Output.Append(LineFeed);
Output.Append(LoadResStr("IDS_CNS_EFFECTS"));
}
for (C4Effect *pEffect = pEffects; pEffect; pEffect = pEffect->pNext)
{
Output.Append(LineFeed);
// Effect name
Output.AppendFormat(" %s: Priority %d, Interval %d", pEffect->GetName(), pEffect->iPriority, pEffect->iInterval);
}
StdStrBuf Output2;
C4ValueNumbers numbers;
DecompileToBuf_Log<StdCompilerINIWrite>(mkNamingAdapt(mkInsertAdapt(mkParAdapt(*this, &numbers),
mkNamingAdapt(numbers, "Values"), false),
"Object"), &Output2, "C4Object::GetDataString");
Output.Append(LineFeed);
Output.Append(Output2);
return Output;
}
void C4Object::SetName(const char * NewName)
{
if (!NewName && Info)
C4PropList::SetName(Info->Name);
else
C4PropList::SetName(NewName);
}
int32_t C4Object::GetValue(C4Object *pInBase, int32_t iForPlayer)
{
C4Value r = Call(PSF_CalcValue, &C4AulParSet(C4VObj(pInBase), C4VInt(iForPlayer)));
int32_t iValue;
if (r != C4VNull)
iValue = r.getInt();
else
{
// get value of def
// Caution: Do not pass pInBase here, because the def base value is to be queried
// - and not the value if you had to buy the object in this particular base
iValue = Def->GetValue(NULL, iForPlayer);
}
// Con percentage
iValue = iValue * Con / FullCon;
// do any adjustments based on where the item is bought
if (pInBase)
{
r = pInBase->Call(PSF_CalcSellValue, &C4AulParSet(C4VObj(this), C4VInt(iValue)));
if (r != C4VNull)
iValue = r.getInt();
}
return iValue;
}
bool C4Object::Promote(int32_t torank, bool exception, bool fForceRankName)
{
if (!Info) return false;
// get rank system
C4Def *pUseDef = C4Id2Def(Info->id);
C4RankSystem *pRankSys;
if (pUseDef && pUseDef->pRankNames)
pRankSys = pUseDef->pRankNames;
else
pRankSys = &::DefaultRanks;
// always promote info
Info->Promote(torank,*pRankSys, fForceRankName);
// silent update?
if (!pRankSys->GetRankName(torank,false)) return false;
GameMsgObject(FormatString(LoadResStr("IDS_OBJ_PROMOTION"),GetName (),Info->sRankName.getData()).getData(),this);
// call to object
Call(PSF_Promotion);
StartSoundEffect("Trumpet",0,100,this);
return true;
}
void C4Object::ClearPointers(C4Object *pObj)
{
// mesh attachments and animation nodes
if(pMeshInstance) pMeshInstance->ClearPointers(pObj);
// effects
if (pEffects) pEffects->ClearPointers(pObj);
// contents/contained: not necessary, because it's done in AssignRemoval and StatusDeactivate
// Action targets
if (Action.Target==pObj) Action.Target=NULL;
if (Action.Target2==pObj) Action.Target2=NULL;
// Commands
C4Command *cCom;
for (cCom=Command; cCom; cCom=cCom->Next)
cCom->ClearPointers(pObj);
// Menu
if (Menu) Menu->ClearPointers(pObj);
// Layer
if (Layer==pObj) Layer=NULL;
// gfx overlays
if (pGfxOverlay)
{
C4GraphicsOverlay *pNextGfxOvrl = pGfxOverlay, *pGfxOvrl;
while ((pGfxOvrl = pNextGfxOvrl))
{
pNextGfxOvrl = pGfxOvrl->GetNext();
if (pGfxOvrl->GetOverlayObject() == pObj)
// overlay relying on deleted object: Delete!
RemoveGraphicsOverlay(pGfxOvrl->GetID());
}
}
}
bool C4Object::SetPhase(int32_t iPhase)
{
C4PropList* pActionDef = GetAction();
if (!pActionDef) return false;
const int32_t length = pActionDef->GetPropertyInt(P_Length);
Action.Phase=BoundBy<int32_t>(iPhase,0,length);
Action.PhaseDelay = 0;
return true;
}
void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode, float offX, float offY)
{
#ifndef USE_CONSOLE
C4Facet ccgo;
// Status
if (!Status || !Def) return;
// visible?
if (!IsVisible(iByPlayer, !!eDrawMode)) return;
// Line
if (Def->Line) { DrawLine(cgo); return; }
// background particles (bounds not checked)
if (BackParticles) BackParticles->Draw(cgo, this);
// Object output position
float newzoom;
if (eDrawMode!=ODM_Overlay)
{
if (!GetDrawPosition(cgo, offX, offY, newzoom)) return;
}
ZoomDataStackItem zdsi(newzoom);
bool fYStretchObject=false;
C4PropList* pActionDef = GetAction();
if (pActionDef)
if (pActionDef->GetPropertyInt(P_FacetTargetStretch))
fYStretchObject=true;
// Set audibility
if (!eDrawMode) SetAudibilityAt(cgo, GetX(), GetY());
// Output boundary
if (!fYStretchObject && !eDrawMode && !(Category & C4D_Parallax))
{
if (pActionDef && fix_r == Fix0 && !pActionDef->GetPropertyInt(P_FacetBase) && Con<=FullCon)
{
// active
if ( !Inside<float>(offX+Shape.GetX()+Action.FacetX,cgo.X-Action.Facet.Wdt,cgo.X+cgo.Wdt)
|| (!Inside<float>(offY+Shape.GetY()+Action.FacetY,cgo.Y-Action.Facet.Hgt,cgo.Y+cgo.Hgt)) )
{
if (FrontParticles && !Contained) FrontParticles->Draw(cgo, this);
return;
}
}
else
// idle
if ( !Inside<float>(offX+Shape.GetX(),cgo.X-Shape.Wdt,cgo.X+cgo.Wdt)
|| (!Inside<float>(offY+Shape.GetY(),cgo.Y-Shape.Hgt,cgo.Y+cgo.Hgt)) )
{
if (FrontParticles && !Contained) FrontParticles->Draw(cgo, this);
return;
}
}
// ensure correct color is set
if (GetGraphics()->Type == C4DefGraphics::TYPE_Bitmap)
if (GetGraphics()->Bmp.BitmapClr) GetGraphics()->Bmp.BitmapClr->SetClr(Color);
// Debug Display //////////////////////////////////////////////////////////////////////
if (::GraphicsSystem.ShowCommand && !eDrawMode)
{
C4Command *pCom;
int32_t ccx=GetX(),ccy=GetY();
float offX1, offY1, offX2, offY2, newzoom;
char szCommand[200];
StdStrBuf Cmds;
int32_t iMoveTos=0;
for (pCom=Command; pCom; pCom=pCom->Next)
{
switch (pCom->Command)
{
case C4CMD_MoveTo:
// Angle
int32_t iAngle; iAngle=Angle(ccx,ccy,pCom->Tx._getInt(),pCom->Ty); while (iAngle>180) iAngle-=360;
// Path
if(GetDrawPosition(cgo, ccx, ccy, cgo.Zoom, offX1, offY1, newzoom) &&
GetDrawPosition(cgo, pCom->Tx._getInt(), pCom->Ty, cgo.Zoom, offX2, offY2, newzoom))
{
ZoomDataStackItem zdsi(newzoom);
pDraw->DrawLineDw(cgo.Surface,offX1,offY1,offX2,offY2,C4RGB(0xca,0,0));
pDraw->DrawFrameDw(cgo.Surface,offX2-1,offY2-1,offX2+1,offY2+1,C4RGB(0xca,0,0));
}
ccx=pCom->Tx._getInt(); ccy=pCom->Ty;
// Message
iMoveTos++; szCommand[0]=0;
//sprintf(szCommand,"%s %d/%d",CommandName(pCom->Command),pCom->Tx,pCom->Ty,iAngle);
break;
case C4CMD_Put:
sprintf(szCommand,"%s %s to %s",CommandName(pCom->Command),pCom->Target2 ? pCom->Target2->GetName() : pCom->Data ? pCom->Data.getC4ID().ToString() : "Content",pCom->Target ? pCom->Target->GetName() : "");
break;
case C4CMD_Buy: case C4CMD_Sell:
sprintf(szCommand,"%s %s at %s",CommandName(pCom->Command),pCom->Data.getC4ID().ToString(),pCom->Target ? pCom->Target->GetName() : "closest base");
break;
case C4CMD_Acquire:
sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Data.getC4ID().ToString());
break;
case C4CMD_Call:
sprintf(szCommand,"%s %s in %s",CommandName(pCom->Command),pCom->Text->GetCStr(),pCom->Target ? pCom->Target->GetName() : "(null)");
break;
case C4CMD_None:
szCommand[0]=0;
break;
case C4CMD_Transfer:
// Path
if(GetDrawPosition(cgo, ccx, ccy, cgo.Zoom, offX1, offY1, newzoom) &&
GetDrawPosition(cgo, pCom->Tx._getInt(), pCom->Ty, cgo.Zoom, offX2, offY2, newzoom))
{
ZoomDataStackItem zdsi(newzoom);
pDraw->DrawLineDw(cgo.Surface,offX1,offY1,offX2,offY2,C4RGB(0,0xca,0));
pDraw->DrawFrameDw(cgo.Surface,offX2-1,offY2-1,offX2+1,offY2+1,C4RGB(0,0xca,0));
}
ccx=pCom->Tx._getInt(); ccy=pCom->Ty;
// Message
sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Target ? pCom->Target->GetName() : "");
break;
default:
sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Target ? pCom->Target->GetName() : "");
break;
}
// Compose command stack message
if (szCommand[0])
{
// End MoveTo stack first
if (iMoveTos) { Cmds.AppendChar('|'); Cmds.AppendFormat("%dx MoveTo",iMoveTos); iMoveTos=0; }
// Current message
Cmds.AppendChar('|');
if (pCom->Finished) Cmds.Append("<i>");
Cmds.Append(szCommand);
if (pCom->Finished) Cmds.Append("</i>");
}
}
// Open MoveTo stack
if (iMoveTos) { Cmds.AppendChar('|'); Cmds.AppendFormat("%dx MoveTo",iMoveTos); iMoveTos=0; }
// Draw message
int32_t cmwdt,cmhgt; ::GraphicsResource.FontRegular.GetTextExtent(Cmds.getData(),cmwdt,cmhgt,true);
pDraw->TextOut(Cmds.getData(), ::GraphicsResource.FontRegular, 1.0, cgo.Surface,offX,offY+Shape.GetY()-10-cmhgt,C4Draw::DEFAULT_MESSAGE_COLOR,ACenter);
}
// Debug Display ///////////////////////////////////////////////////////////////////////////////
// Don't draw (show solidmask)
if (::GraphicsSystem.ShowSolidMask)
if (SolidMask.Wdt)
{
// DrawSolidMask(cgo); - no need to draw it, because the 8bit-surface will be shown
return;
}
// Contained check
if (Contained && !eDrawMode) return;
// Visibility inside FoW
bool fOldClrModEnabled = !!(Category & C4D_IgnoreFoW);
if (fOldClrModEnabled)
{
fOldClrModEnabled = pDraw->GetClrModMapEnabled();
pDraw->SetClrModMapEnabled(false);
}
// Fire facet - always draw, even if particles are drawn as well
if (OnFire && eDrawMode!=ODM_BaseOnly)
{
C4Facet fgo;
// Straight: Full Shape.Rect on fire
if (fix_r == Fix0)
{
fgo.Set(cgo.Surface,offX + Shape.GetX(),offY + Shape.GetY(),
Shape.Wdt,Shape.Hgt-Shape.FireTop);
}
// Rotated: Reduced fire rect
else
{
C4Rect fr;
Shape.GetVertexOutline(fr);
fgo.Set(cgo.Surface,
offX + fr.x,
offY + fr.y,
fr.Wdt, fr.Hgt);
}
::GraphicsResource.fctFire.Draw(fgo,false,(Number + Game.FrameCounter) % MaxFirePhase);
}
// color modulation (including construction sign...)
if (ColorMod != 0xffffffff || BlitMode) if (!eDrawMode) PrepareDrawing();
// Not active or rotated: BaseFace only
if (!pActionDef)
{
DrawFace(cgo, offX, offY);
}
// Active
else
{
// FacetBase
if (pActionDef->GetPropertyInt(P_FacetBase) || GetGraphics()->Type != C4DefGraphics::TYPE_Bitmap)
DrawFace(cgo, offX, offY, 0, Action.DrawDir);
// Special: stretched action facet
if (Action.Facet.Surface && pActionDef->GetPropertyInt(P_FacetTargetStretch))
{
if (Action.Target)
pDraw->Blit(Action.Facet.Surface,
float(Action.Facet.X),float(Action.Facet.Y),float(Action.Facet.Wdt),float(Action.Facet.Hgt),
cgo.Surface,
offX + Shape.GetX() + Action.FacetX, offY + Shape.GetY() + Action.FacetY,Action.Facet.Wdt,
(fixtof(Action.Target->fix_y) + Action.Target->Shape.GetY()) - (fixtof(fix_y) + Shape.GetY() + Action.FacetY),
true);
}
else if (Action.Facet.Surface)
DrawActionFace(cgo, offX, offY);
}
// end of color modulation
if (ColorMod != 0xffffffff || BlitMode) if (!eDrawMode) FinishedDrawing();
// draw overlays - after blit mode changes, because overlay gfx set their own
if (pGfxOverlay) if (eDrawMode!=ODM_BaseOnly)
for (C4GraphicsOverlay *pGfxOvrl = pGfxOverlay; pGfxOvrl; pGfxOvrl = pGfxOvrl->GetNext())
if (!pGfxOvrl->IsPicture())
pGfxOvrl->Draw(cgo, this, iByPlayer);
// local particles in front of the object
if (eDrawMode!=ODM_BaseOnly)
{
if (FrontParticles)
FrontParticles->Draw(cgo, this);
}
// Debug Display ////////////////////////////////////////////////////////////////////////
if (::GraphicsSystem.ShowVertices) if (eDrawMode!=ODM_BaseOnly)
{
int32_t cnt;
if (Shape.VtxNum>1)
for (cnt=0; cnt<Shape.VtxNum; cnt++)
{
DrawVertex(cgo,
offX+Shape.VtxX[cnt],
offY+Shape.VtxY[cnt],
(Shape.VtxCNAT[cnt] & CNAT_NoCollision) ? C4RGB(0, 0, 0xff) : (Mobile ? C4RGB(0xff, 0, 0) : C4RGB(0xef, 0xef, 0)),
Shape.VtxContactCNAT[cnt]);
}
}
if (::GraphicsSystem.ShowEntrance) if (eDrawMode!=ODM_BaseOnly)
{
if (OCF & OCF_Entrance)
pDraw->DrawFrameDw(cgo.Surface,offX+Def->Entrance.x,
offY+Def->Entrance.y,
offX+Def->Entrance.x+Def->Entrance.Wdt-1,
offY+Def->Entrance.y+Def->Entrance.Hgt-1,
C4RGB(0, 0, 0xff));
if (OCF & OCF_Collection)
pDraw->DrawFrameDw(cgo.Surface,offX+Def->Collection.x,
offY+Def->Collection.y,
offX+Def->Collection.x+Def->Collection.Wdt-1,
offY+Def->Collection.y+Def->Collection.Hgt-1,
C4RGB(0xca, 0, 0));
}
if (::GraphicsSystem.ShowAction) if (eDrawMode!=ODM_BaseOnly)
{
if (pActionDef)
{
StdStrBuf str;
str.Format("%s (%d)",pActionDef->GetName(),Action.Phase);
int32_t cmwdt,cmhgt; ::GraphicsResource.FontRegular.GetTextExtent(str.getData(),cmwdt,cmhgt,true);
pDraw->TextOut(str.getData(), ::GraphicsResource.FontRegular,
1.0, cgo.Surface, offX, offY + Shape.GetY() - cmhgt,
InLiquid ? 0xfa0000FF : C4Draw::DEFAULT_MESSAGE_COLOR, ACenter);
}
}
// Debug Display ///////////////////////////////////////////////////////////////////////
// Restore visibility inside FoW
if (fOldClrModEnabled) pDraw->SetClrModMapEnabled(fOldClrModEnabled);
#endif
}
void C4Object::DrawTopFace(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode, float offX, float offY)
{
#ifndef USE_CONSOLE
// Status
if (!Status || !Def) return;
// visible?
if (!IsVisible(iByPlayer, eDrawMode==ODM_Overlay)) return;
// target pos (parallax)
float newzoom;
if (eDrawMode!=ODM_Overlay) GetDrawPosition(cgo, offX, offY, newzoom);
ZoomDataStackItem zdsi(newzoom);
// Clonk name
// Name of Owner/Clonk (only when Crew Member; never in films)
if (OCF & OCF_CrewMember)
if ((Config.Graphics.ShowCrewNames || Config.Graphics.ShowCrewCNames) && (!Game.C4S.Head.Film || !Game.C4S.Head.Replay))
if (!eDrawMode)
if (Owner != iByPlayer && !Contained)
{
// inside screen range?
if (!Inside<int>(offX + Shape.GetX(), cgo.X - Shape.Wdt, cgo.X + cgo.Wdt)
|| !Inside<int>(offY + Shape.GetY(), cgo.Y - Shape.Hgt, cgo.Y + cgo.Hgt)) return;
// get player
C4Player* pOwner = ::Players.Get(Owner);
if (pOwner)
if (!Hostile(Owner, iByPlayer))
if (!pOwner->IsInvisible())
{
// compose string
char szText[C4GM_MaxText+1];
if (Config.Graphics.ShowCrewNames)
if (Config.Graphics.ShowCrewCNames)
sprintf(szText, "%s (%s)", GetName(), pOwner->GetName());
else
SCopy(pOwner->GetName(),szText);
else
SCopy(GetName(),szText);
// Word wrap to cgo width
int32_t iCharWdt, dummy; ::GraphicsResource.FontRegular.GetTextExtent("m", iCharWdt, dummy, false);
int32_t iMaxLine = Max<int32_t>( cgo.Wdt / iCharWdt, 20 );
SWordWrap(szText,' ','|',iMaxLine);
// Adjust position by output boundaries
float iTX,iTY;
int iTWdt,iTHgt;
::GraphicsResource.FontRegular.GetTextExtent(szText,iTWdt,iTHgt, true);
iTX = BoundBy<int>(offX, cgo.X + iTWdt / 2, cgo.X + cgo.Wdt - iTWdt / 2);
iTY = BoundBy<int>(offY - Def->Shape.Hgt / 2 - 20 - iTHgt, cgo.Y, cgo.Y + cgo.Hgt - iTHgt);
// Draw
pDraw->TextOut(szText, ::GraphicsResource.FontRegular, 1.0, cgo.Surface, iTX, iTY,
pOwner->ColorDw|0x7f000000,ACenter);
}
}
// TopFace
if (!(TopFace.Surface || (OCF & OCF_Construct))) return;
// Output bounds check
if (!Inside<float>(offX, cgo.X - Shape.Wdt, cgo.X + cgo.Wdt)
|| !Inside<float>(offY, cgo.Y - Shape.Hgt, cgo.Y + cgo.Hgt))
return;
// Don't draw (show solidmask)
if (::GraphicsSystem.ShowSolidMask && SolidMask.Wdt) return;
// Contained
if (Contained) if (eDrawMode!=ODM_Overlay) return;
// Construction sign
if (OCF & OCF_Construct && fix_r == Fix0)
if (eDrawMode!=ODM_BaseOnly)
{
C4Facet &fctConSign = ::GraphicsResource.fctConstruction;
pDraw->Blit(fctConSign.Surface,
fctConSign.X, fctConSign.Y,
fctConSign.Wdt, fctConSign.Hgt,
cgo.Surface,
offX + Shape.GetX(), offY + Shape.GetY() + Shape.Hgt - fctConSign.Hgt,
fctConSign.Wdt, fctConSign.Hgt, true);
}
if(TopFace.Surface)
{
// FacetTopFace: Override TopFace.GetX()/GetY()
C4PropList* pActionDef = GetAction();
if (pActionDef && pActionDef->GetPropertyInt(P_FacetTopFace))
{
int32_t iPhase = Action.Phase;
if (pActionDef->GetPropertyInt(P_Reverse)) iPhase = pActionDef->GetPropertyInt(P_Length) - 1 - Action.Phase;
TopFace.X = pActionDef->GetPropertyInt(P_X) + Def->TopFace.x + pActionDef->GetPropertyInt(P_Wdt) * iPhase;
TopFace.Y = pActionDef->GetPropertyInt(P_Y) + Def->TopFace.y + pActionDef->GetPropertyInt(P_Hgt) * Action.DrawDir;
}
// ensure correct color is set
if (GetGraphics()->Bmp.BitmapClr) GetGraphics()->Bmp.BitmapClr->SetClr(Color);
// color modulation
if (!eDrawMode) PrepareDrawing();
// Draw top face bitmap
if (Con!=FullCon && Def->GrowthType)
// stretched
pDraw->Blit(TopFace.Surface,
TopFace.X, TopFace.Y, TopFace.Wdt, TopFace.Hgt,
cgo.Surface,
offX + Shape.GetX() + float(Def->TopFace.tx * Con) / FullCon, offY + Shape.GetY() + float(Def->TopFace.ty * Con) / FullCon,
float(TopFace.Wdt * Con) / FullCon, float(TopFace.Hgt * Con) / FullCon,
true, pDrawTransform ? &C4DrawTransform(*pDrawTransform, offX, offY) : NULL);
else
// normal
pDraw->Blit(TopFace.Surface,
TopFace.X,TopFace.Y,
TopFace.Wdt,TopFace.Hgt,
cgo.Surface,
offX + Shape.GetX() + Def->TopFace.tx, offY + Shape.GetY() + Def->TopFace.ty,
TopFace.Wdt, TopFace.Hgt,
true, pDrawTransform ? &C4DrawTransform(*pDrawTransform, offX, offY) : NULL);
}
// end of color modulation
if (!eDrawMode) FinishedDrawing();
#endif
}
void C4Object::DrawLine(C4TargetFacet &cgo)
{
#ifndef USE_CONSOLE
// Audibility
SetAudibilityAt(cgo, Shape.VtxX[0],Shape.VtxY[0]);
SetAudibilityAt(cgo, Shape.VtxX[Shape.VtxNum-1],Shape.VtxY[Shape.VtxNum-1]);
// additive mode?
PrepareDrawing();
// Draw line segments
C4Value colorsV; GetProperty(P_LineColors, &colorsV);
C4ValueArray *colors = colorsV.getArray();
int32_t color0 = 0xFFFF00FF, color1 = 0xFFFF00FF; // use bright colors so author notices
if (colors)
{
color0 = colors->GetItem(0).getInt();
color1 = colors->GetItem(1).getInt();
}
for (int32_t vtx=0; vtx+1<Shape.VtxNum; vtx++)
cgo.DrawLineDw(Shape.VtxX[vtx],Shape.VtxY[vtx],
Shape.VtxX[vtx+1],Shape.VtxY[vtx+1],
color0, color1);
// reset blit mode
FinishedDrawing();
#endif
}
void C4Object::CompileFunc(StdCompiler *pComp, C4ValueNumbers * numbers)
{
bool fCompiler = pComp->isCompiler();
if (fCompiler)
Clear();
// Compile ID, search definition
pComp->Value(mkNamingAdapt(id, "id", C4ID::None ));
if (fCompiler)
{
Def = ::Definitions.ID2Def(id);
if (!Def)
{ pComp->excNotFound(LoadResStr("IDS_PRC_UNDEFINEDOBJECT"),id.ToString()); return; }
}
pComp->Value(mkNamingAdapt( mkParAdapt(static_cast<C4PropListNumbered&>(*this), numbers), "Properties"));
pComp->Value(mkNamingAdapt( Status, "Status", 1 ));
if (Info) nInfo = Info->Name; else nInfo.Clear();
pComp->Value(mkNamingAdapt( toC4CStrBuf(nInfo), "Info", "" ));
pComp->Value(mkNamingAdapt( Owner, "Owner", NO_OWNER ));
pComp->Value(mkNamingAdapt( Controller, "Controller", NO_OWNER ));
pComp->Value(mkNamingAdapt( LastEnergyLossCausePlayer, "LastEngLossPlr", NO_OWNER ));
pComp->Value(mkNamingAdapt( Category, "Category", 0 ));
pComp->Value(mkNamingAdapt( Plane, "Plane", 0 ));
pComp->Value(mkNamingAdapt( iLastAttachMovementFrame, "LastSolidAtchFrame", -1 ));
pComp->Value(mkNamingAdapt( NoCollectDelay, "NoCollectDelay", 0 ));
pComp->Value(mkNamingAdapt( Con, "Size", 0 ));
pComp->Value(mkNamingAdapt( OwnMass, "OwnMass", 0 ));
pComp->Value(mkNamingAdapt( Mass, "Mass", 0 ));
pComp->Value(mkNamingAdapt( Damage, "Damage", 0 ));
pComp->Value(mkNamingAdapt( Energy, "Energy", 0 ));
pComp->Value(mkNamingAdapt( Alive, "Alive", false ));
pComp->Value(mkNamingAdapt( Breath, "Breath", 0 ));
pComp->Value(mkNamingAdapt( Color, "Color", 0u ));
pComp->Value(mkNamingAdapt( fix_x, "X", Fix0 ));
pComp->Value(mkNamingAdapt( fix_y, "Y", Fix0 ));
pComp->Value(mkNamingAdapt( fix_r, "R", Fix0 ));
pComp->Value(mkNamingAdapt( xdir, "XDir", 0 ));
pComp->Value(mkNamingAdapt( ydir, "YDir", 0 ));
pComp->Value(mkNamingAdapt( rdir, "RDir", 0 ));
pComp->Value(mkParAdapt(Shape, &Def->Shape));
pComp->Value(mkNamingAdapt( fOwnVertices, "OwnVertices", false ));
pComp->Value(mkNamingAdapt( SolidMask, "SolidMask", Def->SolidMask ));
pComp->Value(mkNamingAdapt( PictureRect, "Picture" ));
pComp->Value(mkNamingAdapt( Mobile, "Mobile", false ));
pComp->Value(mkNamingAdapt( OnFire, "OnFire", false ));
pComp->Value(mkNamingAdapt( InLiquid, "InLiquid", false ));
pComp->Value(mkNamingAdapt( EntranceStatus, "EntranceStatus", false ));
pComp->Value(mkNamingAdapt( OCF, "OCF", 0u ));
pComp->Value(Action);
pComp->Value(mkNamingAdapt( Contained, "Contained", C4ObjectPtr::Null ));
pComp->Value(mkNamingAdapt( Action.Target, "ActionTarget1", C4ObjectPtr::Null ));
pComp->Value(mkNamingAdapt( Action.Target2, "ActionTarget2", C4ObjectPtr::Null ));
pComp->Value(mkNamingAdapt( Component, "Component", Def->Component ));
pComp->Value(mkNamingAdapt( mkParAdapt(Contents, numbers), "Contents" ));
pComp->Value(mkNamingAdapt( PlrViewRange, "PlrViewRange", 0 ));
pComp->Value(mkNamingAdapt( ColorMod, "ColorMod", 0xffffffffu ));
pComp->Value(mkNamingAdapt( BlitMode, "BlitMode", 0u ));
pComp->Value(mkNamingAdapt( CrewDisabled, "CrewDisabled", false ));
pComp->Value(mkNamingAdapt( Layer, "Layer", C4ObjectPtr::Null ));
pComp->Value(mkNamingAdapt( C4DefGraphicsAdapt(pGraphics), "Graphics", &Def->Graphics ));
pComp->Value(mkNamingPtrAdapt( pDrawTransform, "DrawTransform" ));
pComp->Value(mkParAdapt(mkNamingPtrAdapt( pEffects, "Effects" ), numbers));
pComp->Value(mkNamingAdapt( C4GraphicsOverlayListAdapt(pGfxOverlay),"GfxOverlay", (C4GraphicsOverlay *)NULL));
// Serialize mesh instance if we have a mesh graphics
if(pGraphics->Type == C4DefGraphics::TYPE_Mesh)
{
if(pComp->isCompiler())
{
assert(!pMeshInstance);
pMeshInstance = new StdMeshInstance(*pGraphics->Mesh, Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
}
pComp->Value(mkNamingAdapt(mkParAdapt(*pMeshInstance, C4MeshDenumeratorFactory), "Mesh"));
// Does not work because unanimated meshes without attached meshes
// do not even write a [Mesh] header so this does not create a mesh instance in that case
/* pComp->Value(mkNamingContextPtrAdapt( pMeshInstance, *pGraphics->Mesh, "Mesh"));
if(!pMeshInstance)
pComp->excCorrupt("Mesh graphics without mesh instance");*/
}
// TODO: Animations / attached meshes
// Commands
if (pComp->FollowName("Commands"))
{
if (fCompiler)
{
C4Command *pCmd = NULL;
for (int i = 1; ; i++)
{
// Every command has its own naming environment
StdStrBuf Naming = FormatString("Command%d", i);
pComp->Value(mkParAdapt(mkNamingPtrAdapt(pCmd ? pCmd->Next : Command, Naming.getData()), numbers));
// Last command?
pCmd = (pCmd ? pCmd->Next : Command);
if (!pCmd)
break;
pCmd->cObj = this;
}
}
else
{
C4Command *pCmd = Command;
for (int i = 1; pCmd; i++, pCmd = pCmd->Next)
{
StdStrBuf Naming = FormatString("Command%d", i);
pComp->Value(mkNamingAdapt(mkParAdapt(*pCmd, numbers), Naming.getData()));
}
}
}
// Compiling? Do initialization.
if (fCompiler)
{
// add to def count
Def->Count++;
// Set action (override running data)
/* FIXME
int32_t iTime=Action.Time;
int32_t iPhase=Action.Phase;
int32_t iPhaseDelay=Action.PhaseDelay;
if (SetActionByName(Action.pActionDef->GetName(),0,0,false))
{
Action.Time=iTime;
Action.Phase=iPhase; // No checking for valid phase
Action.PhaseDelay=iPhaseDelay;
}*/
if (pMeshInstance)
{
// Set Action animation by slot 0
Action.Animation = pMeshInstance->GetRootAnimationForSlot(0);
pMeshInstance->SetFaceOrderingForClrModulation(ColorMod);
}
// blit mode not assigned? use definition default then
if (!BlitMode) BlitMode = Def->BlitMode;
// object needs to be resorted? May happen if there's unsorted objects in savegame
if (Unsorted) Game.fResortAnyObject = true;
}
}
void C4Object::Denumerate(C4ValueNumbers * numbers)
{
C4PropList::Denumerate(numbers);
// Standard enumerated pointers
Contained.DenumeratePointers();
Action.Target.DenumeratePointers();
Action.Target2.DenumeratePointers();
Layer.DenumeratePointers();
// Post-compile object list
Contents.DenumeratePointers();
// Commands
for (C4Command *pCom=Command; pCom; pCom=pCom->Next)
pCom->Denumerate(numbers);
// effects
if (pEffects) pEffects->Denumerate(numbers);
// gfx overlays
if (pGfxOverlay)
for (C4GraphicsOverlay *pGfxOvrl = pGfxOverlay; pGfxOvrl; pGfxOvrl = pGfxOvrl->GetNext())
pGfxOvrl->DenumeratePointers();
// mesh instance
if (pMeshInstance) pMeshInstance->DenumeratePointers();
}
void C4Object::DrawPicture(C4Facet &cgo, bool fSelected, C4DrawTransform* transform)
{
// Draw def picture with object color
Def->Draw(cgo,fSelected,Color,this,0,0,transform);
}
void C4Object::Picture2Facet(C4FacetSurface &cgo)
{
// set picture rect to facet
C4Rect fctPicRect = PictureRect;
if (!fctPicRect.Wdt) fctPicRect = Def->PictureRect;
C4Facet fctPicture;
fctPicture.Set(GetGraphics()->GetBitmap(Color),fctPicRect.x,fctPicRect.y,fctPicRect.Wdt,fctPicRect.Hgt);
// use direct facet w/o own data if possible
if (ColorMod == 0xffffffff && BlitMode == C4GFXBLIT_NORMAL && !pGfxOverlay)
{
cgo.Set(fctPicture);
return;
}
// otherwise, draw to picture facet
if (!cgo.Create(cgo.Wdt, cgo.Hgt)) return;
// specific object color?
PrepareDrawing();
// draw picture itself
fctPicture.Draw(cgo,true);
// draw overlays
if (pGfxOverlay)
for (C4GraphicsOverlay *pGfxOvrl = pGfxOverlay; pGfxOvrl; pGfxOvrl = pGfxOvrl->GetNext())
if (pGfxOvrl->IsPicture())
pGfxOvrl->DrawPicture(cgo, this, NULL);
// done; reset drawing states
FinishedDrawing();
}
bool C4Object::ValidateOwner()
{
// Check owner and controller
if (!ValidPlr(Owner)) Owner=NO_OWNER;
if (!ValidPlr(Controller)) Controller=NO_OWNER;
// Color is not reset any more, because many scripts change colors to non-owner-colors these days
// Additionally, player colors are now guarantueed to remain the same in savegame resumes
return true;
}
bool C4Object::AssignInfo()
{
if (Info || !ValidPlr(Owner)) return false;
// In crew list?
C4Player *pPlr = ::Players.Get(Owner);
if (pPlr->Crew.GetLink(this))
{
// Register with player
if (!::Players.Get(Owner)->MakeCrewMember(this, true, false))
pPlr->Crew.Remove(this);
return true;
}
// Info set, but not in crew list, so
// a) The savegame is old-style (without crew list)
// or b) The clonk is dead
// or c) The clonk belongs to a script player that's restored without Game.txt
else if (nInfo.getLength())
{
if (!::Players.Get(Owner)->MakeCrewMember(this, true, false))
return false;
// Dead and gone (info flags, remove from crew/cursor)
if (!Alive)
{
if (ValidPlr(Owner)) ::Players.Get(Owner)->ClearPointers(this, true);
}
return true;
}
return false;
}
bool C4Object::AssignPlrViewRange()
{
// no range?
if (!PlrViewRange) return true;
// add to FoW-repellers
PlrFoWActualize();
// success
return true;
}
void C4Object::ClearInfo(C4ObjectInfo *pInfo)
{
if (Info==pInfo)
{
Info=NULL;
}
}
void C4Object::Clear()
{
ClearParticleLists();
if (pEffects) { delete pEffects; pEffects=NULL; }
if (pSolidMaskData) { delete pSolidMaskData; pSolidMaskData=NULL; }
if (Menu) delete Menu; Menu=NULL;
if (MaterialContents) delete MaterialContents; MaterialContents=NULL;
// clear commands!
C4Command *pCom, *pNext;
for (pCom=Command; pCom; pCom=pNext)
{
pNext=pCom->Next; delete pCom; pCom=pNext;
}
if (pDrawTransform) { delete pDrawTransform; pDrawTransform=NULL; }
if (pGfxOverlay) { delete pGfxOverlay; pGfxOverlay=NULL; }
if (pMeshInstance) { delete pMeshInstance; pMeshInstance = NULL; }
}
bool C4Object::MenuCommand(const char *szCommand)
{
// Native script execution
if (!Def || !Status) return false;
return !! Def->Script.DirectExec(this, szCommand, "MenuCommand");
}
C4Object *C4Object::ComposeContents(C4ID id)
{
int32_t cnt,cnt2;
C4ID c_id;
bool fInsufficient = false;
C4Object *pObj;
C4ID idNeeded=C4ID::None;
int32_t iNeeded=0;
// Get def
C4Def *pDef = C4Id2Def(id); if (!pDef) return NULL;
// get needed contents
C4IDList NeededComponents;
pDef->GetComponents(&NeededComponents, NULL);
// Check for sufficient components
StdStrBuf Needs; Needs.Format(LoadResStr("IDS_CON_BUILDMATNEED"),pDef->GetName());
for (cnt=0; (c_id=NeededComponents.GetID(cnt)); cnt++)
if (NeededComponents.GetCount(cnt) > Contents.ObjectCount(c_id))
{
Needs.AppendFormat("|%ix %s", NeededComponents.GetCount(cnt) - Contents.ObjectCount(c_id), C4Id2Def(c_id) ? C4Id2Def(c_id)->GetName() : c_id.ToString() );
if (!idNeeded) { idNeeded=c_id; iNeeded=NeededComponents.GetCount(cnt)-Contents.ObjectCount(c_id); }
fInsufficient = true;
}
// Insufficient
if (fInsufficient)
{
// BuildNeedsMaterial call to object...
if (!Call(PSF_BuildNeedsMaterial,&C4AulParSet(C4VPropList(C4Id2Def(idNeeded)), C4VInt(iNeeded))))
// ...game message if not overloaded
GameMsgObjectError(Needs.getData(),this);
// Return
return NULL;
}
// Remove components
for (cnt=0; (c_id=NeededComponents.GetID(cnt)); cnt++)
for (cnt2=0; cnt2<NeededComponents.GetCount(cnt); cnt2++)
if (!( pObj = Contents.Find(c_id) ))
return NULL;
else
pObj->AssignRemoval();
// Create composed object
// the object is created with default components instead of builder components
// this is done because some objects (e.g. arrow packs) will set custom components during initialization, which should not be overriden
return CreateContents(C4Id2Def(id));
}
void C4Object::SetSolidMask(int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, int32_t iTX, int32_t iTY)
{
// remove old
if (pSolidMaskData) { delete pSolidMaskData; pSolidMaskData=NULL; }
// set new data
SolidMask.Set(iX,iY,iWdt,iHgt,iTX,iTY);
// re-put if valid
if (CheckSolidMaskRect()) UpdateSolidMask(false);
}
bool C4Object::CheckSolidMaskRect()
{
// Ensure SolidMask rect lies within bounds of SolidMask bitmap in definition
CSurface8 *sfcGraphics = Def->pSolidMask;
if (!sfcGraphics)
{
// no graphics to set solid in
SolidMask.Set(0,0,0,0,0,0);
return false;
}
SolidMask.Set(Max<int32_t>(SolidMask.x,0), Max<int32_t>(SolidMask.y,0),
Min<int32_t>(SolidMask.Wdt,sfcGraphics->Wdt-SolidMask.x), Min<int32_t>(SolidMask.Hgt, sfcGraphics->Hgt-SolidMask.y),
SolidMask.tx, SolidMask.ty);
if (SolidMask.Hgt<=0) SolidMask.Wdt=0;
return SolidMask.Wdt>0;
}
void C4Object::SyncClearance()
{
// Misc. no-save safeties
Action.t_attach = CNAT_None;
InMat = MNone;
t_contact = 0;
// Update OCF
SetOCF();
// Menu
CloseMenu(true);
// Material contents
if (MaterialContents) delete MaterialContents; MaterialContents=NULL;
// reset speed of staticback-objects
if (Category & C4D_StaticBack)
{
xdir = ydir = 0;
}
}
void C4Object::DrawSelectMark(C4TargetFacet &cgo) const
{
// Status
if (!Status) return;
// No select marks in film playback
if (Game.C4S.Head.Film && Game.C4S.Head.Replay) return;
// target pos (parallax)
float offX, offY, newzoom;
GetDrawPosition(cgo, offX, offY, newzoom);
// Output boundary
if (!Inside<float>(offX, cgo.X, cgo.X + cgo.Wdt)
|| !Inside<float>(offY, cgo.Y, cgo.Y + cgo.Hgt)) return;
// Draw select marks
float cox = offX + Shape.GetX() - cgo.X + cgo.X - 2;
float coy = offY + Shape.GetY() - cgo.Y + cgo.Y - 2;
GfxR->fctSelectMark.Draw(cgo.Surface,cox,coy,0);
GfxR->fctSelectMark.Draw(cgo.Surface,cox+Shape.Wdt,coy,1);
GfxR->fctSelectMark.Draw(cgo.Surface,cox,coy+Shape.Hgt,2);
GfxR->fctSelectMark.Draw(cgo.Surface,cox+Shape.Wdt,coy+Shape.Hgt,3);
}
void C4Object::ClearCommands()
{
C4Command *pNext;
while (Command)
{
pNext=Command->Next;
if (!Command->iExec)
delete Command;
else
Command->iExec = 2;
Command=pNext;
}
}
void C4Object::ClearCommand(C4Command *pUntil)
{
C4Command *pCom,*pNext;
for (pCom=Command; pCom; pCom=pNext)
{
// Last one to clear
if (pCom==pUntil) pNext=NULL;
// Next one to clear after this
else pNext=pCom->Next;
Command=pCom->Next;
if (!pCom->iExec)
delete pCom;
else
pCom->iExec = 2;
}
}
bool C4Object::AddCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int32_t iTy,
int32_t iUpdateInterval, C4Object *pTarget2,
bool fInitEvaluation, C4Value iData, bool fAppend,
int32_t iRetries, C4String *szText, int32_t iBaseMode)
{
// Command stack size safety
const int32_t MaxCommandStack = 35;
C4Command *pCom,*pLast; int32_t iCommands;
for (pCom=Command,iCommands=0; pCom; pCom=pCom->Next,iCommands++) {}
if (iCommands>=MaxCommandStack) return false;
// Valid command safety
if (!Inside(iCommand,C4CMD_First,C4CMD_Last)) return false;
// Allocate and set new command
if (!(pCom=new C4Command)) return false;
pCom->Set(iCommand,this,pTarget,iTx,iTy,pTarget2,iData,
iUpdateInterval,!fInitEvaluation,iRetries,szText,iBaseMode);
// Append to bottom of stack
if (fAppend)
{
for (pLast=Command; pLast && pLast->Next; pLast=pLast->Next) {}
if (pLast) pLast->Next=pCom;
else Command=pCom;
}
// Add to top of command stack
else
{
pCom->Next=Command;
Command=pCom;
}
// Success
//sprintf(OSTR,"%s command %s added: %i/%i %s %s (%i)",GetName(),CommandName(iCommand),iTx,iTy,pTarget ? pTarget->GetName() : "O",pTarget2 ? pTarget2->GetName() : "O",iUpdateInterval); Log(OSTR);
return true;
}
void C4Object::SetCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int32_t iTy,
C4Object *pTarget2, bool fControl, C4Value iData,
int32_t iRetries, C4String *szText)
{
// Decrease NoCollectDelay
if (NoCollectDelay>0) NoCollectDelay--;
// Clear stack
ClearCommands();
// Close menu
if (fControl)
if (!CloseMenu(false)) return;
// Script overload
if (fControl)
if (!!Call(PSF_ControlCommand,&C4AulParSet(C4VString(CommandName(iCommand)),
C4VObj(pTarget),
iTx,
C4VInt(iTy),
C4VObj(pTarget2),
iData)))
return;
// Inside vehicle control overload
if (Contained)
if (Contained->Def->VehicleControl & C4D_VehicleControl_Inside)
{
Contained->Controller=Controller;
if (!!Contained->Call(PSF_ControlCommand,&C4AulParSet(C4VString(CommandName(iCommand)),
C4VObj(pTarget),
iTx,
C4VInt(iTy),
C4VObj(pTarget2),
iData,
C4VObj(this))))
return;
}
// Outside vehicle control overload
if (GetProcedure()==DFA_PUSH)
if (Action.Target) if (Action.Target->Def->VehicleControl & C4D_VehicleControl_Outside)
{
Action.Target->Controller=Controller;
if (!!Action.Target->Call(PSF_ControlCommand,&C4AulParSet(C4VString(CommandName(iCommand)),
C4VObj(pTarget),
iTx,
C4VInt(iTy),
C4VObj(pTarget2),
iData)))
return;
}
// Add new command
AddCommand(iCommand,pTarget,iTx,iTy,0,pTarget2,true,iData,false,iRetries,szText,C4CMD_Mode_Base);
}
C4Command *C4Object::FindCommand(int32_t iCommandType) const
{
// seek all commands
for (C4Command *pCom = Command; pCom; pCom=pCom->Next)
if (pCom->Command == iCommandType) return pCom;
// nothing found
return NULL;
}
bool C4Object::ExecuteCommand()
{
// Execute first command
if (Command) Command->Execute();
// Command finished: engine call
if (Command && Command->Finished)
Call(PSF_ControlCommandFinished,&C4AulParSet(C4VString(CommandName(Command->Command)), C4VObj(Command->Target), Command->Tx, C4VInt(Command->Ty), C4VObj(Command->Target2), Command->Data));
// Clear finished commands
while (Command && Command->Finished) ClearCommand(Command);
// Done
return true;
}
void C4Object::Resort()
{
// Flag resort
Unsorted=true;
Game.fResortAnyObject = true;
// Must not immediately resort - link change/removal would crash Game::ExecObjects
}
C4PropList* C4Object::GetAction() const
{
C4Value value;
GetProperty(P_Action, &value);
return value.getPropList();
}
bool C4Object::SetAction(C4PropList * Act, C4Object *pTarget, C4Object *pTarget2, int32_t iCalls, bool fForce)
{
C4Value vLastAction;
GetProperty(P_Action, &vLastAction);
C4PropList * LastAction = vLastAction.getPropList();
int32_t iLastPhase=Action.Phase;
C4Object *pLastTarget = Action.Target;
C4Object *pLastTarget2 = Action.Target2;
// No other action
if (LastAction)
if (LastAction->GetPropertyInt(P_NoOtherAction) && !fForce)
if (Act != LastAction)
return false;
// Set animation on instance. Abort if the mesh does not have
// such an animation.
if (pMeshInstance)
{
if (Action.Animation) pMeshInstance->StopAnimation(Action.Animation);
Action.Animation = NULL;
C4String* Animation = Act ? Act->GetPropertyStr(P_Animation) : NULL;
if (Animation)
{
// note that weight is ignored
Action.Animation = pMeshInstance->PlayAnimation(Animation->GetData(), 0, NULL, new C4ValueProviderAction(this), new C4ValueProviderConst(itofix(1)));
}
}
// Stop previous act sound
if (LastAction)
if (Act != LastAction)
if (LastAction->GetPropertyStr(P_Sound))
StopSoundEffect(LastAction->GetPropertyStr(P_Sound)->GetCStr(),this);
// Unfullcon objects no action
if (Con<FullCon)
if (!Def->IncompleteActivity)
Act = 0;
// Reset action time on change
if (Act!=LastAction)
{
Action.Time=0;
// reset action data if procedure is changed
if ((Act ? Act->GetPropertyP(P_Procedure) : -1)
!= (LastAction ? LastAction->GetPropertyP(P_Procedure) : -1))
Action.Data = 0;
}
// Set new action
SetProperty(P_Action, C4VPropList(Act));
Action.Phase=Action.PhaseDelay=0;
// Set target if specified
if (pTarget) Action.Target=pTarget;
if (pTarget2) Action.Target2=pTarget2;
// Set Action Facet
UpdateActionFace();
// update flipdir
if ((LastAction ? LastAction->GetPropertyInt(P_FlipDir) : 0)
!= (Act ? Act->GetPropertyInt(P_FlipDir) : 0)) UpdateFlipDir();
// Start act sound
if (Act)
if (Act != LastAction)
if (Act->GetPropertyStr(P_Sound))
StartSoundEffect(Act->GetPropertyStr(P_Sound)->GetCStr(),+1,100,this);
// Reset OCF
SetOCF();
// issue calls
// Execute EndCall for last action
if (iCalls & SAC_EndCall && !fForce)
if (LastAction)
{
if (LastAction->GetPropertyStr(P_EndCall))
{
C4Def *pOldDef = Def;
Call(LastAction->GetPropertyStr(P_EndCall)->GetCStr());
// abort exeution if def changed
if (Def != pOldDef || !Status) return true;
}
}
// Execute AbortCall for last action
if (iCalls & SAC_AbortCall && !fForce)
if (LastAction)
{
if (LastAction->GetPropertyStr(P_AbortCall))
{
C4Def *pOldDef = Def;
if (pLastTarget && !pLastTarget->Status) pLastTarget = NULL;
if (pLastTarget2 && !pLastTarget2->Status) pLastTarget2 = NULL;
Call(LastAction->GetPropertyStr(P_AbortCall)->GetCStr(), &C4AulParSet(C4VInt(iLastPhase), C4VObj(pLastTarget), C4VObj(pLastTarget2)));
// abort exeution if def changed
if (Def != pOldDef || !Status) return true;
}
}
// Execute StartCall for new action
if (iCalls & SAC_StartCall)
if (Act)
{
if (Act->GetPropertyStr(P_StartCall))
{
C4Def *pOldDef = Def;
Call(Act->GetPropertyStr(P_StartCall)->GetCStr());
// abort exeution if def changed
if (Def != pOldDef || !Status) return true;
}
}
C4Def *pOldDef = Def;
Call(PSF_OnActionChanged, &C4AulParSet(C4VString(LastAction ? LastAction->GetName() : "Idle")));
if (Def != pOldDef || !Status) return true;
return true;
}
void C4Object::UpdateActionFace()
{
// Default: no action face
Action.Facet.Default();
// Active: get action facet from action definition
C4PropList* pActionDef = GetAction();
if (pActionDef)
{
if (pActionDef->GetPropertyInt(P_Wdt)>0)
{
Action.Facet.Set(GetGraphics()->GetBitmap(Color),
pActionDef->GetPropertyInt(P_X),pActionDef->GetPropertyInt(P_Y),
pActionDef->GetPropertyInt(P_Wdt),pActionDef->GetPropertyInt(P_Hgt));
Action.FacetX=pActionDef->GetPropertyInt(P_OffX);
Action.FacetY=pActionDef->GetPropertyInt(P_OffY);
}
}
}
bool C4Object::SetActionByName(C4String *ActName,
C4Object *pTarget, C4Object *pTarget2,
int32_t iCalls, bool fForce)
{
assert(ActName);
// If we get the null string or ActIdle by name, set ActIdle
if (!ActName || ActName == &Strings.P[P_Idle])
return SetAction(0,0,0,iCalls,fForce);
C4Value ActMap; GetProperty(P_ActMap, &ActMap);
if (!ActMap.getPropList()) return false;
C4Value Action; ActMap.getPropList()->GetPropertyByS(ActName, &Action);
if (!Action.getPropList()) return false;
return SetAction(Action.getPropList(),pTarget,pTarget2,iCalls,fForce);
}
bool C4Object::SetActionByName(const char * szActName,
C4Object *pTarget, C4Object *pTarget2,
int32_t iCalls, bool fForce)
{
C4String * ActName = Strings.RegString(szActName);
ActName->IncRef();
bool r = SetActionByName(ActName, pTarget, pTarget2, iCalls, fForce);
ActName->DecRef();
return r;
}
void C4Object::SetDir(int32_t iDir)
{
// Not active
C4PropList* pActionDef = GetAction();
if (!pActionDef) return;
// Invalid direction
if (!Inside<int32_t>(iDir,0,pActionDef->GetPropertyInt(P_Directions)-1)) return;
// Execute turn action
if (iDir != Action.Dir)
if (pActionDef->GetPropertyStr(P_TurnAction))
{ SetActionByName(pActionDef->GetPropertyStr(P_TurnAction)); }
// Set dir
Action.Dir=iDir;
// update by flipdir?
if (pActionDef->GetPropertyInt(P_FlipDir))
UpdateFlipDir();
else
Action.DrawDir=iDir;
}
int32_t C4Object::GetProcedure() const
{
C4PropList* pActionDef = GetAction();
if (!pActionDef) return -1;
return pActionDef->GetPropertyP(P_Procedure);
}
void GrabLost(C4Object *cObj)
{
// Grab lost script call on target (quite hacky stuff...)
cObj->Action.Target->Call(PSF_GrabLost);
// Also, delete the target from the clonk's action (Newton)
cObj->Action.Target = NULL;
// Clear commands down to first PushTo (if any) in command stack
for (C4Command *pCom=cObj->Command; pCom; pCom=pCom->Next)
if (pCom->Next && pCom->Next->Command==C4CMD_PushTo)
{
cObj->ClearCommand(pCom);
break;
}
}
static void DoGravity(C4Object *cobj);
void C4Object::NoAttachAction()
{
// Active objects
if (GetAction())
{
int32_t iProcedure = GetProcedure();
// Scaling upwards: corner scale
if (iProcedure == DFA_SCALE && Action.ComDir != COMD_Stop && ComDirLike(Action.ComDir, COMD_Up))
if (ObjectActionCornerScale(this)) return;
if (iProcedure == DFA_SCALE && Action.ComDir == COMD_Left && Action.Dir == DIR_Left)
if (ObjectActionCornerScale(this)) return;
if (iProcedure == DFA_SCALE && Action.ComDir == COMD_Right && Action.Dir == DIR_Right)
if (ObjectActionCornerScale(this)) return;
// Scaling and stopped: fall off to side (avoid zuppel)
if ((iProcedure == DFA_SCALE) && (Action.ComDir == COMD_Stop))
{
if (Action.Dir == DIR_Left)
{ if (ObjectActionJump(this,itofix(1),Fix0,false)) return; }
else
{ if (ObjectActionJump(this,itofix(-1),Fix0,false)) return; }
}
// Pushing: grab loss
if (iProcedure==DFA_PUSH) GrabLost(this);
// Else jump
ObjectActionJump(this,xdir,ydir,false);
}
// Inactive objects, simple mobile natural gravity
else
{
DoGravity(this);
Mobile=1;
}
}
void C4Object::ContactAction()
{
// Take certain action on contact. Evaluate t_contact-CNAT and Procedure.
// Determine Procedure
C4PropList* pActionDef = GetAction();
if (!pActionDef) return;
int32_t iProcedure=pActionDef->GetPropertyP(P_Procedure);
int32_t fDisabled=pActionDef->GetPropertyInt(P_ObjectDisabled);
//------------------------------- Hit Bottom ---------------------------------------------
if (t_contact & CNAT_Bottom)
switch (iProcedure)
{
case DFA_FLIGHT:
if (ydir < 0) return;
// Jump: FlatHit / HardHit / Walk
if ((OCF & OCF_HitSpeed4) || fDisabled)
if (ObjectActionFlat(this,Action.Dir)) return;
if (OCF & OCF_HitSpeed3)
if (ObjectActionKneel(this)) return;
ObjectActionWalk(this);
ydir = 0;
return;
case DFA_SCALE:
// Scale down: stand
if (ComDirLike(Action.ComDir, COMD_Down))
{
ObjectActionStand(this);
return;
}
break;
case DFA_DIG:
// no special action
break;
case DFA_SWIM:
// Try corner scale out
if (!GBackLiquid(GetX(),GetY()-1+Def->Float*Con/FullCon-1))
if (ObjectActionCornerScale(this)) return;
break;
}
//------------------------------- Hit Ceiling -----------------------------------------
if (t_contact & CNAT_Top)
switch (iProcedure)
{
case DFA_WALK:
// Walk: Stop
ObjectActionStand(this); return;
case DFA_SCALE:
// Scale: Try hangle, else stop if going upward
if (ComDirLike(Action.ComDir, COMD_Up))
{
if (ObjectActionHangle(this))
{
SetDir(Action.Dir == DIR_Left ? DIR_Right : DIR_Left);
return;
}
Action.ComDir=COMD_Stop;
}
break;
case DFA_FLIGHT:
// Jump: Try hangle, else bounce off
// High Speed Flight: Tumble
if ((OCF & OCF_HitSpeed3) || fDisabled)
{ ObjectActionTumble(this, Action.Dir, xdir, ydir); break; }
if (ObjectActionHangle(this)) return;
break;
case DFA_DIG:
// No action
break;
case DFA_HANGLE:
Action.ComDir=COMD_Stop;
break;
}
//---------------------------- Hit Left Wall ----------------------------------------
if (t_contact & CNAT_Left)
{
switch (iProcedure)
{
case DFA_FLIGHT:
// High Speed Flight: Tumble
if ((OCF & OCF_HitSpeed3) || fDisabled)
{ ObjectActionTumble(this, DIR_Left, xdir, ydir); break; }
// Else
else if (!ComDirLike(Action.ComDir, COMD_Right) && ObjectActionScale(this,DIR_Left)) return;
break;
case DFA_WALK:
// Walk: Try scale
if (ComDirLike(Action.ComDir, COMD_Left))
{
if (ObjectActionScale(this,DIR_Left))
{
ydir = C4REAL100(-1);
return;
}
}
// Heading away from solid
if (ComDirLike(Action.ComDir, COMD_Right))
{
// Slide off
ObjectActionJump(this,xdir/2,ydir,false);
}
return;
case DFA_SWIM:
// Only scale if swimming at the surface
if (!GBackLiquid(GetX(),GetY()-1+Def->Float*Con/FullCon-1))
{
// Try scale, only if swimming at the surface.
if (ComDirLike(Action.ComDir, COMD_Left))
if (ObjectActionScale(this,DIR_Left)) return;
// Try corner scale out
if (ObjectActionCornerScale(this)) return;
}
return;
case DFA_HANGLE:
// Hangle: Try scale
if (ObjectActionScale(this,DIR_Left))
{
ydir = C4REAL100(1);
return;
}
return;
case DFA_DIG:
// Dig: no action
break;
}
}
//------------------------------ Hit Right Wall --------------------------------------
if (t_contact & CNAT_Right)
{
switch (iProcedure)
{
case DFA_FLIGHT:
// High Speed Flight: Tumble
if ((OCF & OCF_HitSpeed3) || fDisabled)
{ ObjectActionTumble(this, DIR_Right, xdir, ydir); break; }
// Else Scale
else if (!ComDirLike(Action.ComDir, COMD_Left) && ObjectActionScale(this,DIR_Right)) return;
break;
case DFA_WALK:
// Walk: Try scale
if (ComDirLike(Action.ComDir, COMD_Right))
{
if (ObjectActionScale(this,DIR_Right))
{
ydir = C4REAL100(-1);
return;
}
}
// Heading away from solid
if (ComDirLike(Action.ComDir, COMD_Left))
{
// Slide off
ObjectActionJump(this,xdir/2,ydir,false);
}
return;
case DFA_SWIM:
// Only scale if swimming at the surface
if (!GBackLiquid(GetX(),GetY()-1+Def->Float*Con/FullCon-1))
{
// Try scale
if (ComDirLike(Action.ComDir, COMD_Right))
if (ObjectActionScale(this,DIR_Right)) return;
// Try corner scale out
if (ObjectActionCornerScale(this)) return;
}
return;
case DFA_HANGLE:
// Hangle: Try scale
if (ObjectActionScale(this,DIR_Right))
{
ydir = C4REAL100(1);
return;
}
return;
case DFA_DIG:
// Dig: no action
break;
}
}
//---------------------------- Unresolved Cases ---------------------------------------
// Flight stuck
if (iProcedure==DFA_FLIGHT)
{
// Enforce slide free (might slide through tiny holes this way)
if (!ydir)
{
int fAllowDown = !(t_contact & CNAT_Bottom);
if (t_contact & CNAT_Right)
{
ForcePosition(fix_x - 1, fix_y + fAllowDown);
xdir=ydir=0;
}
if (t_contact & CNAT_Left)
{
ForcePosition(fix_x + 1, fix_y + fAllowDown);
xdir=ydir=0;
}
}
if (!xdir)
{
if (t_contact & CNAT_Top)
{
ForcePosition(fix_x, fix_y + 1);
xdir=ydir=0;
}
}
}
}
void Towards(C4Real &val, C4Real target, C4Real step)
{
if (val==target) return;
if (Abs(val-target)<=step) { val=target; return; }
if (val<target) val+=step; else val-=step;
}
bool DoBridge(C4Object *clk)
{
int32_t iBridgeTime; bool fMoveClonk, fWall; int32_t iBridgeMaterial;
clk->Action.GetBridgeData(iBridgeTime, fMoveClonk, fWall, iBridgeMaterial);
if (!iBridgeTime) iBridgeTime = 100; // default bridge time
if (clk->Action.Time>=iBridgeTime) { ObjectActionStand(clk); return false; }
// get bridge advancement
int32_t dtp;
if (fWall) switch (clk->Action.ComDir)
{
case COMD_Left: case COMD_Right: dtp = 4; fMoveClonk = false; break; // vertical wall: default 25 pixels
case COMD_UpLeft: case COMD_UpRight: dtp = 5; fMoveClonk = false; break; // diagonal roof over Clonk: default 20 pixels up and 20 pixels side (28 pixels - optimized to close tunnels completely)
case COMD_Up: dtp = 5; break; // horizontal roof over Clonk
default: return true; // bridge procedure just for show
}
else switch (clk->Action.ComDir)
{
case COMD_Left: case COMD_Right: dtp = 5; break; // horizontal bridges: default 20 pixels
case COMD_Up: dtp = 4; break; // vertical bridges: default 25 pixels (same as
case COMD_UpLeft: case COMD_UpRight: dtp = 6; break; // diagonal bridges: default 16 pixels up and 16 pixels side (23 pixels)
default: return true; // bridge procedure just for show
}
if (clk->Action.Time % dtp) return true; // no advancement in this frame
// get target pos for Clonk and bridge
int32_t cx=clk->GetX(), cy=clk->GetY(), cw=clk->Shape.Wdt, ch=clk->Shape.Hgt;
int32_t tx=cx,ty=cy+ch/2;
int32_t dt;
if (fMoveClonk) dt = 0; else dt = clk->Action.Time / dtp;
if (fWall) switch (clk->Action.ComDir)
{
case COMD_Left: tx-=cw/2; ty+=-dt; break;
case COMD_Right: tx+=cw/2; ty+=-dt; break;
case COMD_Up:
{
int32_t x0;
if (fMoveClonk) x0=-3; else x0=(iBridgeTime/dtp)/-2;
tx+=(x0+dt)*((clk->Action.Dir==DIR_Right)*2-1); cx+=((clk->Action.Dir==DIR_Right)*2-1); ty-=ch+3; break;
}
case COMD_UpLeft: tx-=-4+dt; ty+=-ch-7+dt; break;
case COMD_UpRight: tx+=-4+dt; ty+=-ch-7+dt; break;
}
else switch (clk->Action.ComDir)
{
case COMD_Left: tx+=-3-dt; --cx; break;
case COMD_Right: tx+=+2+dt; ++cx; break;
case COMD_Up: tx+=(-cw/2+(cw-1)*(clk->Action.Dir==DIR_Right))*(!fMoveClonk); ty+=-dt-fMoveClonk; --cy; break;
case COMD_UpLeft: tx+=-5-dt+fMoveClonk*3; ty+=2-dt-fMoveClonk*3; --cx; --cy; break;
case COMD_UpRight: tx+=+5+dt-fMoveClonk*2; ty+=2-dt-fMoveClonk*3; ++cx; --cy; break;
}
// check if Clonk movement is posible
if (fMoveClonk)
{
int32_t cx2=cx, cy2=cy;
if (/*!clk->Shape.Attach(cx2, cy2, (clk->Action.t_attach & CNAT_Flags) | CNAT_Bottom) ||*/ clk->Shape.CheckContact(cx2, cy2-1))
{
// Clonk would collide here: Change to nonmoving Clonk mode and redo bridging
iBridgeTime -= clk->Action.Time;
clk->Action.Time = 0;
if (fWall && clk->Action.ComDir==COMD_Up)
{
// special for roof above Clonk: The nonmoving roof is started at bridgelength before the Clonkl
// so, when interrupted, an action time halfway through the action must be set
clk->Action.Time = iBridgeTime;
iBridgeTime += iBridgeTime;
}
clk->Action.SetBridgeData(iBridgeTime, false, fWall, iBridgeMaterial);
return DoBridge(clk);
}
}
// draw bridge into landscape
::Landscape.DrawMaterialRect(iBridgeMaterial,tx-2,ty,4,3);
// Move Clonk
if (fMoveClonk) clk->MovePosition(cx-clk->GetX(), cy-clk->GetY());
return true;
}
static void DoGravity(C4Object *cobj)
{
// Floatation in liquids
if (cobj->InLiquid && cobj->Def->Float)
{
cobj->ydir-=GravAccel * C4REAL100(80);
if (cobj->ydir<C4REAL100(-160)) cobj->ydir=C4REAL100(-160);
if (cobj->xdir<-FloatFriction) cobj->xdir+=FloatFriction;
if (cobj->xdir>+FloatFriction) cobj->xdir-=FloatFriction;
if (cobj->rdir<-FloatFriction) cobj->rdir+=FloatFriction;
if (cobj->rdir>+FloatFriction) cobj->rdir-=FloatFriction;
if (!GBackLiquid(cobj->GetX(),cobj->GetY()-1+ cobj->Def->Float*cobj->GetCon()/FullCon -1 ))
if (cobj->ydir<0) cobj->ydir=0;
}
// Free fall gravity
else if (~cobj->Category & C4D_StaticBack)
cobj->ydir+=GravAccel;
}
void StopActionDelayCommand(C4Object *cobj)
{
ObjectComStop(cobj);
cobj->AddCommand(C4CMD_Wait,NULL,0,0,50);
}
bool ReduceLineSegments(C4Shape &rShape, bool fAlternate)
{
// try if line could go by a path directly when skipping on evertex. If fAlternate is true, try by skipping two vertices
for (int32_t cnt=0; cnt+2+fAlternate<rShape.VtxNum; cnt++)
if (PathFree(rShape.VtxX[cnt],rShape.VtxY[cnt],
rShape.VtxX[cnt+2+fAlternate],rShape.VtxY[cnt+2+fAlternate]))
{
if (fAlternate) rShape.RemoveVertex(cnt+2);
rShape.RemoveVertex(cnt+1);
return true;
}
return false;
}
void C4Object::ExecAction()
{
C4Real iTXDir;
C4Real lftspeed,tydir;
int32_t iTargetX;
int32_t iPushRange,iPushDistance;
// Standard phase advance
int32_t iPhaseAdvance=1;
// Upright attachment check
if (!Mobile)
if (Def->UprightAttach)
if (Inside<int32_t>(GetR(),-StableRange,+StableRange))
{
Action.t_attach|=Def->UprightAttach;
Mobile=1;
}
C4PropList* pActionDef = GetAction();
// No IncompleteActivity? Reset action if there was one
if (!(OCF & OCF_FullCon) && !Def->IncompleteActivity && pActionDef)
{
SetAction(0);
pActionDef = 0;
}
// InLiquidAction check
if (InLiquid)
if (pActionDef && pActionDef->GetPropertyStr(P_InLiquidAction))
{
SetActionByName(pActionDef->GetPropertyStr(P_InLiquidAction));
pActionDef = GetAction();
}
// Idle objects do natural gravity only
if (!pActionDef)
{
Action.t_attach = CNAT_None;
if (Mobile) DoGravity(this);
return;
}
C4Real fWalk,fMove;
// Action time advance
Action.Time++;
C4Value Attach;
pActionDef->GetProperty(P_Attach, &Attach);
if (Attach.GetType() != C4V_Nil)
{
Action.t_attach = Attach.getInt();
}
else switch (pActionDef->GetPropertyP(P_Procedure))
{
case DFA_SCALE:
if (Action.Dir == DIR_Left) Action.t_attach = CNAT_Left;
if (Action.Dir == DIR_Right) Action.t_attach = CNAT_Right;
break;
case DFA_HANGLE:
Action.t_attach = CNAT_Top;
break;
case DFA_WALK:
case DFA_KNEEL:
case DFA_THROW:
case DFA_BRIDGE:
case DFA_PUSH:
case DFA_PULL:
case DFA_DIG:
Action.t_attach = CNAT_Bottom;
break;
default:
Action.t_attach = CNAT_None;
}
// if an object is in controllable state, so it can be assumed that if it dies later because of NO_OWNER's cause,
// it has been its own fault and not the fault of the last one who threw a flint on it
// do not reset for burning objects to make sure the killer is set correctly if they fall out of the map while burning
if (!pActionDef->GetPropertyInt(P_ObjectDisabled) && pActionDef->GetPropertyP(P_Procedure) != DFA_FLIGHT && !OnFire)
LastEnergyLossCausePlayer = NO_OWNER;
// Handle Default Action Procedure: evaluates Procedure and Action.ComDir
// Update xdir,ydir,Action.Dir,attachment,iPhaseAdvance
int32_t dir = Action.Dir;
C4Real accel = C4REAL100(pActionDef->GetPropertyInt(P_Accel));
C4Real decel = accel;
{
C4Value decel_val;
pActionDef->GetProperty(P_Decel, &decel_val);
if (decel_val.GetType() != C4V_Nil)
decel = C4REAL100(decel_val.getInt());
}
C4Real limit = C4REAL100(pActionDef->GetPropertyInt(P_Speed));
switch (pActionDef->GetPropertyP(P_Procedure))
{
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_WALK:
switch (Action.ComDir)
{
case COMD_Left: case COMD_UpLeft: case COMD_DownLeft:
// breaaak!!!
if (dir == DIR_Right)
xdir-=decel;
else
xdir-=accel;
if (xdir<-limit) xdir=-limit;
break;
case COMD_Right: case COMD_UpRight: case COMD_DownRight:
if (dir == DIR_Left)
xdir+=decel;
else
xdir+=accel;
if (xdir>+limit) xdir=+limit;
break;
case COMD_Stop: case COMD_Up: case COMD_Down:
if (xdir<0) xdir+=decel;
if (xdir>0) xdir-=decel;
if ((xdir>-decel) && (xdir<+decel)) xdir=0;
break;
}
iPhaseAdvance=0;
if (xdir<0)
{
if (dir != DIR_Left) { SetDir(DIR_Left); xdir = -1; }
iPhaseAdvance=-fixtoi(xdir*10);
}
if (xdir>0)
{
if (dir != DIR_Right) { SetDir(DIR_Right); xdir = 1; }
iPhaseAdvance=+fixtoi(xdir*10);
}
Mobile=1;
// object is rotateable? adjust to ground, if in horizontal movement or not attached to the center vertex
if (Def->Rotateable && Shape.AttachMat != MNone && (!!xdir || Def->Shape.VtxX[Shape.iAttachVtx]))
AdjustWalkRotation(20, 20, 100);
else
rdir=0;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_KNEEL:
ydir=0;
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_SCALE:
{
int ComDir = Action.ComDir;
if (Shape.CheckScaleToWalk(GetX(), GetY()))
{
ObjectActionWalk(this);
return;
}
if ((Action.Dir == DIR_Left && ComDir == COMD_Left) || (Action.Dir == DIR_Right && ComDir == COMD_Right))
{
/*if (ydir > 0)
ComDir = COMD_Down;
else
ComDir = COMD_Up;*/
ComDir = COMD_Up;
}
switch (ComDir)
{
case COMD_Up: case COMD_UpRight: case COMD_UpLeft:
if (ydir > 0) ydir -= decel;
else ydir -= accel;
if (ydir < -limit) ydir = -limit; break;
case COMD_Down: case COMD_DownRight: case COMD_DownLeft:
if (ydir < 0) ydir += decel;
else ydir += accel;
if (ydir > +limit) ydir = +limit; break;
case COMD_Left: case COMD_Right: case COMD_Stop:
if (ydir < 0) ydir += decel;
if (ydir > 0) ydir -= decel;
if ((ydir > -decel) && (ydir < +decel)) ydir = 0;
break;
}
iPhaseAdvance=0;
if (ydir<0) iPhaseAdvance=-fixtoi(ydir*14);
if (ydir>0) iPhaseAdvance=+fixtoi(ydir*14);
xdir=0;
Mobile=1;
break;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_HANGLE:
switch (Action.ComDir)
{
case COMD_Left: case COMD_UpLeft: case COMD_DownLeft:
if (xdir > 0) xdir -= decel;
else xdir -= accel;
if (xdir < -limit) xdir = -limit;
break;
case COMD_Right: case COMD_UpRight: case COMD_DownRight:
if (xdir < 0) xdir += decel;
else xdir += accel;
if (xdir > +limit) xdir = +limit;
break;
case COMD_Up:
if (Action.Dir == DIR_Left)
if (xdir > 0) xdir -= decel;
else xdir -= accel;
else
if (xdir < 0) xdir += decel;
else xdir += accel;
if (xdir < -limit) xdir = -limit;
if (xdir > +limit) xdir = +limit;
break;
case COMD_Stop: case COMD_Down:
if (xdir < 0) xdir += decel;
if (xdir > 0) xdir -= decel;
if ((xdir > -decel) && (xdir < +decel)) xdir = 0;
break;
}
iPhaseAdvance=0;
if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); }
if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); }
ydir=0;
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_FLIGHT:
// Contained: fall out (one try only)
if (!::Game.iTick10)
if (Contained)
{
StopActionDelayCommand(this);
SetCommand(C4CMD_Exit);
}
switch (Action.ComDir)
{
case COMD_Left: case COMD_UpLeft: case COMD_DownLeft:
xdir -= Max(Min(limit + xdir, xdir > 0 ? decel : accel), itofix(0));
break;
case COMD_Right: case COMD_UpRight: case COMD_DownRight:
xdir += Max(Min(limit - xdir, xdir < 0 ? decel : accel), itofix(0));
break;
}
// Gravity/mobile
DoGravity(this);
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_DIG:
{
int32_t smpx = GetX(), smpy = GetY();
bool fAttachOK = false;
if (Action.t_attach & CNAT_Bottom && Shape.Attach(smpx,smpy,CNAT_Bottom)) fAttachOK = true;
else if (Action.t_attach & CNAT_Left && Shape.Attach(smpx,smpy,CNAT_Left)) { fAttachOK = true; }
else if (Action.t_attach & CNAT_Right && Shape.Attach(smpx,smpy,CNAT_Right)) { fAttachOK = true; }
else if (Action.t_attach & CNAT_Top && Shape.Attach(smpx,smpy,CNAT_Top)) fAttachOK = true;
if (!fAttachOK)
{ ObjectComStopDig(this); return; }
iPhaseAdvance=40*limit;
if (xdir < 0) SetDir(DIR_Left); else if (xdir > 0) SetDir(DIR_Right);
Action.t_attach=CNAT_None;
Mobile=1;
break;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_SWIM:
// ComDir changes xdir/ydir
switch (Action.ComDir)
{
case COMD_Up: ydir-=accel; break;
case COMD_UpRight: ydir-=accel; xdir+=accel; break;
case COMD_Right: xdir+=accel; break;
case COMD_DownRight:ydir+=accel; xdir+=accel; break;
case COMD_Down: ydir+=accel; break;
case COMD_DownLeft: ydir+=accel; xdir-=accel; break;
case COMD_Left: xdir-=accel; break;
case COMD_UpLeft: ydir-=accel; xdir-=accel; break;
case COMD_Stop:
if (xdir<0) xdir+=decel;
if (xdir>0) xdir-=decel;
if ((xdir>-decel) && (xdir<+decel)) xdir=0;
if (ydir<0) ydir+=decel;
if (ydir>0) ydir-=decel;
if ((ydir>-decel) && (ydir<+decel)) ydir=0;
break;
}
// Out of liquid check
if (!InLiquid)
{
// Just above liquid: move down
if (GBackLiquid(GetX(),GetY()+1+Def->Float*Con/FullCon-1)) ydir=+accel;
// Free fall: walk
else { ObjectActionWalk(this); return; }
}
// xdir/ydir bounds, don't apply if COMD_None
if (Action.ComDir != COMD_None)
{
if (ydir<-limit) ydir=-limit; if (ydir>+limit) ydir=+limit;
if (xdir>+limit) xdir=+limit; if (xdir<-limit) xdir=-limit;
}
// Surface dir bound
if (!GBackLiquid(GetX(),GetY()-1+Def->Float*Con/FullCon-1)) if (ydir<0) ydir=0;
// Dir, Phase, Attach
if (xdir<0) SetDir(DIR_Left);
if (xdir>0) SetDir(DIR_Right);
iPhaseAdvance=fixtoi(limit*10);
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_THROW:
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_BRIDGE:
{
if (!DoBridge(this)) return;
switch (Action.ComDir)
{
case COMD_Left: case COMD_UpLeft: SetDir(DIR_Left); break;
case COMD_Right: case COMD_UpRight: SetDir(DIR_Right); break;
}
ydir=0; xdir=0;
Mobile=1;
}
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_PUSH:
// No target
if (!Action.Target) { StopActionDelayCommand(this); return; }
// Inside target
if (Contained==Action.Target) { StopActionDelayCommand(this); return; }
// Target pushing force
bool fStraighten;
iTXDir=0; fStraighten=false;
switch (Action.ComDir)
{
case COMD_Left: case COMD_DownLeft: iTXDir=-limit; break;
case COMD_UpLeft: fStraighten=1; iTXDir=-limit; break;
case COMD_Right: case COMD_DownRight: iTXDir=+limit; break;
case COMD_UpRight: fStraighten=1; iTXDir=+limit; break;
case COMD_Up: fStraighten=1; break;
case COMD_Stop: case COMD_Down: iTXDir=0; break;
}
// Push object
if (!Action.Target->Push(iTXDir,accel,fStraighten))
{ StopActionDelayCommand(this); return; }
// Set target controller
Action.Target->Controller=Controller;
// ObjectAction got hold check
iPushDistance = Max(Shape.Wdt/2-8,0);
iPushRange = iPushDistance + 10;
int32_t sax,say,sawdt,sahgt;
Action.Target->GetArea(sax,say,sawdt,sahgt);
// Object lost
if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange)
|| !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange))
{
// Wait command (why, anyway?)
StopActionDelayCommand(this);
// Grab lost action
GrabLost(this);
// Done
return;
}
// Follow object (full xdir reset)
// Vertical follow: If object moves out at top, assume it's being pushed upwards and the Clonk must run after it
if (GetY()-iPushDistance > say+sahgt && iTXDir) { if (iTXDir>0) sax+=sawdt/2; sawdt/=2; }
// Horizontal follow
iTargetX=BoundBy(GetX(),sax-iPushDistance,sax+sawdt-1+iPushDistance);
if (GetX()==iTargetX) xdir=0;
else { if (GetX()<iTargetX) xdir=+limit; if (GetX()>iTargetX) xdir=-limit; }
// Phase by XDir
if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); }
if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); }
// No YDir
ydir=0;
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_PULL:
// No target
if (!Action.Target) { StopActionDelayCommand(this); return; }
// Inside target
if (Contained==Action.Target) { StopActionDelayCommand(this); return; }
// Target contained
if (Action.Target->Contained) { StopActionDelayCommand(this); return; }
int32_t iPullDistance;
int32_t iPullX;
iPullDistance = Action.Target->Shape.Wdt/2 + Shape.Wdt/2;
iTargetX=GetX();
if (Action.ComDir==COMD_Right) iTargetX = Action.Target->GetX()+iPullDistance;
if (Action.ComDir==COMD_Left) iTargetX = Action.Target->GetX()-iPullDistance;
iPullX=Action.Target->GetX();
if (Action.ComDir==COMD_Right) iPullX = GetX()-iPullDistance;
if (Action.ComDir==COMD_Left) iPullX = GetX()+iPullDistance;
fWalk = limit;
fMove = 0;
if (Action.ComDir==COMD_Right) fMove = +fWalk;
if (Action.ComDir==COMD_Left) fMove = -fWalk;
iTXDir = fMove + fWalk * BoundBy<int32_t>(iPullX-Action.Target->GetX(),-10,+10) / 10;
// Push object
if (!Action.Target->Push(iTXDir,accel,false))
{ StopActionDelayCommand(this); return; }
// Set target controller
Action.Target->Controller=Controller;
// Train pulling: com dir transfer
if ( (Action.Target->GetProcedure()==DFA_WALK)
|| (Action.Target->GetProcedure()==DFA_PULL) )
{
Action.Target->Action.ComDir=COMD_Stop;
if (iTXDir<0) Action.Target->Action.ComDir=COMD_Left;
if (iTXDir>0) Action.Target->Action.ComDir=COMD_Right;
}
// Pulling range
iPushDistance = Max(Shape.Wdt/2-8,0);
iPushRange = iPushDistance + 20;
Action.Target->GetArea(sax,say,sawdt,sahgt);
// Object lost
if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange)
|| !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange))
{
// Wait command (why, anyway?)
StopActionDelayCommand(this);
// Grab lost action
GrabLost(this);
// Lose target
Action.Target=NULL;
// Done
return;
}
// Move to pulling position
xdir = fMove + fWalk * BoundBy<int32_t>(iTargetX-GetX(),-10,+10) / 10;
// Phase by XDir
iPhaseAdvance=0;
if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); }
if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); }
// No YDir
ydir=0;
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_LIFT:
// Valid check
if (!Action.Target) { SetAction(0); return; }
// Target lifting force
lftspeed=itofix(2); tydir=0;
switch (Action.ComDir)
{
case COMD_Up: tydir=-lftspeed; break;
case COMD_Stop: tydir=-GravAccel; break;
case COMD_Down: tydir=+lftspeed; break;
}
// Lift object
if (!Action.Target->Lift(tydir,C4REAL100(50)))
{ SetAction(0); return; }
// Check LiftTop
if (Def->LiftTop)
if (Action.Target->GetY()<=(GetY()+Def->LiftTop))
if (Action.ComDir==COMD_Up)
Call(PSF_LiftTop);
// General
DoGravity(this);
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_FLOAT:
// ComDir changes xdir/ydir
switch (Action.ComDir)
{
case COMD_Up:
ydir-=accel;
if (xdir<0) xdir+=decel;
if (xdir>0) xdir-=decel;
if ((xdir>-decel) && (xdir<+decel)) xdir=0;
break;
case COMD_UpRight:
ydir-=accel; xdir+=accel; break;
case COMD_Right:
xdir+=accel;
if (ydir<0) ydir+=decel;
if (ydir>0) ydir-=decel;
if ((ydir>-decel) && (ydir<+decel)) ydir=0;
break;
case COMD_DownRight:
ydir+=accel; xdir+=accel; break;
case COMD_Down:
ydir+=accel;
if (xdir<0) xdir+=decel;
if (xdir>0) xdir-=decel;
if ((xdir>-decel) && (xdir<+decel)) xdir=0;
break;
case COMD_DownLeft:
ydir+=accel; xdir-=accel; break;
case COMD_Left:
xdir-=accel;
if (ydir<0) ydir+=decel;
if (ydir>0) ydir-=decel;
if ((ydir>-decel) && (ydir<+decel)) ydir=0;
break;
case COMD_UpLeft:
ydir-=accel; xdir-=accel; break;
case COMD_Stop:
if (xdir<0) xdir+=decel;
if (xdir>0) xdir-=decel;
if ((xdir>-decel) && (xdir<+decel)) xdir=0;
if (ydir<0) ydir+=decel;
if (ydir>0) ydir-=decel;
if ((ydir>-decel) && (ydir<+decel)) ydir=0;
break;
}
// xdir/ydir bounds, don't apply if COMD_None
if (Action.ComDir != COMD_None)
{
if (ydir<-limit) ydir=-limit; if (ydir>+limit) ydir=+limit;
if (xdir>+limit) xdir=+limit; if (xdir<-limit) xdir=-limit;
}
Mobile=1;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ATTACH: Force position to target object
// own vertex index is determined by high-order byte of action data
// target vertex index is determined by low-order byte of action data
case DFA_ATTACH:
// No target
if (!Action.Target)
{
if (Status)
{
SetAction(0);
Call(PSF_AttachTargetLost);
}
return;
}
// Target incomplete and no incomplete activity
if (!(Action.Target->OCF & OCF_FullCon))
if (!Action.Target->Def->IncompleteActivity)
{ SetAction(0); return; }
// Force containment
if (Action.Target->Contained!=Contained)
{
if (Action.Target->Contained)
Enter(Action.Target->Contained);
else
Exit(GetX(),GetY(),GetR());
}
// Object might have detached in Enter/Exit call
if (!Action.Target) break;
// Move position (so objects on solidmask move)
MovePosition(Action.Target->fix_x + Action.Target->Shape.VtxX[Action.Data&255]
-Shape.VtxX[Action.Data>>8] - fix_x,
Action.Target->fix_y + Action.Target->Shape.VtxY[Action.Data&255]
-Shape.VtxY[Action.Data>>8] - fix_y);
// must zero motion...
xdir=ydir=0;
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case DFA_CONNECT:
{
bool fBroke=false;
// Line destruction check: Target missing or incomplete
if (!Action.Target || (Action.Target->Con<FullCon)) fBroke=true;
if (!Action.Target2 || (Action.Target2->Con<FullCon)) fBroke=true;
if (fBroke)
{
Call(PSF_LineBreak,&C4AulParSet(C4VBool(true)));
AssignRemoval();
return;
}
// Movement by Target
// Connect to attach vertex
C4Value lineAttachV; C4ValueArray *lineAttach;
Action.Target->GetProperty(P_LineAttach, &lineAttachV);
lineAttach = lineAttachV.getArray();
int32_t iConnectX1, iConnectY1;
iConnectX1 = Action.Target->GetX();
iConnectY1 = Action.Target->GetY();
if (lineAttach)
{
iConnectX1 += lineAttach->GetItem(0).getInt();
iConnectY1 += lineAttach->GetItem(1).getInt();
}
if ((iConnectX1!=Shape.VtxX[0]) || (iConnectY1!=Shape.VtxY[0]))
{
// Regular wrapping line
if (Def->LineIntersect == 0)
if (!Shape.LineConnect(iConnectX1,iConnectY1,0,+1,
Shape.VtxX[0],Shape.VtxY[0])) fBroke=true;
// No-intersection line
if (Def->LineIntersect == 1)
{ Shape.VtxX[0]=iConnectX1; Shape.VtxY[0]=iConnectY1; }
}
// Movement by Target2
// Connect to attach vertex
Action.Target2->GetProperty(P_LineAttach, &lineAttachV);
lineAttach = lineAttachV.getArray();
int32_t iConnectX2, iConnectY2;
iConnectX2 = Action.Target2->GetX();
iConnectY2 = Action.Target2->GetY();
if (lineAttach)
{
iConnectX2 += lineAttach->GetItem(0).getInt();
iConnectY2 += lineAttach->GetItem(1).getInt();
}
if ((iConnectX2!=Shape.VtxX[Shape.VtxNum-1]) || (iConnectY2!=Shape.VtxY[Shape.VtxNum-1]))
{
// Regular wrapping line
if (Def->LineIntersect == 0)
if (!Shape.LineConnect(iConnectX2,iConnectY2,Shape.VtxNum-1,-1,
Shape.VtxX[Shape.VtxNum-1],Shape.VtxY[Shape.VtxNum-1])) fBroke=true;
// No-intersection line
if (Def->LineIntersect == 1)
{ Shape.VtxX[Shape.VtxNum-1]=iConnectX2; Shape.VtxY[Shape.VtxNum-1]=iConnectY2; }
}
// Check max length
int32_t max_dist;
max_dist = GetPropertyInt(P_LineMaxDistance);
if (max_dist)
{
int32_t dist_x = iConnectX2 - iConnectX1, dist_y = iConnectY2 - iConnectY1;
int64_t dist_x2 = int64_t(dist_x)*dist_x, dist_y2 = int64_t(dist_y)*dist_y, max_dist2 = int64_t(max_dist)*max_dist;
if (dist_x2+dist_y2 > max_dist2) fBroke = true;
}
// Line fBroke
if (fBroke)
{
Call(PSF_LineBreak,0);
AssignRemoval();
return;
}
// Reduce line segments
if (!::Game.iTick35)
ReduceLineSegments(Shape, !::Game.iTick2);
}
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
default:
// Attach
if (Action.t_attach)
{
xdir = ydir = 0;
Mobile = 1;
}
// Free gravity
else
DoGravity(this);
break;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}
// Phase Advance (zero delay means no phase advance)
if (pActionDef->GetPropertyInt(P_Delay))
{
Action.PhaseDelay+=iPhaseAdvance;
if (Action.PhaseDelay >= pActionDef->GetPropertyInt(P_Delay))
{
// Advance Phase
Action.PhaseDelay=0;
Action.Phase += pActionDef->GetPropertyInt(P_Step);
// Phase call
if (pActionDef->GetPropertyStr(P_PhaseCall))
{
Call(pActionDef->GetPropertyStr(P_PhaseCall)->GetCStr());
}
// Phase end
if (Action.Phase>=pActionDef->GetPropertyInt(P_Length))
{
C4String *next_action = pActionDef->GetPropertyStr(P_NextAction);
// Keep current action if there is no NextAction
if (!next_action)
Action.Phase = 0;
// set new action if it's not Hold
else if (next_action == &Strings.P[P_Hold])
{
Action.Phase = pActionDef->GetPropertyInt(P_Length)-1;
Action.PhaseDelay = pActionDef->GetPropertyInt(P_Delay)-1;
}
else
{
// Set new action
SetActionByName(next_action, NULL, NULL, SAC_StartCall | SAC_EndCall);
}
}
}
}
return;
}
bool C4Object::SetOwner(int32_t iOwner)
{
C4Player *pPlr;
// Check valid owner
if (!(ValidPlr(iOwner) || iOwner == NO_OWNER)) return false;
// always set color, even if no owner-change is done
if (iOwner != NO_OWNER)
if (GetGraphics()->IsColorByOwner())
{
Color=::Players.Get(iOwner)->ColorDw;
UpdateFace(false);
}
// no change?
if (Owner == iOwner) return true;
// remove old owner view
if (ValidPlr(Owner))
{
pPlr = ::Players.Get(Owner);
while (pPlr->FoWViewObjs.Remove(this)) {}
}
else
for (pPlr = ::Players.First; pPlr; pPlr = pPlr->Next)
while (pPlr->FoWViewObjs.Remove(this)) {}
// set new owner
int32_t iOldOwner=Owner;
Owner=iOwner;
if (Owner != NO_OWNER)
// add to plr view
PlrFoWActualize();
// this automatically updates controller
Controller = Owner;
// script callback
Call(PSF_OnOwnerChanged, &C4AulParSet(C4VInt(Owner), C4VInt(iOldOwner)));
// done
return true;
}
bool C4Object::SetPlrViewRange(int32_t iToRange)
{
// set new range
PlrViewRange = iToRange;
// resort into player's FoW-repeller-list
PlrFoWActualize();
// success
return true;
}
void C4Object::PlrFoWActualize()
{
C4Player *pPlr;
// single owner?
if (ValidPlr(Owner))
{
// single player's FoW-list
pPlr = ::Players.Get(Owner);
while (pPlr->FoWViewObjs.Remove(this)) {}
if (PlrViewRange) pPlr->FoWViewObjs.Add(this, C4ObjectList::stNone);
}
// no owner?
else
{
// all players!
for (pPlr = ::Players.First; pPlr; pPlr = pPlr->Next)
{
while (pPlr->FoWViewObjs.Remove(this)) {}
if (PlrViewRange) pPlr->FoWViewObjs.Add(this, C4ObjectList::stNone);
}
}
}
void C4Object::SetAudibilityAt(C4TargetFacet &cgo, int32_t iX, int32_t iY)
{
// target pos (parallax)
float offX, offY, newzoom;
GetDrawPosition(cgo, iX, iY, cgo.Zoom, offX, offY, newzoom);
Audible = Max<int>(Audible, BoundBy(100 - 100 * Distance(cgo.X + cgo.Wdt / 2, cgo.Y + cgo.Hgt / 2, offX, offY) / 700, 0, 100));
AudiblePan = BoundBy<int>(200 * (offX - cgo.X - (cgo.Wdt / 2)) / cgo.Wdt, -100, 100);
}
bool C4Object::IsVisible(int32_t iForPlr, bool fAsOverlay) const
{
bool fDraw;
C4Value vis;
if (!GetProperty(P_Visibility, &vis))
return true;
int32_t Visibility;
C4ValueArray *parameters = vis.getArray();
if (parameters && parameters->GetSize())
{
Visibility = parameters->GetItem(0).getInt();
}
else
{
Visibility = vis.getInt();
}
// check layer
if (Layer && Layer != this && !fAsOverlay)
{
fDraw = Layer->IsVisible(iForPlr, false);
if (Layer->GetPropertyInt(P_Visibility) & VIS_LayerToggle) fDraw = !fDraw;
if (!fDraw) return false;
}
// no flags set?
if (!Visibility) return true;
// check overlay
if (Visibility & VIS_OverlayOnly)
{
if (!fAsOverlay) return false;
if (Visibility == VIS_OverlayOnly) return true;
}
// check visibility
fDraw=false;
if (Visibility & VIS_Owner) fDraw = fDraw || (iForPlr==Owner);
if (iForPlr!=NO_OWNER)
{
// check all
if (Visibility & VIS_Allies) fDraw = fDraw || (iForPlr!=Owner && !Hostile(iForPlr, Owner));
if (Visibility & VIS_Enemies) fDraw = fDraw || (iForPlr!=Owner && Hostile(iForPlr, Owner));
if (parameters)
{
if (Visibility & VIS_Select) fDraw = fDraw || parameters->GetItem(1+iForPlr).getBool();
}
}
else fDraw = fDraw || (Visibility & VIS_God);
return fDraw;
}
bool C4Object::IsInLiquidCheck() const
{
return GBackLiquid(GetX(),GetY()+Def->Float*Con/FullCon-1);
}
void C4Object::SetRotation(int32_t nr)
{
while (nr<0) nr+=360; nr%=360;
// remove solid mask
if (pSolidMaskData) pSolidMaskData->Remove(false);
// set rotation
fix_r=itofix(nr);
// Update face
UpdateFace(true);
}
void C4Object::PrepareDrawing() const
{
// color modulation
if (ColorMod != 0xffffffff || (BlitMode & (C4GFXBLIT_MOD2 | C4GFXBLIT_CLRSFC_MOD2))) pDraw->ActivateBlitModulation(ColorMod);
// other blit modes
pDraw->SetBlitMode(BlitMode);
}
void C4Object::FinishedDrawing() const
{
// color modulation
pDraw->DeactivateBlitModulation();
// extra blitting flags
pDraw->ResetBlitMode();
}
void C4Object::DrawSolidMask(C4TargetFacet &cgo) const
{
// mask must exist
if (!pSolidMaskData) return;
// draw it
pSolidMaskData->Draw(cgo);
}
void C4Object::UpdateSolidMask(bool fRestoreAttachedObjects)
{
// solidmask doesn't make sense with non-existant objects
// (the solidmask has already been destroyed in AssignRemoval -
// do not reset it!)
if (!Status) return;
// Determine necessity, update cSolidMask, put or remove mask
// Mask if enabled, fullcon, not contained
if (SolidMask.Wdt > 0 && Con >= FullCon && !Contained)
{
// Recheck and put mask
if (!pSolidMaskData)
{
pSolidMaskData = new C4SolidMask(this);
}
else
pSolidMaskData->Remove(false);
pSolidMaskData->Put(true, NULL, fRestoreAttachedObjects);
}
// Otherwise, remove and destroy mask
else if (pSolidMaskData)
{
delete pSolidMaskData; pSolidMaskData = NULL;
}
}
bool C4Object::Collect(C4Object *pObj)
{
// Object enter container
bool fRejectCollect;
if (!pObj->Enter(this, true, false, &fRejectCollect))
return false;
// Cancel attach (hacky)
ObjectComCancelAttach(pObj);
// Container Collection call
Call(PSF_Collection,&C4AulParSet(C4VObj(pObj)));
// Object Hit call
if (pObj->Status && pObj->OCF & OCF_HitSpeed1) pObj->Call(PSF_Hit);
if (pObj->Status && pObj->OCF & OCF_HitSpeed2) pObj->Call(PSF_Hit2);
if (pObj->Status && pObj->OCF & OCF_HitSpeed3) pObj->Call(PSF_Hit3);
// post-copy the motion of the new container
if (pObj->Contained == this) pObj->CopyMotion(this);
// done, success
return true;
}
bool C4Object::GrabInfo(C4Object *pFrom)
{
// safety
if (!pFrom) return false; if (!Status || !pFrom->Status) return false;
// even more safety (own info: success)
if (pFrom == this) return true;
// only if other object has info
if (!pFrom->Info) return false;
// clear own info object
if (Info)
{
Info->Retire();
ClearInfo (Info);
}
// remove objects from any owning crews
::Players.ClearPointers(pFrom);
::Players.ClearPointers(this);
// set info
Info = pFrom->Info; pFrom->ClearInfo (pFrom->Info);
// set name
SetName(Info->Name);
// retire from old crew
Info->Retire();
// if alive, recruit to new crew
if (Alive) Info->Recruit();
// make new crew member
C4Player *pPlr = ::Players.Get(Owner);
if (pPlr) pPlr->MakeCrewMember(this);
// done, success
return true;
}
bool C4Object::ShiftContents(bool fShiftBack, bool fDoCalls)
{
// get current object
C4Object *c_obj = Contents.GetObject();
if (!c_obj) return false;
// get next/previous
C4ObjectLink *pLnk = fShiftBack ? (Contents.Last) : (Contents.First->Next);
for (;;)
{
// end reached without success
if (!pLnk) return false;
// check object
C4Object *pObj = pLnk->Obj;
if (pObj->Status)
if (!c_obj->CanConcatPictureWith(pObj))
{
// object different: shift to this
DirectComContents(pObj, !!fDoCalls);
return true;
}
// next/prev item
pLnk = fShiftBack ? (pLnk->Prev) : (pLnk->Next);
}
// not reached
}
void C4Object::DirectComContents(C4Object *pTarget, bool fDoCalls)
{
// safety
if (!pTarget || !pTarget->Status || pTarget->Contained != this) return;
// Desired object already at front?
if (Contents.GetObject() == pTarget) return;
// select object via script?
if (fDoCalls)
if (Call("~ControlContents", &C4AulParSet(C4VPropList(pTarget))))
return;
// default action
if (!(Contents.ShiftContents(pTarget))) return;
// Selection sound
if (fDoCalls) if (!Contents.GetObject()->Call("~Selection", &C4AulParSet(C4VObj(this)))) StartSoundEffect("Grab",false,100,this);
// update menu with the new item in "put" entry
if (Menu && Menu->IsActive() && Menu->IsContextMenu())
{
Menu->Refill();
}
// Done
return;
}
void C4Object::GetParallaxity(int32_t *parX, int32_t *parY) const
{
assert(parX); assert(parY);
*parX = 100; *parY = 100;
if (Category & C4D_Foreground)
{
*parX = 0; *parY = 0;
return;
}
if (!(Category & C4D_Parallax)) return;
C4Value parV; GetProperty(P_Parallaxity, &parV);
C4ValueArray *par = parV.getArray();
if (!par) return;
*parX = par->GetItem(0).getInt();
*parY = par->GetItem(1).getInt();
}
bool C4Object::GetDragImage(C4Object **drag_object, C4ID *drag_id) const
{
// drag is possible if MouseDragImage is assigned
C4Value parV; GetProperty(P_MouseDragImage, &parV);
if (!parV) return false;
// determine drag object/id
C4Object *obj=NULL; C4ID id;
if (parV.CheckConversion(C4V_Object)) obj = parV.getObj();
else if (parV.CheckConversion(C4V_Def)) id = parV.getC4ID();
if (drag_object) *drag_object = obj;
if (drag_id) *drag_id = id;
// drag possible, even w./o image
return true;
}
bool C4Object::DoSelect()
{
// selection allowed?
if (CrewDisabled) return false;
// do callback
Call(PSF_CrewSelection, &C4AulParSet(C4VBool(false)));
// done
return true;
}
void C4Object::UnSelect()
{
// do callback
Call(PSF_CrewSelection, &C4AulParSet(C4VBool(true)));
}
bool C4Object::GetDrawPosition(const C4TargetFacet & cgo,
float & resultx, float & resulty, float & resultzoom) const
{
return GetDrawPosition(cgo, fixtof(fix_x), fixtof(fix_y), cgo.Zoom, resultx, resulty, resultzoom);
}
bool C4Object::GetDrawPosition(const C4TargetFacet & cgo, float objx, float objy, float zoom, float & resultx, float & resulty, float & resultzoom) const
{
// for HUD
if(Category & C4D_Foreground)
{
resultzoom = zoom;
if(fix_x < 0)
resultx = cgo.X + objx + cgo.Wdt;
else
resultx = cgo.X + objx;
if(fix_y < 0)
resulty = cgo.Y + objy + cgo.Hgt;
else
resulty = cgo.Y + objy;
return true;
}
// zoom with parallaxity
int iParX, iParY;
GetParallaxity(&iParX, &iParY);
float targetx = cgo.TargetX; float targety = cgo.TargetY;
float parx = iParX / 100.0f; float pary = iParY / 100.0f;
float par = parx; // and pary?
// Step 1: project to landscape coordinates
resultzoom = 1.0 / (1.0 - (par - par/zoom));
// it would be par / (1.0 - (par - par/zoom)) if objects would get smaller farther away
if (resultzoom <= 0 || resultzoom > 100) // FIXME: optimize treshhold
return false;
float rx = ((1 - parx) * targetx) * resultzoom + objx / (parx + zoom - parx * zoom);
float ry = ((1 - pary) * targety) * resultzoom + objy / (pary + zoom - pary * zoom);
// Step 2: convert to screen coordinates
if(parx == 0 && fix_x < 0)
resultx = cgo.X + (objx + cgo.Wdt) * zoom / resultzoom;
else
resultx = cgo.X + (rx - targetx) * zoom / resultzoom;
if(pary == 0 && fix_y < 0)
resulty = cgo.Y + (objy + cgo.Hgt) * zoom / resultzoom;
else
resulty = cgo.Y + (ry - targety) * zoom / resultzoom;
return true;
}
void C4Object::GetViewPosPar(float &riX, float &riY, float tx, float ty, const C4Facet &fctViewport) const
{
int iParX, iParY;
GetParallaxity(&iParX, &iParY);
// get drawing pos, then subtract original target pos to get drawing pos on landscape
if (!iParX && GetX()<0)
// HUD element at right viewport pos
riX=fixtof(fix_x)+tx+fctViewport.Wdt;
else
// regular parallaxity
riX=fixtof(fix_x)-(tx*(iParX-100)/100);
if (!iParY && GetY()<0)
// HUD element at bottom viewport pos
riY=fixtof(fix_y)+ty+fctViewport.Hgt;
else
// regular parallaxity
riY=fixtof(fix_y)-(ty*(iParY-100)/100);
}
bool C4Object::PutAwayUnusedObject(C4Object *pToMakeRoomForObject)
{
// get unused object
C4Object *pUnusedObject;
C4AulFunc *pFnObj2Drop = GetFunc(PSF_GetObject2Drop);
if (pFnObj2Drop)
pUnusedObject = pFnObj2Drop->Exec(this, pToMakeRoomForObject ? &C4AulParSet(C4VObj(pToMakeRoomForObject)) : NULL).getObj();
else
{
// is there any unused object to put away?
if (!Contents.Last) return false;
// defaultly, it's the last object in the list
// (contents list cannot have invalid status-objects)
pUnusedObject = Contents.Last->Obj;
}
// no object to put away? fail
if (!pUnusedObject) return false;
// grabbing something?
bool fPushing = (GetProcedure()==DFA_PUSH);
if (fPushing)
// try to put it in there
if (ObjectComPut(this, Action.Target, pUnusedObject))
return true;
// in container? put in there
if (Contained)
{
// try to put it in directly
// note that this works too, if an object is grabbed inside the container
if (ObjectComPut(this, Contained, pUnusedObject))
return true;
// now putting didn't work - drop it outside
AddCommand(C4CMD_Drop, pUnusedObject);
AddCommand(C4CMD_Exit);
return true;
}
else
// if uncontained, simply try to drop it
// if this doesn't work, it won't ever
return !!ObjectComDrop(this, pUnusedObject);
}
bool C4Object::SetGraphics(const char *szGraphicsName, C4Def *pSourceDef)
{
// safety
if (!Status) return false;
// default def
if (!pSourceDef) pSourceDef = Def;
// get graphics
C4DefGraphics *pGrp = pSourceDef->Graphics.Get(szGraphicsName);
if (!pGrp) return false;
// no change? (no updates need to be done, then)
//if (pGraphics == pGrp) return true; // that's not exactly true because the graphics itself might have changed, for example on def reload
// set new graphics
pGraphics = pGrp;
// update Color, etc.
UpdateGraphics(true);
// success
return true;
}
bool C4Object::SetGraphics(C4DefGraphics *pNewGfx, bool fTemp)
{
// safety
if (!pNewGfx) return false;
// set it and update related stuff
pGraphics = pNewGfx;
UpdateGraphics(true, fTemp);
return true;
}
C4GraphicsOverlay *C4Object::GetGraphicsOverlay(int32_t iForID) const
{
// search in list until ID is found or passed
C4GraphicsOverlay *pOverlay = pGfxOverlay, *pPrevOverlay = NULL;
while (pOverlay && pOverlay->GetID() < iForID) { pPrevOverlay = pOverlay; pOverlay = pOverlay->GetNext(); }
// exact match found?
if (pOverlay && pOverlay->GetID() == iForID) return pOverlay;
// none found
return NULL;
}
C4GraphicsOverlay *C4Object::GetGraphicsOverlay(int32_t iForID, bool fCreate)
{
// search in list until ID is found or passed
C4GraphicsOverlay *pOverlay = pGfxOverlay, *pPrevOverlay = NULL;
while (pOverlay && pOverlay->GetID() < iForID) { pPrevOverlay = pOverlay; pOverlay = pOverlay->GetNext(); }
// exact match found?
if (pOverlay && pOverlay->GetID() == iForID) return pOverlay;
// ID has been passed: Create new if desired
if (!fCreate) return NULL;
C4GraphicsOverlay *pNewOverlay = new C4GraphicsOverlay();
pNewOverlay->SetID(iForID);
pNewOverlay->SetNext(pOverlay);
if (pPrevOverlay) pPrevOverlay->SetNext(pNewOverlay); else pGfxOverlay = pNewOverlay;
// return newly created overlay
return pNewOverlay;
}
bool C4Object::RemoveGraphicsOverlay(int32_t iOverlayID)
{
// search in list until ID is found or passed
C4GraphicsOverlay *pOverlay = pGfxOverlay, *pPrevOverlay = NULL;
while (pOverlay && pOverlay->GetID() < iOverlayID) { pPrevOverlay = pOverlay; pOverlay = pOverlay->GetNext(); }
// exact match found?
if (pOverlay && pOverlay->GetID() == iOverlayID)
{
// remove it
if (pPrevOverlay) pPrevOverlay->SetNext(pOverlay->GetNext()); else pGfxOverlay = pOverlay->GetNext();
pOverlay->SetNext(NULL); // prevents deletion of following overlays
delete pOverlay;
// removed
return true;
}
// no match found
return false;
}
bool C4Object::HasGraphicsOverlayRecursion(const C4Object *pCheckObj) const
{
C4Object *pGfxOvrlObj;
if (pGfxOverlay)
for (C4GraphicsOverlay *pGfxOvrl = pGfxOverlay; pGfxOvrl; pGfxOvrl = pGfxOvrl->GetNext())
if ((pGfxOvrlObj = pGfxOvrl->GetOverlayObject()))
{
if (pGfxOvrlObj == pCheckObj) return true;
if (pGfxOvrlObj->HasGraphicsOverlayRecursion(pCheckObj)) return true;
}
return false;
}
bool C4Object::StatusActivate()
{
// readd to main list
::Objects.InactiveObjects.Remove(this);
Status = C4OS_NORMAL;
::Objects.Add(this);
// update some values
UpdateGraphics(false);
UpdateFace(true);
UpdatePos();
Call(PSF_OnSynchronized);
// done, success
return true;
}
bool C4Object::StatusDeactivate(bool fClearPointers)
{
// clear particles
ClearParticleLists();
// put into inactive list
::Objects.Remove(this);
Status = C4OS_INACTIVE;
::Objects.InactiveObjects.Add(this, C4ObjectList::stMain);
// if desired, clear game pointers
if (fClearPointers)
{
// in this case, the object must also exit any container, and any contained objects must be exited
ClearContentsAndContained();
Game.ClearPointers(this);
}
else
{
// always clear transfer
Game.TransferZones.ClearPointers(this);
}
// done, success
return true;
}
void C4Object::ClearContentsAndContained(bool fDoCalls)
{
// exit contents from container
C4Object *cobj; C4ObjectLink *clnk,*next;
for (clnk=Contents.First; clnk && (cobj=clnk->Obj); clnk=next)
{
next=clnk->Next;
cobj->Exit(GetX(), GetY(), 0,Fix0,Fix0,Fix0, fDoCalls);
}
// remove from container *after* contents have been removed!
if (Contained) Exit(GetX(), GetY(), 0, Fix0, Fix0, Fix0, fDoCalls);
}
bool C4Object::AdjustWalkRotation(int32_t iRangeX, int32_t iRangeY, int32_t iSpeed)
{
int32_t iDestAngle;
// attachment at middle (bottom) vertex?
if (Shape.iAttachVtx<0 || !Def->Shape.VtxX[Shape.iAttachVtx])
{
// evaluate floor around attachment pos
int32_t iSolidLeft=0, iSolidRight=0;
// left
int32_t iXCheck = Shape.iAttachX-iRangeX;
if (GBackSolid(iXCheck, Shape.iAttachY))
{
// up
while (--iSolidLeft>-iRangeY)
if (GBackSolid(iXCheck, Shape.iAttachY+iSolidLeft))
{ ++iSolidLeft; break; }
}
else
// down
while (++iSolidLeft<iRangeY)
if (GBackSolid(iXCheck, Shape.iAttachY+iSolidLeft))
{ --iSolidLeft; break; }
// right
iXCheck += 2*iRangeX;
if (GBackSolid(iXCheck, Shape.iAttachY))
{
// up
while (--iSolidRight>-iRangeY)
if (GBackSolid(iXCheck, Shape.iAttachY+iSolidRight))
{ ++iSolidRight; break; }
}
else
// down
while (++iSolidRight<iRangeY)
if (GBackSolid(iXCheck, Shape.iAttachY+iSolidRight))
{ --iSolidRight; break; }
// calculate destination angle
// 100% accurate for large values of Pi ;)
iDestAngle=(iSolidRight-iSolidLeft)*(35/Max<int32_t>(iRangeX, 1));
}
else
{
// attachment at other than horizontal middle vertex: get your feet to the ground!
// rotate target to large angle is OK, because rotation will stop once the real
// bottom vertex hits solid ground
if (Shape.VtxX[Shape.iAttachVtx] > 0)
iDestAngle = -50;
else
iDestAngle = 50;
}
// move to destination angle
if (Abs(iDestAngle-GetR())>2)
{
rdir = itofix(BoundBy<int32_t>(iDestAngle-GetR(), -15,+15));
rdir/=(10000/iSpeed);
}
else rdir=0;
// done, success
return true;
}
void C4Object::UpdateInLiquid()
{
// InLiquid check
if (IsInLiquidCheck()) // In Liquid
{
if (!InLiquid) // Enter liquid
{
if (OCF & OCF_HitSpeed2) if (Mass>3)
Splash(GetX(),GetY()+1,Min(Shape.Wdt*Shape.Hgt/10,20),this);
InLiquid=1;
}
}
else // Out of liquid
{
if (InLiquid) // Leave liquid
InLiquid=0;
}
}
StdStrBuf C4Object::GetInfoString()
{
StdStrBuf sResult;
// no info for invalid objects
if (!Status) return sResult;
// first part always description
//sResult.Copy(Def->GetDesc());
// go through all effects and add their desc
for (C4Effect *pEff = pEffects; pEff; pEff = pEff->pNext)
{
C4Value par[7];
C4Value vInfo = pEff->DoCall(this, PSFS_FxInfo, par[0], par[1], par[2], par[3], par[4], par[5], par[6]);
if (!vInfo) continue;
// debug: warn for wrong return types
if (vInfo.GetType() != C4V_String)
DebugLogF("Effect %s(#%d) on object %s (#%d) returned wrong info type %d.", pEff->GetName(), pEff->Number, GetName(), Number, vInfo.GetType());
// get string val
C4String *psInfo = vInfo.getStr(); const char *szEffInfo;
if (psInfo && (szEffInfo = psInfo->GetCStr()))
if (*szEffInfo)
{
// OK; this effect has a desc. Add it!
if (sResult.getLength()) sResult.AppendChar('|');
sResult.Append(szEffInfo);
}
}
// done
return sResult;
}
void C4Object::GrabContents(C4Object *pFrom)
{
// create a temp list of all objects and transfer it
// this prevents nasty deadlocks caused by RejectEntrance-scripts
C4ObjectList tmpList; tmpList.Copy(pFrom->Contents);
C4ObjectLink *cLnk;
for (cLnk=tmpList.First; cLnk; cLnk=cLnk->Next)
if (cLnk->Obj->Status)
cLnk->Obj->Enter(this);
}
bool C4Object::CanConcatPictureWith(C4Object *pOtherObject) const
{
// check current definition ID
if (id != pOtherObject->id) return false;
// def overwrite of stack conditions
int32_t allow_picture_stack = Def->AllowPictureStack;
if (!(allow_picture_stack & APS_Color))
{
// check color if ColorByOwner (flags)
if (Color != pOtherObject->Color && Def->ColorByOwner) return false;
// check modulation
if (ColorMod != pOtherObject->ColorMod) return false;
if (BlitMode != pOtherObject->BlitMode) return false;
}
if (!(allow_picture_stack & APS_Graphics))
{
// check graphics
if (pGraphics != pOtherObject->pGraphics) return false;
// check any own picture rect
if (PictureRect != pOtherObject->PictureRect) return false;
}
if (!(allow_picture_stack & APS_Name))
{
// check name, so zagabar's sandwiches don't stack
if (GetName() != pOtherObject->GetName()) return false;
}
if (!(allow_picture_stack & APS_Overlay))
{
// check overlay graphics
for (C4GraphicsOverlay *pOwnOverlay = pGfxOverlay; pOwnOverlay; pOwnOverlay = pOwnOverlay->GetNext())
if (pOwnOverlay->IsPicture())
{
C4GraphicsOverlay *pOtherOverlay = pOtherObject->GetGraphicsOverlay(pOwnOverlay->GetID(), false);
if (!pOtherOverlay || !(*pOtherOverlay == *pOwnOverlay)) return false;
}
for (C4GraphicsOverlay *pOtherOverlay = pOtherObject->pGfxOverlay; pOtherOverlay; pOtherOverlay = pOtherOverlay->GetNext())
if (pOtherOverlay->IsPicture())
if (!GetGraphicsOverlay(pOtherOverlay->GetID())) return false;
}
// concat OK
return true;
}
void C4Object::UpdateScriptPointers()
{
if (pEffects)
pEffects->ReAssignAllCallbackFunctions();
}
StdStrBuf C4Object::GetNeededMatStr() const
{
C4Def* pComponent;
int32_t cnt, ncnt;
StdStrBuf NeededMats;
C4IDList NeededComponents;
Def->GetComponents(&NeededComponents, NULL);
C4ID idComponent;
for (cnt = 0; (idComponent=NeededComponents.GetID(cnt)); cnt ++)
{
if (NeededComponents.GetCount(cnt)!=0)
{
ncnt = NeededComponents.GetCount(cnt) - Component.GetIDCount(idComponent);
if (ncnt > 0)
{
//if(!NeededMats) NeededMats.Append(", "); what was this for...?
NeededMats.AppendFormat("|%dx ", ncnt);
if ((pComponent = C4Id2Def(idComponent)))
NeededMats.Append(pComponent->GetName());
else
NeededMats.Append(idComponent.ToString());
}
}
}
StdStrBuf result;
if (!!NeededMats)
{ result.Format(LoadResStr("IDS_CON_BUILDMATNEED"), GetName()); result.Append(NeededMats.getData()); }
else
result.Format(LoadResStr("IDS_CON_BUILDMATNONE"), GetName());
return result;
}
bool C4Object::IsPlayerObject(int32_t iPlayerNumber) const
{
bool fAnyPlr = (iPlayerNumber == NO_OWNER);
// if an owner is specified: only owned objects
if (fAnyPlr && !ValidPlr(Owner)) return false;
// and crew objects
if (fAnyPlr || Owner == iPlayerNumber)
{
// flags are player objects
if (id == C4ID::Flag) return true;
C4Player *pOwner = ::Players.Get(Owner);
if (pOwner)
{
if (pOwner && pOwner->Crew.IsContained(this)) return true;
}
else
{
// Do not force that the owner exists because the function must work for unjoined players (savegame resume)
if (Def->CrewMember)
return true;
}
}
// otherwise, not a player object
return false;
}
bool C4Object::IsUserPlayerObject()
{
// must be a player object at all
if (!IsPlayerObject()) return false;
// and the owner must not be a script player
C4Player *pOwner = ::Players.Get(Owner);
if (!pOwner || pOwner->GetType() != C4PT_User) return false;
// otherwise, it's a user playeer object
return true;
}
void C4Object::SetPropertyByS(C4String * k, const C4Value & to)
{
if (k >= &Strings.P[0] && k < &Strings.P[P_LAST])
{
switch(k - &Strings.P[0])
{
case P_Plane:
if (!to.getInt()) throw new C4AulExecError("invalid Plane 0");
SetPlane(to.getInt());
return;
}
}
C4PropListNumbered::SetPropertyByS(k, to);
}
void C4Object::ResetProperty(C4String * k)
{
if (k >= &Strings.P[0] && k < &Strings.P[P_LAST])
{
switch(k - &Strings.P[0])
{
case P_Plane:
SetPlane(GetPropertyInt(P_Plane));
return;
}
}
return C4PropListNumbered::ResetProperty(k);
}
bool C4Object::GetPropertyByS(C4String *k, C4Value *pResult) const
{
if (k >= &Strings.P[0] && k < &Strings.P[P_LAST])
{
switch(k - &Strings.P[0])
{
case P_Plane: *pResult = C4VInt(Plane); return true;
}
}
return C4PropListNumbered::GetPropertyByS(k, pResult);
}
C4ValueArray * C4Object::GetProperties() const
{
C4ValueArray * a = C4PropList::GetProperties();
int i;
i = a->GetSize();
a->SetSize(i + 1);
(*a)[i++] = C4VString(&::Strings.P[P_Plane]);
return a;
}
| [
"notprathap@gmail.com"
] | notprathap@gmail.com |
5918c8881f0f7845b6224640bbdeb8668016e6fc | 21838a0e840c641687250decf9726db5e549a1f4 | /DefaultWindows/Client/Effect.cpp | 83767d81d97ea629feb6ab9767c8617535b89ca4 | [] | no_license | isr02220/Tengai08 | ac4bf537058e289291a34cebcb245f9fb24108f7 | 848accff2b7ce756e8532f5c1e497c5635026942 | refs/heads/master | 2022-12-01T14:22:59.537598 | 2020-08-14T05:58:33 | 2020-08-14T05:58:33 | 286,426,911 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,998 | cpp | #include "Effect.h"
#include "Bullet.h"
#include "Particle.h"
#include "Player.h"
#include "Monster.h"
CEffect::CEffect(const FLOAT& _degree, const FLOAT& _speed, const FLOAT& _diffuse, const UINT& _count, const LONG& _size)
: CObj()
, degree(_degree), diffuse(_diffuse), count(_count), size(_size) {
objectType = OBJ::BULLET;
lstrcpy(info->name, L"ÀÌÆåÆ®");
info->size = { (FLOAT)_size, (FLOAT)_size , 0.f };
speed = _speed;
float rad = D3DXToRadian(_degree);
info->force = { cosf(rad), sinf(rad), 0.f };
}
CEffect::~CEffect() {
}
void CEffect::Ready() {
D3DXVECTOR3 vecLT = info->position - info->size / 2.f;
D3DXVECTOR3 vecRB = info->position + info->size / 2.f;
localVertex[0] = { info->size.x / 2.f, -info->size.y / 2.f, 0.f };
localVertex[1] = { info->size.x / 2.f, info->size.y / 2.f, 0.f };
localVertex[2] = { -info->size.x / 2.f, info->size.y / 2.f, 0.f };
localVertex[3] = { -info->size.x / 2.f, -info->size.y / 2.f, 0.f };
FLOAT tempDegree;
CObj* particleObj;
for (UINT i = 0; i < count; i++) {
tempDegree = degree - diffuse * INT(count / 2 - i);
particleObj = new CParticle(tempDegree, speed, size);
particleObj->SetFillColor(RGB(255, 0, 0));
particleObj->SetStrokeColor(RGB(255, 0, 0));
particleObj->SetPosition(info->position);
vecParticles.emplace_back(particleObj);
CObjManager::GetInstance()->AddObject(particleObj, OBJ::EFFECT);
}
particleObj = new CParticle(tempDegree, 2.f, size*2);
particleObj->SetFillColor(RGB(255, 255, 255));
particleObj->SetStrokeColor(RGB(255, 255, 255));
particleObj->SetPosition(info->position);
vecParticles.emplace_back(particleObj);
CObjManager::GetInstance()->AddObject(particleObj, OBJ::EFFECT);
SetRect(rect, (LONG)vecLT.x, (LONG)vecLT.y, (LONG)vecRB.x, (LONG)vecRB.y);
}
int CEffect::Update() {
CObj::UpdateRect();
if (dead) {
for (UINT i = 0; i < count + 1; i++) {
vecParticles[i]->SetDead();
}
return STATE::DEAD;
}
info->position += info->force * speed;
for (UINT i = 0; i < count + 1; i++) {
vecParticles[i]->GetInfo()->size *= FLOAT(rand() % 300 + 700) / 1000.f;
if(vecParticles[i]->GetInfo()->size.x < 15.f)
vecParticles[i]->SetFillColor(RGB(255, 128, 0));
if(vecParticles[i]->GetInfo()->size.x < 8.f)
vecParticles[i]->SetFillColor(RGB(255, 255, 0));
if(i == count)
vecParticles[i]->GetInfo()->size *= 0.1f;
else if (vecParticles[i]->GetInfo()->size.x < 0.1f)
SetDead();
}
return STATE::NO_EVENT;
}
void CEffect::LateUpdate() {
}
void CEffect::Render(HDC hDC) {
CObj::UpdateRect();
HPEN hPen = CreatePen(PS_SOLID, 1, strokeColor);
HBRUSH hBrush = CreateSolidBrush(fillColor);
HPEN oldPen = (HPEN)SelectObject(hDC, hPen);
HBRUSH oldBrush = (HBRUSH)SelectObject(hDC, hBrush);
//Ellipse(hDC, rect->left, rect->top, rect->right, rect->bottom);
SelectObject(hDC, oldPen);
SelectObject(hDC, oldBrush);
DeleteObject(hPen);
DeleteObject(hBrush);
}
void CEffect::Release() {
}
void CEffect::OnCollision(CObj* _SrcObj) {
SetDead();
}
| [
"isr02220@gmail.com"
] | isr02220@gmail.com |
98efcef3c1e95fc96e4220fb795af0226e9c6f55 | 95b386b63e2f447c9661a74c3f762f29354a31ca | /thesis_examples/chapter3/section3/hpx_queue_template_migrable/myqueue.hpp | 72fea8c5df81e89b7c7e2b48d217aefab21c9ed8 | [] | no_license | tiagofgon/hpx_examples | 37baf0b9e96dcf16a6f30968029cf32c3fd83d13 | 87de76e3ceb7a81def501e42ed2c92b21a35104d | refs/heads/main | 2023-02-22T21:23:36.329548 | 2021-01-28T00:48:03 | 2021-01-28T00:48:03 | 304,325,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,848 | hpp |
#include <hpx/hpx.hpp>
#include <queue>
template <typename T>
class MyQueue: public hpx::components::migration_support< hpx::components::component_base<MyQueue<T>> >
{
public:
friend class hpx::serialization::access;
typedef hpx::components::migration_support< hpx::components::component_base<MyQueue<T>> > base_type;
// Components which should be migrated using hpx::migrate<> need to
// be Serializable and CopyConstructable. Components can be
// MoveConstructable in which case the serialized data is moved into the
// component's constructor.
MyQueue(MyQueue const& rhs)
: base_type(rhs), myqueue(rhs.myqueue)
{}
MyQueue(MyQueue && rhs)
: base_type(std::move(rhs)), myqueue(rhs.myqueue)
{}
MyQueue& operator=(MyQueue const & rhs)
{
myqueue = rhs.myqueue;
return *this;
}
MyQueue& operator=(MyQueue && rhs)
{
myqueue = rhs.myqueue;
return *this;
}
MyQueue() = default;
template <typename ... Args>
void Push(Args ... args) {
(myqueue.push_back(args), ...);
}
T Pop() {
T element = myqueue.front();
myqueue.erase(myqueue.begin());
return element;
}
size_t Size() {
return myqueue.size();
}
HPX_DEFINE_COMPONENT_ACTION(MyQueue, Pop, Pop_action_MyQueue);
HPX_DEFINE_COMPONENT_ACTION(MyQueue, Size, Size_action_MyQueue);
template <typename ... Args>
struct Push_action_MyQueue
: hpx::actions::make_action<
decltype(&MyQueue::Push<Args...>),
&MyQueue::Push<Args...>
>::type {};
template <typename Archive>
void serialize(Archive& ar, unsigned version)
{
ar & myqueue;
}
private:
std::vector<T> myqueue;
};
#define REGISTER_MYQUEUE_DECLARATION(type) \
HPX_REGISTER_ACTION_DECLARATION( \
MyQueue<type>::Pop_action_MyQueue, \
HPX_PP_CAT(__MyQueue_Pop_action_MyQueue_, type)); \
HPX_REGISTER_ACTION_DECLARATION( \
MyQueue<type>::Size_action_MyQueue, \
HPX_PP_CAT(__MyQueue_Size_action_MyQueue_, type)); \
#define REGISTER_MYQUEUE(type) \
HPX_REGISTER_ACTION( \
MyQueue<type>::Pop_action_MyQueue, \
HPX_PP_CAT(__MyQueue_Pop_action_MyQueue_, type)); \
HPX_REGISTER_ACTION( \
MyQueue<type>::Size_action_MyQueue, \
HPX_PP_CAT(__MyQueue_Size_action_MyQueue_, type)); \
typedef ::hpx::components::component< MyQueue<type> > HPX_PP_CAT(__MyQueue_, type); \
HPX_REGISTER_COMPONENT(HPX_PP_CAT(__MyQueue_, type))
| [
"tiago.fg@outlook.com"
] | tiago.fg@outlook.com |
3d01d45a2e0505497dcaf8d1886154bcb7bcbbc0 | 817dc9bebf0d278fcf474f31a77cb23ada61056c | /QL/CommonClass/ClassDB/DBP_Planning.cpp | 9f9fcb496e7c7dcbe582a04f436d8df6b528e3be | [] | no_license | dudugi/NewForTortoise | 6f7d82cea00b49af3c38f1e332937ce3edf894b4 | 685ba32e8d7ee16c22f115b681a21f3d4e3fddf8 | refs/heads/master | 2022-02-08T11:56:42.102049 | 2022-01-25T07:02:47 | 2022-01-25T07:02:47 | 196,016,007 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 12,001 | cpp | #include "StdAfx.h"
#include "DBP_Planning.h"
IMPLEMENT_SERIAL(CDBP_PlanningData, CDataMid, 1)
IMPLEMENT_SERIAL(CDBP_PlanningList, CDataListMid, 1)
CDBP_PlanningData::CDBP_PlanningData(void)
{
ResetData();
}
CDBP_PlanningData::~CDBP_PlanningData(void)
{
}
void CDBP_PlanningData::ResetData()
{
m_nID =0 ; //ID
m_nYears =0 ; //年度
m_strSeason =_T(""); //季节
m_strSubjectName =_T(""); //主题名
m_strBrand =_T(""); //品牌
m_strRemark =_T(""); //主题备注
m_bCheckState =FALSE ; //审核标识
m_strCreateUserID =_T(""); //创建人
m_strCreateTime =_T(""); //创建时间
m_strLastAcTime =_T(""); //最后操作时间
m_strCheckUserID =_T(""); //审核人
m_strCheckTime =_T(""); //审核时间
SetDataType(DAT_PLANNING);
}
void CDBP_PlanningData::Copy( CDBP_PlanningData *pData )
{
ASSERT(pData != NULL);
CDataMid::Copy(pData);
m_nID =pData->m_nID ;
m_nYears =pData->m_nYears ;
m_strSeason =pData->m_strSeason ;
m_strSubjectName =pData->m_strSubjectName ;
m_strBrand =pData->m_strBrand ;
m_strRemark =pData->m_strRemark ;
m_bCheckState =pData->m_bCheckState ;
m_strCreateUserID =pData->m_strCreateUserID ;
m_strCreateTime =pData->m_strCreateTime ;
m_strLastAcTime =pData->m_strLastAcTime ;
m_strCheckUserID =pData->m_strCheckUserID ;
m_strCheckTime =pData->m_strCheckTime ;
;
}
BOOL CDBP_PlanningData::GetAllDBInfo( CADOConn *pADOConn)
{
ASSERT(pADOConn);
if (pADOConn == nullptr)
{
return FALSE;
}
m_nID =pADOConn->GetValueInt64(DBP_Planning_Key_ID );
m_nYears =pADOConn->GetValueInt(DBP_Planning_Key_nYears );
m_strSeason =pADOConn->GetValueString(DBP_Planning_Key_cSeason );
m_strSubjectName =pADOConn->GetValueString(DBP_Planning_Key_cSubjectName );
m_strBrand =pADOConn->GetValueString(DBP_Planning_Key_cBrand );
m_strRemark =pADOConn->GetValueString(DBP_Planning_Key_cRemark );
m_bCheckState =_ttoi(pADOConn->GetValueString(DBP_Planning_Key_bCheckState ));
m_strCreateUserID =pADOConn->GetValueString(DBP_Planning_Key_cCreateUserID);
m_strCreateTime =pADOConn->GetValueString(DBP_Planning_Key_cCreateTime );
m_strLastAcTime =pADOConn->GetValueString(DBP_Planning_Key_cLastActTime );
m_strCheckUserID =pADOConn->GetValueString(DBP_Planning_Key_cCheckUserID );
m_strCheckTime =pADOConn->GetValueString(DBP_Planning_Key_cCheckTime );
return TRUE;
}
BOOL CDBP_PlanningData::GetAllDBInfoByID(CADOConn *pADOConn)
{
CString strSQL = _T("");
ASSERT(pADOConn != nullptr);
if (pADOConn == nullptr)
{
return FALSE;
}
strSQL.Format(_T("select * from %s where %s = %ld"),DB_TABLE_PLANNING,DBP_Planning_Key_ID,m_nID);
pADOConn->GetRecordSet(strSQL);
if(!pADOConn->adoEOF())
{
m_nID =pADOConn->GetValueInt64(DBP_Planning_Key_ID );
m_nYears =pADOConn->GetValueInt(DBP_Planning_Key_nYears );
m_strSeason =pADOConn->GetValueString(DBP_Planning_Key_cSeason );
m_strSubjectName =pADOConn->GetValueString(DBP_Planning_Key_cSubjectName );
m_strBrand =pADOConn->GetValueString(DBP_Planning_Key_cBrand );
m_strRemark =pADOConn->GetValueString(DBP_Planning_Key_cRemark );
m_bCheckState =_ttoi(pADOConn->GetValueString(DBP_Planning_Key_bCheckState ));
m_strCreateUserID =pADOConn->GetValueString(DBP_Planning_Key_cCreateUserID);
m_strCreateTime =pADOConn->GetValueString(DBP_Planning_Key_cCreateTime );
m_strLastAcTime =pADOConn->GetValueString(DBP_Planning_Key_cLastActTime );
m_strCheckUserID =pADOConn->GetValueString(DBP_Planning_Key_cCheckUserID );
m_strCheckTime =pADOConn->GetValueString(DBP_Planning_Key_cCheckTime );
}
return TRUE;
}
BOOL CDBP_PlanningData::InsertAllDBInfo( CADOConn *pADOConn )
{
CString strSqlValue = _T("");
CString strSqlKey = _T("");
CString strSQL = _T("");
strSqlKey.Format(_T("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"),DBP_Planning_Key_nYears
,DBP_Planning_Key_cSeason ,DBP_Planning_Key_cSubjectName ,DBP_Planning_Key_cBrand ,DBP_Planning_Key_cRemark ,DBP_Planning_Key_bCheckState
,DBP_Planning_Key_cCreateUserID,DBP_Planning_Key_cCreateTime ,DBP_Planning_Key_cLastActTime ,DBP_Planning_Key_cCheckUserID ,DBP_Planning_Key_cCheckTime);
strSqlValue.Format(_T("%d,'%s','%s','%s','%s',%d,'%s',%s,%s,'%s','%s'"),
m_nYears,m_strSeason,m_strSubjectName,m_strBrand,
m_strRemark,m_bCheckState,m_strCreateUserID ,DBS_GETDATESTR,DBS_GETDATESTR,
m_strCheckUserID ,m_strCheckTime
);
strSQL.Format(_T("insert into %s(%s) values(%s)"),DB_TABLE_PLANNING,strSqlKey,strSqlValue);
if (pADOConn != NULL)
{
BOOL bExecute = pADOConn->ExecuteSQL(strSQL);
if (bExecute)
{
return TRUE;
}
return FALSE;
}
return FALSE;
}
BOOL CDBP_PlanningData::UpdateAllDBInfoByID( CADOConn *pADOConn )
{
CString strSQL = _T("");
strSQL.Format(_T("Update %s set %s = %d,%s = '%s',%s = '%s',%s = '%s',%s = '%s',\
%s = %d, %s = '%s',%s = '%s',%s = '%s',%s = '%s',%s = '%s' where %s=%ld"),DB_TABLE_PLANNING
,DBP_Planning_Key_nYears ,m_nYears
,DBP_Planning_Key_cSeason ,m_strSeason
,DBP_Planning_Key_cSubjectName ,m_strSubjectName
,DBP_Planning_Key_cBrand ,m_strBrand
,DBP_Planning_Key_cRemark ,m_strRemark
,DBP_Planning_Key_bCheckState ,m_bCheckState
,DBP_Planning_Key_cCreateUserID ,m_strCreateUserID
,DBP_Planning_Key_cCreateTime ,m_strCreateTime
,DBP_Planning_Key_cLastActTime ,m_strLastAcTime
,DBP_Planning_Key_cCheckUserID ,m_strCheckUserID
,DBP_Planning_Key_cCheckTime ,m_strCheckTime
,DBP_Planning_Key_ID ,m_nID
);
if (pADOConn != NULL)
{
BOOL bExecute = pADOConn->ExecuteSQL(strSQL);
if (bExecute)
{
return TRUE;
}
return FALSE;
}
return FALSE;
}
BOOL CDBP_PlanningData::DelAllDBInfoByID( CADOConn *pADOConn )
{
CString strSQL = _T("");
strSQL.Format(_T("delete from %s where %s = %lld"),DB_TABLE_PLANNING,DBP_Planning_Key_ID,m_nID);
if (pADOConn != NULL)
{
BOOL bExecute = pADOConn->ExecuteSQL(strSQL);
if (bExecute)
{
return TRUE;
}
return FALSE;
}
return FALSE;
}
BOOL CDBP_PlanningData::GetIDByCondition( CADOConn *pADOConn )
{
ASSERT(pADOConn != nullptr);
CString strSQL;
strSQL.Format(_T("select ID from %s \
where %s = '%s' and %s = %d and %s = '%s' and %s = '%s'"),
DB_TABLE_PLANNING,
DBP_Planning_Key_cSubjectName,m_strSubjectName,
DBP_Planning_Key_nYears,m_nYears,
DBP_Planning_Key_cSeason,m_strSeason,
DBP_Planning_Key_cBrand,m_strBrand
);
pADOConn->GetRecordSet(strSQL);
if (!pADOConn->adoEOF())
{
m_nID = pADOConn->GetValueInt64(DBP_Planning_Key_ID);
return TRUE;
}
return FALSE;
}
CDBP_PlanningList::CDBP_PlanningList( void )
{
}
CDBP_PlanningList::~CDBP_PlanningList( void )
{
}
void CDBP_PlanningList::Copy( CDBP_PlanningList *pList )
{
if (pList != NULL)
{
for (int nIndex = 0;nIndex < pList->GetCount();nIndex++)
{
CDBP_PlanningData *pPlanning =(CDBP_PlanningData *)pList->GetAt(pList->FindIndex(nIndex));
if (pPlanning != NULL)
{
AddItem(pPlanning);
}
}
}
}
void CDBP_PlanningList::AddItem( CDBP_PlanningData *pItem )
{
ASSERT(pItem != NULL);
CDBP_PlanningData *pPlanning = new CDBP_PlanningData;
pPlanning->Copy(pItem);
AddTail(pPlanning);
}
void CDBP_PlanningList::DeleteItemByIndex( int nIndex )
{
if (nIndex != NULL)
{
CDBP_PlanningData *pPlanning =(CDBP_PlanningData *)GetAt(FindIndex(nIndex));
if (pPlanning != NULL)
{
RemoveAt(FindIndex(nIndex));
}
}
}
#ifdef USING_GRIDCTRL_MARK
void CDBP_PlanningList::GetAllDBInfoByCondition( CADOConn *pADO,CString strSQL,MAP_GridCtrl_AllData &mapALLData )
{
if (pADO == NULL || strSQL.IsEmpty())
{
return;
}
pADO->GetRecordSet(strSQL);
int nRow = 0;
while(!pADO->adoEOF())
{
MAP_GridCtrl_RowData map_row_data;
CDBP_PlanningData DBPlanning;
DBPlanning.GetAllDBInfo(pADO);
//ID
S_GridCtrl_FieldData map_Field_ID;
CString strID;
strID.Format(FORMAT_INT,DBPlanning.m_nID);
map_Field_ID.strValue = strID;
map_row_data.insert(make_pair(DBP_Planning_Key_ID ,map_Field_ID));
//Years
S_GridCtrl_FieldData map_Field_Years;
CString strYears;
strYears.Format(FORMAT_INT,DBPlanning.m_nYears);
map_Field_Years.strValue = strYears;
map_row_data.insert(make_pair(DBP_Planning_Key_nYears ,map_Field_Years));
//CheckState
S_GridCtrl_FieldData map_Field_CheckState;
CString strCheckState;
strCheckState.Format(FORMAT_INT,DBPlanning.m_bCheckState);
map_Field_CheckState.strValue = strCheckState;
map_row_data.insert(make_pair(DBP_Planning_Key_bCheckState ,map_Field_CheckState));
//Brand
S_GridCtrl_FieldData map_Field_Brand;
map_Field_Brand.strValue = DBPlanning.m_strBrand;
map_row_data.insert(make_pair(DBP_Planning_Key_cBrand ,map_Field_Brand));
//SubjectName
S_GridCtrl_FieldData map_Field_SubjectName;
map_Field_SubjectName.strValue = DBPlanning.m_strSubjectName;
map_row_data.insert(make_pair(DBP_Planning_Key_cSubjectName ,map_Field_SubjectName));
//Searson
S_GridCtrl_FieldData map_Field_Searson;
map_Field_Searson.strValue = DBPlanning.m_strSeason;
map_row_data.insert(make_pair(DBP_Planning_Key_cSeason ,map_Field_Searson));
//Remark
S_GridCtrl_FieldData map_Field_Remark;
map_Field_Remark.strValue = DBPlanning.m_strRemark;
map_row_data.insert(make_pair(DBP_Planning_Key_cRemark ,map_Field_Remark));
//CheckTime
S_GridCtrl_FieldData map_Field_CheckTime;
map_Field_CheckTime.strValue = DBPlanning.m_strCheckTime;
map_row_data.insert(make_pair(DBP_Planning_Key_cCheckTime ,map_Field_CheckTime));
//CheckUserID
S_GridCtrl_FieldData map_Field_CheckUserID;
map_Field_CheckUserID.strValue = DBPlanning.m_strCheckUserID;
map_row_data.insert(make_pair(DBP_Planning_Key_cCheckUserID ,map_Field_CheckUserID));
//CreateTime
S_GridCtrl_FieldData map_Field_CreateTime;
map_Field_CreateTime.strValue = DBPlanning.m_strCreateTime;
map_row_data.insert(make_pair(DBP_Planning_Key_cCreateTime ,map_Field_CreateTime));
//CreateUserID
S_GridCtrl_FieldData map_Field_CreateUserID;
map_Field_CreateUserID.strValue = DBPlanning.m_strCreateUserID;
map_row_data.insert(make_pair(DBP_Planning_Key_cCreateUserID ,map_Field_CreateUserID));
//LastAcTime
S_GridCtrl_FieldData map_Field_LastAcTime;
map_Field_LastAcTime.strValue = DBPlanning.m_strLastAcTime;
map_row_data.insert(make_pair(DBP_Planning_Key_cLastActTime ,map_Field_LastAcTime));
mapALLData.insert(make_pair(nRow++,map_row_data));
AddItem(&DBPlanning);
pADO->MoveNext();
}
}
#endif
| [
"du_chen_hi@126.com"
] | du_chen_hi@126.com |
226f925e2792d61788231be2227942ba233b497f | 27b6bd7a4e219df70d47a971230c26acd6b95cd0 | /JJson.h | f944a84f091f1349c0f7d047a31d6b3460f8980d | [] | no_license | lw000/ldb_demo | ad32c201235c8e90d407eee07168bdd9afefbf0f | 69d1a25b393e9b2d796b8d7e932d890c00e4c3c4 | refs/heads/master | 2020-08-22T20:02:58.621814 | 2019-10-22T07:38:42 | 2019-10-22T07:38:42 | 216,469,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84 | h | #pragma once
class JJson
{
public:
JJson();
~JJson();
public:
void Test();
};
| [
"373102227@qq.com"
] | 373102227@qq.com |
4b3a62625f25f969b4cb2a65c1583a1f63d38fbc | dbd7e25b0a117205550245bdc4656c19eded713e | /Project-3/BareMinimum.ino | 242b8af4a99baf761f65329c0cc014b0fa54618a | [] | no_license | jessicanathania/IMK | b011ee28816d3fd440bb60be467fbb898331346b | 56740bab64581c9cb26b8945facb298efc6965ef | refs/heads/master | 2021-01-21T13:57:03.431081 | 2016-05-18T12:40:58 | 2016-05-18T12:40:58 | 52,497,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132 | ino | void setup() {
// Ini dibiarkan kosong saja gan.. hehehehehe
}
void loop() {
// Ini juga dikosongkan saja gan.. hihihihihihi
}
| [
"jessica.nathania1995@gmail.com"
] | jessica.nathania1995@gmail.com |
b2c58386989a8d3c9fcad5a788c57855f924f220 | 89ce80be73507b4680f1f5ab083ccaeb2c5be5c2 | /Floyd-Warshall.cpp | 45d530c1a9c891834adce492d2b525c1aeedfb13 | [] | no_license | angelowen/Algorithm | 9bc803e59854d37cc2b25554f98cd6baa7893e75 | f0bfd2c1a5db10a60a42d317f1787eb55110781d | refs/heads/master | 2020-06-13T03:02:57.357924 | 2019-06-30T12:14:20 | 2019-06-30T12:14:20 | 194,512,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,087 | cpp | #include <bits/stdc++.h>
using namespace std;
int w[9][9]; // 一張有權重的圖
int d[9][9]; // 最短路徑長度
int medium[9][9]; // 由i點到j點的路徑,其中繼點為medium[i][j]。
void Floyd_Warshall() {
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++) {
d[i][j] = w[i][j];
medium[i][j] = -1; // 預設為沒有中繼點
}
for (int i = 0; i < 9; i++) d[i][i] = 0;
for (int k = 0; k < 9; k++)
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
if (d[i][k] + d[k][j] < d[i][j]) {
d[i][j] = d[i][k] + d[k][j];
medium[i][j] = k; // 由i點走到j點經過了k點
}
}
// 這支函式並不會印出起點和終點,必須另行印出。
void find_path(int i, int j) // 印出由i點到j點的最短路徑
{
if (medium[i][j] == -1) return; // 沒有中繼點就結束
find_path(i, medium[i][j]); // 先把前面的路徑都印出來
cout << medium[i][j]; // 再把中繼點印出來
find_path(medium[i][j], j); // 最後把後面的路徑都印出來
} | [
"f12angelo@gmail.com"
] | f12angelo@gmail.com |
ad71736965063a62ced540925cf9dd8bb83ac777 | 4166435508bb5b94885d193f910979536e84af4f | /C++/c++Lab/c++Lab1/Node.h | 3153c394bf23a6bf5226f09ed6c648e76e3b1f78 | [] | no_license | iorilan/Samples | 8c8cb770fdfc2058cb658ac7e5e28f0c1d137528 | 726155b6d934c48506c9b347c1332706e2d3b324 | refs/heads/master | 2021-03-12T19:11:35.345094 | 2018-04-08T09:35:13 | 2018-04-08T09:35:13 | 91,454,657 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,074 | h | #pragma once
////节点类
class Node
{
public:
////methods
Node(void);
Node(int data);
~Node(void);
/////members
Node* next;
int data;
};
////叶子节点类
class TNode
{
public:
////methods
TNode(void);
TNode(int data);
~TNode(void);
/////members
TNode* left;
TNode* right;
int data;
};
////链表类
class MyLinkTable{
public:
//////methods
void RemovdeAt(int position,Node* head);
void Add(Node* node,Node* head);
void AddAfter(int position,Node* head,Node* node);
bool IsEmpty(Node* head);
void PrintNodes(Node* head);
/////members
Node* head;
};
/////////////链栈类///////////////
class MyLinkStack{
public:
////mothods
void Push(Node* node,Node* top);
Node* Pop(Node* top);
bool IsEmpty(Node* top);
void PrintStack(Node* top);
////members
Node* top;
};
//////////二叉搜索树///////////
class BTree{
public:
////methods
void InsertNode(TNode* node);
void PrintNode(TNode* head);
TNode* FindValue(TNode* head,int value);
TNode* Find(TNode* head,TNode* node);
bool IsEmpty(TNode* head);
////members
TNode* head;
}; | [
"iorilan@hotmail.com"
] | iorilan@hotmail.com |
eb2bae8258ee876beca5c9e070398d425c0a5c8d | 8a089e59fb97a86aae3172d3d1222093e2c7be38 | /Exercise/CA3/deitel_cpp10_sourcecode/deitel_cpp10_sourcecode/ch10/fig10_17_19/HugeInteger.h | d1b5746489f183a5a98e4b34dd4b96393342fcdb | [] | no_license | schemp98/Cpp_Certification_Course | 3e653747d5c92d635b3205e07f59ef21f7f17a3d | 19bbaf460b780eecfcf63a7cc7086e118b3c3bdb | refs/heads/master | 2021-08-08T03:05:01.514460 | 2021-02-17T00:14:49 | 2021-02-17T00:14:49 | 243,670,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | h | // Fig. 10.17: Hugeinteger.h
// HugeInteger class definition.
#ifndef HugeInteger_H
#define HugeInteger_H
#include <array>
#include <iostream>
#include <string>
class HugeInteger {
friend std::ostream& operator<<(std::ostream&, const HugeInteger&);
public:
static const int digits{40}; // maximum digits in a HugeInteger
HugeInteger(long = 0); // conversion/default constructor
HugeInteger(const std::string&); // conversion constructor
// addition operator; HugeInteger + HugeInteger
HugeInteger operator+(const HugeInteger&) const;
// addition operator; HugeInteger + int
HugeInteger operator+(int) const;
// addition operator;
// HugeInteger + string that represents large integer value
HugeInteger operator+(const std::string&) const;
private:
std::array<short, digits> integer{}; // default init to 0s
};
#endif
/**************************************************************************
* (C) Copyright 1992-2017 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| [
"schemp98@hotmail.com"
] | schemp98@hotmail.com |
cfc80773a90c3b6f74515b3114e58f10f8ec531c | 21a63ea5f349644e7797842b428af4f762032d87 | /Rush00-2/Entity.class.hpp | 8f534541ba0348c6c489d642de4a036dfda78145 | [] | no_license | icareus/pisc-cpp | 1a4a7b2b803fcb5407296a01c30a62de9020a0d4 | 3451b790e3e94b29b917dc3764fe72a162d8e058 | refs/heads/master | 2020-06-02T13:22:14.358844 | 2015-01-14T07:30:57 | 2015-01-14T07:30:57 | 28,852,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* gameEntity.class.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abarbaro <abarbaro@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/01/11 19:05:18 by abarbaro #+# #+# */
/* Updated: 2015/01/11 20:00:48 by abarbaro ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef ENTITY_CLASS_HPP
# define ENTITY_CLASS_HPP
#include <string>
#include <iostream>
#include <ncurses.h>
#include <sys/ioctl.h>
#include <unistd.h>
class Entity
{
public:
Entity();
Entity(int X, int Y,
int speed, char skin);
Entity(Entity const & src);
~Entity();
Entity & operator=(Entity const & rhs);
int getPosX(void);
int getPosY(void);
int getSpeed(void);
char getSkin(void);
virtual void move() = 0;
virtual bool collide(Entity & u) = 0;
virtual bool collide(int x, int y) = 0;
virtual void getInput(void) = 0;
virtual void update(void) = 0;
virtual void display(void) = 0;
protected:
int _posX;
int _posY;
int _speed;
char _skin;
};
std::ostream & operator<<(std::ostream & o, Entity & u);
#endif
| [
"abarbaro@e2r8p2.42.fr"
] | abarbaro@e2r8p2.42.fr |
d8a9990c68196f1138acf13e9c681b539d2924a3 | 444e376e71b0e60593ee5720e0fcf9617ad5a50c | /C++/自加自减问题.cpp | 799417bbf523030d17234e73f290aa63770f90ac | [
"MIT"
] | permissive | shifushihuaidan/op11 | 740767692dbe890379ce1184f0efda5cf8954243 | b16fd69b5501f914f2312fd4618fd2961cd23135 | refs/heads/master | 2021-01-20T01:03:43.518945 | 2015-08-25T00:53:42 | 2015-08-25T00:53:42 | 41,278,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | cpp | #include<iostream>
using namespace std;
int main()
{
float x=1;
float y;
y=(++x)/(++x)/(++x);
cout<<x<<endl;
cout<<y<<endl;
/*int j=5;
int i=j++*((++j+j++)*j--); //j=j+1=6 i=j*((j+j)*j) =432 j=j+1 =7 j=j+1=8 j=j-1=7
cout<<i<<endl;
cout<<j<<endl; */
return 0;
} | [
"1072340870@qq.com"
] | 1072340870@qq.com |
dee9c53efbeacdc4d3d2b5c2e359fc95770eb3a3 | 8992bfd3ae4d5427d5e5ff8343056f5cc8c87d3e | /cpuv2/fpu_4clk/test/src/common.cpp | aa9db449865a27f574255561c13238e177d5577b | [] | no_license | ksk9687/cpuex-cpu | ec28e796d1c7b524b45d581018af839c74a4cf69 | 17a2d408e4663aa71f632bdbd5d646f34a9a5c42 | refs/heads/master | 2021-01-18T13:49:39.038999 | 2012-09-09T18:29:39 | 2012-09-09T18:29:39 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,098 | cpp | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include "common.hpp"
int is_normalized(float f) {
myfloat mf;
mf.f = f;
return 1 <= mf.e && mf.e <= 254;
}
float make_float(uint s, uint e, uint m) {
uint t = (s << 31) | (e << 23) | m;
return *(float*)(void*)&t;
}
float make_random_float() {
return make_float(rand() % 2, 1 + rand() % 254, rand() & ((1 << 23) - 1));
}
// リトルエンディアン専用
void print_bits(char *p, int b) {
p += b - 1;
for (int i = 0; i < b; i++) {
for (int j = 7; j >= 0; j--) {
printf("%d", ((*p) >> j) & 1);
}
p--;
}
}
void print_float(float f) {
print_bits((char*)&f, 4);
printf(" : %e", f);
myfloat mf;
mf.f = f;
printf(" (%d %d %d)\n", mf.s, mf.e, mf.m);
}
void check(float a, float b, double err) {
if (fabs(a - b) > err
&& fabs(a - b) > err * fmax(fabs(a), fabs(b))) {
fprintf(stderr, "check failed: %.8e %.8e (%.3e / %.3e)\n",
a, b, fabs(a - b), fabs(a - b) / fmax(fabs(a), fabs(b)));
exit(EXIT_FAILURE);
}
}
| [
"none@none"
] | none@none |
178af19645ba47a47979d9d65eea02457b3c02f1 | ed0603e9cfcd498fad620782dde0aca6200c7477 | /fpp/fppmodels/201208431.1/SDSS_r.cc | 82eec7dcbd333f7f91707d20464dc1d7c75ea71e | [] | no_license | benmontet/k2-characterization | 79f65c54e17024b4d270dd5c9aa03d0a0760c4f6 | 3f78801dfbfe4346ff4c7f5e2939b7d947751053 | refs/heads/master | 2021-01-01T05:30:47.939190 | 2015-06-22T21:01:19 | 2015-06-22T21:01:19 | 31,000,961 | 0 | 0 | null | 2015-03-05T21:00:11 | 2015-02-19T04:17:59 | TeX | UTF-8 | C++ | false | false | 250 | cc | 2.799999999999999822e+00 7.909000000000000696e+00
4.000000000000000000e+00 7.909000000000000696e+00
8.000000000000000000e+00 7.909000000000000696e+00
1.200000000000000000e+01 7.909000000000000696e+00
2.500000000000000000e+01 7.909000000000000696e+00
| [
"tim.morton@gmail.com"
] | tim.morton@gmail.com |
61ea8da7c7af138425a0579a8590bbe35d6d8128 | c0efd4ec01395b6a1404357f0d9a365294206012 | /Libraries/LibBareMetal/IO.h | 860753e155bdadc314beefd4be70ed1deaec781b | [
"BSD-2-Clause"
] | permissive | Mindavi/serenity | b546484539c4b12878cb5ce65c5c409715c5bc74 | e9c65b6566d3cc7fc6f8056cea5619d3ae87b340 | refs/heads/master | 2022-12-12T04:40:13.846020 | 2020-04-13T15:20:47 | 2020-04-13T15:38:27 | 255,405,818 | 0 | 0 | BSD-2-Clause | 2020-04-13T18:07:49 | 2020-04-13T18:07:48 | null | UTF-8 | C++ | false | false | 5,129 | h | /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/Assertions.h>
#include <AK/LogStream.h>
#include <AK/String.h>
#include <AK/Types.h>
#if defined(KERNEL)
# include <Kernel/Arch/i386/CPU.h>
#endif
namespace IO {
inline u8 in8(u16 port)
{
u8 value;
asm volatile("inb %1, %0"
: "=a"(value)
: "Nd"(port));
return value;
}
inline u16 in16(u16 port)
{
u16 value;
asm volatile("inw %1, %0"
: "=a"(value)
: "Nd"(port));
return value;
}
inline u32 in32(u16 port)
{
u32 value;
asm volatile("inl %1, %0"
: "=a"(value)
: "Nd"(port));
return value;
}
inline void repeated_in16(u16 port, u8* buffer, int buffer_size)
{
asm volatile("rep insw"
: "+D"(buffer), "+c"(buffer_size)
: "d"(port)
: "memory");
}
inline void out8(u16 port, u8 value)
{
asm volatile("outb %0, %1" ::"a"(value), "Nd"(port));
}
inline void out16(u16 port, u16 value)
{
asm volatile("outw %0, %1" ::"a"(value), "Nd"(port));
}
inline void out32(u16 port, u32 value)
{
asm volatile("outl %0, %1" ::"a"(value), "Nd"(port));
}
inline void repeated_out16(u16 port, const u8* data, int data_size)
{
asm volatile("rep outsw"
: "+S"(data), "+c"(data_size)
: "d"(port));
}
inline void delay()
{
// ~3 microsecs
for (auto i = 0; i < 32; i++) {
IO::in8(0x80);
}
}
}
class IOAddress {
public:
IOAddress() {}
explicit IOAddress(u16 address)
: m_address(address)
{
}
IOAddress offset(u16 o) const { return IOAddress(m_address + o); }
u16 get() const { return m_address; }
void set(u16 address) { m_address = address; }
void mask(u16 m) { m_address &= m; }
template<typename T>
[[gnu::always_inline]] inline T in()
{
if constexpr (sizeof(T) == 4)
return IO::in32(get());
if constexpr (sizeof(T) == 2)
return IO::in16(get());
if constexpr (sizeof(T) == 1)
return IO::in8(get());
ASSERT_NOT_REACHED();
}
template<typename T>
[[gnu::always_inline]] inline void out(T value)
{
if constexpr (sizeof(T) == 4) {
IO::out32(get(), value);
return;
}
if constexpr (sizeof(T) == 2) {
IO::out16(get(), value);
return;
}
if constexpr (sizeof(T) == 1) {
IO::out8(get(), value);
return;
}
ASSERT_NOT_REACHED();
}
inline void out(u32 value, u8 bit_width)
{
if (bit_width == 32) {
IO::out32(get(), value);
return;
}
if (bit_width == 16) {
IO::out16(get(), value);
return;
}
if (bit_width == 8) {
IO::out8(get(), value);
return;
}
ASSERT_NOT_REACHED();
}
bool is_null() const { return m_address == 0; }
bool operator==(const IOAddress& other) const { return m_address == other.m_address; }
bool operator!=(const IOAddress& other) const { return m_address != other.m_address; }
bool operator>(const IOAddress& other) const { return m_address > other.m_address; }
bool operator>=(const IOAddress& other) const { return m_address >= other.m_address; }
bool operator<(const IOAddress& other) const { return m_address < other.m_address; }
bool operator<=(const IOAddress& other) const { return m_address <= other.m_address; }
private:
u16 m_address { 0 };
};
inline const LogStream& operator<<(const LogStream& stream, IOAddress value)
{
return stream << "IO " << String::format("%x", value.get());
}
| [
"kling@serenityos.org"
] | kling@serenityos.org |
0ae8ddf70eeced7b0d3bc7f0ae06288495df0077 | 082d86eb8a25d12c026162c1a7721ad43b0e7bb7 | /include/D435Camera.h | 96033ac88693fa7afb68044f77970de4ed1f491d | [
"Apache-2.0"
] | permissive | YiChenCityU/OpenARK | 07629008cb7ab4114016d57fc5cbae2ddb836290 | a93754d552abbd956a33b977b40575422f44988c | refs/heads/master | 2020-09-30T09:33:10.378740 | 2019-11-26T05:53:07 | 2019-11-26T05:53:07 | 227,260,741 | 1 | 1 | Apache-2.0 | 2019-12-11T02:40:04 | 2019-12-11T02:40:03 | null | UTF-8 | C++ | false | false | 1,876 | h | #pragma once
// OpenCV Libraries
#include "Version.h"
#include <opencv2/core.hpp>
#include <librealsense2/rs.hpp>
// OpenARK Libraries
#include "CameraSetup.h"
namespace ark {
/**
* Class defining the behavior of a generic Intel RealSense Camera using RSSDK2.
* Example on how to read from sensor and visualize its output
* @include SensorIO.cpp
*/
class D435Camera : public CameraSetup
{
public:
/**
* Public constructor initializing the RealSense Camera.
* @param use_rgb_stream if true, uses the RGB stream and disable the IR stream (which is on by default)
* This results in a smaller field of view and has an appreciable performance cost.
*/
explicit D435Camera();
/**
* Destructor for the RealSense Camera.
*/
~D435Camera() override;
/**
* Get the camera's model name.
*/
const std::string getModelName() const override;
/**
* Get image size
*/
cv::Size getImageSize() const;
/**
* Sets the external hardware sync ans starts the camera
*/
void start() override;
/**
* Gets the new frame from the sensor (implements functionality).
* Updates xyzMap and ir_map.
*/
void update(MultiCameraFrame & frame) override;
protected:
/** Converts an D435 raw depth image to an ordered point cloud based on the current camera's intrinsics */
void project(const rs2::frame & depth_frame, cv::Mat & xyz_map);
std::shared_ptr<rs2::pipeline> pipe;
rs2::config config;
rs2::depth_sensor* depth_sensor;
rs2::device device;
rs2_intrinsics depthIntrinsics;
double scale;
int width, height;
bool badInputFlag;
};
}
| [
"joemenke@berkeley.edu"
] | joemenke@berkeley.edu |
d94229e72255b96e109bc18c5738a43d48f4d7d0 | 2454b2f778ae2e5116e835c84bf5cfc0d293e62c | /Practica7/15-Texturizado/src/Cylinder.cpp | 0ebc74446666e860319db0dfadacd460cb5fa555 | [] | no_license | jppatricio/Practica6LabCompu | 1e06964d1df52a7ce2117023ac796b9353c0d062 | 611fdb39b7c0dfc59aa1d91f970c12e066e5a54f | refs/heads/master | 2020-04-29T05:15:34.577480 | 2019-03-23T06:46:09 | 2019-03-23T06:46:09 | 175,876,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,585 | cpp | #include "Headers/Cylinder.h"
Cylinder::Cylinder(int slices, int stacks, float topRadius, float bottomRadius, float height) {
float stackHeight = height / stacks;
float radiusStep = (topRadius - bottomRadius) / stacks;
int count = 0;
vertexArray.resize((slices + 1) * (stacks + 1) + 2 * (slices + 1) + 2);
index.resize(slices * stacks * 2 * 3 + 2 * slices * 3);
for (int i = 0; i <= stacks; i++) {
float y = -0.5f * height + i * stackHeight;
float r = bottomRadius + i * radiusStep;
float dTheta = float(2.0f * M_PI) / slices;
for (int j = 0; j <= slices; j++) {
float c = cos(j * dTheta);
float s = sin(j * dTheta);
vertexArray[count++] = Vertex(glm::vec3(r * c, y, r * s), glm::vec3(), glm::vec2(), glm::vec3(r * c, y, r * s));
}
}
//top cap
float y = 0.5f * height;
float dTheta = float(2.0f * M_PI) / slices;
for (int i = slices; i >= 0; i--) {
float x = topRadius * cos(i * dTheta);
float z = topRadius * sin(i * dTheta);
vertexArray[count++] = Vertex(glm::vec3(x, y, z), glm::vec3(), glm::vec2(), glm::vec3(0, 0, z));
}
vertexArray[count++] = Vertex(glm::vec3(0, y, 0), glm::vec3(), glm::vec2(), glm::vec3(0, y, 0));
//bottom cap
y = -y;
for (int i = 0; i <= slices; i++) {
float x = bottomRadius * cos(i * dTheta);
float z = bottomRadius * sin(i * dTheta);
vertexArray[count++] = Vertex(glm::vec3(x, y, z), glm::vec3(), glm::vec2(), glm::vec3(0, 0, z));
}
vertexArray[count++] = Vertex(glm::vec3(0, y, 0), glm::vec3(), glm::vec2(), glm::vec3(0, y, 0));
//fill indices array
int ringVertexCount = slices + 1;
int id = 0;
for (int i = 0; i < stacks; i++) {
for (int j = 0; j < slices; j++) {
index[id++] = (i * ringVertexCount + j);
index[id++] = ((i + 1) * ringVertexCount + j);
index[id++] = ((i + 1) * ringVertexCount + j + 1);
index[id++] = (i * ringVertexCount + j);
index[id++] = ((i + 1) * ringVertexCount + j + 1);
index[id++] = (i * ringVertexCount + j + 1);
}
}
//top cap
int baseIndex = (slices + 1) * (stacks + 1);
int centerIndex = baseIndex + (slices + 1);
for (int i = 0; i < slices; i++) {
index[id++] = centerIndex;
index[id++] = baseIndex + i;
index[id++] = baseIndex + i + 1;
}
//bottom cap
baseIndex = centerIndex + 1;
centerIndex = baseIndex + (slices + 1);
for (int i = 0; i < slices; i++) {
index[id++] = centerIndex;
index[id++] = baseIndex + i;
index[id++] = baseIndex + i + 1;
}
typeModel = TypeModel::CYLINDER;
}
Cylinder::~Cylinder() {
}
bool Cylinder::rayPicking(glm::vec3 init, glm::vec3 end, glm::vec3 &intersection) {
return false;
} | [
"reymar_44@hotmail.com"
] | reymar_44@hotmail.com |
c90502cb913f697fdca6a727f56cd0ad53c8de57 | 13330a7cfa45c3c3d32d2e116a32d602a519c3ea | /Mario_Last/Level1.h | 3d382d6cb7e6f40609f8767e73507cc1e855b66e | [] | no_license | omargamal253/Super-Mario-bros | 986737d5e4a8eba99212d5d5f430a71ff8926c59 | 796a508b60eb97ef2b64a925b757b589be4283e4 | refs/heads/master | 2023-02-18T18:51:23.534422 | 2021-01-21T03:51:04 | 2021-01-21T03:51:04 | 272,838,956 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,719 | h | #ifndef LEVEL1_H
#define LEVEL1_H
#include <SFML/Graphics.hpp>
#include <iostream>
#include<string>
#include<SFML/Audio.hpp>
#include<SFML/System/Time.hpp>
using namespace std;
class Level1
{
public:
int a = 0;
bool b = 0;
int x = 0, y = 0;
const double gravity = 0.4;
int groundHeight = 500;
float movespeed = 6, jumpSpeed = 9.f;
bool marioDie = 0;
sf::SoundBuffer buffer_jump;
sf::Sound sound_jump;
sf::RenderWindow window;
sf::Texture texture;
sf::Texture texturesun;
sf::Texture textureGround;
sf::Texture textureHigh_Ground;
sf::Texture mario_die_texture;
sf::Texture gameOver_texture;
sf::Texture groundheigh;
sf::Texture gabal;
sf::Texture elnahaya;
sf::Texture box;
sf::Texture balata;
sf::View view;
//sf::Sprite gabal;
sf::Sprite mario;
sf::Sprite sun;
sf::Sprite gameOver_sprite;
sf::Sprite tile;
sf::Sprite tile2;
sf::Sprite map1[4][20];
int countL = -1, countR = -1;
sf::Vector2f velocity;
sf::Text text_score;
sf::Text text_score2;
sf::Font font;
int coin_score = 0;
int ghoust_score = 0;
string geek;
string geek2;
sf::Texture coin_texture2;
sf::Sprite coin_sprite2;
sf::Texture mashrom_texture2;
sf::Sprite mashrom_sprite2;
sf::Texture ghoust_texture2;
sf::Sprite ghoust_sprite2;
sf::Time t1;
sf::Clock clock;
sf::Time elapsed1;
sf::Text texttimer;
sf::Text timer;
string geek3;
sf::Text textTime;
sf::Time time;
public:
void loadFiles();
void drawing();
void loadMap();
bool ghoust_collision_mario();
bool collision(int order);
bool mario_died();
void loadTimer();
void load_Score(int, int);
Level1();
/** Default destructor */
virtual ~Level1();
protected:
private:
};
#endif // LEVEL1_H
| [
"omargamal253@gmail.com"
] | omargamal253@gmail.com |
d349adfbe2f26a2ef8de35e2c4d286fe0b1de63f | 796301ee9758e21ed85577c375885d5168780fbc | /First_assignment_Arduino/12_ultrasonicDistanceSensor.ino | 02bd26a2f9d6843d250e81e2dbe5f223e74b1b47 | [] | no_license | gitLabor8/NDL-TeamWintendo | ec20c49f14cbc26b509c9a8a3be899df251dafe0 | edc6508aa30e2902749bcbc02887135258a70353 | refs/heads/master | 2018-09-06T13:56:29.969285 | 2018-07-18T09:41:19 | 2018-07-18T09:41:19 | 120,478,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | ino | /*
* p12-13
* Ultrasonic sensor
* Create weird bliep-blops
*
*/
#define trigPin A2
#define echoPin A1
void setup() {
Serial.begin(9600);
// Defining names for the pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Sending pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure echo time duration
int duration = pulseIn(echoPin, HIGH);
// Print results
Serial.print(duration);
Serial.println(" ms");
Serial.print((duration / 2) / 29);
Serial.println(" cm");
delay(1000);
}
| [
"frank.gerlings@student.ru.nl"
] | frank.gerlings@student.ru.nl |
faebf50065d85f1fc4e1786579a5071e1844a217 | 1aa36cad409fcc3651a28b14737ab97c2cbfbd81 | /UESTC 2019 SummerTraining/Day09-[nowcoder01]/H/sol.cpp | 0cb503740ca9e85b0e804aa57494c49bd37eee6d | [] | no_license | Pengjq0000000/ICPC | 10f1afc8fbe69c27f6dcb1848e52070ca50e5110 | 035923da45082a3253c80288b37cca9d802bbbc8 | refs/heads/master | 2021-07-20T11:18:10.524316 | 2020-05-06T11:17:07 | 2020-05-06T11:17:07 | 154,973,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,093 | cpp | #include<bits/stdc++.h>
#define LL long long
#define MEM(x,y) memset(x,y,sizeof(x))
#define MOD(x) ((x)%mod)
#define mod 1000000007
#define pb push_back
#define STREAM_FAST ios::sync_with_stdio(false)
using namespace std;
const int N_bs = 64;
struct LinearBase
{
LL bs[N_bs + 1];
LL num[N_bs + 1];
int tot = 0;
void init() {tot = 0; MEM(bs, 0);}
void add(LL x) {num[tot++] = x;}
bool insert(LL x)
{
LL tmp = x;
for (int i = N_bs; i >= 0; i--)
{
if ((x >> i) & 1)
if (!bs[i]) {bs[i] = x; add(tmp); return 1;}
else x ^= bs[i];
}
return 0;
}
inline void build() {for (int i = 0; i < tot; i++) insert(num[i]);}
inline bool check(LL x)
{
for (int i = N_bs; i >= 0; i--)
{
if ((x >> i) & 1)
if (!bs[i]) return false;
else x ^= bs[i];
}
return true;
}
inline LL getmax(LL x)
{
LL res = 0;
for (int i = N_bs; i >= 0; i--)
if (bs[i]) res = max(res, (res ^ bs[i]));
return res;
}
}lbs, A, B;
LL ksm(LL a, LL b)
{
LL res = 1, base = a;
while (b) {if (b & 1) res = MOD(res * base); base = MOD(base * base); b /= 2;}
return res;
}
vector<LL>v;
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
lbs.init(); A.init(); B.init();
int cnt = 0;
for (int i = 1; i <= n; i++)
{
LL x; scanf("%lld", &x);
if (!lbs.insert(x)) A.insert(x), cnt++;
}
if (cnt == 0) {puts("0"); continue;}
LL ans = MOD((LL)cnt * ksm(2, cnt - 1));
//for (int i = 0; i < lbs.tot; i++) printf("%lld ", lbs.num[i]); puts("");
for (int i = 0; i < lbs.tot; i++)
{
B = A;
for (int j = 0; j < lbs.tot; j++)
{
if (i == j) continue;
B.insert(lbs.num[j]);
}
if (B.check(lbs.num[i])) ans = MOD(ans + ksm(2, n - 1 - B.tot));
}
printf("%lld\n", ans);
}
return 0;
}
| [
"2324532557@qq.com"
] | 2324532557@qq.com |
52006dbf2fdd7697cb1a9c82edbad29545116950 | 005b7707bba78f73ddc1d3ea4d5647c02c66fdb7 | /p209_min_size_subarray_sum/min_size_subarray_sum.cc | c29fe68c09f7110c9452be4583ac4dbd3b061536 | [] | no_license | pkuwangh/leetcode | 3942908bd162b159fcb489420a106b8bbe1559cf | 36e52ef7b8bf61170663937ac723c12cfec90f26 | refs/heads/master | 2020-09-16T15:04:50.167112 | 2019-10-05T16:55:55 | 2019-10-05T16:55:55 | 67,662,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,318 | cc | /* Given an array of n positive integers and a positive integer s,
* find the minimal length of a contiguous subarray of which the sum ≥ s.
* If there isn't one, return 0 instead.
* For example, given the array [2,3,1,2,4,3] and s = 7,
* the subarray [4,3] has the minimal length under the problem constraint.
*/
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int size = nums.size();
if (size == 0) return 0;
int min_len = 0;
int left = 0;
int sum = 0;
for (int right = 0; right < size; ++right) {
sum += nums[right];
// move left pointer towards right
while (sum - nums[left] >= s) {
sum -= nums[left];
++ left;
}
// check if sum meets constraint
if (sum >= s) {
int len = right - left + 1;
if (min_len == 0 || min_len > len) {
min_len = len;
}
}
}
return min_len;
}
};
int main() {
Solution obj;
auto run = [&obj](int s, vector<int> nums)->void {
cout << obj.minSubArrayLen(s, nums) << endl;
};
run(7, {2, 3, 1, 2, 4, 3});
return 0;
}
| [
"pkuwangh@gmail.com"
] | pkuwangh@gmail.com |
db3289ab0a47b5a8b59736c53303a2fcc19b0744 | 4947a7a26a8c2df5932b3e33385b004474aba80e | /C1.cpp | becf24b3ae0f4c7097b9ccb8bdefc5b4c2793825 | [] | no_license | kuron99/mixingRTTI | 76018462f4716498a998ddf51ec0560d9601303f | 3df2908225a64c566ebad0b5eb1a5dbf4b9e48b5 | refs/heads/master | 2020-03-24T20:10:09.256358 | 2018-07-31T05:18:36 | 2018-07-31T05:18:36 | 142,962,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41 | cpp | #include "C1.h"
void C1::anchor() {
}
| [
"kuro009900@gmail.com"
] | kuro009900@gmail.com |
4ea54623d28677a8e0b6afe638f09604d4ff2346 | d18c4464af78f715ffc5d5addb1e005d018ca68d | /LSU oj/字符查找.cpp | 9ecec24f2f656050aff6f545d4ad19f6dcb7132c | [] | no_license | xiaoshidefeng/ACM | 508f71ba7da6e603e8c6fbbccfa9d68d497f15a9 | b646ae0a624fc5db2d7ac46b7baef9a2779fef7b | refs/heads/master | 2021-01-19T22:05:47.518409 | 2018-05-14T14:09:51 | 2018-05-14T14:09:51 | 82,564,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char a[1000];
int len1,i,sum=0;
char c;
gets(a);
len1=strlen(a);
scanf("%c",&c);
for(i=0;i<len1;i++)
{
if(a[i]==c)
sum++;
}
printf("%d\n",sum);
} | [
"1330661071@qq.com"
] | 1330661071@qq.com |
76226b94827c5479f8ad7fdd293ee8125f0925d6 | dceff34eaceed8f7a52ea908958645104167e3e1 | /src/backup-redundant-features/combined-extern/model/HyperParams.h | 6c5a65c1745cea38399988ffcc8d0c85feda3e02 | [] | no_license | zhangmeishan/NNRelationExtraction | a100acc0f6c9d5fd0db7686249b647a21ae908b2 | 8efd8173b2503bc75274b2238b2392476a86a8e9 | refs/heads/master | 2021-01-11T19:48:25.552293 | 2017-07-30T13:23:56 | 2017-07-30T13:23:56 | 79,401,948 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,767 | h | #ifndef SRC_HyperParams_H_
#define SRC_HyperParams_H_
#include "N3L.h"
#include "Options.h"
#include <unordered_set>
struct HyperParams {
Alphabet ner_labels;
Alphabet rel_labels;
unordered_map<string, unordered_set<int> > rel_dir;
int ner_noprefix_num;
unordered_map<string, int> word_stat;
int maxlength;
int action_num;
dtype delta;
int beam;
dtype nnRegular; // for optimization
dtype adaAlpha; // for optimization
dtype adaEps; // for optimization
dtype dropProb;
int char_dim;
int word_dim;
int word_ext_dim;
int tag_dim;
int action_dim;
int ner_dim;
int char_context;
int char_represent_dim;
int char_hidden_dim;
int word_context;
int word_represent_dim;
int word_hidden_dim;
int action_hidden_dim;
int word_lstm_dim;
int action_lstm_dim;
int ext_lstm_dim;
int ner_state_concat_dim;
int rel_state_concat_dim;
int state_hidden_dim;
public:
HyperParams() {
beam = 1; // TODO:
maxlength = max_step_size;
bAssigned = false;
}
void setRequared(Options &opt) {
//please specify dictionary outside
//please sepcify char_dim, word_dim and action_dim outside.
beam = opt.beam;
delta = opt.delta;
bAssigned = true;
ner_noprefix_num = (ner_labels.size() - 1) / 4;
nnRegular = opt.regParameter;
adaAlpha = opt.adaAlpha;
adaEps = opt.adaEps;
dropProb = opt.dropProb;
char_dim = opt.charEmbSize;
word_dim = opt.wordEmbSize;
word_ext_dim = opt.wordExtEmbSize;
tag_dim = opt.tagEmbSize;
action_dim = opt.actionEmbSize;
ner_dim = opt.nerEmbSize;
char_context = opt.charContext;
char_represent_dim = (2 * char_context + 1) * char_dim;
char_hidden_dim = opt.charHiddenSize;
word_context = opt.wordContext;
word_represent_dim = word_dim + word_ext_dim + tag_dim + char_hidden_dim;
word_hidden_dim = opt.wordHiddenSize;
word_lstm_dim = opt.wordRNNHiddenSize;
ext_lstm_dim = 300; //fixed
action_hidden_dim = opt.actionHiddenSize;
action_lstm_dim = opt.actionRNNHiddenSize;
ner_state_concat_dim = action_lstm_dim + 2 * (2 * word_context + 1) * word_hidden_dim + 4 * word_lstm_dim;
//rel_state_concat_dim = 10 * tree_lstm_dim;
rel_state_concat_dim = 20 * word_lstm_dim + 2 * ner_dim;
state_hidden_dim = opt.state_hidden_dim; //TODO:
}
void clear() {
bAssigned = false;
}
bool bValid() {
return bAssigned;
}
public:
void print() {
}
private:
bool bAssigned;
};
#endif /* SRC_HyperParams_H_ */
| [
"mason.zms@gmail.com"
] | mason.zms@gmail.com |
8618fdcc80946cc52bdaa3414315c5bf757aa386 | e3c126ea17fee019a067ccaa8df32b7a847b9ee4 | /backend/deployments/deployment_wasm/WasmSyncDeployment.cpp | eca6bf75323b72eb05810358c1735cd1aad5355f | [] | no_license | faunX/ogame-2 | 6ba5550ea6c98467412e8305780546108e75d882 | eb175bd7d16f83e670f5cbc5a9375cd5fcd5b506 | refs/heads/master | 2023-08-21T19:50:45.880660 | 2021-04-06T08:31:19 | 2021-04-06T08:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | cpp | #include "RnDTime.hpp"
#include "Logger.hpp"
#include "StorageDbFactory.hpp"
#include <iostream>
#include "Configuration.hpp"
#include "Time.hpp"
#include "JsonSerializer.hpp"
#include "SingleInstance.hpp"
#include <emscripten.h>
#include <emscripten/bind.h>
#include "Logger.hpp"
#include "RndRequest.hpp"
#include "LoadConfiguration.hpp"
struct Processor
{
sqlitedb::StorageDbFactory dbFactory{"/sqlite/testtest.db"};
Configuration configuration = loadConfiguration("/Configuration.json");
RnDTime rndTime{};
Time time;
ITime& ttime = configuration.realTime ? (ITime&)time : (ITime&)rndTime;
JsonSerializer serializer{};
int dbCheck = (dbFactory.cleanIfNeeded(), 0);
std::shared_ptr<IStorageDb> db = dbFactory.create();
Service service{*db, ttime, configuration};
RnDService rndService{ttime, *db};
SingleInstance instanceee{serializer, configuration, ttime, dbFactory};
int processRequest(int rawRequest)
{
std::string request = {reinterpret_cast<const char*>(rawRequest)};
free(reinterpret_cast<void*>(rawRequest));
auto vecRet = instanceee.process({request.begin(), request.end()});
std::string strRet{vecRet.begin(), vecRet.end()};
void* rawRet = malloc(strRet.size() + 1);
strcpy(reinterpret_cast<char*>(rawRet), strRet.data());
return reinterpret_cast<int>(rawRet);
}
};
std::unique_ptr<Processor> processor;
using namespace emscripten;
EMSCRIPTEN_BINDINGS(elo){
function("init", +[](void)->void{processor = std::make_unique<Processor>();});
function("processRequest", +[](int ptr)->int{return processor->processRequest(ptr);});
function("forwardTime", +[](int seconds){processor->ttime.shiftTimeBy(Duration{seconds});});
//function("clearDb", +[](){processor->instanceee.storageDb->clearAndRecreate();});
function("clearDb", +[](){processor->rndService.handleRequest(RndRequest{.request = ClearDatabaseRequest{}});
EM_ASM({
FS.syncfs(false, function(err){
console.log(err);
window.location.reload(true);
});
});
/*EM_ASM({
window.indexedDB.deleteDatabase("/sqlite");
window.location.reload(true);
});*/
//EM_ASM({})
});
}
int main()
{
EM_ASM({
Module.FileSystem = FS;
FS.mkdir("/sqlite");
FS.mount(IDBFS, {}, '/sqlite');
FS.syncfs(true, function(err){
console.log(err);
Module.init();
});
});
emscripten_set_main_loop(+[]{}, 0, 0);
}
/*EMSCRIPTEN_BINDINGS(elo){
class_<Processor>("Processor")
.constructor<>()
.function("processRequest", &Processor::processRequest);
}
const auto test2 = [](){
EM_ASM({console.log("another global initialized")});
return 5;
}();
struct TestGlobal
{
~TestGlobal()
{
EM_ASM({console.log("global dead")});
}
} globalDead;*/
/*int main()
{
//logger.debug("no elo");
return 0;
}*/
/*int main()
{
EM_ASM({console.log("no elo")});
emscripten_exit_with_live_runtime();
}*/ | [
"ujemnypozyton@gmail.com"
] | ujemnypozyton@gmail.com |
eefd9a9e1e1e51767a230ae0093afcbef7e1a386 | e0ad93c6ccbd1aa645bf42af93e23dc8ed8c9b91 | /mt/evaluation/busy-wait.cc | 7637074f3f622534320f93fe55b12e6562cd1f05 | [] | no_license | minuta/grail | 2ff524f084f6dde49f7ae62a095efd1d9b39dbdc | 9cd2b51dfc8e68791e7e0cceb2c96b243a9d5cc2 | refs/heads/master | 2020-04-24T21:28:37.089044 | 2019-03-28T08:33:46 | 2019-03-28T08:33:46 | 172,279,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,434 | cc | #include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
volatile int i = 0; /* i is global, so it is visible to all functions.
It's also marked volatile, because it
may change in a way which is not predictable by the compiler,
here from a different thread. Thus preventing the compiler from
caching its value.*/
/* f1 uses a spinlock to wait for i to change from 0. */
static void *f1(void *p)
{
printf("Thread 1 : has started...\n");
while (i==0) {
/* do nothing - just keep checking over and over */
}
printf("Thread 1 : Busy-waiting loop is over, because condition is now true...\n");
return NULL;
}
static void *f2(void *p)
{
printf("Thread 2 : has started...\n");
sleep(10); /* sleep for 10 seconds */
printf("Thread 2 : has changed condition for the Thread 1 to true\n");
i = 1;
return NULL;
}
int main()
{
int rc;
pthread_t t1, t2;
rc = pthread_create(&t1, NULL, f1, NULL);
if (rc != 0) {
fprintf(stderr,"pthread f1 failed\n");
return EXIT_FAILURE;
}
rc = pthread_create(&t2, NULL, f2, NULL);
if (rc != 0) {
fprintf(stderr,"pthread f2 failed\n");
return EXIT_FAILURE;
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
puts("All pthreads have finished.\n");
return 0;
}
| [
"gammamustang@gmail.com"
] | gammamustang@gmail.com |
678e63899366e237ed7f8b5001d0412f31fd0f92 | 0fd932b31feb0a66fdafa5315bd0ca15c02206c1 | /mainwindow.h | 9c00ae9af05ec092d60bb3e80dd2b7f558ec09c0 | [] | no_license | Guan912/Qtface | cd24d6c3974b91f8f33a4e68ef9490e832c10426 | ac367d5271a89f03687a5e6aa46a3111457f35ba | refs/heads/master | 2020-03-26T05:12:04.093412 | 2018-08-13T07:26:47 | 2018-08-13T07:26:47 | 144,543,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "videowidget.h"
#include <QDir>
#include <QFileDialog>
#include <Python.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_toolButton_clicked();
void on_pushButton_clicked();
void reshow(QString);
signals:
void sendurl(QString);
private:
Ui::MainWindow *ui;
VideoWidget *vw;
};
#endif // MAINWINDOW_H
| [
"guanyan912@163.com"
] | guanyan912@163.com |
ec34658a5f0b0690b815a3af0cbc4cd5c21a3520 | 5eb44c593e1528fe5b99b49033d931685a7034e3 | /Dependencies/Theron/Include/External/boost/atomic/detail/gcc-armv6+.hpp | dcccd8b6cd04b9b127b63ad606bed177c23344f6 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | zh423328/NFServer | 456135359fdc79ee028fac055a371e497c4e036a | 2b94df566a2552366a81bd4c48d6552306b07fc3 | refs/heads/master | 2021-01-17T17:25:17.105508 | 2016-06-25T06:44:09 | 2016-06-25T06:44:09 | 61,927,159 | 2 | 1 | null | 2016-06-25T06:44:10 | 2016-06-25T04:37:53 | C++ | UTF-8 | C++ | false | false | 6,518 | hpp | #ifndef BOOST_DETAIL_ATOMIC_GCC_ARMV6P_HPP
#define BOOST_DETAIL_ATOMIC_GCC_ARMV6P_HPP
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Copyright (c) 2009 Helge Bahmann
// Copyright (c) 2009 Phil Endecott
// ARM Code by Phil Endecott, based on other architectures.
// From the ARM Architecture Reference Manual for architecture v6:
//
// LDREX{<cond>} <Rd>, [<Rn>]
// <Rd> Specifies the destination register for the memory word addressed by <Rd>
// <Rn> Specifies the register containing the address.
//
// STREX{<cond>} <Rd>, <Rm>, [<Rn>]
// <Rd> Specifies the destination register for the returned status value.
// 0 if the operation updates memory
// 1 if the operation fails to update memory
// <Rm> Specifies the register containing the word to be stored to memory.
// <Rn> Specifies the register containing the address.
// Rd must not be the same register as Rm or Rn.
//
// ARM v7 is like ARM v6 plus:
// There are half-word and byte versions of the LDREX and STREX instructions,
// LDREXH, LDREXB, STREXH and STREXB.
// There are also double-word versions, LDREXD and STREXD.
// (Actually it looks like these are available from version 6k onwards.)
// FIXME these are not yet used; should be mostly a matter of copy-and-paste.
// I think you can supply an immediate offset to the address.
//
// A memory barrier is effected using a "co-processor 15" instruction,
// though a separate assembler mnemonic is available for it in v7.
#define BOOST_ATOMIC_CHAR_LOCK_FREE 2
#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 2
#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 2
#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 2
#define BOOST_ATOMIC_SHORT_LOCK_FREE 2
#define BOOST_ATOMIC_INT_LOCK_FREE 2
#define BOOST_ATOMIC_LONG_LOCK_FREE 2
#define BOOST_ATOMIC_LLONG_LOCK_FREE 0
#define BOOST_ATOMIC_ADDRESS_LOCK_FREE 2
#define BOOST_ATOMIC_BOOL_LOCK_FREE 2
namespace boost {
namespace detail {
namespace atomic {
// "Thumb 1" is a subset of the ARM instruction set that uses a 16-bit encoding. It
// doesn't include all instructions and in particular it doesn't include the co-processor
// instruction used for the memory barrier or the load-locked/store-conditional
// instructions. So, if we're compiling in "Thumb 1" mode, we need to wrap all of our
// asm blocks with code to temporarily change to ARM mode.
//
// You can only change between ARM and Thumb modes when branching using the bx instruction.
// bx takes an address specified in a register. The least significant bit of the address
// indicates the mode, so 1 is added to indicate that the destination code is Thumb.
// A temporary register is needed for the address and is passed as an argument to these
// macros. It must be one of the "low" registers accessible to Thumb code, specified
// usng the "l" attribute in the asm statement.
//
// Architecture v7 introduces "Thumb 2", which does include (almost?) all of the ARM
// instruction set. So in v7 we don't need to change to ARM mode; we can write "universal
// assembler" which will assemble to Thumb 2 or ARM code as appropriate. The only thing
// we need to do to make this "universal" assembler mode work is to insert "IT" instructions
// to annotate the conditional instructions. These are ignored in other modes (e.g. v6),
// so they can always be present.
#if defined(__thumb__) && !defined(__ARM_ARCH_7A__)
// FIXME also other v7 variants.
#define BOOST_ATOMIC_ARM_ASM_START(TMPREG) "adr " #TMPREG ", 1f\n" "bx " #TMPREG "\n" ".arm\n" ".align 4\n" "1: "
#define BOOST_ATOMIC_ARM_ASM_END(TMPREG) "adr " #TMPREG ", 1f + 1\n" "bx " #TMPREG "\n" ".thumb\n" ".align 2\n" "1: "
#else
// The tmpreg is wasted in this case, which is non-optimal.
#define BOOST_ATOMIC_ARM_ASM_START(TMPREG)
#define BOOST_ATOMIC_ARM_ASM_END(TMPREG)
#endif
#if defined(__ARM_ARCH_7A__)
// FIXME ditto.
#define BOOST_ATOMIC_ARM_DMB "dmb\n"
#else
#define BOOST_ATOMIC_ARM_DMB "mcr\tp15, 0, r0, c7, c10, 5\n"
#endif
static inline void
arm_barrier(void)
{
int brtmp;
__asm__ __volatile__ (
BOOST_ATOMIC_ARM_ASM_START(%0)
BOOST_ATOMIC_ARM_DMB
BOOST_ATOMIC_ARM_ASM_END(%0)
: "=&l" (brtmp) :: "memory"
);
}
static inline void
platform_fence_before(memory_order order)
{
switch(order) {
case memory_order_release:
case memory_order_acq_rel:
case memory_order_seq_cst:
arm_barrier();
case memory_order_consume:
default:;
}
}
static inline void
platform_fence_after(memory_order order)
{
switch(order) {
case memory_order_acquire:
case memory_order_acq_rel:
case memory_order_seq_cst:
arm_barrier();
default:;
}
}
static inline void
platform_fence_before_store(memory_order order)
{
platform_fence_before(order);
}
static inline void
platform_fence_after_store(memory_order order)
{
if (order == memory_order_seq_cst)
arm_barrier();
}
static inline void
platform_fence_after_load(memory_order order)
{
platform_fence_after(order);
}
template<typename T>
bool
platform_cmpxchg32(T & expected, T desired, volatile T * ptr)
{
int success;
int tmp;
__asm__ (
BOOST_ATOMIC_ARM_ASM_START(%2)
"mov %1, #0\n" // success = 0
"ldrex %0, %3\n" // expected' = *(&i)
"teq %0, %4\n" // flags = expected'==expected
"ittt eq\n"
"strexeq %2, %5, %3\n" // if (flags.equal) *(&i) = desired, tmp = !OK
"teqeq %2, #0\n" // if (flags.equal) flags = tmp==0
"moveq %1, #1\n" // if (flags.equal) success = 1
BOOST_ATOMIC_ARM_ASM_END(%2)
: "=&r" (expected), // %0
"=&r" (success), // %1
"=&l" (tmp), // %2
"+Q" (*ptr) // %3
: "r" (expected), // %4
"r" (desired) // %5
: "cc"
);
return success;
}
}
}
#define BOOST_ATOMIC_THREAD_FENCE 2
static inline void
atomic_thread_fence(memory_order order)
{
switch(order) {
case memory_order_acquire:
case memory_order_release:
case memory_order_acq_rel:
case memory_order_seq_cst:
detail::atomic::arm_barrier();
default:;
}
}
#define BOOST_ATOMIC_SIGNAL_FENCE 2
static inline void
atomic_signal_fence(memory_order)
{
__asm__ __volatile__ ("" ::: "memory");
}
}
#undef BOOST_ATOMIC_ARM_ASM_START
#undef BOOST_ATOMIC_ARM_ASM_END
#include <boost/atomic/detail/cas32weak.hpp>
#endif
| [
"elite_yang@163.com"
] | elite_yang@163.com |
7e7e0e098e7f8b762ae7cc9c0bc61f8e7fff002b | 624cfa42681a7d7369a2a65ac413d41569a25a3b | /Classes/enemy.h | ce408504c610ae00c66a69345884f494e4c54595 | [] | no_license | xinyunyxq/gamefight | bd4d894bb905bcf57d0efffb0d2d0b7d8db2ba33 | 925458cb5f6372f10dc69308ec013478b9883d2d | refs/heads/master | 2021-03-12T23:11:09.106626 | 2014-05-08T07:10:59 | 2014-05-08T07:10:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 732 | h | #ifndef __ENEMY_H
#define __ENEMY_H
#include "cocos2d.h"
#include "cocos-ext.h"
#include "FightSceneGlobal.h"
#include "GameConstants.h"
USING_NS_CC_EXT;
USING_NS_CC;
using namespace ui;
class Enemy
{
CC_SYNTHESIZE(EnemyState,_enemyState,enemyState);
CC_SYNTHESIZE(int,_enemySpeed,enemySpeed);
CC_SYNTHESIZE(bool,_isleft,isleft);
CC_SYNTHESIZE(int,_hpValue,HpValue);
CC_SYNTHESIZE(int,_hpValueMax,HpValueMax);
CC_SYNTHESIZE(int,_atkValue,AtkValue);
CC_SYNTHESIZE_READONLY(LoadingBar*,_hpBar,HpBar);
CC_SYNTHESIZE_READONLY(LoadingBar*,_mpBar,mpBar);
CCDrawNode* front;
public:
Enemy();
~Enemy(void);
void PlayState(EnemyState state);
CCRect getEnemyArea(CCPoint enemyPosition);
bool inAtkRange();
private:
};
#endif | [
"tcsyzxyxq@163.com"
] | tcsyzxyxq@163.com |
de5bd73299f6fd5c7ac0f999cf666e1cd27266a8 | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-awstransfer/include/aws/awstransfer/model/DeleteStepDetails.h | b7e6999fdb4604846d75a5799dcea9eed7b3561e | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 8,026 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/awstransfer/Transfer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Transfer
{
namespace Model
{
/**
* <p>The name of the step, used to identify the delete step.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteStepDetails">AWS
* API Reference</a></p>
*/
class AWS_TRANSFER_API DeleteStepDetails
{
public:
DeleteStepDetails();
DeleteStepDetails(Aws::Utils::Json::JsonView jsonValue);
DeleteStepDetails& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline DeleteStepDetails& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline DeleteStepDetails& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The name of the step, used as an identifier.</p>
*/
inline DeleteStepDetails& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline const Aws::String& GetSourceFileLocation() const{ return m_sourceFileLocation; }
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline bool SourceFileLocationHasBeenSet() const { return m_sourceFileLocationHasBeenSet; }
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline void SetSourceFileLocation(const Aws::String& value) { m_sourceFileLocationHasBeenSet = true; m_sourceFileLocation = value; }
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline void SetSourceFileLocation(Aws::String&& value) { m_sourceFileLocationHasBeenSet = true; m_sourceFileLocation = std::move(value); }
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline void SetSourceFileLocation(const char* value) { m_sourceFileLocationHasBeenSet = true; m_sourceFileLocation.assign(value); }
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline DeleteStepDetails& WithSourceFileLocation(const Aws::String& value) { SetSourceFileLocation(value); return *this;}
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline DeleteStepDetails& WithSourceFileLocation(Aws::String&& value) { SetSourceFileLocation(std::move(value)); return *this;}
/**
* <p>Specifies which file to use as input to the workflow step: either the output
* from the previous step, or the originally uploaded file for the workflow.</p>
* <ul> <li> <p>Enter <code>${previous.file}</code> to use the previous file as the
* input. In this case, this workflow step uses the output file from the previous
* workflow step as input. This is the default value.</p> </li> <li> <p>Enter
* <code>${original.file}</code> to use the originally-uploaded file location as
* input for this step.</p> </li> </ul>
*/
inline DeleteStepDetails& WithSourceFileLocation(const char* value) { SetSourceFileLocation(value); return *this;}
private:
Aws::String m_name;
bool m_nameHasBeenSet;
Aws::String m_sourceFileLocation;
bool m_sourceFileLocationHasBeenSet;
};
} // namespace Model
} // namespace Transfer
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
f6da6e7a6bd462a78da532a9370ab5cc053a5cbb | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /gpdb/src/model/DescribeDBClusterPerformanceResult.cc | 7e78488ee591e8f324ed6ed0f8e192dd102bfe35 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 3,586 | 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/gpdb/model/DescribeDBClusterPerformanceResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Gpdb;
using namespace AlibabaCloud::Gpdb::Model;
DescribeDBClusterPerformanceResult::DescribeDBClusterPerformanceResult() :
ServiceResult()
{}
DescribeDBClusterPerformanceResult::DescribeDBClusterPerformanceResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeDBClusterPerformanceResult::~DescribeDBClusterPerformanceResult()
{}
void DescribeDBClusterPerformanceResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allPerformanceKeysNode = value["PerformanceKeys"]["PerformanceKey"];
for (auto valuePerformanceKeysPerformanceKey : allPerformanceKeysNode)
{
PerformanceKey performanceKeysObject;
if(!valuePerformanceKeysPerformanceKey["Unit"].isNull())
performanceKeysObject.unit = valuePerformanceKeysPerformanceKey["Unit"].asString();
if(!valuePerformanceKeysPerformanceKey["Name"].isNull())
performanceKeysObject.name = valuePerformanceKeysPerformanceKey["Name"].asString();
auto allSeriesNode = valuePerformanceKeysPerformanceKey["Series"]["SeriesItem"];
for (auto valuePerformanceKeysPerformanceKeySeriesSeriesItem : allSeriesNode)
{
PerformanceKey::SeriesItem seriesObject;
if(!valuePerformanceKeysPerformanceKeySeriesSeriesItem["Role"].isNull())
seriesObject.role = valuePerformanceKeysPerformanceKeySeriesSeriesItem["Role"].asString();
if(!valuePerformanceKeysPerformanceKeySeriesSeriesItem["Name"].isNull())
seriesObject.name = valuePerformanceKeysPerformanceKeySeriesSeriesItem["Name"].asString();
auto allValuesNode = valuePerformanceKeysPerformanceKeySeriesSeriesItem["Values"]["ValueItem"];
for (auto valuePerformanceKeysPerformanceKeySeriesSeriesItemValuesValueItem : allValuesNode)
{
PerformanceKey::SeriesItem::ValueItem valuesObject;
auto allPoint = value["Point"]["Point"];
for (auto value : allPoint)
valuesObject.point.push_back(value.asString());
seriesObject.values.push_back(valuesObject);
}
performanceKeysObject.series.push_back(seriesObject);
}
performanceKeys_.push_back(performanceKeysObject);
}
if(!value["EndTime"].isNull())
endTime_ = value["EndTime"].asString();
if(!value["StartTime"].isNull())
startTime_ = value["StartTime"].asString();
if(!value["DBClusterId"].isNull())
dBClusterId_ = value["DBClusterId"].asString();
}
std::vector<DescribeDBClusterPerformanceResult::PerformanceKey> DescribeDBClusterPerformanceResult::getPerformanceKeys()const
{
return performanceKeys_;
}
std::string DescribeDBClusterPerformanceResult::getEndTime()const
{
return endTime_;
}
std::string DescribeDBClusterPerformanceResult::getStartTime()const
{
return startTime_;
}
std::string DescribeDBClusterPerformanceResult::getDBClusterId()const
{
return dBClusterId_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
bd5491e15747fec04394ed2af8a477ed4293e824 | 84eb2efba353daa648dd1098cc41fcd691c616d2 | /src/sdk/stream/requester/incoming_subscribe_stream.cc | fd4e8d248adbcb558397f5169b55b32c36849096 | [
"Apache-2.0"
] | permissive | iot-dsa-v2/sdk-dslink-cpp | 0b435c25349971c4d43b6b85dfbd4c6f91da37e2 | d7734fba02237bd11bc887058f4d9573aac598d8 | refs/heads/develop | 2020-12-02T06:27:00.008341 | 2018-08-02T17:06:28 | 2018-08-02T17:06:28 | 96,830,480 | 1 | 0 | Apache-2.0 | 2018-08-02T17:06:29 | 2017-07-10T23:36:45 | C++ | UTF-8 | C++ | false | false | 2,093 | cc | #include "dsa_common.h"
#include "incoming_subscribe_stream.h"
#include "core/session.h"
#include "message/request/subscribe_request_message.h"
#include "message/response/subscribe_response_message.h"
#include "module/logger.h"
namespace dsa {
IncomingSubscribeStream::IncomingSubscribeStream(ref_<Session>&& session,
const Path& path, uint32_t rid,
Callback&& callback)
: MessageCacheStream(std::move(session), path, rid),
_callback(std::move(callback)) {}
void IncomingSubscribeStream::receive_message(ref_<Message>&& msg) {
if (msg->type() == MessageType::SUBSCRIBE_RESPONSE) {
IncomingPagesMerger::check_merge(_waiting_pages, msg);
if (_callback != nullptr) {
BEFORE_CALLBACK_RUN();
_callback(*this, std::move(msg));
AFTER_CALLBACK_RUN();
}
}
}
void IncomingSubscribeStream::subscribe(const SubscribeOptions& options) {
_options = options;
auto msg = make_ref_<SubscribeRequestMessage>();
msg->set_subscribe_option(options);
msg->set_target_path(path.full_str());
send_message(std::move(msg));
}
void IncomingSubscribeStream::close() {
if (_closed) return;
_closed = true;
if (!_callback_running) {
_callback = nullptr;
}
send_message(make_ref_<RequestMessage>(MessageType::CLOSE_REQUEST), true);
}
bool IncomingSubscribeStream::check_close_message(MessageCRef& message) {
if (message->type() == MessageType::CLOSE_REQUEST) {
_session->destroy_req_stream(rid);
return true;
}
return false;
}
void IncomingSubscribeStream::update_response_status(Status status) {
if (_callback != nullptr) {
auto response = make_ref_<SubscribeResponseMessage>();
response->set_status(status);
BEFORE_CALLBACK_RUN();
_callback(*this, std::move(response));
AFTER_CALLBACK_RUN();
}
}
bool IncomingSubscribeStream::disconnected() {
update_response_status(Status::NOT_AVAILABLE);
return false;
}
void IncomingSubscribeStream::reconnected() {
if (!_writing) {
subscribe(_options);
}
}
}
| [
"rinick@gmail.com"
] | rinick@gmail.com |
e32f59faa1d755ed5bbb3141db1fa11264cc0a4b | 1ce9a4b44ef07c4849b3a22133aee4e4f119ec1b | /Chap08/8.2.cpp | b2f3857af9b20b954eea51d96a858cc8594be125 | [] | no_license | Suraj-Patro/CLRS-cpp | 01c3b1a05f861041ec6bf7dec4726682b4aea800 | 72e0a1410d3b8d901ce4eadaa6b9fb7313affa67 | refs/heads/master | 2022-12-12T17:47:34.605938 | 2020-09-19T16:21:38 | 2020-09-19T16:26:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | #include "8.2.h"
#include "../print.h"
using namespace CLRS::CH8;
int main() {
print(string("Chapter 8.2 Counting sort"));
cout << "Initialize an array A as Figure 8.2\n";
vector<int> A = {2, 5, 3, 0, 2, 3, 0, 3};
print(A);
cout << "\nInitialize an empty array B as Figure 8.2\n";
vector<int> B(A.size(), 0);
print(B);
cout << "\nPerform COUNTING-SORT(A, B, 5)\n";
countingSort(A, B, 5);
print(B);
} | [
"walkccray@gmail.com"
] | walkccray@gmail.com |
98540b46ae53fe3b00c3eff63f9233451b8c0702 | fe479340153355e43d3ce3f3c3d058b7764d2a98 | /Projects/Plasma/Geometry/MetaNode.cpp | 2b0e3664d0c63297d846ff042cffe3b0e606e703 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | LudoSapiens/Dev | 8496490eda1c4ca4288a841c8cbabb8449135125 | 8ad0be9088d2001ecb13a86d4e47e6c8c38f0f2d | refs/heads/master | 2016-09-16T11:11:56.224090 | 2013-04-17T01:55:59 | 2013-04-17T01:55:59 | 9,486,806 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,876 | cpp | /*=============================================================================
Copyright (c) 2012, Ludo Sapiens Inc. and contributors.
See accompanying file LICENSE.txt for details.
=============================================================================*/
#include <Plasma/Geometry/MetaNode.h>
#include <Plasma/Geometry/MetaGeometry.h>
#include <Fusion/VM/VM.h>
#include <Base/ADT/MemoryPool.h>
#include <algorithm>
USING_NAMESPACE
/*==============================================================================
UNNAMED NAMESPACE
==============================================================================*/
UNNAMESPACE_BEGIN
UNNAMESPACE_END
/*==============================================================================
CLASS MetaNode
==============================================================================*/
//------------------------------------------------------------------------------
//!
void
MetaNode::print( TextStream& os ) const
{
print( os, "" );
}
//------------------------------------------------------------------------------
//!
void
MetaNode::print( TextStream& /*stream*/, const String& /*tab*/ ) const
{
}
/*==============================================================================
CLASS MetaBlocks
==============================================================================*/
//------------------------------------------------------------------------------
//!
void
MetaBlocks::resetCount( uint countID )
{
_countID = countID;
_count = 0;
_backB = false;
_frontB = false;
}
//------------------------------------------------------------------------------
//!
void
MetaBlocks::addIntersection( float t, bool backFacing )
{
if( backFacing )
{
if( t < 0.0001f )
{
if( !_backB )
{
_backB = true;
--count();
}
}
else
--count();
}
else
{
if( t < 0.0001f )
{
if( !_frontB )
{
_frontB = true;
++count();
}
}
else
++count();
}
}
//------------------------------------------------------------------------------
//!
void
MetaBlocks::dump() const
{
StdErr << "count: " << _count << "\n";
StdErr << "back: " << _backB << "\n";
StdErr << "front: "<< _frontB << "\n";
}
//------------------------------------------------------------------------------
//!
void
MetaBlocks::print( TextStream& stream, const String& tab ) const
{
stream << tab << "Blocks: " << this << "\n";
stream << tab << "parent: " << _parent << "\n";
stream << tab << "BBox: " << _box << "\n";
stream << tab << _blocks.size() << " blocks\n";
stream << tab << "Blocks end\n";
}
/*==============================================================================
CLASS MetaCompositeBlocks
==============================================================================*/
//------------------------------------------------------------------------------
//!
void
MetaCompositeBlocks::update()
{
_blocks.clear();
_attractions.clear();
for( uint i = 0; i < _children.size(); ++i )
{
MetaBlocks* mb = _children[i];
for( uint b = 0; b < mb->numBlocks(); ++b )
{
_blocks.pushBack( mb->block(b) );
mb->block(b)->_group = this;
}
AttractionContainer::ConstIterator it;
for( it = mb->attractions().begin(); it != mb->attractions().end(); ++it )
{
_attractions.add( *it );
}
}
}
//------------------------------------------------------------------------------
//!
void
MetaCompositeBlocks::print( TextStream& stream, const String& tab ) const
{
stream << tab << "CompositeBlocks: " << this << "\n";
stream << tab << "parent: " << _parent << "\n";
stream << tab << "BBox: " << _box << "\n";
stream << tab << _blocks.size() << " blocks\n";
stream << tab << "CompositeBlocks end\n";
}
/*==============================================================================
CLASS MetaInput
==============================================================================*/
//------------------------------------------------------------------------------
//!
void
MetaInput::print( TextStream& stream, const String& tab ) const
{
stream << tab << "Input: " << this << "\n";
stream << tab << "parent: " << _parent << "\n";
if( _child ) _child->print( stream, tab + " " );
stream << tab << "Input end\n";
}
/*==============================================================================
CLASS MetaTransform
==============================================================================*/
//------------------------------------------------------------------------------
//!
void
MetaTransform::print( TextStream& stream, const String& tab ) const
{
stream << tab << "Transform: " << this << "\n";
stream << tab << "parent: " << _parent << "\n";
stream << tab << "ref: " << _transform << "\n";
if( _child ) _child->print( stream, tab + " " );
stream << tab << "Transform end\n";
}
/*==============================================================================
CLASS MetaOperation
==============================================================================*/
//------------------------------------------------------------------------------
//!
void
MetaOperation::print( TextStream& stream, const String& tab ) const
{
String str;
switch( type() )
{
case META_UNION: str = "Union"; break;
case META_DIFFERENCE: str = "Difference"; break;
case META_INTERSECTION: str = "Intersection"; break;
default:;
}
stream << tab << str << ": " << this << "\n";
stream << tab << "parent: " << _parent << "\n";
stream << tab << "BBox: " << _box << "\n";
for( uint i = 0; i < _children.size(); ++i )
{
_children[i]->print( stream, tab + " " );
}
stream << tab << str << " end\n";
}
/*==============================================================================
CLASS MetaComposite
==============================================================================*/
//------------------------------------------------------------------------------
//!
inline bool lt_comp( MetaNode* a, MetaNode* b )
{
return a->layer() < b->layer();
}
//------------------------------------------------------------------------------
//!
void
MetaComposite::connectComposites()
{
_interiorNodes.clear();
if( _children.empty() )
{
_mainChild = 0;
return;
}
// First sorts children by their layers.
std::stable_sort( _children.begin(), _children.end(), lt_comp );
// Connect children node together.
MetaUnion* unionNode = 0;
MetaNode* lastNode = child(0);
for( uint i = 1; i < _children.size(); ++i )
{
if( child(i)->type() == META_COMPOSITE )
{
MetaComposite* comp = (MetaComposite*)child(i);
if( comp->input() )
{
comp->input()->child( lastNode );
lastNode = comp;
unionNode = 0;
continue;
}
}
if( !unionNode )
{
unionNode = new MetaUnion();
unionNode->parent( this );
unionNode->add( lastNode );
lastNode = unionNode;
_interiorNodes.pushBack( unionNode );
}
unionNode->add( child(i) );
}
_mainChild = lastNode;
}
//------------------------------------------------------------------------------
//!
void
MetaComposite::print( TextStream& stream, const String& tab ) const
{
stream << tab << "Composite: " << this << "\n";
stream << tab << "parent: " << _parent << "\n";
stream << tab << "BBox: " << _box << "\n";
stream << tab << "ref: " << _transform << "\n";
if( _mainChild ) _mainChild->print( stream, tab + " " );
stream << tab << "Composite end\n";
}
| [
"jocelyn.houle@ludosapiens.com"
] | jocelyn.houle@ludosapiens.com |
48b03f3b632a9c59a8cf5ebb84867289650fefc7 | 5a33aad281c9e3e77a69bfb91e2c9bc6999eee2d | /New folder/GameCastleVania_Tahitu/PorkChop.h | 0f7b37de89e065649898c3dcb6bc6b1d4ac50af1 | [] | no_license | ducptd98/NMGame | e353e157ad7e377e9f8bcad6aa2f3bb75bd49704 | f0f2efd49815a72be618b8b484e6dc190a0b60b5 | refs/heads/master | 2021-09-24T14:14:58.872031 | 2018-10-10T05:53:35 | 2018-10-10T05:53:35 | 152,369,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | h | #pragma once
#include "Brick.h"
class PorkChop : public Brick
{
public:
PorkChop();
~PorkChop();
};
| [
"37102603+ducptd98@users.noreply.github.com"
] | 37102603+ducptd98@users.noreply.github.com |
af6bdc0de595dbf8aed99434a7ec68000cc4820d | c6c8d5f008c29a3f96488a7d16fe9eaa9d70116e | /lala.cpp | 922adda26737126208e49f2dede1bce997b6e1fc | [] | no_license | animeshkarmakarAK/Computer-Programming | 6ad559ce93ac235d2e499de687199f07ec825b5f | 1b1fb9b5ded7c77352167572efb9ad0b7854380b | refs/heads/master | 2020-05-16T05:52:15.462026 | 2019-07-05T09:19:13 | 2019-07-05T09:19:13 | 182,828,945 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 118 | cpp | #include<bits/stdc++.h>
using namespace std;
string a;
int main()
{
cin>>a;
int m=a.size();
cout<<m;
}
| [
"animesh.pust@gmail.com"
] | animesh.pust@gmail.com |
69224ca2c84da6d9e418b8e9292197544eb2934b | e541d2bc575eb68818c0b2eeeeeabe0de209574f | /src/YouMeCommon/yuvlib/convert_argb.cc | c7f9d510cb5f6f0bd9d28c5428daae1d097e1db9 | [] | no_license | wangscript007/dev | 0d673981718993df0b971a5cd7a262cc217c6d9d | e47da659aadc220883b5e8067b25dc80108876b9 | refs/heads/master | 2022-08-05T00:53:31.844228 | 2020-05-24T05:20:44 | 2020-05-24T05:20:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,203 | cc | /*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <yuvlib/convert_argb.h>
#include <yuvlib/cpu_id.h>
#ifdef HAVE_JPEG
#include <yuvlib/mjpeg_decoder.h>
#endif
#include <yuvlib/planar_functions.h> // For CopyPlane and ARGBShuffle.
#include <yuvlib/rotate_argb.h>
#include <yuvlib/row.h>
#include <yuvlib/video_common.h>
#ifdef __cplusplus
namespace YOUME_libyuv {
extern "C" {
#endif
// Copy ARGB with optional flipping
LIBYUV_API
int ARGBCopy(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
if (!src_argb || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_argb = src_argb + (height - 1) * src_stride_argb;
src_stride_argb = -src_stride_argb;
}
CopyPlane(src_argb, src_stride_argb, dst_argb, dst_stride_argb, width * 4,
height);
return 0;
}
// Convert I422 to ARGB with matrix
static int I420ToARGBMatrix(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
const struct YuvConstants* yuvconstants,
int width,
int height) {
int y;
void (*I422ToARGBRow)(const uint8* y_buf, const uint8* u_buf,
const uint8* v_buf, uint8* rgb_buf,
const struct YuvConstants* yuvconstants, int width) =
I422ToARGBRow_C;
if (!src_y || !src_u || !src_v || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_I422TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
I422ToARGBRow = I422ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_I422TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
I422ToARGBRow = I422ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
I422ToARGBRow = I422ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_I422TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I422ToARGBRow = I422ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_I422TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(width, 4) &&
IS_ALIGNED(src_y, 4) && IS_ALIGNED(src_stride_y, 4) &&
IS_ALIGNED(src_u, 2) && IS_ALIGNED(src_stride_u, 2) &&
IS_ALIGNED(src_v, 2) && IS_ALIGNED(src_stride_v, 2) &&
IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
I422ToARGBRow = I422ToARGBRow_DSPR2;
}
#endif
#if defined(HAS_I422TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
I422ToARGBRow = I422ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
I422ToARGBRow(src_y, src_u, src_v, dst_argb, yuvconstants, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
if (y & 1) {
src_u += src_stride_u;
src_v += src_stride_v;
}
}
return 0;
}
// Convert I420 to ARGB.
LIBYUV_API
int I420ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I420ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvI601Constants, width, height);
}
// Convert I420 to ABGR.
LIBYUV_API
int I420ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height) {
return I420ToARGBMatrix(src_y, src_stride_y, src_v,
src_stride_v, // Swap U and V
src_u, src_stride_u, dst_abgr, dst_stride_abgr,
&kYvuI601Constants, // Use Yvu matrix
width, height);
}
// Convert J420 to ARGB.
LIBYUV_API
int J420ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I420ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvJPEGConstants, width, height);
}
// Convert J420 to ABGR.
LIBYUV_API
int J420ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height) {
return I420ToARGBMatrix(src_y, src_stride_y, src_v,
src_stride_v, // Swap U and V
src_u, src_stride_u, dst_abgr, dst_stride_abgr,
&kYvuJPEGConstants, // Use Yvu matrix
width, height);
}
// Convert H420 to ARGB.
LIBYUV_API
int H420ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I420ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvH709Constants, width, height);
}
// Convert H420 to ABGR.
LIBYUV_API
int H420ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height) {
return I420ToARGBMatrix(src_y, src_stride_y, src_v,
src_stride_v, // Swap U and V
src_u, src_stride_u, dst_abgr, dst_stride_abgr,
&kYvuH709Constants, // Use Yvu matrix
width, height);
}
// Convert I422 to ARGB with matrix
static int I422ToARGBMatrix(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
const struct YuvConstants* yuvconstants,
int width,
int height) {
int y;
void (*I422ToARGBRow)(const uint8* y_buf, const uint8* u_buf,
const uint8* v_buf, uint8* rgb_buf,
const struct YuvConstants* yuvconstants, int width) =
I422ToARGBRow_C;
if (!src_y || !src_u || !src_v || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width && src_stride_u * 2 == width &&
src_stride_v * 2 == width && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = src_stride_u = src_stride_v = dst_stride_argb = 0;
}
#if defined(HAS_I422TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
I422ToARGBRow = I422ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_I422TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
I422ToARGBRow = I422ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
I422ToARGBRow = I422ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_I422TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I422ToARGBRow = I422ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_I422TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(width, 4) &&
IS_ALIGNED(src_y, 4) && IS_ALIGNED(src_stride_y, 4) &&
IS_ALIGNED(src_u, 2) && IS_ALIGNED(src_stride_u, 2) &&
IS_ALIGNED(src_v, 2) && IS_ALIGNED(src_stride_v, 2) &&
IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
I422ToARGBRow = I422ToARGBRow_DSPR2;
}
#endif
#if defined(HAS_I422TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
I422ToARGBRow = I422ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
I422ToARGBRow(src_y, src_u, src_v, dst_argb, yuvconstants, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
src_u += src_stride_u;
src_v += src_stride_v;
}
return 0;
}
// Convert I422 to ARGB.
LIBYUV_API
int I422ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I422ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvI601Constants, width, height);
}
// Convert I422 to ABGR.
LIBYUV_API
int I422ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height) {
return I422ToARGBMatrix(src_y, src_stride_y, src_v,
src_stride_v, // Swap U and V
src_u, src_stride_u, dst_abgr, dst_stride_abgr,
&kYvuI601Constants, // Use Yvu matrix
width, height);
}
// Convert J422 to ARGB.
LIBYUV_API
int J422ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I422ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvJPEGConstants, width, height);
}
// Convert J422 to ABGR.
LIBYUV_API
int J422ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height) {
return I422ToARGBMatrix(src_y, src_stride_y, src_v,
src_stride_v, // Swap U and V
src_u, src_stride_u, dst_abgr, dst_stride_abgr,
&kYvuJPEGConstants, // Use Yvu matrix
width, height);
}
// Convert H422 to ARGB.
LIBYUV_API
int H422ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I422ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvH709Constants, width, height);
}
// Convert H422 to ABGR.
LIBYUV_API
int H422ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height) {
return I422ToARGBMatrix(src_y, src_stride_y, src_v,
src_stride_v, // Swap U and V
src_u, src_stride_u, dst_abgr, dst_stride_abgr,
&kYvuH709Constants, // Use Yvu matrix
width, height);
}
// Convert I444 to ARGB with matrix
static int I444ToARGBMatrix(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
const struct YuvConstants* yuvconstants,
int width,
int height) {
int y;
void (*I444ToARGBRow)(const uint8* y_buf, const uint8* u_buf,
const uint8* v_buf, uint8* rgb_buf,
const struct YuvConstants* yuvconstants, int width) =
I444ToARGBRow_C;
if (!src_y || !src_u || !src_v || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width && src_stride_u == width && src_stride_v == width &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = src_stride_u = src_stride_v = dst_stride_argb = 0;
}
#if defined(HAS_I444TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
I444ToARGBRow = I444ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
I444ToARGBRow = I444ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_I444TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
I444ToARGBRow = I444ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
I444ToARGBRow = I444ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_I444TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I444ToARGBRow = I444ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I444ToARGBRow = I444ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_I444TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
I444ToARGBRow = I444ToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 8)) {
I444ToARGBRow = I444ToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_I444TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
I444ToARGBRow = I444ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
I444ToARGBRow = I444ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
I444ToARGBRow(src_y, src_u, src_v, dst_argb, yuvconstants, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
src_u += src_stride_u;
src_v += src_stride_v;
}
return 0;
}
// Convert I444 to ARGB.
LIBYUV_API
int I444ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I444ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvI601Constants, width, height);
}
// Convert I444 to ABGR.
LIBYUV_API
int I444ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height) {
return I444ToARGBMatrix(src_y, src_stride_y, src_v,
src_stride_v, // Swap U and V
src_u, src_stride_u, dst_abgr, dst_stride_abgr,
&kYvuI601Constants, // Use Yvu matrix
width, height);
}
// Convert J444 to ARGB.
LIBYUV_API
int J444ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return I444ToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, dst_argb, dst_stride_argb,
&kYuvJPEGConstants, width, height);
}
// Convert I420 with Alpha to preattenuated ARGB.
static int I420AlphaToARGBMatrix(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
const uint8* src_a,
int src_stride_a,
uint8* dst_argb,
int dst_stride_argb,
const struct YuvConstants* yuvconstants,
int width,
int height,
int attenuate) {
int y;
void (*I422AlphaToARGBRow)(const uint8* y_buf, const uint8* u_buf,
const uint8* v_buf, const uint8* a_buf,
uint8* dst_argb,
const struct YuvConstants* yuvconstants,
int width) = I422AlphaToARGBRow_C;
void (*ARGBAttenuateRow)(const uint8* src_argb, uint8* dst_argb, int width) =
ARGBAttenuateRow_C;
if (!src_y || !src_u || !src_v || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_I422ALPHATOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_I422ALPHATOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_I422ALPHATOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_NEON;
}
}
#endif
#if defined(HAS_I422ALPHATOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(width, 4) &&
IS_ALIGNED(src_y, 4) && IS_ALIGNED(src_stride_y, 4) &&
IS_ALIGNED(src_u, 2) && IS_ALIGNED(src_stride_u, 2) &&
IS_ALIGNED(src_v, 2) && IS_ALIGNED(src_stride_v, 2) &&
IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_DSPR2;
}
#endif
#if defined(HAS_I422ALPHATOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
I422AlphaToARGBRow = I422AlphaToARGBRow_MSA;
}
}
#endif
#if defined(HAS_ARGBATTENUATEROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
ARGBAttenuateRow = ARGBAttenuateRow_Any_SSSE3;
if (IS_ALIGNED(width, 4)) {
ARGBAttenuateRow = ARGBAttenuateRow_SSSE3;
}
}
#endif
#if defined(HAS_ARGBATTENUATEROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
ARGBAttenuateRow = ARGBAttenuateRow_Any_AVX2;
if (IS_ALIGNED(width, 8)) {
ARGBAttenuateRow = ARGBAttenuateRow_AVX2;
}
}
#endif
#if defined(HAS_ARGBATTENUATEROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ARGBAttenuateRow = ARGBAttenuateRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
ARGBAttenuateRow = ARGBAttenuateRow_NEON;
}
}
#endif
#if defined(HAS_ARGBATTENUATEROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
ARGBAttenuateRow = ARGBAttenuateRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
ARGBAttenuateRow = ARGBAttenuateRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
I422AlphaToARGBRow(src_y, src_u, src_v, src_a, dst_argb, yuvconstants,
width);
if (attenuate) {
ARGBAttenuateRow(dst_argb, dst_argb, width);
}
dst_argb += dst_stride_argb;
src_a += src_stride_a;
src_y += src_stride_y;
if (y & 1) {
src_u += src_stride_u;
src_v += src_stride_v;
}
}
return 0;
}
// Convert I420 with Alpha to ARGB.
LIBYUV_API
int I420AlphaToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
const uint8* src_a,
int src_stride_a,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height,
int attenuate) {
return I420AlphaToARGBMatrix(src_y, src_stride_y, src_u, src_stride_u, src_v,
src_stride_v, src_a, src_stride_a, dst_argb,
dst_stride_argb, &kYuvI601Constants, width,
height, attenuate);
}
// Convert I420 with Alpha to ABGR.
LIBYUV_API
int I420AlphaToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
const uint8* src_a,
int src_stride_a,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height,
int attenuate) {
return I420AlphaToARGBMatrix(
src_y, src_stride_y, src_v, src_stride_v, // Swap U and V
src_u, src_stride_u, src_a, src_stride_a, dst_abgr, dst_stride_abgr,
&kYvuI601Constants, // Use Yvu matrix
width, height, attenuate);
}
// Convert I400 to ARGB.
LIBYUV_API
int I400ToARGB(const uint8* src_y,
int src_stride_y,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*I400ToARGBRow)(const uint8* y_buf, uint8* rgb_buf, int width) =
I400ToARGBRow_C;
if (!src_y || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = dst_stride_argb = 0;
}
#if defined(HAS_I400TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
I400ToARGBRow = I400ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
I400ToARGBRow = I400ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_I400TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
I400ToARGBRow = I400ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
I400ToARGBRow = I400ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_I400TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I400ToARGBRow = I400ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I400ToARGBRow = I400ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_I400TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
I400ToARGBRow = I400ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 16)) {
I400ToARGBRow = I400ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
I400ToARGBRow(src_y, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
}
return 0;
}
// Convert J400 to ARGB.
LIBYUV_API
int J400ToARGB(const uint8* src_y,
int src_stride_y,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*J400ToARGBRow)(const uint8* src_y, uint8* dst_argb, int width) =
J400ToARGBRow_C;
if (!src_y || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_y = src_y + (height - 1) * src_stride_y;
src_stride_y = -src_stride_y;
}
// Coalesce rows.
if (src_stride_y == width && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = dst_stride_argb = 0;
}
#if defined(HAS_J400TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
J400ToARGBRow = J400ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
J400ToARGBRow = J400ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_J400TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
J400ToARGBRow = J400ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
J400ToARGBRow = J400ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_J400TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
J400ToARGBRow = J400ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
J400ToARGBRow = J400ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_J400TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
J400ToARGBRow = J400ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 16)) {
J400ToARGBRow = J400ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
J400ToARGBRow(src_y, dst_argb, width);
src_y += src_stride_y;
dst_argb += dst_stride_argb;
}
return 0;
}
// Shuffle table for converting BGRA to ARGB.
static uvec8 kShuffleMaskBGRAToARGB = {3u, 2u, 1u, 0u, 7u, 6u, 5u, 4u,
11u, 10u, 9u, 8u, 15u, 14u, 13u, 12u};
// Shuffle table for converting ABGR to ARGB.
static uvec8 kShuffleMaskABGRToARGB = {2u, 1u, 0u, 3u, 6u, 5u, 4u, 7u,
10u, 9u, 8u, 11u, 14u, 13u, 12u, 15u};
// Shuffle table for converting RGBA to ARGB.
static uvec8 kShuffleMaskRGBAToARGB = {1u, 2u, 3u, 0u, 5u, 6u, 7u, 4u,
9u, 10u, 11u, 8u, 13u, 14u, 15u, 12u};
// Convert BGRA to ARGB.
LIBYUV_API
int BGRAToARGB(const uint8* src_bgra,
int src_stride_bgra,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return ARGBShuffle(src_bgra, src_stride_bgra, dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskBGRAToARGB), width, height);
}
// Convert ARGB to BGRA (same as BGRAToARGB).
LIBYUV_API
int ARGBToBGRA(const uint8* src_bgra,
int src_stride_bgra,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return ARGBShuffle(src_bgra, src_stride_bgra, dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskBGRAToARGB), width, height);
}
// Convert ABGR to ARGB.
LIBYUV_API
int ABGRToARGB(const uint8* src_abgr,
int src_stride_abgr,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return ARGBShuffle(src_abgr, src_stride_abgr, dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskABGRToARGB), width, height);
}
// Convert ARGB to ABGR to (same as ABGRToARGB).
LIBYUV_API
int ARGBToABGR(const uint8* src_abgr,
int src_stride_abgr,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return ARGBShuffle(src_abgr, src_stride_abgr, dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskABGRToARGB), width, height);
}
// Convert RGBA to ARGB.
LIBYUV_API
int RGBAToARGB(const uint8* src_rgba,
int src_stride_rgba,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
return ARGBShuffle(src_rgba, src_stride_rgba, dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskRGBAToARGB), width, height);
}
// Convert RGB24 to ARGB.
LIBYUV_API
int RGB24ToARGB(const uint8* src_rgb24,
int src_stride_rgb24,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*RGB24ToARGBRow)(const uint8* src_rgb, uint8* dst_argb, int width) =
RGB24ToARGBRow_C;
if (!src_rgb24 || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_rgb24 = src_rgb24 + (height - 1) * src_stride_rgb24;
src_stride_rgb24 = -src_stride_rgb24;
}
// Coalesce rows.
if (src_stride_rgb24 == width * 3 && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_rgb24 = dst_stride_argb = 0;
}
#if defined(HAS_RGB24TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
RGB24ToARGBRow = RGB24ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
RGB24ToARGBRow = RGB24ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_RGB24TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
RGB24ToARGBRow = RGB24ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
RGB24ToARGBRow = RGB24ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_RGB24TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
RGB24ToARGBRow = RGB24ToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 8)) {
RGB24ToARGBRow = RGB24ToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_RGB24TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
RGB24ToARGBRow = RGB24ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 16)) {
RGB24ToARGBRow = RGB24ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
RGB24ToARGBRow(src_rgb24, dst_argb, width);
src_rgb24 += src_stride_rgb24;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert RAW to ARGB.
LIBYUV_API
int RAWToARGB(const uint8* src_raw,
int src_stride_raw,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*RAWToARGBRow)(const uint8* src_rgb, uint8* dst_argb, int width) =
RAWToARGBRow_C;
if (!src_raw || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_raw = src_raw + (height - 1) * src_stride_raw;
src_stride_raw = -src_stride_raw;
}
// Coalesce rows.
if (src_stride_raw == width * 3 && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_raw = dst_stride_argb = 0;
}
#if defined(HAS_RAWTOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
RAWToARGBRow = RAWToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
RAWToARGBRow = RAWToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_RAWTOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
RAWToARGBRow = RAWToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
RAWToARGBRow = RAWToARGBRow_NEON;
}
}
#endif
#if defined(HAS_RAWTOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
RAWToARGBRow = RAWToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 8)) {
RAWToARGBRow = RAWToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_RAWTOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
RAWToARGBRow = RAWToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 16)) {
RAWToARGBRow = RAWToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
RAWToARGBRow(src_raw, dst_argb, width);
src_raw += src_stride_raw;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert RGB565 to ARGB.
LIBYUV_API
int RGB565ToARGB(const uint8* src_rgb565,
int src_stride_rgb565,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*RGB565ToARGBRow)(const uint8* src_rgb565, uint8* dst_argb, int width) =
RGB565ToARGBRow_C;
if (!src_rgb565 || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_rgb565 = src_rgb565 + (height - 1) * src_stride_rgb565;
src_stride_rgb565 = -src_stride_rgb565;
}
// Coalesce rows.
if (src_stride_rgb565 == width * 2 && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_rgb565 = dst_stride_argb = 0;
}
#if defined(HAS_RGB565TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
RGB565ToARGBRow = RGB565ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
RGB565ToARGBRow = RGB565ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_RGB565TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
RGB565ToARGBRow = RGB565ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
RGB565ToARGBRow = RGB565ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_RGB565TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
RGB565ToARGBRow = RGB565ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
RGB565ToARGBRow = RGB565ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_RGB565TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
RGB565ToARGBRow = RGB565ToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 8)) {
RGB565ToARGBRow = RGB565ToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_RGB565TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
RGB565ToARGBRow = RGB565ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 16)) {
RGB565ToARGBRow = RGB565ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
RGB565ToARGBRow(src_rgb565, dst_argb, width);
src_rgb565 += src_stride_rgb565;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert ARGB1555 to ARGB.
LIBYUV_API
int ARGB1555ToARGB(const uint8* src_argb1555,
int src_stride_argb1555,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*ARGB1555ToARGBRow)(const uint8* src_argb1555, uint8* dst_argb,
int width) = ARGB1555ToARGBRow_C;
if (!src_argb1555 || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_argb1555 = src_argb1555 + (height - 1) * src_stride_argb1555;
src_stride_argb1555 = -src_stride_argb1555;
}
// Coalesce rows.
if (src_stride_argb1555 == width * 2 && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_argb1555 = dst_stride_argb = 0;
}
#if defined(HAS_ARGB1555TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_ARGB1555TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_ARGB1555TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_ARGB1555TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 4)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_ARGB1555TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 16)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
ARGB1555ToARGBRow(src_argb1555, dst_argb, width);
src_argb1555 += src_stride_argb1555;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert ARGB4444 to ARGB.
LIBYUV_API
int ARGB4444ToARGB(const uint8* src_argb4444,
int src_stride_argb4444,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*ARGB4444ToARGBRow)(const uint8* src_argb4444, uint8* dst_argb,
int width) = ARGB4444ToARGBRow_C;
if (!src_argb4444 || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_argb4444 = src_argb4444 + (height - 1) * src_stride_argb4444;
src_stride_argb4444 = -src_stride_argb4444;
}
// Coalesce rows.
if (src_stride_argb4444 == width * 2 && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_argb4444 = dst_stride_argb = 0;
}
#if defined(HAS_ARGB4444TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_ARGB4444TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_ARGB4444TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_ARGB4444TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 4)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_ARGB4444TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 16)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
ARGB4444ToARGBRow(src_argb4444, dst_argb, width);
src_argb4444 += src_stride_argb4444;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert NV12 to ARGB.
LIBYUV_API
int NV12ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_uv,
int src_stride_uv,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*NV12ToARGBRow)(const uint8* y_buf, const uint8* uv_buf, uint8* rgb_buf,
const struct YuvConstants* yuvconstants, int width) =
NV12ToARGBRow_C;
if (!src_y || !src_uv || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_NV12TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
NV12ToARGBRow = NV12ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
NV12ToARGBRow = NV12ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
NV12ToARGBRow = NV12ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
NV12ToARGBRow = NV12ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
NV12ToARGBRow = NV12ToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
NV12ToARGBRow = NV12ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
NV12ToARGBRow(src_y, src_uv, dst_argb, &kYuvI601Constants, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
if (y & 1) {
src_uv += src_stride_uv;
}
}
return 0;
}
// Convert NV21 to ARGB.
LIBYUV_API
int NV21ToARGB(const uint8* src_y,
int src_stride_y,
const uint8* src_uv,
int src_stride_uv,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*NV21ToARGBRow)(const uint8* y_buf, const uint8* uv_buf, uint8* rgb_buf,
const struct YuvConstants* yuvconstants, int width) =
NV21ToARGBRow_C;
if (!src_y || !src_uv || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_NV21TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
NV21ToARGBRow = NV21ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
NV21ToARGBRow = NV21ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_NV21TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
NV21ToARGBRow = NV21ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
NV21ToARGBRow = NV21ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_NV21TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
NV21ToARGBRow = NV21ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
NV21ToARGBRow = NV21ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_NV21TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
NV21ToARGBRow = NV21ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
NV21ToARGBRow = NV21ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
NV21ToARGBRow(src_y, src_uv, dst_argb, &kYuvI601Constants, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
if (y & 1) {
src_uv += src_stride_uv;
}
}
return 0;
}
// Convert M420 to ARGB.
LIBYUV_API
int M420ToARGB(const uint8* src_m420,
int src_stride_m420,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*NV12ToARGBRow)(const uint8* y_buf, const uint8* uv_buf, uint8* rgb_buf,
const struct YuvConstants* yuvconstants, int width) =
NV12ToARGBRow_C;
if (!src_m420 || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_NV12TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
NV12ToARGBRow = NV12ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
NV12ToARGBRow = NV12ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
NV12ToARGBRow = NV12ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
NV12ToARGBRow = NV12ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
NV12ToARGBRow = NV12ToARGBRow_Any_DSPR2;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_DSPR2;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
NV12ToARGBRow = NV12ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height - 1; y += 2) {
NV12ToARGBRow(src_m420, src_m420 + src_stride_m420 * 2, dst_argb,
&kYuvI601Constants, width);
NV12ToARGBRow(src_m420 + src_stride_m420, src_m420 + src_stride_m420 * 2,
dst_argb + dst_stride_argb, &kYuvI601Constants, width);
dst_argb += dst_stride_argb * 2;
src_m420 += src_stride_m420 * 3;
}
if (height & 1) {
NV12ToARGBRow(src_m420, src_m420 + src_stride_m420 * 2, dst_argb,
&kYuvI601Constants, width);
}
return 0;
}
// Convert YUY2 to ARGB.
LIBYUV_API
int YUY2ToARGB(const uint8* src_yuy2,
int src_stride_yuy2,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*YUY2ToARGBRow)(const uint8* src_yuy2, uint8* dst_argb,
const struct YuvConstants* yuvconstants, int width) =
YUY2ToARGBRow_C;
if (!src_yuy2 || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_yuy2 = src_yuy2 + (height - 1) * src_stride_yuy2;
src_stride_yuy2 = -src_stride_yuy2;
}
// Coalesce rows.
if (src_stride_yuy2 == width * 2 && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_yuy2 = dst_stride_argb = 0;
}
#if defined(HAS_YUY2TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
YUY2ToARGBRow = YUY2ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
YUY2ToARGBRow = YUY2ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_YUY2TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
YUY2ToARGBRow = YUY2ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 32)) {
YUY2ToARGBRow = YUY2ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_YUY2TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
YUY2ToARGBRow = YUY2ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
YUY2ToARGBRow = YUY2ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_YUY2TOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
YUY2ToARGBRow = YUY2ToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
YUY2ToARGBRow = YUY2ToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
YUY2ToARGBRow(src_yuy2, dst_argb, &kYuvI601Constants, width);
src_yuy2 += src_stride_yuy2;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert UYVY to ARGB.
LIBYUV_API
int UYVYToARGB(const uint8* src_uyvy,
int src_stride_uyvy,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height) {
int y;
void (*UYVYToARGBRow)(const uint8* src_uyvy, uint8* dst_argb,
const struct YuvConstants* yuvconstants, int width) =
UYVYToARGBRow_C;
if (!src_uyvy || !dst_argb || width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_uyvy = src_uyvy + (height - 1) * src_stride_uyvy;
src_stride_uyvy = -src_stride_uyvy;
}
// Coalesce rows.
if (src_stride_uyvy == width * 2 && dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_uyvy = dst_stride_argb = 0;
}
#if defined(HAS_UYVYTOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
UYVYToARGBRow = UYVYToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
UYVYToARGBRow = UYVYToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_UYVYTOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
UYVYToARGBRow = UYVYToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 32)) {
UYVYToARGBRow = UYVYToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_UYVYTOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
UYVYToARGBRow = UYVYToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
UYVYToARGBRow = UYVYToARGBRow_NEON;
}
}
#endif
#if defined(HAS_UYVYTOARGBROW_MSA)
if (TestCpuFlag(kCpuHasMSA)) {
UYVYToARGBRow = UYVYToARGBRow_Any_MSA;
if (IS_ALIGNED(width, 8)) {
UYVYToARGBRow = UYVYToARGBRow_MSA;
}
}
#endif
for (y = 0; y < height; ++y) {
UYVYToARGBRow(src_uyvy, dst_argb, &kYuvI601Constants, width);
src_uyvy += src_stride_uyvy;
dst_argb += dst_stride_argb;
}
return 0;
}
#ifdef __cplusplus
} // extern "C"
} // namespace YOUME_libyuv
#endif
| [
"shuhuan_bruce@icloud.com"
] | shuhuan_bruce@icloud.com |
ff7a1d3e3a4067f7093e39dc6ec00583734c1f1d | 49be2423ad376a89dfc731bbbbc82c4c46fca368 | /5_graph/KosarajuSCC.cpp | b7af68a259ccdfee83d4b263af2df74c83e841b9 | [] | no_license | wind2412/Data-Structure | 731aca083d9ec22da41d5a3e613fee7a15b4b722 | 233f2e33c158223ee472b4f55999943fb1aae7f9 | refs/heads/master | 2021-01-11T21:23:12.874908 | 2017-09-12T03:48:29 | 2017-09-12T03:48:29 | 78,775,246 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,408 | cpp | #ifndef _KOSARAJU_SCC_H_
#define _KOSARAJU_SCC_H_
#include <iostream>
#include "Graph.hpp"
#include <stack>
#include <vector>
using namespace std;
/**
* Kosaraju强连通分量算法。
* 利用了一个图即使reverse了,和原图还是具有相同的强连通分量的性质!
* 非常通俗易懂。ACM之家blog:http://www.acmerblog.com/strongly-connected-components-6099.html
* 有一个图特别易懂。
*
* 算法步骤:
* 1.对所有的结点进行DFS深度遍历。mark所有去过的点。在访问一个点v结束时,把v加入stack中。
* 2.得到图g的reverse版本。然后把stack不断弹出,以反序的形式在反序图上DFS遍历每个访问过的点。然后顺便union-find加到id数组中。
*
* 使用stack是因为,在g图的源点会变成终点。 如果不用stack反序,那在反序图上顺序遍历,0~g.getV()一开始的点全变成终点了。
*
*/
class KosarajuSCC{
private:
Graph & g;
Graph && rev;
vector<bool> marked;
vector<int> id; //union-find并查集
stack<int> s;
int count; //并查集个数。即强连通分量的个数。
public:
KosarajuSCC(Graph & g): g(g), rev(g.reverse()), marked(g.getV(), 0), id(g.getV(), 0), count(0){buildSCC();};
void buildSCC(){
for(int i = 0; i < g.getV(); i ++){
if(!marked[i]){
dfsOrigin(i);
}
}
marked.assign(g.getV(), 0); //归零marked
while(!s.empty()){
int v = s.top(); s.pop();
if(!marked[v]){
dfsReverse(v);
count ++;
}
}
}
void dfsOrigin(int v){ //对原图进行dfs
marked[v] = true;
s.push(v); //加入栈
for(const Edge & e : g.getAdj(v)){
if(!marked[e.to]){
dfsOrigin(e.to);
}
}
}
void dfsReverse(int v){ //对reverse图进行dfs
marked[v] = true;
for(const Edge & e : rev.getAdj(v)){
if(!marked[e.to]){
dfsReverse(e.to);
}
}
id[v] = count;
}
vector<int> getId(){
return id;
}
};
#endif
int main()
{
Graph g(5);
g.addEdge(1, 3, 1.1);
g.addEdge(1, 4, 3.7);
g.addEdge(0, 1, 5.1);
g.addEdge(1, 6, 0.8);
g.addEdge(3, 4, 1.5);
g.addEdge(4, 1, -10);
cout << "1's out_degree: "<<g.getDegree(1) << endl;
g.reverse().print();
g.print();
KosarajuSCC k(g);
vector<int> && v = k.getId();
for(vector<int>::iterator it = v.begin(); it != v.end(); ++it){
cout << *it << " ";
}
}
| [
"944797358@qq.com"
] | 944797358@qq.com |
cd3db08380a7300da12bdea52f40b8928b4960d6 | 21b5398f8368d38cf1c83e81c2112f18c84f5f07 | /Systems Programming/Assignment 2: Random University (C++)/include/PGstudent.h | 2667f638f40518b2d5cab89486ac2ae6c7a569a7 | [] | no_license | efrathaz/my-academic-projects | 04d54e28777590c0cdd65931f97cd6c7ca23a89a | dbfa0ce67c9ae8da859cbd1c76d115a5855036a1 | refs/heads/master | 2021-01-13T01:30:49.945108 | 2015-03-30T14:26:54 | 2015-03-30T14:26:54 | 23,150,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | h | #ifndef PGSTUDENT_H_
#define PGSTUDENT_H_
#include "../include/Student.h"
using namespace std;
class PGstudent : public Student{
public:
PGstudent();
PGstudent(vector<Course*> Failed, int ID, string Image, int Current, int CurrentE, int NumOfElective);
PGstudent(const PGstudent &p);
virtual void study(Course &c);
virtual char type();
};
#endif /* PGSTUDENT_H_ */
| [
"efrat.hazani@gmail.com"
] | efrat.hazani@gmail.com |
cacf15bce31677424ae17bdda201edfe3a44298d | e38f304b299896af8ec057f567027dea7380d286 | /pass4/codes/ReportApStats.cc | 102e2362b6ddb840fb48942d7c0e86ae36df94d0 | [] | no_license | rafopar/BumpHunt_2016 | 90b57e93351e7db391f57a11fcd7b28a05d2e64a | f1e551ddbd4c2f3894c31392c31d943a22ece116 | refs/heads/master | 2021-07-01T15:07:07.216477 | 2020-09-24T16:09:50 | 2020-09-24T16:09:50 | 144,508,102 | 0 | 1 | null | 2020-02-16T01:52:18 | 2018-08-12T23:30:42 | C++ | UTF-8 | C++ | false | false | 613 | cc |
void ReportApStats(){
ofstream out("Ap_Stats.dat");
const int n_masses = 29;
int masses[n_masses] = {30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 155, 160, 165, 170, 175};
for( int i = 0; i < n_masses; i++ ){
cout<<masses[i]<<endl;
TFile *cur_file = new TFile(Form("EventSelection_Ap_%d_MeV.root", masses[i]), "Read");
TH1D *h_Minv_General_Final_1 = (TH1D*)cur_file->Get("h_Minv_General_Final_1");
int entries =h_Minv_General_Final_1 ->GetEntries();
out<<setw(5)<<masses[i]<<setw(10)<<entries<<endl;
}
}
| [
"rafopar@jlab.org"
] | rafopar@jlab.org |
588d8aecc1b9ae01ac2d28d69d9fd9d85012152c | dd749b50623140a601e270b5953b1399bb86cba1 | /include/Withdrawal.h | bf45fb96fe45b0cc2e3056978aafe610d1484a14 | [] | no_license | aramhamidi/ATM | 552e80ed1280a199d8570269d93266950d48a3af | ee2ab090e7162f036b604982ff557208bc354815 | refs/heads/master | 2020-04-12T07:13:57.305927 | 2018-12-19T00:30:36 | 2018-12-19T00:30:36 | 162,361,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | h | /**
* @Author: Aram Hamidi <aramhamidi>
* @Date: 2018-08-21T11:49:06-07:00
* @Email: aram.hamidi@getcruise.com
* @Project: Laser_Driver_A53
* @Filename: Withdrawal.h
* @Last modified by: aramhamidi
* @Last modified time: 2018-08-21T11:49:53-07:00
*/
// Withdrawal.h
// Withdrawal class definition. Represents a withdrawal transaction.
#ifndef WITHDRAWAL_H
#define WITHDRAWAL_H
#include "Transaction.h" // Transaction class definition
class Keypad; // forward declaration of class Keypad
class CashDispenser; // forward declaration of class CashDispenser
class Withdrawal : public Transaction
{
public:
Withdrawal( int, Screen &, BankDatabase &, Keypad &, CashDispenser & );
virtual void execute(); // perform the transaction
private:
int amount; // amount to withdraw
Keypad &keypad; // reference to ATM's keypad
CashDispenser &cashDispenser; // reference to ATM's cash dispenser
int displayMenuOfAmounts() const; // display the withdrawal menu
}; // end class Withdrawal
#endif // WITHDRAWAL_H
| [
"aram.hamidi@getcruise.com"
] | aram.hamidi@getcruise.com |
ba861c0ba60838fbe998ae855220376ee20d659c | 8a2bcab4cfea4773778b71998e58c69a72e2f3bd | /main.cpp | 288eaac3ecbb9df1aee1dd19eb619cca29da6349 | [] | no_license | AginSquash/laba3 | d89f56c2b39aeb632865412f307daf383fa1500d | 679868b5079a29ef8eb8243bcdf86de272abcd8f | refs/heads/master | 2020-07-31T02:12:37.870661 | 2019-09-29T13:37:24 | 2019-09-29T13:37:24 | 210,446,201 | 1 | 0 | null | 2019-09-26T19:42:47 | 2019-09-23T20:27:35 | C++ | UTF-8 | C++ | false | false | 2,615 | cpp | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool isAnswered = false;
string *updateArraySize(string* p_array, int *size );
void print(string *word, string *antonym);
int main() {
setlocale(LC_ALL, "rus"); // Строка в память о тех, кто пользуется виндой (F)
std::string line;
std::ifstream in("dict.txt");
int size = 4;
string *p_array = new string[size];
int i = 0;
if (in.is_open())
{
while (getline(in, line))
{
if ( i == size )
{
#ifdef DEBUG
cout << "Массив будет перегружен, вызов updateArray" << endl;
#endif
p_array = updateArraySize(p_array, & size);
}
p_array[i] = line;
i++;
}
}
in.close();
cout << "Введите слово: ";
string word;
cin >> word;
for (int i = 0; i < size; i++)
{
#ifdef DEBUG
cout << "I: " << i << endl;
cout << "Array: " << p_array[i] << endl;
cout << "Len: " << p_array[i].length() << endl;
cout << "Find word: " << p_array[i].find(word) << endl << endl << endl;
#endif
if ( p_array[i].find(word) < p_array[i].length() ) // find почему-то если строка не соддержит word возвращает безумное занчение
{
int index = p_array[i].find(':'); // Разбиавем строку на два значения по разделителю
string dict[2];
dict[0] = p_array[i].substr(0, index);
index++;
dict[1] = p_array[i].substr(index);
if (dict[0] == word)
{
print( &word, &dict[1]);
} else {
print( &word, &dict[0]);
}
break;
}
}
if (!isAnswered)
{
cout << "К сожалению, этого слова нет в словаре." << endl;
}
delete[] p_array;
return 0;
}
void print(string *word, string *antonym)
{
cout << "Антоним к \"" << *word << "\" это слово \"" << *antonym << "\"." <<endl;
isAnswered = true;
}
string *updateArraySize(string* p_array, int *size )
{
*size *= 2;
string *p_new_array = new string[ *size ];
for (int i = 0; i < (*size/2); i++)
{
p_new_array[i] = p_array[i];
}
#ifdef DEBUG
cout << "Массив обновлен, новый рамзер: " << *size << endl;
#endif
delete[] p_array;
return p_new_array;
} | [
"agins.main@gmail.com"
] | agins.main@gmail.com |
5c2dd5f1796c63c743156becf1637ea44a36fb38 | b2f81aadd492f0fe0046020561510aa9f093cdfb | /run_scan_cos_PD_F1.cpp | 97a5562ea00b42b40b1349c79906050f8502d880 | [] | no_license | zhchenseven/Computational_Physics_Wave_propagation | 0004f765e65ad7544a99e8234666bc03d421f24b | d92bc281dd4c8d4718441dcc625a8150afec5a87 | refs/heads/master | 2021-08-26T09:12:54.198744 | 2017-11-22T19:46:12 | 2017-11-22T19:46:12 | 107,585,665 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,530 | cpp | # include <iostream>
# include <armadillo>
# include "Data_process.h"
using namespace std;
using namespace arma;
int rscP1(int argv, char ** argc)
//int main(int argv, char ** argc)
{
Data_process Project;
rowvec nu_arr(4);
string q_arr[4] = { "LF","UW1","LW","MD" };
nu_arr << 1 << 0.75 << 0.5 << 0.25 << endr;
int N = 32;
double x_low = 0;
double x_sup = 1;
int M = 30;
double a = 1;
double nu = 0.25;
double NT = 1.5;
Project.set_para(N, x_low,x_sup, M, a, nu, NT);
string ini_type = "cos";
string bnd_type = "PD";
Project.set_IBC(ini_type, bnd_type);
string q_type = "UW1";
Project.set_scheme(q_type);
string flux_type = "F1";
Project.set_flux(flux_type);
string vis_name = "cos_PD_F1";
string main_fd_name = "cos_PD_F1_scan";
int index = 0;
string data_type = "dat";
string size_sufx = "size";
Project.set_process_ctrl(vis_name, index, data_type, size_sufx);
Project.set_main_fd(main_fd_name);
double xi = 0.25;
double d = 0.1;
Project.set_para_extra(xi, d);
int i, j;
for (i = 0; i < 4; i++)
{
Project.q_type = q_arr[i];
for (j = 0; j < 4; j++)
{
Project.creat_main_fd_ctrl = 1;
vis_name = ini_type + "_" + bnd_type + "_" + flux_type + "_" + q_arr[i] + "_nu_" + Project.dn2s(nu_arr(j));
Project.set_vis_name(vis_name);
cout << "vis_name is " << Project.vis_name << endl;
Project.nu = nu_arr(j);
if (i != 0 || j != 0)
Project.creat_main_fd_ctrl = 0;
Project.exe_cetr();
Project.process();
Project.write_log();
}
}
system("pause");
return 0;
} | [
"32938765+zhchenseven@users.noreply.github.com"
] | 32938765+zhchenseven@users.noreply.github.com |
52e469f30c5a7240585f8e69cda783462061221e | 80a96581255056a03f126e19b081276d5a66dd2e | /DlgRectProperties.cpp | f3e4a93ef66c77c53fbc5c2a60dc469e0f8c9f5e | [] | no_license | patchell/FrontCad | 6c1c9e4e7642eafe8a8a556c17e098f32077c548 | b2567d6d0b57b22a29efa64aa42d583cd1a457b8 | refs/heads/master | 2023-07-07T04:24:40.368564 | 2023-06-29T03:42:46 | 2023-06-29T03:42:46 | 75,502,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,345 | cpp | // DlgRectProperites.cpp : implementation file
//
#include "pch.h"
// CDlgRectProperties dialog
IMPLEMENT_DYNAMIC(CDlgRectProperties, CDialogEx)
CDlgRectProperties::CDlgRectProperties(CWnd* pParent /*=NULL*/)
: CDialog(IDD_DIALOG_RECTPROPERTIES, pParent)
{
m_pRect = 0;
}
CDlgRectProperties::~CDlgRectProperties()
{
}
void CDlgRectProperties::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_LINE_WIDTH, m_Edit_LineWidth);
DDX_Control(pDX, IDC_STATIC_FILL_COLOR, m_Static_FillColor);
DDX_Control(pDX, IDC_STATIC_LINE_COLOR, m_Static_LineColor);
DDX_Control(pDX, IIDC_CHECK_RECT_NOFILL, m_Check_NoFill);
DDX_Control(pDX, IDC_STATIC_RECT_COLOR_SELECTED, m_Static_ColorSelected);
}
BEGIN_MESSAGE_MAP(CDlgRectProperties, CDialog)
ON_BN_CLICKED(IIDC_CHECK_RECT_NOFILL, &CDlgRectProperties::OnClickedIidcCheckRectNofill)
END_MESSAGE_MAP()
// CDlgRectProperties message handlers
BOOL CDlgRectProperties::OnInitDialog()
{
CDialog::OnInitDialog();
m_Edit_LineWidth.SetDecimalPlaces(3);
m_Edit_LineWidth.SetDoubleValue(m_pRect->GetAttributes().m_LineWidth);
m_Static_LineColor.SetColor(m_pRect->GetAttributes().m_colorLine);
m_Static_FillColor.SetColor(m_pRect->GetAttributes().m_colorFill);
m_Static_ColorSelected.SetColor(m_pRect->GetAttributes().m_colorSelected);
m_Check_NoFill.SetCheck(m_pRect->GetAttributes().m_TransparentFill);
if(m_pRect->GetAttributes().m_TransparentFill)
m_Static_FillColor.ShowWindow(0);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CDlgRectProperties::OnOK()
{
CWnd *pW = GetFocus();
int Id = pW->GetDlgCtrlID();
switch (Id)
{
case IDOK:
m_pRect->GetAttributes().m_colorLine = m_Static_LineColor.GetColor();
m_pRect->GetAttributes().m_colorFill = m_Static_FillColor.GetColor();
m_pRect->GetAttributes().m_colorSelected = m_Static_ColorSelected.GetColor();
m_pRect->GetAttributes().m_TransparentFill = m_Check_NoFill.GetCheck();
m_pRect->GetAttributes().m_LineWidth = m_Edit_LineWidth.GetDoubleValue();
CDialog::OnOK();
break;
}
}
void CDlgRectProperties::OnClickedIidcCheckRectNofill()
{
if (m_Check_NoFill.GetCheck() == BST_CHECKED)
{
m_Static_FillColor.ShowWindow(0);
}
else
{
m_Static_FillColor.ShowWindow(1);
}
}
| [
"patchell@cox.net"
] | patchell@cox.net |
a36db4766bf42a60babef70468be8c5d65142122 | 84b5835643f156c6fc688450a417c74ab2be39d8 | /test/cases/namespace.cch.cc | d2654c7f39e02451fa638b911eb9831036ae438a | [
"MIT"
] | permissive | tjps/cch | c128cf64aab359174b9428b926278578626a4d6c | 1a9cf09fbd02e55704c978baeda846269c5ff7f9 | refs/heads/master | 2021-01-17T10:19:20.703451 | 2020-07-02T18:24:21 | 2020-07-02T18:24:32 | 57,252,789 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 73 | cc | #include "namespace.cch.h"
ns::c::c() {}
ns::c::~c() {}
| [
"tjps636@gmail.com"
] | tjps636@gmail.com |
4aaa43d2af95f884fd0f693c355ef0d3af590ba0 | 60c87069f3f70964f54b8515886f1a3deb1a4429 | /free_gait_core/include/free_gait_core/pose_optimization/PoseOptimizationQP.hpp | bf004244af9ed52c4882bdb8b32d59e96212652f | [] | no_license | HITSZ-LeggedRobotics/quadruped_locomotion | 367ebbb420a8da629e8ce4f49c683e87a33e8621 | 5ec4feb3496348aa8d984c50c1cb9d7f854ac11e | refs/heads/master | 2022-06-14T22:12:38.432967 | 2022-05-18T10:39:05 | 2022-05-18T10:39:05 | 177,237,609 | 6 | 5 | null | 2020-07-17T07:07:33 | 2019-03-23T03:05:33 | C++ | UTF-8 | C++ | false | false | 990 | hpp | /*
* PoseOptimizationQP.hpp
*
* Created on: Jun 10, 2015
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#pragma once
#include "free_gait_core/TypeDefs.hpp"
#include "free_gait_core/pose_optimization/PoseOptimizationBase.hpp"
#include <grid_map_core/Polygon.hpp>
#include <qp_solver/quadraticproblemsolver.h>
#include <unordered_map>
#include <memory>
namespace free_gait {
class PoseOptimizationQP : public PoseOptimizationBase
{
public:
PoseOptimizationQP(const AdapterBase& adapter);
virtual ~PoseOptimizationQP();
// PoseOptimizationQP(const PoseOptimizationQP& other);
/*!
* Computes the optimized pose.
* @param[in/out] pose the pose to optimize from the given initial guess.
* @return true if successful, false otherwise.
*/
bool optimize(Pose& pose);
private:
std::unique_ptr<qp_solver::QuadraticProblemSolver> solver_;
unsigned int nStates_;
unsigned int nDimensions_;
};
} /* namespace loco */
| [
"wshy1995@outlook.com"
] | wshy1995@outlook.com |
92cbd2ea8486111f65592a9b813885b83ec82794 | 0814eaa8e3496606e19d823eed7dfcb337df98d4 | /core/RandomGenerators-DS.h | 2ca92c7ec7afd286a112c4d6d0d175ee7ecfd233 | [] | no_license | davor-/GoSum | be18c0fafdcc350e9493fbbe8a5aadfbf3428ce9 | cbe8296f561aff1e9b92b677957eafb706547f36 | refs/heads/master | 2016-09-06T09:28:22.392095 | 2015-07-21T17:24:29 | 2015-07-21T17:24:29 | 39,459,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,155 | h | #ifndef CRANDOMGENERATORS_H
#define CRANDOMGENERATORS_H
#include <Eigen/Dense>
using namespace Eigen;
#if !defined(UINT32_MAX)
#define UINT32_MAX 0xffffffff
#endif
//! \brief
//! Abstract base class for all uniform random number generators (RNG).
class CBaseRNG {
public:
virtual void setSeed(unsigned int s)=0; //!< Sets seed of the RNG.
virtual unsigned int rndi()=0; //!< Returns randomly generated unsigned int.
virtual double rnd()=0; //!< Returns randomly generated double between 0 and 1.
virtual double rnd(double a, double b) { return a+((b-a)*rnd()); } //!< Returns randomly generated double between a and b.
};
//! \brief
//! Class for uniform RNG with large period = 3.138*10^57.
class CLargePeriodRNG : public CBaseRNG {
private:
#ifdef _MSC_VER
typedef unsigned __int64 Ullong;
#else
typedef unsigned long long int Ullong;
#endif
Ullong u,v,w; //!< Parameters of the large period RNG.
private:
inline Ullong int64() //!< Private function needed in setSeed() and rnd().
{ u = u * 2862933555777941757LL + 7046029254386353087LL;
v ^= v >> 17; v ^= v << 31; v ^= v >> 8;
w = 4294957665U * (w & 0xffffffff) + (w >> 32);
Ullong x = u ^ (u << 21); x ^= x >> 35; x ^= x << 4;
return (x + v) ^ w; }
//inline unsigned int int32(){return (unsigned int)int64();} //!< private function
public:
CLargePeriodRNG() { setSeed(111); }
CLargePeriodRNG(unsigned int s) { setSeed(s); }
virtual ~CLargePeriodRNG() {}
public:
virtual void setSeed(unsigned int s) //!< Sets seed of the RNG.
{ v=4101842887655102017LL; w=1;
u = s ^ v; int64();
v = u; int64();
w = v; int64(); }
virtual unsigned int rndi() { return (unsigned int)int64(); } //!< Returns randomly generated unsigned int.
virtual double rnd() { return 5.42101086242752217E-20*int64(); } //!< Returns randomly generated double between 0 and 1.
};
//! \brief
//! Class for dynamic system uniform RNG.
class CDynamicSystemRNG : public CBaseRNG {
private:
#ifdef _MSC_VER
typedef __int64 Long;
#else
typedef long long int Long;
#endif
unsigned int k; //!< Paramters of the DS RNG.
unsigned int i, j; //!< Paramters of the DS RNG.
Long n; //!< Paramters of the DS RNG.
Array<long double,Dynamic,1> x; //!< Paramters of the DS RNG.
Array<long double,Dynamic,1> w; //!< Paramters of the DS RNG.
private:
Array<long double,Dynamic,1> prepare(unsigned int M); //!< Private function.
public:
CDynamicSystemRNG() { setSeed(1); }
CDynamicSystemRNG(unsigned int s) { setSeed(s); }
virtual ~CDynamicSystemRNG() {}
public:
virtual void setSeed(unsigned int s) //!< Sets seed of the RNG.
{ n=0;
const Array<long double,Dynamic,1> ir=prepare(s);
k=s;
x.resize(k);
w.resize(k);
for (i=0; i<k; i++)
{ w(i) = ir(i);
x(i) = 0.5L - w(i); } }
virtual unsigned int rndi() { return rnd()*UINT32_MAX; } //!< Returns randomly generated unsigned int.
virtual double rnd() //!< Returns randomly generated double between 0 and 1.
{ j = (n++)%k;
x(j) = x(j) + w(j);
x(j) = x(j) - (int)x(j);
return x(j); }
};
//! \brief
//! Class for uniform RNG with small period = 10^8.
#define NTAB 32
class CSmallPeriodRNG : public CBaseRNG {
private:
static long iy1; //!< Paramters of the small period RNG.
static long iv1[NTAB]; //!< Paramters of the small period RNG.
static long idum1; //!< Paramters of the small period RNG.
public:
CSmallPeriodRNG() { setSeed(111); }
CSmallPeriodRNG(unsigned int s) { setSeed(s); }
virtual ~CSmallPeriodRNG() {}
public:
virtual void setSeed(unsigned int s); //!< Sets seed of the RNG.
virtual unsigned int rndi() { return rnd()*UINT32_MAX; } //!< Returns randomly generated unsigned int.
virtual double rnd(); //!< Returns randomly generated double between 0 and 1.
};
#undef NTAB
//! \brief
//! Class for uniform RNG with medium period = 2 * 10^18.
#define NTAB 32
class CMediumPeriodRNG : public CBaseRNG {
private:
static long idum2; //!< Paramters of the medium period RNG.
static long iy2; //!< Paramters of the medium period RNG.
static long iv2[NTAB]; //!< Paramters of the medium period RNG.
static long idum; //!< Paramters of the medium period RNG.
public:
CMediumPeriodRNG() { setSeed(111); }
CMediumPeriodRNG(unsigned int s) { setSeed(s); }
virtual ~CMediumPeriodRNG() {}
public:
virtual void setSeed(unsigned int s); //!< Sets seed of the RNG.
virtual unsigned int rndi() { return rnd()*UINT32_MAX; } //!< Returns randomly generated unsigned int.
virtual double rnd(); //!< Returns randomly generated double between 0 and 1.
};
#undef NTAB
//! \brief
//! Class for uniform RNG which is not linearily congruential.
#define NTAB 32
class CNLCRNG : public CBaseRNG {
private:
static int inext,inextp; //!< Paramters of the nlc RNG.
static long ma[56]; //!< Paramters of the nlc RNG.
public:
CNLCRNG() { setSeed(111); }
CNLCRNG(unsigned int s) { setSeed(s); }
virtual ~CNLCRNG() {}
public:
virtual void setSeed(unsigned int s); //!< Sets seed of the RNG.
virtual unsigned int rndi() { return rnd()*UINT32_MAX; } //!< Returns randomly generated unsigned int.
virtual double rnd(); //!< Returns randomly generated double between 0 and 1.
};
#undef NTAB
//! \brief
//! Class for NOMAD RNG with period = 2^96-1.
class CNomadRNG : public CBaseRNG {
private:
static unsigned int x,y,z;
public:
public:
CNomadRNG() { setSeed(111); }
CNomadRNG(unsigned int s) { setSeed(s); }
virtual ~CNomadRNG() {}
public:
virtual void setSeed(unsigned int s) { x=s; } //!< Sets seed of the RNG.
virtual unsigned int rndi();
virtual double rnd() { return rndi()/UINT32_MAX; } //!< Returns randomly generated double between 0 and 1.
};
//! \brief
//! Class that holds all implemented uniform RNGs as static.
//! and allows switching between them.
class CRandomGenerator {
public:
enum rngtype {smallperiod, mediumperiod, nonlinearcongruential, largeperiod, nomads }; //!< Implemented RNG types.
static rngtype Type(std::string _stype); //!< Converts rng type name (string) to rngtype enumerator.
private:
static CSmallPeriodRNG sp; //!< Small period RNG, static.
static CMediumPeriodRNG mp; //!< Medium period RNG, static.
static CNLCRNG nlc; //!< Non linearily congruential RNG, static.
static CLargePeriodRNG lp; //!< Large period RNG, static.
static CNomadRNG mad; //!< Dynamic system RNG, static.
static CBaseRNG *p; //!< Poitner to the active RNG, static.
static enum rngtype type; //!< Type of the active RNG.
public:
static void Set(rngtype _type,unsigned int s=111); //!< Sets RNG of rngtype _type as active.
static void SetSmallPeriod(unsigned int s=111) { type=smallperiod; p=&sp; p->setSeed(s); } //!< Sets small period RNG as active.
static void SetMediumPeriod(unsigned int s=111) { type=mediumperiod; p=∓ p->setSeed(s); } //!< Sets medium period RNG as active.
static void SetNonlinearCongruential(unsigned int s=111) { type=nonlinearcongruential; p=&nlc; p->setSeed(s); } //!< Sets non lienarily congruential RNG as active.
static void SetLargePeriod(unsigned int s=111) { type=largeperiod; p=&lp; p->setSeed(s); } //!< Sets large period RNG as active.
static void SetNomads(unsigned int s=111) { type=nomads; p=&mad; p->setSeed(s); } //!< Sets dynamic system RNG as active.
static rngtype &Type() { return type; } //!< Returns type of the active RNG.
static void SetSeed(unsigned int s) { p->setSeed(s); } //!< Sets seed of the active RNG.
static unsigned int RndInt() { return p->rndi(); } //!< Returns an unsigned int randomly generated by the active RNG.
static double Rnd() { return p->rnd(); } //!< Returns a double between 0 and 1 randomly generated by the active RNG.
static double Rnd(double a,double b) { return p->rnd(a,b); } //!< Returns a double between a and b randomly generated by the active RNG.
};
#endif // CRANDOMGENERATORS_H
| [
"davor.kegalj@gmail.com"
] | davor.kegalj@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.