hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
acc5899e2c95db984a27d65911eeac7134921880
808
cpp
C++
tests/direct_Z3.cpp
finnhaedicke/metaSMT
949245da0bf0f3c042cb589aaea5d015e2ed9e9a
[ "MIT" ]
33
2015-04-09T14:14:25.000Z
2022-03-27T08:55:58.000Z
tests/direct_Z3.cpp
finnhaedicke/metaSMT
949245da0bf0f3c042cb589aaea5d015e2ed9e9a
[ "MIT" ]
28
2015-03-13T14:21:33.000Z
2019-04-02T07:59:34.000Z
tests/direct_Z3.cpp
finnhaedicke/metaSMT
949245da0bf0f3c042cb589aaea5d015e2ed9e9a
[ "MIT" ]
9
2015-04-22T18:10:51.000Z
2021-08-06T12:44:12.000Z
#define BOOST_TEST_MODULE direct_Z3 #include <metaSMT/DirectSolver_Context.hpp> #include <metaSMT/backend/Z3_Backend.hpp> #include <metaSMT/API/Comment.hpp> #include <metaSMT/API/SymbolTable.hpp> #include <metaSMT/API/Group.hpp> using namespace metaSMT::solver; using namespace metaSMT; struct Solver_Fixture { typedef DirectSolver_Context< IgnoreSymbolTable< IgnoreComments< Group< Z3_Backend > > > > ContextType; ContextType ctx ; }; #include "test_solver.cpp" #include "test_QF_BV.cpp" #include "test_QF_UF.cpp" #include "test_Array.cpp" #include "test_group.cpp" #include "test_unsat.cpp" #include "test_cardinality.cpp" #include "test_annotate.cpp" #include "test_stack.cpp" #include "test_Types.cpp" #include "test_simplify.cpp" #include "test_optimization.cpp" #include "test_evaluator.cpp"
27.862069
92
0.787129
finnhaedicke
acc69c9db7b1a263444b3ae7e66691765abff5f0
1,519
cpp
C++
codeforces/C - Vladik and Memorable Trip/Wrong answer on test 29 (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Vladik and Memorable Trip/Wrong answer on test 29 (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Vladik and Memorable Trip/Wrong answer on test 29 (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Jan/15/2018 21:53 * solution_verdict: Wrong answer on test 29 language: GNU C++14 * run_time: 202 ms memory_used: 2200 KB * problem: https://codeforces.com/contest/811/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long dp[5003],num[5003],n; map<long,long>mp; struct data { long first,last; } arr[5003]; int main() { cin>>n; for(long i=1; i<=n; i++) { cin>>num[i]; if(arr[num[i]].first==0)arr[num[i]].first=i; arr[num[i]].last=i; } for(long k=1; k<=n; k++) { for(long i=1;i<k;i++)dp[k]=max(dp[k],dp[i]); long x=num[k],f=0,xr=0; mp.clear(); for(long i=arr[x].first; i<=arr[x].last; i++) { if(arr[num[i]].first<arr[x].first||arr[num[i]].last>arr[x].last) { f=-1; break; } if(mp[num[i]]==0) { xr=xr^num[i]; mp[num[i]]=1; } } if(f==-1)xr=0; dp[arr[x].last]=max(dp[arr[x].last],dp[arr[x].first-1]+xr); } cout<<dp[n]<<endl; return 0; }
31.645833
111
0.366689
kzvd4729
acc8f060c7d4f3384ccd212e39f12feab0e0dfb7
1,298
cpp
C++
test/my_stress_test/topological_sort.test.cpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
1
2022-01-25T23:03:10.000Z
2022-01-25T23:03:10.000Z
test/my_stress_test/topological_sort.test.cpp
atree4728/competitive-library
1aaa4d2cf9283b9a1a3d4c7f114ff7b867ca2f8b
[ "CC0-1.0" ]
6
2021-10-06T01:17:04.000Z
2022-01-16T14:45:47.000Z
test/my_stress_test/topological_sort.test.cpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
null
null
null
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A" #include <algorithm> #include <cassert> #include <iostream> #include <numeric> #include <random> #include "lib/graph/topological_sort.hpp" using namespace std; random_device seed_gen; mt19937_64 rnd(seed_gen()); int rand() { return uniform_int_distribution<int>(0, 100000)(rnd); } void test() { for (size_t _ = 0; _ < 500000; _++) { size_t n = rand() % 20, m = n ? rand() % 30 : 0; bool is_cycle = rand() % 2; vector<size_t> ordered(n); iota(begin(ordered), end(ordered), 0); shuffle(begin(ordered), end(ordered), rnd); vector<vector<size_t>> ed(n); for (size_t i = 0; i < m; i++) { int a = rand() % n; int b = rand() % n; if (is_cycle and a >= b) continue; ed[ordered[a]].push_back(ordered[b]); } const auto ret = topological_sort(ed); if (is_cycle) assert(size(ret) == n); else assert(size(ret) <= n); vector<int> seen(n); for (const auto& i: ret) { assert(not seen[i]++); for (const auto& j: ed[i]) assert(not seen[j]); } } } int main() { test(); std::cout << "Hello World\n"; return 0; }
27.617021
84
0.548536
atree-GitHub
accb6cfdd522312fc4587578bb52b8cfaaf68860
313
hpp
C++
library/include/reduction/reduction.hpp
Grayson/reduction
ab35bd3dd74e58180e6bf6e126d202cf57169010
[ "BSD-2-Clause" ]
null
null
null
library/include/reduction/reduction.hpp
Grayson/reduction
ab35bd3dd74e58180e6bf6e126d202cf57169010
[ "BSD-2-Clause" ]
null
null
null
library/include/reduction/reduction.hpp
Grayson/reduction
ab35bd3dd74e58180e6bf6e126d202cf57169010
[ "BSD-2-Clause" ]
null
null
null
#include <string> #include <vector> #include <deduction/datatypes/parse-result.hpp> #include "bridge.hpp" namespace reduction { extern std::string const version; deduction::parse_result parse_json(std::string const & jsonString); std::vector<bridge> create_wrappers(deduction::parse_result parsedResults); }
26.083333
76
0.782748
Grayson
accc49848e423f82e730d58a4dc1967346b939a8
600
cpp
C++
xmd/src/stats/gyration.cpp
vitreusx/xmd
09f7df4b398f41f0e59abdced25998b53470f0a4
[ "MIT" ]
1
2021-12-16T02:26:30.000Z
2021-12-16T02:26:30.000Z
xmd/src/stats/gyration.cpp
vitreusx/xmd
09f7df4b398f41f0e59abdced25998b53470f0a4
[ "MIT" ]
null
null
null
xmd/src/stats/gyration.cpp
vitreusx/xmd
09f7df4b398f41f0e59abdced25998b53470f0a4
[ "MIT" ]
null
null
null
#include "stats/gyration.h" namespace xmd { void compute_gyration_radius::operator()() const { vec3r center_of_mass = vec3r::Zero(); real total_mass = 0.0; for (int idx = 0; idx < num_particles; ++idx) { center_of_mass += mass[idx] * r[idx]; total_mass += mass[idx]; } center_of_mass /= total_mass; real gyration_r = 0.0; for (int idx = 0; idx < num_particles; ++idx) { gyration_r += norm_squared(r[idx] - center_of_mass); } *gyration_radius = sqrt(gyration_r / num_particles); } }
30
64
0.565
vitreusx
acccbae1624cbc63fc8c43b515cef2f305680977
8,388
cpp
C++
src/servers/task_space_multiple_move_action_server.cpp
psh117/assembly_dual_controllers
2bbc10d83d4cb795dc145a6943283e2eb482c2e8
[ "MIT" ]
1
2021-08-03T05:31:01.000Z
2021-08-03T05:31:01.000Z
src/servers/task_space_multiple_move_action_server.cpp
psh117/assembly_dual_controllers
2bbc10d83d4cb795dc145a6943283e2eb482c2e8
[ "MIT" ]
2
2022-02-10T19:34:12.000Z
2022-02-11T09:02:39.000Z
src/servers/task_space_multiple_move_action_server.cpp
psh117/assembly_dual_controllers
2bbc10d83d4cb795dc145a6943283e2eb482c2e8
[ "MIT" ]
null
null
null
#include <assembly_dual_controllers/servers/task_space_multiple_move_action_server.h> #define EYE(X) Eigen::Matrix<double, X, X>::Identity() TaskSpaceMultipleMoveActionServer::TaskSpaceMultipleMoveActionServer(std::string name, ros::NodeHandle &nh, std::map<std::string, std::shared_ptr<FrankaModelUpdater> > &mu) : ActionServerBase(name,nh,mu), as_(nh,name,false) { as_.registerGoalCallback(boost::bind(&TaskSpaceMultipleMoveActionServer::goalCallback, this)); as_.registerPreemptCallback(boost::bind(&TaskSpaceMultipleMoveActionServer::preemptCallback, this)); as_.start(); for (auto & arm : mu) { const auto & arm_name = arm.first; sub_tasks_1_[arm_name] = SubTaskState(); sub_tasks_2_[arm_name] = SubTaskState(); sub_tasks_1_[arm_name].resize(2,dof); sub_tasks_2_[arm_name].resize(6,dof); } } void TaskSpaceMultipleMoveActionServer::goalCallback() { feedback_header_stamp_ = 0; goal_ = as_.acceptNewGoal(); ROS_INFO("[TaskSpaceMultipleMoveActionServer::goalCallback] Joint trajectory goal has been received."); int len_arms = goal_->arm_names.size(); bool active_more_than_one_arm {false}; Eigen::Isometry3d target_relative_pose[3]; for (int i=0; i< len_arms; ++i) { auto & arm_name = goal_->arm_names[i]; auto & target_pose = goal_->target_poses[i]; auto it = mu_.find(arm_name); if (it == mu_.end()) { ROS_WARN("[TaskSpaceMultipleMoveActionServer::goalCallback] Arm name %s does not exist in the arm names. Just passing it.", arm_name.c_str()); as_.setAborted(); return; } tf::poseMsgToEigen(target_pose, target_relative_pose[i]); std::cout<<target_pose.orientation.x<<std::endl; std::cout<<target_pose.orientation.y<<std::endl; std::cout<<target_pose.orientation.z<<std::endl; std::cout<<target_pose.orientation.w<<std::endl; if (target_relative_pose[i].translation().norm() > 0.5) { ROS_WARN("[TaskSpaceMultipleMoveActionServer::goalCallback] DO NOT USE THIS ACTION with over 50 cm movement goal. Just passing it."); as_.setAborted(); return; } if (Eigen::Quaterniond(target_relative_pose[i].linear()).angularDistance(Eigen::Quaterniond::Identity()) > 1.560796) { ROS_WARN("[TaskSpaceMultipleMoveActionServer::goalCallback] DO NOT USE THIS ACTION with over 90 degree rotation goal. Just passing it."); as_.setAborted(); return; } active_arms_[arm_name] = true; target_poses_[arm_name] = mu_[arm_name]->initial_transform_ * target_relative_pose[i]; active_more_than_one_arm = true; } if ( ! active_more_than_one_arm) { as_.setAborted(); return; } control_running_ = true; start_time_ = ros::Time::now(); } void TaskSpaceMultipleMoveActionServer::preemptCallback() { ROS_INFO("[%s] Preempted", action_name_.c_str()); as_.setPreempted(); } bool TaskSpaceMultipleMoveActionServer::compute(ros::Time time) { if (!as_.isActive()) return false; if(!control_running_) // wait for acceptance of the goal, active but not accepted return false; for (auto & active_arm : active_arms_) { if (active_arm.second == true) { computeArm(time, active_arm.first); } } return false; } bool TaskSpaceMultipleMoveActionServer::computeArm(ros::Time time, const std::string &arm_name) { FrankaModelUpdater &arm = *mu_[arm_name]; auto & target_pose = target_poses_[arm_name]; Eigen::Matrix<double, 7, 1> desired_torque; ros::Duration passed_time = time - start_time_; Eigen::Vector3d position_now; bool value_updated = false; Eigen::Vector3d p, p_dot, p_ddot; for(int i=0; i<3; i++) { auto result = dyros_math::quinticSpline(passed_time.toSec(), 0, goal_->execution_time, arm.initial_transform_.translation()(i), 0, 0, target_pose.translation()(i), 0, 0); p(i) = result(0); p_dot(i) = result(1); p_ddot(i) = result(2); } double kp = 1000, kv = 20; double kp_o = 4000, kv_o = 30; Eigen::Matrix3d desired_rotation; Eigen::Vector3d r_error, omega, omega_dot; dyros_math::rotationQuinticZero(passed_time.toSec(), 0, goal_->execution_time, arm.rotation_, target_pose.linear(), desired_rotation, omega, omega_dot); r_error = - 0.5 * dyros_math::getPhi(arm.rotation_, desired_rotation); // std::cout << "p: " << p.transpose() << std::endl // << "arm.position_: " << arm.position_.transpose() << std::endl // << "r_error: " << r_error.transpose() << std::endl // << "arm.xd_: " << arm.xd_.transpose() << std::endl // << "omega: " << omega.transpose() << std::endl // << "omega_dot: " << omega_dot.transpose() << std::endl; Eigen::Vector3d f_star = p_ddot + kp * (p - arm.position_) + kv * (p_dot - arm.xd_.head<3>()); Eigen::Vector3d m_star = omega_dot + kp_o * (r_error) + kv_o * (omega - arm.xd_.tail<3>()); // std::cout << "f_star: " << f_star.transpose() << std::endl // << "m_star: " << m_star.transpose() << std::endl; Eigen::Vector6d fm_star; fm_star << f_star, m_star; desired_torque = arm.jacobian_.transpose() * arm.modified_lambda_matrix_ * fm_star; ////////////////////////////////// Task Transition ///////////////////////////////////////// Eigen::MatrixXd A_inv_ = arm.modified_mass_matrix_.inverse(); auto & _task1 = sub_tasks_1_[arm_name]; auto & _task2 = sub_tasks_2_[arm_name]; _task1.J.setZero(); _task1.J(0, 0) = 1.0; _task1.J(1, 1) = 1.0; _task1.JT = _task1.J.transpose(); _task1.lambda_inv = _task1.J * A_inv_ * _task1.JT; _task1.lambda = _task1.lambda_inv.inverse(); _task1.J_barT = _task1.lambda * _task1.J * A_inv_; _task1.J_bar = _task1.J_barT.transpose(); _task1.NT = EYE(dof) - _task1.JT * _task1.J_barT; _task1.N = _task1.NT.transpose(); _task1.setActive2(-166.0/180.0*M_PI, 166.0/180.0*M_PI, arm.q_(0), true); _task1.setPotential_3(-166.0/180.0*M_PI, 166.0/180.0*M_PI, arm.q_(0), arm.qd_(0), true); _task1.setActive2(-101.0/180.0*M_PI, 101.0/180.0*M_PI, arm.q_(1), false); _task1.setPotential_3(-101.0/180.0*M_PI, 101.0/180.0*M_PI, arm.q_(1), arm.qd_(1), false); _task1.h = std::max(_task1.h1, _task1.h2); if (_task1.h > 0) { // std::cout << "Joint limit task" << std::endl; } _task2.J = arm.jacobian_; _task2.JT = _task2.J.transpose(); _task2.lambda_inv = _task2.J * A_inv_ * _task2.JT; _task2.lambda = _task2.lambda_inv.inverse(); //_limit_task.h = 0.0; _task2.f.head(3) = f_star; _task2.f.tail(3) = m_star; //std::cout << _task1.fi.transpose() << std::endl; _task1.fi = _task1.h * _task1.f + (1.0 - _task1.h) * _task1.J * A_inv_ * (_task2.JT * _task2.lambda * _task2.f); //_task1.fi = _task1.h * _task1.f; //std::cout << _task1.fi.transpose() << std::endl; _task2.fi = _task2.f; _task1.T = _task1.JT * _task1.lambda * _task1.fi; Eigen::Matrix6d lambda_12; Eigen::Matrix6d lambda_12_inv; lambda_12_inv = _task2.J * _task1.N * A_inv_ * _task1.NT * _task2.JT + 0.001*EYE(6); lambda_12 = lambda_12_inv.inverse(); desired_torque = _task1.T + _task1.NT * (_task2.JT * lambda_12 * _task2.fi); ///////////////////////////////////////////////////////////////////////////////////////////////////// //std::cout << "desired_torque" <<arm.q_(0)/M_PI*180.0 << std::endl; // std::cout<<"desried_torque: "<< desired_torque.transpose() <<std::endl; //desired_torque.setZero(); if(time.toSec() > (start_time_.toSec() + goal_->execution_time + 0.8)) { ROS_INFO("[TaskSpaceMultipleMoveActionServer::goalCallback] arriving to the goal"); std::cout << "position error: " << (target_pose.translation() - arm.position_).transpose() << std::endl; std::cout << "rotational error: " << r_error.transpose() << std::endl; arm.setInitialValues(target_pose); arm.idle_controlled_ = true; arm.setTorque(desired_torque, true); active_arms_[arm_name] = false; // check processing all arm is finished bool finished_all = true; for (auto & active_arm : active_arms_) { if (active_arm.second) { finished_all = false; } } // final arm if (finished_all) { control_running_ = false; as_.setSucceeded(); } return true; } arm.setTorque(desired_torque); return true; }
33.15415
154
0.64485
psh117
acd4aa4ca4e76780edb28760acb0eeb5785bc02e
813
cpp
C++
LeetCodeCPP/372. Super Pow/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
1
2019-03-29T03:33:56.000Z
2019-03-29T03:33:56.000Z
LeetCodeCPP/372. Super Pow/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
LeetCodeCPP/372. Super Pow/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
// // main.cpp // 372. Super Pow // // Created by admin on 2019/9/19. // Copyright © 2019年 liu. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { private: int base=1337; int pow(int a,int k){ a=a%base; int ret=1; for(int i=0;i<k;i++){ ret=(ret*a)%base; } return ret; } public: int superPow(int a, vector<int>& b) { if(b.empty()){ return 1; } int lastNum=b.back(); b.pop_back(); return pow(superPow(a,b),10)*pow(a,lastNum)%base; } }; int main(int argc, const char * argv[]) { Solution so=Solution(); vector<int> input={2,0}; int ret=so.superPow(2,input); cout<<"The ret is:"<<ret<<endl; return 0; }
18.477273
57
0.521525
18600130137
acde6a89a545d1d987c1f2f543190b53514306ad
26,855
cc
C++
oracle.cc
intraDAT/VShop2
028cde36a0462ffde5d244f40d45a1bca63c3957
[ "Apache-2.0" ]
null
null
null
oracle.cc
intraDAT/VShop2
028cde36a0462ffde5d244f40d45a1bca63c3957
[ "Apache-2.0" ]
null
null
null
oracle.cc
intraDAT/VShop2
028cde36a0462ffde5d244f40d45a1bca63c3957
[ "Apache-2.0" ]
null
null
null
#include <stdlib.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <stdio.h> #include <malloc.h> #include <time.h> #include <unistd.h> #ifndef VSADMIN #include "cgic.h" #include "hfct.h" #include "error.h" #endif #include "oracle.h" #ifdef WIN32 #include <process.h> #include "win32tools.h" #endif // // alter table TABLENAME drop SPALTE -> alter table TABLENAME delete column SPALTE // // (SYS.)ALL_TABLES // ALL_TAB_COLUMNS // ALL_INDEXES // ALL_IND_COLUMNS // // #ifdef VSADMIN char* Replace(char* QuellString,char* SuchString,char* ErsetzString) { char Buffer[8192]; char *ptr,*ptr2=QuellString; char *dest=Buffer; if (strstr(QuellString,SuchString)) { *dest=0; ptr=strstr(ptr2,SuchString); while ( ptr ) { while (ptr2<ptr) *dest++=*ptr2++; strcpy(dest,ErsetzString); dest= (char*)dest+strlen(ErsetzString); ptr2=(char*)ptr+strlen(SuchString); ptr=strstr(ptr2,SuchString); } if (ptr!=QuellString) { strcpy(dest,ptr2); strcpy(QuellString,Buffer); } } return(QuellString); } #endif /*--------------------------------------------------------------------------------*/ #ifndef VSADMIN int GetVar(char* VarName, char* VarValue) { int Ret = 0; char* Value; char ID[21]; Value = cgiString(VarName); if (Value == NULL) { if (cgiFormString("ID",ID,20) != cgiFormNotFound) { if ((Value = EngineDB->GetVar(ID,VarName)) != NULL) { strcpy(VarValue,Value); Ret = 1; } } } else { strcpy(VarValue,Value); Ret = 1; } return Ret; } #endif /*********************************************************************************/ // CField /*********************************************************************************/ CDBField::CDBField() { strcpy(Name,""); StringLength = 0; Long = 0; Double = 0; String = NULL; } /*--------------------------------------------------------------------------------*/ CDBField::CDBField(char* FieldName) { strcpy(Name, FieldName); Name[strcspn(Name," ")] = '\0'; StringLength = 0; Long = 0; Double = 0; String = NULL; } /*--------------------------------------------------------------------------------*/ CDBField::CDBField(char* FieldName, int NewStringLength) { strcpy(Name, FieldName); Name[strcspn(Name," ")] = '\0'; StringLength = 0; Long = 0; Double = 0; String = (char*) malloc(NewStringLength+1); StringLength = NewStringLength; memset (String, '\0', StringLength); } /*--------------------------------------------------------------------------------*/ CDBField::~CDBField() { if ((Type == FT_STRING) || (Type == FT_MEMO) || (Type == FT_DATE)) free(String); } /*********************************************************************************/ // CDBFieldList /*********************************************************************************/ CDBFieldList::CDBFieldList() { Items = new _Item; Items->Element = NULL; Items->Next = NULL; p = Items; } /*--------------------------------------------------------------------------------*/ CDBFieldList::~CDBFieldList() { // Clear(); // delete Items; } /*--------------------------------------------------------------------------------*/ void CDBFieldList::Add(CDBField* Item) { p = Items; while (p->Next != NULL) p = p->Next; p->Next = new _Item; p = p->Next; p->Element = Item; p->Next = NULL; // cout << "new " << p << " " << Item->Name << endl; } /*--------------------------------------------------------------------------------*/ void CDBFieldList::Clear() { _Item *tmp; p = Items->Next; while (p!=NULL) { tmp = p->Next; //cout << "free " << p << " " << p->Element->Name << endl; delete p; p = tmp; } Items->Next = NULL; } /*--------------------------------------------------------------------------------*/ CDBField* CDBFieldList::Seek(char* Name) { p = Items; while(p->Next != NULL) { if (strcasecmp(Name, p->Next->Element->Name) == 0) return p->Next->Element; p = p->Next; } return NULL; } /*--------------------------------------------------------------------------------*/ CDBField* CDBFieldList::Seek(int Index) { int Counter = 1; p = Items; while(p->Next != NULL) { if (Index == Counter) return p->Next->Element; Counter++; p = p->Next; } return NULL; } /*--------------------------------------------------------------------------------*/ CDBField* CDBFieldList::GetFirstItem() { p = Items; if (p->Next != NULL) { return p->Next->Element; } else return NULL; } /*--------------------------------------------------------------------------------*/ CDBField* CDBFieldList::GetItem() { p = Items; if (p->Next != NULL) { return p->Next->Element; } else return NULL; } /*--------------------------------------------------------------------------------*/ CDBField* CDBFieldList::GetNextItem() { p = p->Next; if (p->Next != NULL) { return p->Next->Element; } else return NULL; } /*--------------------------------------------------------------------------------*/ void CDBFieldList::SetNull() { return; p = Items; while(p->Next != NULL) { switch (((CDBField*) p->Next->Element)->Type) { case FT_STRING: case FT_MEMO: memset (((CDBField*)p->Next->Element)->String, '\0', ((CDBField*)p->Next->Element)->StringLength); break; case FT_LONG : case FT_BOOLEAN : memset (&((CDBField*)p->Next->Element)->Long, '\0', sizeof(((CDBField*)p->Next->Element)->Long)); break; case FT_DOUBLE : memset (&((CDBField*)p->Next->Element)->Double, '\0', sizeof(((CDBField*)p->Next->Element)->Double)); break; case FT_DATE : memset (&((CDBField*)p->Next->Element)->Date, '\0', sizeof(((CDBField*)p->Next->Element)->Date)); break; case FT_TIME : memset (&((CDBField*)p->Next->Element)->Time, '\0', sizeof(((CDBField*)p->Next->Element)->Time)); break; case FT_TIMESTAMP : memset (&((CDBField*)p->Next->Element)->TimeStamp, '\0', sizeof(((CDBField*)p->Next->Element)->TimeStamp)); break; } p = p->Next; } } /*********************************************************************************/ // CAdabas /*********************************************************************************/ CEngineDB::CEngineDB() { int Counter; numwidth = 8; LastError = 0; for (Counter = 0; Counter < MAX_SQLSELECT+1; Counter++) { /* mysqlda[Counter].sqlmax = MAX_SQLVAR; */ Row[Counter] = 0; NumRows[Counter] = 0; EndOfFile[Counter] = 0; } } /*--------------------------------------------------------------------------------*/ void CEngineDB::SQLError(Cda_Def *cda) { text msg[512]; sword n; LastError = (int) oerhms(&lda, cda->rc, msg, (sword) sizeof (msg)); #ifndef VSADMIN msg[strlen((char*) msg)-1] = '\0'; RuntimeError4((char*) msg,SQLVarQueryString); #endif //cerr << endl << msg << " ["<< SQLVarQueryString << "] "<< endl; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetLastError() { return LastError; } /*--------------------------------------------------------------------------------*/ int CEngineDB::Connect(char* ServerDB, char* Username, char* Password, char* Servernode) { int Counter; memset(hda,'\0',sizeof(hda)); if (olog(&lda, (ub1 *)hda, (text*) Username, -1, (text*) Password, -1,(text *) ServerDB, -1, (ub4)OCI_LM_DEF)) return 0; else { for (Counter = 0; Counter < MAX_SQLSELECT+1; Counter++) { if (oopen(&cda[Counter], &lda, (text *) 0, -1, -1, (text *) 0, -1)) { ologof(&lda); return 0; } } } return 1; return 0; } /*--------------------------------------------------------------------------------*/ CEngineDB::~CEngineDB() { int Counter; for (Counter = 0; Counter < MAX_SQLSELECT+1; Counter++) { oclose(&cda[Counter]); } ologof(&lda); } /*--------------------------------------------------------------------------------*/ void CEngineDB::Close() { int Counter; for (Counter = 0; Counter < MAX_SQLSELECT+1; Counter++) { oclose(&cda[Counter]); } ologof(&lda); } /*--------------------------------------------------------------------------------*/ int CEngineDB::Commit() { if (ocom(&lda)) return 0; return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::CreateSession(char* ID) { char Date[9]; char Time[7]; time_t TimeT; tm* Today; char Referer[500]; time(&TimeT); Today = localtime(&TimeT); sprintf(Date,"%i%.2i%.2i",Today->tm_year+1900,Today->tm_mon+1,Today->tm_mday); sprintf(Time,"%.2i%.2i%.2i",Today->tm_hour,Today->tm_min,Today->tm_sec); #ifndef VSADMIN strcpy(Referer,cgiReferer); strcat(Referer,""); if (strlen(Referer) > 119) Referer[118]='\0'; sprintf(SQLVarQueryString,"insert into SESSIONS (VSINDEX,ENTRYTIME,LASTUSAGE,REFERER,TOTALPAGES,USERIP,GATEWAY,OLD) values ('%s','%s%s','%s%s','%s',1,'%s','%s',0)", ID,Date,Time,Date,Time,Referer,cgiRemoteAddr,cgiRemoteHost); #endif if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } sprintf(SQLVarQueryString,"insert into SESSIONVAR (VSINDEX,NAME,VALUE) values ('%s','LOGIN','ANONYM')",ID); if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::UpdateSession(char* ID) { char Date[9]; char Time[6]; time_t TimeT; tm* Today; CDBField* DBField; time(&TimeT); Today = localtime(&TimeT); sprintf(Date,"%i%.2i%.2i",Today->tm_year+1900,Today->tm_mon+1,Today->tm_mday); sprintf(Time,"%.2i%.2i%.2i",Today->tm_hour,Today->tm_min,Today->tm_sec); sprintf(SQLVarQueryString,"update SESSIONS set LASTUSAGE='%s%s',TOTALPAGES=TOTALPAGES+1 where VSINDEX='%s' AND OLD=0 ", Date,Time,ID); //cerr << endl << SQLVarQueryString << endl; if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } //cerr << endl << "UpdateSession returned 1" << endl; return cda[MAX_SQLSELECT].rpc > 0; } /*--------------------------------------------------------------------------------*/ int CEngineDB::UpdateVar(char* ID,char* VarName,char* VarValue) { sprintf(SQLVarQueryString,"update SESSIONVAR set VALUE='%s' where VSINDEX='%s' and NAME='%s'",VarValue,ID,VarName); // cerr << endl << SQLVarQueryString << endl; if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } return cda[MAX_SQLSELECT].rpc > 0; } /*--------------------------------------------------------------------------------*/ int CEngineDB::InsertVar(char* ID,char* VarName,char* VarValue) { if (strlen(VarValue) < 150) { sprintf(SQLVarQueryString,"insert into SESSIONVAR (VSINDEX,NAME,VALUE) values ('%s','%s','%s')",ID,VarName,VarValue); //cerr << endl << SQLVarQueryString << endl; if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } return cda[MAX_SQLSELECT].rpc > 0;; } else return 0; } /*--------------------------------------------------------------------------------*/ char* CEngineDB::GetVar(char* ID,char* VarName) { CDBField* DBField; sprintf(SQLVarQueryString,"select VALUE from SESSIONVAR where VSINDEX='%s' AND NAME='%s'",ID,VarName); if (SQLSelect(MAX_SQLSELECT,SQLVarQueryString) == 1) { DBField = GetField(MAX_SQLSELECT,1); } else return NULL; return DBField->String; } /*--------------------------------------------------------------------------------*/ int CEngineDB::DescribeFields(int Index, Cda_Def *cda) { CDBField* DBField; sword col, deflen, deftyp; static ub1 *defptr; DBFieldList[Index].Clear(); /* Describe the select-list items. */ for (col = 0; col < MAX_SELECT_LIST_SIZE; col++) { DBField = new CDBField(); DBField->buflen = MAX_NAMELENGTH; if (odescr(cda, col + 1, &DBField->dbsize, &DBField->dbtype, (sb1*) &DBField->Name[0], &DBField->buflen, &DBField->dsize, &DBField->precision, &DBField->scale, &DBField->nullok)) { delete DBField; /* Break on end of select list. */ if (cda->rc == VAR_NOT_IN_LIST) break; else { SQLError(cda); return 0; } } DBField->Name[strcspn(DBField->Name," ")] = '\0'; switch (DBField->dbtype) { case NUMBER_TYPE: DBField->dbsize = numwidth; /* Handle NUMBER with scale as float. */ if (DBField->scale != 0) { defptr = (ub1 *) &DBField->flt_buf; deflen = (sword) sizeof(float); deftyp = FLOAT_TYPE; DBField->dbtype = FLOAT_TYPE; DBField->Type = FT_DOUBLE; DBField->Col = col; } else { defptr = (ub1 *) &DBField->int_buf; deflen = (sword) sizeof(sword); deftyp = INT_TYPE; DBField->dbtype = INT_TYPE; DBField->Type = FT_LONG; DBField->Col = col; } break; case DATE_TYPE: deftyp = SQLT_DAT; DBField->String = (char*) malloc(7 + 1); DBField->StringLength = 7 + 1; defptr = (ub1 *) DBField->String; deflen = 7; DBField->dbtype = SQLT_DAT; DBField->Type = FT_DATE; DBField->Col = col; break; default: if (DBField->dbtype == ROWID_TYPE) DBField->dbsize = 18; DBField->String = (char*) malloc(DBField->dbsize + 1); DBField->StringLength = DBField->dbsize + 1; deflen = DBField->dbsize+1; defptr = (ub1 *) DBField->String; deftyp = STRING_TYPE; DBField->Type = FT_STRING; DBField->Col = col; break; } if (odefin(cda, col + 1, defptr, deflen, deftyp, -1, &DBField->indp, (text *) 0, -1, -1, &DBField->col_retlen, &DBField->col_retcode)) { SQLError(cda); return 0; } DBFieldList[Index].Add(DBField); } return col; } /*--------------------------------------------------------------------------------*/ int CEngineDB::SQLSelect(int Index, char* SQLString) { strcpy(SQLVarQueryString,SQLString); while (strstr(SQLVarQueryString,"=''") != NULL) { strcpy(SQLVarQueryString,Replace(SQLVarQueryString,"=''"," IS NULL")); } while (strstr(SQLVarQueryString,"= ''") != NULL) { strcpy(SQLVarQueryString,Replace(SQLVarQueryString,"= ''"," IS NULL")); } //cerr << endl << "SQL[" << Index << "][" << SQLVarQueryString << "]" << endl; Row[Index] = 0; EndOfFile[Index] = 1; if (oparse(&cda[Index], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[Index]); return 0; } if ((NumCols[Index] = DescribeFields(Index, &cda[Index])) == -1) return 0; if (oexec(&cda[Index])) { SQLError(&cda[Index]); return 0; } if (ofetch(&cda[Index])) { //cerr << endl << "RETURN 0" << endl; if (cda[Index].rc != 0) return 0; } EndOfFile[Index] = 0; NumRows[Index] = cda[Index].rpc; Row[Index] = cda[Index].rpc; //cerr << endl << "SQL-RPC[" << cda[Index].rpc << "]" << endl; return 1; } int CEngineDB::SQL(char* SQLString) { return SQLUpdate(SQLString); } /*--------------------------------------------------------------------------------*/ int CEngineDB::SQLUpdate(char* SQLString) { char* Ptr; int i; char Buffer[1000]; strcpy(SQLVarQueryString, SQLString); i = 0; while(SQLVarQueryString[i]) { SQLVarQueryString[i]=tolower(SQLVarQueryString[i]); i++; } if ((Ptr = strstr (SQLVarQueryString, "where")) != NULL) { strcpy(SQLVarQueryString, SQLString); strcpy(Buffer, Ptr); while (strstr(Buffer,"=''") != NULL) { strcpy(Buffer,Replace(Buffer,"=''"," IS NULL")); } while (strstr(Buffer,"= ''") != NULL) { strcpy(Buffer,Replace(Buffer,"= ''"," IS NULL")); } strcpy(Ptr, Buffer); } else strcpy(SQLVarQueryString, SQLString); if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::SQLInsert(char* SQLString,char* ID) { long t; int Ret; #ifndef HPUX long c; #endif time(&t); #ifndef HPUX #ifdef WIN32 c=_getpid() % 100; #else c=getpid() % 100; #endif sprintf(ID,"%ld%ld",t,c); #else sprintf(ID,"%ld",t); #endif do { sprintf(SQLVarQueryString,"insert into %s (VSINDEX) values ('%s')",SQLString,ID); if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } Ret = oexec(&cda[MAX_SQLSELECT]); if (Ret) { t += 1; #ifndef HPUX sprintf(ID,"%ld%ld",t,c); #else sprintf(ID,"%ld",t); #endif } } while(Ret); return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::SQLCreate(char* TableName,char* OldTable) { sprintf(SQLVarQueryString,"create table %s as select * from %s",TableName,OldTable); if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::SQLDrop(char* TableName) { sprintf(SQLVarQueryString,"drop table %s",TableName); if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::SQLDelete(char* TableName, char* Index) { int Ret; sprintf(SQLVarQueryString,"delete from %s where VSINDEX='%s'",TableName,Index); if (oparse(&cda[MAX_SQLSELECT], (text *) SQLVarQueryString, (sb4) -1,(sword) PARSE_NO_DEFER, (ub4) PARSE_V7_LNG)) { SQLError(&cda[MAX_SQLSELECT]); return 0; } if (oexec(&cda[MAX_SQLSELECT])) { SQLError(&cda[MAX_SQLSELECT]); return 0; } return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::IsEOF(int SelectIndex) { return EndOfFile[SelectIndex]; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetFirst(int SelectIndex) { return 0; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetLast(int SelectIndex) { return 0; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetNext(int SelectIndex) { if (ofetch(&cda[SelectIndex])) { if (cda[SelectIndex].rc != 0) { EndOfFile[SelectIndex] = 1; return 0; } } Row[SelectIndex] = cda[SelectIndex].rpc; return 1; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetPrev(int SelectIndex) { return 0; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetAt(int SelectIndex, int Position) { return 0; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetCurrentRow(int SelectIndex) { return cda[SelectIndex].rpc; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetNumRows(int SelectIndex) { // return NumRows[SelectIndex]; return cda[SelectIndex].rpc; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetNumCols(int SelectIndex) { return NumCols[SelectIndex]; } /*--------------------------------------------------------------------------------*/ CDBField* CEngineDB::SetField(CDBField* DBField, int Index) { struct tm TM; char TimeBuffer[25]; if (DBField != NULL) { /* if (DBField->indp < 0) DBField->Indicator = -1; */ DBField->Indicator = 0; switch (DBField->Type) { case FT_STRING: //cerr << endl << " FeldInhalt von "<<DBField->Name<<" : ["<< DBField->String << "] "<< endl; break; case FT_DATE: memcpy(&DBField->DateEx,DBField->String,7); if (DBField->DateEx._year < 100) { DBField->DateEx.year = 100*(100-DBField->DateEx._century) + (100-DBField->DateEx._year); } else { DBField->DateEx.year = 100*(DBField->DateEx._century-100) + (DBField->DateEx._year-100); } sprintf(DBField->Time,"%02d%02d%02d", DBField->DateEx.hour, DBField->DateEx.minute, DBField->DateEx.second); sprintf(DBField->Date,"%04d%02d%02d", DBField->DateEx.year, DBField->DateEx.month, DBField->DateEx.day); sprintf(DBField->TimeStamp,"%04d%02d%02d%02d%02d%02d000000", DBField->DateEx.year, DBField->DateEx.month, DBField->DateEx.day, DBField->DateEx.hour, DBField->DateEx.minute, DBField->DateEx.second); sprintf(TimeBuffer,"%04d%02d%02d%02d%02d%02d", DBField->DateEx.year, DBField->DateEx.month, DBField->DateEx.day, DBField->DateEx.hour, DBField->DateEx.minute, DBField->DateEx.second); //strptime(TimeBuffer,"%Y%m%d%H%M%S",&TM); DBField->TimeInSeconds = mktime(&TM); break; case FT_DOUBLE: if (DBField->indp < 0) DBField->Double = 0; else DBField->Double = DBField->flt_buf; break; case FT_LONG: if (DBField->indp < 0) DBField->Long = 0; else DBField->Long = DBField->int_buf; break; } } return DBField; } /*--------------------------------------------------------------------------------*/ CDBField* CEngineDB::GetField(int SelectIndex, char* FieldName) { return SetField(DBFieldList[SelectIndex].Seek(FieldName), SelectIndex); } /*--------------------------------------------------------------------------------*/ CDBField* CEngineDB::GetField(int SelectIndex, int Index) { return SetField(DBFieldList[SelectIndex].Seek(Index), SelectIndex); } /*--------------------------------------------------------------------------------*/ CDBField* CEngineDB::GetFirstField(int SelectIndex) { return SetField(DBFieldList[SelectIndex].GetFirstItem(), SelectIndex); } /*--------------------------------------------------------------------------------*/ CDBField* CEngineDB::GetNextField(int SelectIndex) { return SetField(DBFieldList[SelectIndex].GetNextItem(), SelectIndex); } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetFirstListField(char* Category,char* ColumnName, char* Name, char* Value) { CDBField* ListField; strcpy(SQLVarQueryString,"SELECT LISTS.VSINDEX,LISTS.CATEGORY, LISTS.COLUMNNAME, LISTITEMS.LISTINDEX, LISTITEMS.NAME, "); strcat(SQLVarQueryString,"LISTITEMS.VALUE FROM LISTS,LISTITEMS WHERE"); strcat(SQLVarQueryString,"(LISTS.VSINDEX = LISTITEMS.LISTINDEX) AND (LISTS.CATEGORY='"); strcat(SQLVarQueryString,Category); strcat(SQLVarQueryString,"') AND (LISTS.COLUMNNAME='"); strcat(SQLVarQueryString,ColumnName); strcat(SQLVarQueryString,"')"); if (SQLSelect(MAX_SQLSELECT,SQLVarQueryString) == 0) return 0; if ((ListField = GetField(MAX_SQLSELECT,5)) != NULL) { strcpy(Name,ListField->String); if ((ListField = GetField(MAX_SQLSELECT,6)) != NULL) { strcpy(Value,ListField->String); return 1; } } return 0; } /*--------------------------------------------------------------------------------*/ int CEngineDB::GetNextListField(char* Name, char* Value) { CDBField* ListField; if (GetNext(MAX_SQLSELECT) == 0) return 0; if ((ListField = GetField(MAX_SQLSELECT,5)) != NULL) { strcpy(Name,ListField->String); if ((ListField = GetField(MAX_SQLSELECT,6)) != NULL) { strcpy(Value,ListField->String); return 1; } } return 0; } /*--------------------------------------------------------------------------------*/ #ifndef VSADMIN CEngineDB* EngineDB; #endif
25.168697
166
0.482517
intraDAT
ace12355cb4c5c6690d6b3b1d7ff5b230e038084
3,284
cpp
C++
bindgen/ir/Function.cpp
ekrich/scala-native-bindgen
df13474833c2fe01691e63e57c2cd9d1a623db20
[ "BSD-3-Clause" ]
8
2018-05-18T19:09:55.000Z
2018-07-02T14:42:07.000Z
bindgen/ir/Function.cpp
ekrich/scala-native-bindgen
df13474833c2fe01691e63e57c2cd9d1a623db20
[ "BSD-3-Clause" ]
111
2018-05-24T18:50:22.000Z
2018-08-22T12:54:42.000Z
bindgen/ir/Function.cpp
ekrich/scala-native-bindgen
df13474833c2fe01691e63e57c2cd9d1a623db20
[ "BSD-3-Clause" ]
1
2018-06-25T20:00:15.000Z
2018-06-25T20:00:15.000Z
#include "Function.h" #include "../Utils.h" #include "Struct.h" #include "Union.h" #include <sstream> Parameter::Parameter(std::string name, std::shared_ptr<const Type> type) : TypeAndName(std::move(name), type) {} Function::Function(const std::string &name, std::vector<std::shared_ptr<Parameter>> parameters, std::shared_ptr<const Type> retType, bool isVariadic) : name(name), scalaName(name), parameters(std::move(parameters)), retType(std::move(retType)), isVariadic(isVariadic) {} std::string Function::getDefinition(const LocationManager &locationManager) const { std::stringstream s; if (scalaName != name) { s << " @native.link(\"" << name << "\")\n"; } s << " def " << handleReservedWords(scalaName) << "("; std::string sep = ""; for (const auto &param : parameters) { s << sep << handleReservedWords(param->getName()) << ": " << param->getType()->str(locationManager); sep = ", "; } if (isVariadic) { /* the C Iso require at least one argument in a variadic function, so * the comma is fine */ s << ", " << getVarargsParameterName() << ": native.CVararg*"; } s << "): " << retType->str(locationManager) << " = native.extern\n"; return s.str(); } bool Function::usesType( std::shared_ptr<const Type> type, bool stopOnTypeDefs, std::vector<std::shared_ptr<const Type>> &visitedTypes) const { visitedTypes.clear(); if (*retType == *type || retType.get()->usesType(type, stopOnTypeDefs, visitedTypes)) { return true; } for (const auto &parameter : parameters) { visitedTypes.clear(); if (*parameter->getType() == *type || parameter->getType().get()->usesType(type, stopOnTypeDefs, visitedTypes)) { return true; } } return false; } std::string Function::getName() const { return name; } std::string Function::getVarargsParameterName() const { std::string parameterName = "varArgs"; int i = 0; while (existsParameterWithName(parameterName)) { parameterName = "varArgs" + std::to_string(i++); } return parameterName; } bool Function::existsParameterWithName(const std::string &parameterName) const { for (const auto &parameter : parameters) { if (parameter->getName() == parameterName) { return true; } } return false; } void Function::setScalaName(std::string scalaName) { this->scalaName = std::move(scalaName); } bool Function::isLegalScalaNativeFunction() const { /* Return type and parameters types cannot be array types because array type * in this case is always represented as a pointer to element type */ if (isAliasForType<Struct>(retType.get()) || isAliasForType<Union>(retType.get()) || isAliasForOpaqueType(retType.get())) { return false; } for (const auto &parameter : parameters) { if (isAliasForType<Struct>(parameter->getType().get()) || isAliasForType<Union>(parameter->getType().get()) || isAliasForOpaqueType(parameter->getType().get())) { return false; } } return true; }
33.510204
80
0.605968
ekrich
ace321cbc06551b85a66114a6665dcd3471b4333
5,412
hpp
C++
include/havoqgt/impl/edge_data.hpp
niklas-uhl/havoqgt
24df89686c8ca52b9f18ac86ba4e94689da2242e
[ "MIT" ]
23
2017-05-15T08:33:00.000Z
2022-01-22T17:28:03.000Z
include/havoqgt/impl/edge_data.hpp
niklas-uhl/havoqgt
24df89686c8ca52b9f18ac86ba4e94689da2242e
[ "MIT" ]
5
2020-09-25T15:32:47.000Z
2021-03-16T15:39:35.000Z
include/havoqgt/impl/edge_data.hpp
niklas-uhl/havoqgt
24df89686c8ca52b9f18ac86ba4e94689da2242e
[ "MIT" ]
12
2017-02-09T15:30:29.000Z
2021-12-13T10:19:26.000Z
// Copyright 2013-2020 Lawrence Livermore National Security, LLC and other // HavoqGT Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: MIT #ifndef HAVOQGT_MPI_IMPL_EDGE_DATA_HPP_ #define HAVOQGT_MPI_IMPL_EDGE_DATA_HPP_ #include <havoqgt/delegate_partitioned_graph.hpp> namespace havoqgt { template <typename Allocator> template <typename T, typename AllocatorOther> class delegate_partitioned_graph<Allocator>::edge_data { public: typedef typename bip::vector< T, other_allocator<AllocatorOther, T>>::iterator iterator; typedef T value_type; T& operator[](const edge_iterator& itr) { if (itr.m_source.is_delegate()) { assert(itr.m_edge_offset < m_delegate_edge_data.size()); return m_delegate_edge_data[itr.m_edge_offset]; } assert(itr.m_edge_offset < m_owned_edge_data.size()); return m_owned_edge_data[itr.m_edge_offset]; } const T& operator[](const edge_iterator& itr) const { if (itr.m_source.is_delegate()) { assert(itr.m_edge_offset < m_delegate_edge_data.size()); return m_delegate_edge_data[itr.m_edge_offset]; } assert(itr.m_edge_offset < m_owned_edge_data.size()); return m_owned_edge_data[itr.m_edge_offset]; } void reset(const T& r) { for (size_t i = 0; i < m_owned_edge_data.size(); ++i) { m_owned_edge_data[i] = r; } for (size_t i = 0; i < m_delegate_edge_data.size(); ++i) { m_delegate_edge_data[i] = r; } } iterator delegate_begin() { return m_delegate_edge_data.begin(); } iterator delegate_end() { return m_delegate_edge_data.end(); } iterator owned_begin() { return m_owned_edge_data.begin(); } iterator owned_end() { return m_owned_edge_data.end(); } // private: friend class delegate_partitioned_graph; edge_data(const delegate_partitioned_graph& dpg, AllocatorOther allocate = AllocatorOther() ) : m_owned_edge_data(allocate) , m_delegate_edge_data(allocate) { //m_owned_edge_data.resize(dpg.m_owned_targets_size); //m_delegate_edge_data.resize(dpg.m_delegate_targets_size); resize(dpg); } edge_data(AllocatorOther allocate = AllocatorOther() ) : m_owned_edge_data(allocate) , m_delegate_edge_data(allocate) {} void resize(const delegate_partitioned_graph& dpg) { m_owned_edge_data.resize(dpg.m_owned_targets_size); m_delegate_edge_data.resize(dpg.m_delegate_targets_size); } // edge_data(uint64_t owned_size, uint64_t delegate_size, // SegManagerOther* sm); // edge_data(uint64_t owned_size, uint64_t delegate_size, const T& init, // SegManagerOther* sm); // private: protected: bip::vector< T, other_allocator<AllocatorOther, T>> m_owned_edge_data; bip::vector< T, other_allocator<AllocatorOther, T>> m_delegate_edge_data; }; //////////////////////////////////////////////////////////////////////////////// // edge_data // //////////////////////////////////////////////////////////////////////////////// // template <typename SegmentManager> // template<typename T, typename Allocator> // delegate_partitioned_graph<SegmentManager>::edge_data<T,Allocator>:: // edge_data(const delegate_partitioned_graph& dpg, Allocator allocate = // Allocator() ) // : m_owned_edge_data(allocate) // , m_delegate_edge_data(allocate) { // m_owned_vert_data.resize(dpg.m_owned_targets.size()); // m_delegate_data.resize(dpg.m_delegate_targets.size()); // } // // // template <typename SegmentManager> // template<typename T, typename Allocator> // delegate_partitioned_graph<SegmentManager>::edge_data<T,Allocator>:: // edge_data(uint64_t owned_size, uint64_t delegate_size, SegManagerOther* sm) // : m_owned_edge_data(sm->template get_allocator<T>()) // , m_delegate_edge_data(sm->template get_allocator<T>()) { // m_owned_edge_data.resize(owned_size); // m_delegate_edge_data.resize(delegate_size); // } // // template <typename SegmentManager> // template<typename T, typename Allocator> // delegate_partitioned_graph<SegmentManager>::edge_data<T, Allocator>:: // edge_data(uint64_t owned_size, uint64_t delegate_size, const T& init, // SegManagerOther* sm) // : m_owned_edge_data(owned_size, init, sm->template get_allocator<T>()) // , m_delegate_edge_data(delegate_size, init, sm->template // get_allocator<T>()) { } // template <typename SegmentManager> // template<typename T, typename Allocator> // T& // delegate_partitioned_graph<SegmentManager>::edge_data<T, Allocator>:: // operator[](const edge_iterator& itr) { // if(itr.m_source.is_delegate()) { // assert(itr.m_edge_offset < m_delegate_edge_data.size()); // return m_delegate_edge_data[itr.m_edge_offset]; // } // assert(itr.m_edge_offset < m_owned_edge_data.size()); // return m_owned_edge_data[itr.m_edge_offset]; // } // // template <typename SegmentManager> // template<typename T, typename Allocator> // const T& // delegate_partitioned_graph<SegmentManager>::edge_data<T, // Allocator>::operator[](const edge_iterator& itr) const { // if(itr.m_source.is_delegate()) { // assert(itr.m_edge_offset < m_delegate_edge_data.size()); // return m_delegate_edge_data[itr.m_edge_offset]; // } // assert(itr.m_edge_offset < m_owned_edge_data.size()); // return m_owned_edge_data[itr.m_edge_offset]; // } } // namespace havoqgt #endif // HAVOQGT_MPI_IMPL_EDGE_DATA_HPP_
37.846154
95
0.705654
niklas-uhl
ace3564985be311e78be2035dca989ef3daffa5d
11,094
cpp
C++
src/graphics/maptools/texgen/tiledb.cpp
Terebinth/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
117
2015-01-13T14:48:49.000Z
2022-03-16T01:38:19.000Z
src/graphics/maptools/texgen/tiledb.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
4
2015-05-01T13:09:53.000Z
2017-07-22T09:11:06.000Z
src/graphics/maptools/texgen/tiledb.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
78
2015-01-13T09:27:47.000Z
2022-03-18T14:39:09.000Z
/*******************************************************************************\ TileDB.cpp Provides an interface to the tile database written by the tile tool. At present this is only used by the TexGen tool. Scott Randolph Spectrum HoloByte October 8, 1996 \*******************************************************************************/ #include <stdio.h> #include <math.h> #include "TileDB.h" // Terrain and feature types defined in the the visual basic tile tool // (Not all are features, but we have the whole list here for completeness sake) const int COVERAGE_WATER = 1; const int COVERAGE_RIVER = 2; const int COVERAGE_SWAMP = 3; const int COVERAGE_PLAINS = 4; const int COVERAGE_BRUSH = 5; const int COVERAGE_THINFOREST = 6; const int COVERAGE_THICKFOREST = 7; const int COVERAGE_ROCKY = 8; const int COVERAGE_URBAN = 9; const int COVERAGE_ROAD = 10; const int COVERAGE_RAIL = 11; const int COVERAGE_BRIDGE = 12; const int COVERAGE_RUNWAY = 13; const int COVERAGE_STATION = 14; void TileDatabase::Load(char *filename) { HANDLE inputFile; DWORD bytes; char message[80]; int tile; // Open the texture tile database for reading inputFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (inputFile == INVALID_HANDLE_VALUE) { PutErrorString(message); strcat(message, ": Failed tile database open"); ShiError(message); } // Read the file header ReadFile(inputFile, &header, 29, &bytes, NULL); if (bytes != 29) { PutErrorString(message); strcat(message, ": Failed file header read"); ShiError(message); } // Verify the file header if (strncmp(header.title, "TILE DATABASE O", sizeof(header.title)) != 0) { ShiError("Unrecognized file header"); } if (strncmp(header.version, "1.1 ", sizeof(header.version)) != 0) { ShiError("Unrecognized file version"); } // Allocate memory for the tile list header.tiles = (TileRecord*)malloc(header.numTiles * sizeof(*header.tiles)); // Loop for each tile for (tile = 0; tile < header.numTiles; tile++) { ReadTile(inputFile, &header.tiles[tile]); } // Close the tile database CloseHandle(inputFile); } void TileDatabase::Free(void) { int tile, feature; for (tile = 0; tile < header.numTiles; tile++) { for (feature = 0; feature < header.tiles[tile].numFeatures; feature++) { free(header.tiles[tile].features[feature].points); header.tiles[tile].features[feature].points = NULL; } free(header.tiles[tile].colors); free(header.tiles[tile].elevations); free(header.tiles[tile].features); free(header.tiles[tile].paths); free(header.tiles[tile].areas); header.tiles[tile].colors = NULL; header.tiles[tile].elevations = NULL; header.tiles[tile].features = NULL; header.tiles[tile].areas = NULL; header.tiles[tile].paths = NULL; } free(header.tiles); header.tiles = NULL; memset(&header, 0, sizeof(header)); } void TileDatabase::ReadTile(HANDLE inputFile, TileRecord *tile) { DWORD bytes; char string[8]; char message[80]; char codeString[8]; int feature; DWORD arraySize; // Read the tile record header ReadFile(inputFile, tile, 17, &bytes, NULL); if (bytes != 17) { PutErrorString(message); strcat(message, ": Failed the tile header read"); ShiError(message); } // Extract the original tile code from the file name strcpy(codeString, "0x"); strncpy(&codeString[2], &tile->basename[5], 3); sscanf(codeString, "%hx", &tile->code); // Read and verify the color record header ReadFile(inputFile, &string, 4, &bytes, NULL); if (strncmp(string, "CLR ", 4) != 0) { PutErrorString(message); strcat(message, ": Failed the color tag read/verify"); ShiError(message); } // Allocate the memory for the color array arraySize = header.gridXsize * header.gridYsize * 4; tile->colors = (colorRecord*)malloc(arraySize); ShiAssert(tile->colors); // Read the color array ReadFile(inputFile, tile->colors, arraySize, &bytes, NULL); if (bytes != arraySize) { PutErrorString(message); strcat(message, ": Failed the color read"); ShiError(message); } // Read and verify the elevation record header ReadFile(inputFile, &string, 4, &bytes, NULL); if (strncmp(string, "ELEV", 4) != 0) { PutErrorString(message); strcat(message, ": Failed the color tag read/verify"); ShiError(message); } // Allocate the memory for the elevation array arraySize = header.gridXsize * header.gridYsize * 3; tile->elevations = (elevationRecord*)malloc(arraySize); ShiAssert(tile->elevations); // Read the elevation array ReadFile(inputFile, tile->elevations, arraySize, &bytes, NULL); if (bytes != arraySize) { PutErrorString(message); strcat(message, ": Failed the elevation read"); ShiError(message); } // Read and verify the feature record header ReadFile(inputFile, &string, 4, &bytes, NULL); if (strncmp(string, "FEAT", 4) != 0) { PutErrorString(message); strcat(message, ": Failed the feature group tag read/verify"); ShiError(message); } // Allocate memory for the features in this tile tile->features = (FeatureRecord*)malloc(tile->numFeatures * sizeof(*tile->features)); tile->sortedFeatures = (FeatureRecord**)malloc(tile->numFeatures * sizeof(void*)); tile->nareas = 0; tile->npaths = 0; // Read each feature description and count types for (feature = 0; feature < tile->numFeatures; feature++) { ReadFeature(inputFile, &tile->features[feature]); tile->sortedFeatures[feature] = &tile->features[feature]; if (typeIsPath(tile->features[feature].type)) { // Make sure each path has at least two defining points ShiAssert(tile->features[feature].numPoints >= 2); tile->npaths += tile->features[feature].numPoints - 1; } else { // Make sure each area has exactly one center point ShiAssert(tile->features[feature].numPoints == 1); tile->nareas++; } } // Sort the feature descriptions by type SortArray(tile->sortedFeatures, tile->numFeatures); // Build the path and area records as appropriate for each feature tile->areas = (AreaRecord*)malloc(tile->nareas * sizeof(AreaRecord)); tile->paths = (PathRecord*)malloc(tile->npaths * sizeof(PathRecord)); ShiAssert(tile->areas); ShiAssert(tile->paths); int areaIndex = 0; int pathIndex = 0; for (feature = 0; feature < tile->numFeatures; feature++) { if (typeIsPath(tile->features[feature].type)) { int pntIndex = 1; while (pntIndex < tile->features[feature].numPoints) { ShiAssert(pathIndex < tile->npaths); tile->paths[pathIndex].type = tile->features[feature].type; tile->paths[pathIndex].size = tile->features[feature].size; tile->paths[pathIndex].x1 = tile->features[feature].points[pntIndex - 1].x; tile->paths[pathIndex].y1 = tile->features[feature].points[pntIndex - 1].y; tile->paths[pathIndex].x2 = tile->features[feature].points[pntIndex].x; tile->paths[pathIndex].y2 = tile->features[feature].points[pntIndex].y; pathIndex++; pntIndex++; } } else { ShiAssert(areaIndex < tile->nareas); tile->areas[areaIndex].type = tile->features[feature].type; tile->areas[areaIndex].size = tile->features[feature].size; tile->areas[areaIndex].x = tile->features[feature].points[0].x; tile->areas[areaIndex].y = tile->features[feature].points[0].y; areaIndex++; } } } void TileDatabase::ReadFeature(HANDLE inputFile, FeatureRecord *feature) { DWORD bytes; char message[80]; // Read the feature record header ReadFile(inputFile, feature, 13, &bytes, NULL); if (bytes != 13) { PutErrorString(message); strcat(message, ": Failed feature record read"); ShiError(message); } // Verify the feature tag if (strncmp(feature->tag, "1FTR", 4) != 0) { ShiError("Failed feature tag check"); } // Allocate memory for the list of points feature->points = (PointRecord*)malloc(feature->numPoints * sizeof(*feature->points)); ShiAssert(feature->points); // Read the point records ReadFile(inputFile, feature->points, 8 * feature->numPoints, &bytes, NULL); if (bytes != (DWORD)8 * feature->numPoints) { PutErrorString(message); strcat(message, ": Failed read of a point record"); ShiError(message); } } void TileDatabase::SortArray(FeatureRecord **array, int numElements) { int i, j, k; FeatureRecord *p; for (i = 1; i < numElements; i++) { // Decide where to place this element in the list j = i; while ((j > 0) && (array[j - 1]->type > array[i]->type)) { j--; } // Only adjust the list if we need to if (j != i) { // Remove the element under consideration (i) from its current location p = array[i]; for (k = i; k < numElements - 1; k++) { array[k] = array[k + 1]; } // Insert the element under consideration in front of the identified element for (k = numElements - 1; k > j; k--) { array[k] = array[k - 1]; } array[j] = p; } } } TileRecord* TileDatabase::GetTileRecord(WORD code) { int tile; for (tile = 0; tile < header.numTiles; tile++) { if (header.tiles[tile].code == code) { return &header.tiles[tile]; } } // We didn't find a match return NULL; } AreaRecord* TileDatabase::GetArea(TileRecord *pTile, int area) { if (pTile == NULL) { return NULL; } ShiAssert(area < pTile->nareas); return &pTile->areas[area]; } PathRecord* TileDatabase::GetPath(TileRecord *pTile, int path) { if (pTile == NULL) { return NULL; } ShiAssert(path < pTile->npaths); return &pTile->paths[path]; } BOOL TileDatabase::typeIsPath(BYTE featureType) { return ((featureType == COVERAGE_RIVER) || (featureType == COVERAGE_ROAD) || (featureType == COVERAGE_RAIL) || (featureType == COVERAGE_BRIDGE) || (featureType == COVERAGE_RUNWAY)); }
26.2891
118
0.591401
Terebinth
ace48798ce3265e96316a01380ee79e945faccc4
28,780
cc
C++
metadb/metadb.cc
yux20000304/indexfs
e0b9a742e2fe9b231f06803a5af2e0c596e0d7c6
[ "BSD-3-Clause" ]
2
2021-05-29T07:27:23.000Z
2022-02-26T18:16:07.000Z
metadb/metadb.cc
yux20000304/indexfs
e0b9a742e2fe9b231f06803a5af2e0c596e0d7c6
[ "BSD-3-Clause" ]
null
null
null
metadb/metadb.cc
yux20000304/indexfs
e0b9a742e2fe9b231f06803a5af2e0c596e0d7c6
[ "BSD-3-Clause" ]
3
2021-01-18T03:42:53.000Z
2022-01-02T14:50:03.000Z
// Copyright (c) 2014 The IndexFS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #ifdef RADOS #include "env/obj_set.h" using leveldb::ObjEnv; using leveldb::ObjEnvFactory; #endif #include <algorithm> #include <sstream> #include <iomanip> #include <time.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include "common/gigaidx.h" #include "common/logging.h" #include "metadb/metadb.h" #include "metadb/dbtypes.h" #include "metadb/dboptions.h" #include "util/leveldb_types.h" #include "util/leveldb_reader.h" namespace indexfs { namespace mdb { class LevelMDB; // Local configuration. // static const bool kDeleteCheck = false; // Default permission bits. // static const mode_t DEFAULT_FILE_MODE = /* 644 */ S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH | S_IFREG; static const mode_t DEFAULT_DIR_MODE = /* 755 */ S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH | S_IFDIR; // Error status using classic POSIX messages. // static const Status ERR_NOT_FOUND = Status::NotFound("No such file or directory"); static const Status ERR_ALREADY_EXISTS = Status::AlreadyExists("File exists"); static const Status ERR_OP_NOT_SUPPORTED = Status::NotSupported("Operation not supported"); // Overrides the original name hash with the specified hash prefix. // static inline void PutHash(MDBKey *key, const Slice &hash) { if (!hash.empty()) { size_t hash_size = std::min(key->GetHashSize(), hash.size()); memcpy(key->GetNameHash(), hash.data(), hash_size); } } // Default DirScanner implementation built on top of LevelDB. // struct MDBDirScanner: public DirScanner { virtual ~MDBDirScanner() { if (it_ != NULL) { delete it_; } } Iterator* it_; int64_t parent_id_; int16_t partition_id_; virtual void Next() { it_->Next(); } virtual bool Valid(); virtual void RetrieveEntryStat(StatInfo *info); virtual void RetrieveEntryName(std::string *name); virtual void RetrieveEntryHash(std::string *hash); }; // A specific BulkExtractor implementation built on top of LevelDB // that performs both bulk extraction and bulk insertion // but only on a single DB instance. // struct MDBLocalBulkExtractor: virtual public BulkExtractor { virtual ~MDBLocalBulkExtractor() { if (batch_ != NULL) { delete batch_; } } WriteBatch* batch_; int num_entries_extracted_; DB* db_; LevelMDB* mdb_; const std::string null_output_dir_; Status Commit(); Status Extract(uint64_t *min_seq, uint64_t *max_seq); int GetNumEntriesExtracted() { return num_entries_extracted_; } const std::string& GetBulkExtractOutputDir() { return null_output_dir_; } }; // The default BulkExtractor implementation built on top of LevelDB. // struct MDBBulkExtractor: virtual public BulkExtractor { virtual ~MDBBulkExtractor() { if (batch_ != NULL) { delete batch_; } } WriteBatch* batch_; int num_entries_extracted_; DB* db_; Env* env_; LevelMDB* mdb_; std::string dir_path_; std::string sstable_path_; // Setup the temporary sstable file for storing // a sorted list of bulk insertion entries to be extracted from the DB. // Status PrepareFile(WritableFile **sst_file); Status Commit(); Status Extract(uint64_t *min_seq, uint64_t *max_seq); int GetNumEntriesExtracted() { return num_entries_extracted_; } const std::string& GetBulkExtractOutputDir() { return dir_path_; } }; // Default MetaDB implementation built on top of LevelDB. // class LevelMDB: virtual public MetaDB { public: LevelMDB(Config* config, Env* env = NULL); virtual ~LevelMDB(); int64_t GetCurrentInodeNo(); int64_t ReserveNextInodeNo(); Status Flush(); Status Init(OptionInitializer opt_initializer); DirScanner* CreateDirScanner(const KeyOffset &offset); Status PutEntry(const KeyInfo &key, const StatInfo &info); Status PutEntryWithMode(const KeyInfo &key, const StatInfo &info, mode_t new_mode); Status EntryExists(const KeyInfo &key); Status DeleteEntry(const KeyInfo &key); Status GetEntry(const KeyInfo &key, StatInfo *info); Status UpdateEntry(const KeyInfo &key, const StatInfo &info); Status InsertEntry(const KeyInfo &key, const StatInfo &info); Status SetFileMode(const KeyInfo &key, mode_t new_mode); Status NewFile(const KeyInfo &key); Status NewDirectory(const KeyInfo &key, int16_t zeroth_server, int64_t inode_no); Status GetMapping(int64_t dir_id, std::string *dmap_data); Status UpdateMapping(int64_t dir_id, const Slice &dmap_data); Status InsertMapping(int64_t dir_id, const Slice &dmap_data); BulkExtractor* CreateLocalBulkExtractor(); BulkExtractor* CreateBulkExtractor(const std::string &tmp_path); Status BulkInsert(uint64_t min_seq, uint64_t max_seq, const std::string &tmp_path); Status ListEntries(const KeyOffset &offset, NameList *names, StatList *infos); Status FetchData(const KeyInfo &key, int32_t *size, char *buffer); Status WriteData(const KeyInfo &key, uint32_t offset, uint32_t size, const char *data); private: enum FileStatus { kRegular = 0, kEmbedded = 1, }; static inline bool IsEmbedded(int16_t status) { return (status & kEmbedded) == kEmbedded; } enum SpecialKeys { kInodeKey = -1, }; Status SaveInodeCounter(); // save to disk Status RetrieveInodeCounter(); // read from disk Status CreateNewFileSystem(const std::string &db_path); // initialize an empty namespace Status LoadExistingFileSystem(const std::string &db_path); // restore existing namespace Config* config_; Env* user_env_; // This can be NULL DB* db_; Options options_; // Use options_.env to access Env Options builder_options_; Mutex inode_mu_; int64_t inode_counter_; // LevelDB write options WriteOptions write_sync_; WriteOptions write_async_; // LevelDB read options ReadOptions read_fill_cache_; ReadOptions read_pass_cache_; friend class MDBDirScanner; friend class MDBBulkExtractor; friend class MDBLocalBulkExtractor; // No copying allowed LevelMDB(const LevelMDB&); LevelMDB& operator=(const LevelMDB&); }; LevelMDB::~LevelMDB() { if (db_ != NULL) { SaveInodeCounter(); delete db_; } if (options_.block_cache != NULL) { delete options_.block_cache; } // Leave comparator and filter_policy } LevelMDB::LevelMDB(Config* config, Env* env) : config_(config), user_env_(env), db_(NULL), inode_counter_(0) { DLOG_ASSERT(config_ != NULL); write_sync_.sync = true; write_async_.sync = false; read_fill_cache_.fill_cache = true; read_pass_cache_.fill_cache = false; } Status LevelMDB::Flush() { DLOG_ASSERT(db_ != NULL); return db_->Flush(); } Status LevelMDB::Init(OptionInitializer opt_initializer) { DLOG_ASSERT(db_ == NULL); opt_initializer(&options_, config_, user_env_); DLOG_ASSERT(options_.env != NULL); DLOG_ASSERT(options_.block_cache != NULL); builder_options_ = options_; DLOG_ASSERT(options_.comparator != NULL); builder_options_.comparator = NewInternalComparator(options_.comparator); DLOG_ASSERT(options_.filter_policy != NULL); builder_options_.filter_policy = NewInternalFilterPolicy(options_.filter_policy); std::string db_home = config_->GetDBHomeDir(); return (!options_.env->FileExists(db_home + "/CURRENT")) ? CreateNewFileSystem(db_home) : LoadExistingFileSystem(db_home); } Status LevelMDB::CreateNewFileSystem(const std::string &db_path) { Status s; options_.create_if_missing = true; options_.error_if_exists = true; s = DB::Open(options_, db_path, &db_); if (!s.ok()) { return Status::Corruption("Cannot open LevelDB", s.ToString()); } if (config_->IsServer()) { inode_counter_ = config_->GetSrvId(); s = SaveInodeCounter(); if (!s.ok()) { return Status::Corruption("Cannot initialize inode counter", s.ToString()); } } return s; } Status LevelMDB::LoadExistingFileSystem(const std::string &db_path) { Status s; options_.create_if_missing = false; options_.error_if_exists = false; s = DB::Open(options_, db_path, &db_); if (!s.ok()) { return Status::Corruption("Cannot open LevelDB", s.ToString()); } if (config_->IsServer()) { s = RetrieveInodeCounter(); if (!s.ok()) { if (config_->HasOldData()) { inode_counter_ = config_->GetSrvId(); s = SaveInodeCounter(); } else { s = Status::Corruption("Cannot fetch inode counter", s.ToString()); } } } return s; } Status LevelMDB::SaveInodeCounter() { MDBKey key(kInodeKey); std::string value; MutexLock lock(&inode_mu_); PutFixed64(&value, inode_counter_); return db_->Put(write_sync_, key.ToSlice(), value); } Status LevelMDB::RetrieveInodeCounter() { MDBKey key(kInodeKey); std::string value; MutexLock lock(&inode_mu_); Status s = db_->Get(read_fill_cache_, key.ToSlice(), &value); if (s.ok()) { inode_counter_ = DecodeFixed64(value.data()); } return s; } inline int64_t LevelMDB::GetCurrentInodeNo() { MutexLock lock(&inode_mu_); return inode_counter_; } inline int64_t LevelMDB::ReserveNextInodeNo() { MutexLock lock(&inode_mu_); inode_counter_ += DEFAULT_MAX_NUM_SERVERS; return inode_counter_; } Status LevelMDB::PutEntry(const KeyInfo &key, const StatInfo &info) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); MDBValue mdb_val(key.file_name_); mdb_val->SetInodeNo(info.id); mdb_val->SetFileSize(info.size); mdb_val->SetFileMode(info.mode); mdb_val->SetFileStatus(info.is_embedded ? kEmbedded : kRegular); mdb_val->SetZerothServer(info.zeroth_server); mdb_val->SetUserId(-1); mdb_val->SetGroupId(-1); mdb_val->SetChangeTime(info.ctime); mdb_val->SetModifyTime(info.mtime); return db_->Put(write_async_, mdb_key.ToSlice(), mdb_val.ToSlice()); } Status LevelMDB::PutEntryWithMode(const KeyInfo &key, const StatInfo &info, mode_t new_mode) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); new_mode &= (S_IRWXU | S_IRWXG | S_IRWXO); mode_t old_mode = info.mode & ~(S_IRWXU | S_IRWXG | S_IRWXO); MDBValue mdb_val(key.file_name_); mdb_val->SetInodeNo(info.id); mdb_val->SetFileSize(info.size); mdb_val->SetFileMode(old_mode | new_mode); mdb_val->SetFileStatus(info.is_embedded ? kEmbedded : kRegular); mdb_val->SetZerothServer(info.zeroth_server); mdb_val->SetUserId(-1); mdb_val->SetGroupId(-1); mdb_val->SetChangeTime(info.ctime); mdb_val->SetModifyTime(info.mtime); return db_->Put(write_async_, mdb_key.ToSlice(), mdb_val.ToSlice()); } Status LevelMDB::SetFileMode(const KeyInfo &key, mode_t new_mode) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); std::string buffer; Status s = db_->Get(read_fill_cache_, mdb_key.ToSlice(), &buffer); if (!s.ok()) { return s.IsNotFound() ? ERR_NOT_FOUND : s; } char* ptr = const_cast<char*>(buffer.data()); FileStat* file_stat = reinterpret_cast<FileStat*>(ptr); new_mode &= (S_IRWXU | S_IRWXG | S_IRWXO); mode_t old_mode = file_stat->FileMode() & ~(S_IRWXU | S_IRWXG | S_IRWXO); file_stat->SetFileMode(old_mode | new_mode); return db_->Put(write_async_, mdb_key.ToSlice(), buffer); } Status LevelMDB::EntryExists(const KeyInfo &key) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); return db_->Exists(read_fill_cache_, mdb_key.ToSlice()); } Status LevelMDB::DeleteEntry(const KeyInfo &key) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); if (kDeleteCheck) { std::string buffer; Status s = db_->Get(read_fill_cache_, mdb_key.ToSlice(), &buffer); if (!s.ok()) { return s.IsNotFound() ? ERR_NOT_FOUND : s; } const char* ptr = buffer.data(); const FileStat* file_stat = reinterpret_cast<const FileStat*>(ptr); if (S_ISDIR(file_stat->FileMode())) { return ERR_OP_NOT_SUPPORTED; } } return db_->Delete(write_async_, mdb_key.ToSlice()); } Status LevelMDB::GetEntry(const KeyInfo &key, StatInfo *info) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); std::string buffer; Status s = db_->Get(read_fill_cache_, mdb_key.ToSlice(), &buffer); if (!s.ok()) { return s.IsNotFound() ? ERR_NOT_FOUND : s; } const char* ptr = buffer.data(); const FileStat* file_stat = reinterpret_cast<const FileStat*>(ptr); info->id = file_stat->InodeNo(); info->size = file_stat->FileSize(); info->mode = file_stat->FileMode(); info->is_embedded = IsEmbedded(file_stat->FileStatus()); info->zeroth_server = file_stat->ZerothServer(); info->gid = info->uid = -1; info->ctime = file_stat->ChangeTime(); info->mtime = file_stat->ModifyTime(); return Status::OK(); } Status LevelMDB::UpdateEntry(const KeyInfo &key, const StatInfo &info) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); std::string buffer; Status s = db_->Get(read_fill_cache_, mdb_key.ToSlice(), &buffer); if (!s.ok()) { return s.IsNotFound() ? ERR_NOT_FOUND : s; } char* ptr = const_cast<char*>(buffer.data()); FileStat* file_stat = reinterpret_cast<FileStat*>(ptr); file_stat->SetInodeNo(info.id); file_stat->SetFileSize(info.size); file_stat->SetFileMode(info.mode); file_stat->SetFileStatus(info.is_embedded ? kEmbedded : kRegular); file_stat->SetZerothServer(info.zeroth_server); file_stat->SetUserId(-1); file_stat->SetGroupId(-1); file_stat->SetChangeTime(info.ctime); file_stat->SetModifyTime(info.mtime); return db_->Put(write_async_, mdb_key.ToSlice(), buffer); } Status LevelMDB::InsertEntry(const KeyInfo &key, const StatInfo &info) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); Status s = db_->Exists(read_fill_cache_, mdb_key.ToSlice()); if (!s.IsNotFound()) { return s.ok() ? ERR_ALREADY_EXISTS : s; } MDBValue mdb_val(key.file_name_); mdb_val->SetInodeNo(info.id); mdb_val->SetFileSize(info.size); mdb_val->SetFileMode(info.mode); mdb_val->SetFileStatus(info.is_embedded ? kEmbedded : kRegular); mdb_val->SetZerothServer(info.zeroth_server); mdb_val->SetUserId(-1); mdb_val->SetGroupId(-1); mdb_val->SetChangeTime(info.ctime); mdb_val->SetModifyTime(info.mtime); return db_->Put(write_async_, mdb_key.ToSlice(), mdb_val.ToSlice()); } Status LevelMDB::NewFile(const KeyInfo &key) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); Status s = db_->Exists(read_fill_cache_, mdb_key.ToSlice()); if (!s.IsNotFound()) { return s.ok() ? ERR_ALREADY_EXISTS : s; } MDBValue mdb_val(key.file_name_); mdb_val->SetInodeNo(-1); mdb_val->SetFileSize(0); mdb_val->SetFileMode(DEFAULT_FILE_MODE); mdb_val->SetFileStatus(kEmbedded); mdb_val->SetZerothServer(-1); mdb_val->SetUserId(-1); mdb_val->SetGroupId(-1); mdb_val->SetTime(time(NULL)); return db_->Put(write_async_, mdb_key.ToSlice(), mdb_val.ToSlice()); } Status LevelMDB::NewDirectory(const KeyInfo &key, int16_t zeroth_server, int64_t inode_no) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); Status s = db_->Exists(read_fill_cache_, mdb_key.ToSlice()); if (!s.IsNotFound()) { return s.ok() ? ERR_ALREADY_EXISTS : s; } MDBValue mdb_val(key.file_name_); mdb_val->SetInodeNo(inode_no); mdb_val->SetFileSize(-1); mdb_val->SetFileMode(DEFAULT_DIR_MODE); mdb_val->SetFileStatus(kRegular); mdb_val->SetZerothServer(zeroth_server); mdb_val->SetUserId(-1); mdb_val->SetGroupId(-1); mdb_val->SetTime(time(NULL)); return db_->Put(write_async_, mdb_key.ToSlice(), mdb_val.ToSlice()); } Status LevelMDB::GetMapping(int64_t dir_id, std::string *dmap_data) { MDBKey mdb_key(dir_id, -1); Status s = db_->Get(read_fill_cache_, mdb_key.ToSlice(), dmap_data); return s.IsNotFound() ? ERR_NOT_FOUND : s; } Status LevelMDB::UpdateMapping(int64_t dir_id, const Slice &dmap_data) { MDBKey mdb_key(dir_id, -1); Status s = db_->Exists(read_fill_cache_, mdb_key.ToSlice()); if (!s.ok()) { return s.IsNotFound() ? ERR_NOT_FOUND : s; } return db_->Put(write_async_, mdb_key.ToSlice(), dmap_data); } Status LevelMDB::InsertMapping(int64_t dir_id, const Slice &dmap_data) { MDBKey mdb_key(dir_id, -1); Status s = db_->Exists(read_fill_cache_, mdb_key.ToSlice()); if (!s.IsNotFound()) { return s.ok() ? ERR_ALREADY_EXISTS : s; } return db_->Put(write_async_, mdb_key.ToSlice(), dmap_data); } Status LevelMDB::ListEntries(const KeyOffset &offset, NameList *names, StatList *infos) { MDBKey start_key(offset.parent_id_, offset.partition_id_); PutHash(&start_key, offset.start_hash_); MDBIterator it(db_->NewIterator(read_pass_cache_)); for (it->Seek(start_key.ToSlice()); it->Valid(); it->Next()) { const MDBKey* key = reinterpret_cast<const MDBKey*>(it->key().data()); if (key->GetParent() != offset.parent_id_ || key->GetPartition() != offset.partition_id_) { break; } MDBValueRef val(it->value()); if (infos != NULL) { StatInfo info; info.id = val->InodeNo(); info.size = val->FileSize(); info.mode = val->FileMode(); info.is_embedded = IsEmbedded(val->FileStatus()); info.zeroth_server = val->ZerothServer(); info.uid = info.gid = -1; info.ctime = val->ChangeTime(); info.mtime = val->ModifyTime(); infos->push_back(info); } if (names != NULL) { names->push_back(val.GetName().ToString()); } } return Status::OK(); } Status LevelMDB::FetchData(const KeyInfo &key, int32_t *size, char *databuf) { MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); std::string buffer; Status s = db_->Get(read_fill_cache_, mdb_key.ToSlice(), &buffer); if (!s.ok()) { return s.IsNotFound() ? ERR_NOT_FOUND : s; } MDBValueRef val(buffer.data(), buffer.size()); if (!IsEmbedded(val->FileStatus())) { *size = -1; return Status::OK(); } const Slice& data = val.GetEmbeddedData(); DLOG_ASSERT(data.size() <= DEFAULT_SMALLFILE_THRESHOLD); *size = static_cast<int32_t>(data.size()); memcpy(databuf, data.data(), data.size()); return Status::OK(); } Status LevelMDB::WriteData(const KeyInfo &key, uint32_t offset, uint32_t size, const char *data) { DLOG_ASSERT(offset + size <= DEFAULT_SMALLFILE_THRESHOLD); MDBKey mdb_key(key.parent_id_, key.partition_id_, key.file_name_); std::string buffer; Status s = db_->Get(read_fill_cache_, mdb_key.ToSlice(), &buffer); if (!s.ok()) { return s.IsNotFound() ? ERR_NOT_FOUND : s; } MDBValueRef old_val(buffer.data(), buffer.size()); DLOG_ASSERT(IsEmbedded(old_val->FileStatus())); DLOG_ASSERT(old_val.GetStoragePath().size() == 0); DLOG_ASSERT(old_val.GetEmbeddedData().size() <= DEFAULT_SMALLFILE_THRESHOLD); MDBValue new_val(old_val, offset, size, data); new_val->SetFileSize(new_val.GetEmbeddedData().size()); return db_->Put(write_async_, mdb_key.ToSlice(), new_val.ToSlice()); } DirScanner* LevelMDB::CreateDirScanner(const KeyOffset &offset) { MDBKey start_key(offset.parent_id_, offset.partition_id_); PutHash(&start_key, offset.start_hash_); MDBDirScanner* scanner = new MDBDirScanner(); scanner->it_ = db_->NewIterator(read_pass_cache_); scanner->it_->Seek(start_key.ToSlice()); scanner->parent_id_ = offset.parent_id_; scanner->partition_id_ = offset.partition_id_; return scanner; } BulkExtractor* LevelMDB::CreateLocalBulkExtractor() { MDBLocalBulkExtractor* extractor = new MDBLocalBulkExtractor(); extractor->db_ = db_; extractor->mdb_ = this; extractor->batch_ = new WriteBatch(); extractor->num_entries_extracted_ = 0; return extractor; } BulkExtractor* LevelMDB::CreateBulkExtractor(const std::string &tmp_path) { MDBBulkExtractor* extractor = new MDBBulkExtractor(); extractor->db_ = db_; extractor->env_ = options_.env; extractor->mdb_ = this; extractor->dir_path_ = tmp_path; extractor->batch_ = new WriteBatch(); extractor->num_entries_extracted_ = 0; return extractor; } Status LevelMDB::BulkInsert(uint64_t min_seq, uint64_t max_seq, const std::string &tmp_path) { return db_->BulkInsert(write_async_, tmp_path, min_seq, max_seq); } // -------------------------------------------- // Directory Scanner // -------------------------------------------- bool MDBDirScanner::Valid() { if (!it_->Valid()) { return false; } const MDBKey* key = reinterpret_cast<const MDBKey*>(it_->key().data()); return key->GetParent() == parent_id_ && key->GetPartition() == partition_id_; } void MDBDirScanner::RetrieveEntryStat(StatInfo *info) { DLOG_ASSERT(it_->Valid()); MDBValueRef val(it_->value()); info->id = val->InodeNo(); info->size = val->FileSize(); info->mode = val->FileMode(); info->is_embedded = LevelMDB::IsEmbedded(val->FileStatus()); info->zeroth_server = val->ZerothServer(); info->uid = info->gid = -1; info->ctime = val->ChangeTime(); info->mtime = val->ModifyTime(); } void MDBDirScanner::RetrieveEntryName(std::string *name) { DLOG_ASSERT(it_->Valid()); MDBValueRef val(it_->value()); const Slice& name_buffer = val.GetName(); name->assign(name_buffer.data(), name_buffer.size()); } void MDBDirScanner::RetrieveEntryHash(std::string *hash) { DLOG_ASSERT(it_->Valid()); const MDBKey* key = reinterpret_cast<const MDBKey*>(it_->key().data()); hash->assign(key->GetNameHash(), key->GetHashSize()); } // -------------------------------------------- // Bulk Extractor // -------------------------------------------- namespace { static const MDBKey* ToMDBKey(const Slice& key) { return reinterpret_cast<const MDBKey*>(key.data()); } } Status MDBLocalBulkExtractor::Commit() { Status s; if (num_entries_extracted_ > 0) { s = db_->Write(mdb_->write_async_, batch_); } return s; } Status MDBLocalBulkExtractor::Extract(uint64_t *min_seq, uint64_t *max_seq) { Status s; int num_entries_moved = 0; MDBIterator it(db_->NewIterator(mdb_->read_pass_cache_)); for (it->Seek(MDBKey(dir_id_, old_partition_).ToSlice()); it->Valid(); it->Next()) { const MDBKey* key = ToMDBKey(it->key()); if (key->GetParent() != dir_id_ || key->GetPartition() != old_partition_) { break; } if (DirIndex::ToBeMigrated(new_partition_, key->GetNameHash())) { num_entries_moved++; MDBKey new_key(dir_id_, new_partition_); PutHash(&new_key, Slice(key->GetNameHash(), key->GetHashSize())); batch_->Delete(it->key()); batch_->Put(new_key.ToSlice(), it->value()); } } *min_seq = *max_seq = 0; num_entries_extracted_ = num_entries_moved; return s; } Status MDBBulkExtractor::Commit() { Status s; if (num_entries_extracted_ > 0) { s = db_->Write(mdb_->write_async_, batch_); } # if !defined(HDFS) if (s.ok()) { s = env_->DeleteFile(sstable_path_); } # endif return !s.ok() ? s : env_->DeleteDir(dir_path_); } Status MDBBulkExtractor::PrepareFile(WritableFile **sst_file) { Status s; if (!env_->FileExists(dir_path_)) { s = env_->CreateDir(dir_path_); if (!s.ok()) { return s; } } sstable_path_ = TableFileName(dir_path_, 1); return env_->NewWritableFile(sstable_path_, sst_file); } Status MDBBulkExtractor::Extract(uint64_t *min_seq, uint64_t *max_seq) { *min_seq = *max_seq = 0; WritableFile* sst_file; Status s = PrepareFile(&sst_file); if (!s.ok()) { return s; } int num_entries_moved = 0; MDBTableBuilder builder(mdb_->builder_options_, sst_file); char key_space[128]; MDBIterator it(db_->NewIterator(mdb_->read_pass_cache_)); for (it->Seek(MDBKey(dir_id_, old_partition_).ToSlice()); it->Valid(); it->Next()) { const Slice& internal_key = it->internalkey(); const MDBKey* key = ToMDBKey(internal_key); if (key->GetParent() != dir_id_ || key->GetPartition() != old_partition_) { break; } if (DirIndex::ToBeMigrated(new_partition_, key->GetNameHash())) { batch_->Delete(it->key()); MDBKey new_key(dir_id_, new_partition_); DLOG_ASSERT(internal_key.size() < sizeof(key_space)); memcpy(key_space, internal_key.data(), internal_key.size()); memcpy(key_space, new_key.data(), new_key.GetPrefixSize()); builder->Add(Slice(key_space, internal_key.size()), it->value()); uint64_t seq = MDBHelper::FetchSeqNum(internal_key); if (num_entries_moved == 0) { *min_seq = *max_seq = seq; } num_entries_moved++; *min_seq = std::min(*min_seq, seq); *max_seq = std::max(*max_seq, seq); } } num_entries_extracted_ = builder->NumEntries(); DLOG_ASSERT(num_entries_extracted_ = num_entries_moved); return builder.Seal(); } } /* namespace mdb */ // -------------------------------------------- // Default MetaDB Factory Method // -------------------------------------------- Status LoadManifestFile(const std::string& manifest, int num_tables, Env* env, VersionMerger* merger) { Status s; SequentialFile* file; s = env->NewSequentialFile(manifest, &file); if (s.ok()) { LogReporter reporter; reporter.status = &s; LogReader reader(file, &reporter, false/*checksum*/, 0/*initial_offset*/); Slice record; std::string scratch; if (reader.ReadRecord(&record, &scratch) && s.ok()) { s = merger->Merge(record, num_tables); } if (reader.ReadRecord(&record, &scratch) && s.ok()) { s = Status::NotSupported("Multiple records within a manifest file"); } } DLOG(INFO) << "Load manifest file: " << manifest << " " << s.ToString(); delete file; return s; } Status LinkDataDirecrory(const std::string& sst_dir, int& sst_no, Config* config, Env* env, VersionMerger* merger) { Status s; int num_tables = 0; std::string manifest; std::vector<std::string> names; s = env->GetChildren(sst_dir, &names); if (s.ok()) { for (size_t j = 0; j < names.size() && s.ok(); ++j) { if (IsManifestFile(names[j])) { if (manifest.empty()) { manifest = sst_dir + "/" + names[j]; } else { s = Status::NotSupported("Multiple DB manifest files"); } } if (IsSSTableFile(names[j])) { num_tables++; std::string src = sst_dir + "/" + names[j]; std::string target = TableFileName(config->GetDBHomeDir(), ++sst_no); s = env->SymlinkFile(src, target); DLOG(INFO) << "Link table: " << src << "->" << target << " " << s.ToString(); } } if (s.ok() && num_tables > 0) { if (manifest.empty()) { s = Status::NotFound("No DB manifest file"); } else { s = LoadManifestFile(manifest, num_tables, env, merger); } } } return s; } Status MetaDB::Repair(Config* config, Env* env) { Status s; DLOG_ASSERT(config->HasOldData()); VersionMerger merger; int sst_no = 1; int manifest_no = 1; const std::pair<std::string, int>& old_data = config->GetDBDataDirs(); for (int i = 0; i < old_data.second && s.ok(); ++i) { std::stringstream ss; ss << old_data.first << i; std::string sst_dir = ss.str(); # ifdef RADOS ObjEnv* obj_env = ObjEnvFactory::FetchObjEnv(); assert(obj_env != NULL); s = obj_env->LoadSet(sst_dir); if (!s.ok()) { break; } # endif s = LinkDataDirecrory(sst_dir, sst_no, config, env, &merger); } if (s.ok()) { merger.Finish(); std::string record; merger.EncodeTo(&record); std::string manifest = DescriptorFileName(config->GetDBHomeDir(), manifest_no); WritableFile* file; s = env->NewWritableFile(manifest, &file); if (s.ok()) { LogWriter writer(file); s = writer.AddRecord(record); if (s.ok()) { s = file->Sync(); } } delete file; DLOG(INFO) << "New manifest file " << manifest << " " << s.ToString(); if (s.ok()) { s = SetCurrentFile(env, config->GetDBHomeDir(), manifest_no); DLOG(INFO) << "Install current file " << s.ToString(); } } return s; } Status MetaDB::Open(Config* config, MetaDB** dbptr, Env* env) { using mdb::LevelMDB; using mdb::DefaultLevelDBOptionInitializer; using mdb::BatchClientLevelDBOptionInitializer; Status s; *dbptr = NULL; LevelMDB* new_db = new LevelMDB(config, env); if (config->IsServer()) { s = new_db->Init(DefaultLevelDBOptionInitializer); } else if (config->IsBatchClient()) { s = new_db->Init(BatchClientLevelDBOptionInitializer); } else { abort(); } if (!s.ok()) { delete new_db; return s; } *dbptr = new_db; return s; } } /* namespace indexfs */
30.35865
90
0.679361
yux20000304
ace5dd57acebee263c99e627222362371a576c1b
21,797
cpp
C++
ee512.cpp
ckaraca/queue-algorithm-simulator
bdabf651343bca24d1fedb86ffd9727fb21ae6af
[ "MIT" ]
null
null
null
ee512.cpp
ckaraca/queue-algorithm-simulator
bdabf651343bca24d1fedb86ffd9727fb21ae6af
[ "MIT" ]
null
null
null
ee512.cpp
ckaraca/queue-algorithm-simulator
bdabf651343bca24d1fedb86ffd9727fb21ae6af
[ "MIT" ]
null
null
null
// ee512.cpp : Copyright 2002 - Cem KARACA // #include "ee512.h" int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; HACCEL hAccelTable; INITCOMMONCONTROLSEX cc; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_EE512, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); srand((int)time(NULL)); // Perform application initialization: if (!InitInstance (hInstance)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_EE512); hMenu=GetMenu(hWnd); hMenu1= GetSubMenu(hMenu,3); CheckMenuRadioItem(hMenu1,ID_PRIORITY_ABOVENORMAL,ID_PRIORITY_HIGHEST,ID_PRIORITY_NORMAL,MF_BYCOMMAND); CheckMenuRadioItem(hMenu,ID_1 ,ID_4, ID_1, MF_BYCOMMAND ); EnableMenuItem(hMenu,ID_STOP,MF_GRAYED); EnableMenuItem(hMenu,ID_RESUME,MF_GRAYED); cc.dwSize = sizeof(INITCOMMONCONTROLSEX); cc.dwICC = ICC_BAR_CLASSES | ICC_UPDOWN_CLASS ; InitCommonControlsEx(&cc); while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_CLASSDC; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_EE512); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = CreateSolidBrush(RGB(204,204,204)); wcex.lpszMenuName = (LPCSTR)IDC_EE512; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance) { hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, SW_SHOW); UpdateWindow(hWnd); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_CREATE: SetTimer(hWnd,1,quanta,NULL); hRed = CreateSolidBrush(RGB(255,0,0)); hGreen = CreateSolidBrush(RGB(0,255,0)); hBlack = CreateSolidBrush(RGB(0,0,0)); CreateWindow("STATIC","static",SS_BLACKFRAME | WS_CHILD | WS_VISIBLE,0,175,470,55,hWnd,NULL,hInst,NULL); CreateWindow("STATIC","static",SS_BLACKFRAME | WS_CHILD | WS_VISIBLE,0,235,470,55,hWnd,NULL,hInst,NULL); CreateWindow("STATIC","static",SS_BLACKFRAME | WS_CHILD | WS_VISIBLE,0,295,250,55,hWnd,NULL,hInst,NULL); CreateWindow("STATIC","static",SS_BLACKFRAME | WS_CHILD | WS_VISIBLE,260,295,210,55,hWnd,NULL,hInst,NULL); CreateWindow("STATIC","static",SS_BLACKFRAME | WS_CHILD | WS_VISIBLE,0,355,250,55,hWnd,NULL,hInst,NULL); hEboxWnd = CreateWindow("EDIT", "edit Box", WS_CHILD | WS_VISIBLE | ES_CENTER | ES_NUMBER | ES_READONLY , 360,315,45,20,hWnd,NULL,hInst,NULL); udWnd = CreateUpDownControl( WS_CHILD | WS_BORDER | WS_VISIBLE | UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_NOTHOUSANDS, 5, 5, 24, 12, hWnd, IDD_UPDOWN, hInst, hEboxWnd, 300, 10, quanta); hTrack = CreateWindow(TRACKBAR_CLASS, "Track Bar", WS_CHILD | WS_VISIBLE | WS_TABSTOP , 5,195,200,30,hWnd,NULL,hInst,NULL); SendMessage(hTrack,TBM_SETRANGE,(WPARAM)1,(LPARAM)MAKELONG(10,500)); SendMessage(hTrack,TBM_SETPOS,(WPARAM)1,(LPARAM)200); hTrack1= CreateWindow(TRACKBAR_CLASS, "Track Bar1", WS_CHILD | WS_VISIBLE | WS_TABSTOP , 5,255,200,30,hWnd,NULL,hInst,NULL); SendMessage(hTrack1,TBM_SETRANGE,(WPARAM)1,(LPARAM)MAKELONG(600,999)); SendMessage(hTrack1,TBM_SETPOS,(WPARAM)1,(LPARAM)800); hTrack2= CreateWindow(TRACKBAR_CLASS, "Track Bar2", WS_CHILD | WS_VISIBLE | WS_TABSTOP , 5,315,200,30,hWnd,NULL,hInst,NULL); SendMessage(hTrack2,TBM_SETRANGE,(WPARAM)1,(LPARAM)MAKELONG(10,300)); SendMessage(hTrack2,TBM_SETPOS,(WPARAM)1,(LPARAM)150); hTrack3= CreateWindow(TRACKBAR_CLASS, "Track Bar3", WS_CHILD | WS_VISIBLE | WS_TABSTOP , 5,375,200,30,hWnd,NULL,hInst,NULL); SendMessage(hTrack3,TBM_SETRANGE,(WPARAM)1,(LPARAM)MAKELONG(500,999)); SendMessage(hTrack3,TBM_SETPOS,(WPARAM)1,(LPARAM)500); hCheck1= CreateWindow("button", "Use Poisson time interval", BS_AUTOCHECKBOX| WS_CHILD | WS_VISIBLE , 250,200,210,20,hWnd,NULL,hInst,NULL); hCheck2= CreateWindow("button", "Use Poisson Packet Size", BS_AUTOCHECKBOX| WS_CHILD | WS_VISIBLE , 250,260,210,20,hWnd,NULL,hInst,NULL); break; case WM_COMMAND: //BM_GETCHECK wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case BN_CLICKED: if((HWND)lParam==hCheck1) Check1 = SendMessage(hCheck1,BM_GETCHECK,0,0); if((HWND)lParam==hCheck2) Check2 = SendMessage(hCheck2,BM_GETCHECK,0,0); break; case ID_START: EnableMenuItem(hMenu,ID_START,MF_GRAYED); EnableMenuItem(hMenu,ID_STOP,MF_ENABLED); t1=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Source, (LPVOID) hWnd, 0, &Tid1); hdc=GetDC(hWnd); TextOut(hdc,10,0,"Starting source",15); ReleaseDC(hWnd,hdc); t2=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Queue1, (LPVOID) hWnd, 0, &Tid2); t3=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Queue2, (LPVOID) hWnd, 0, &Tid3); t5=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Queue3, (LPVOID) hWnd, 0, &Tid4); t6=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Queue4, (LPVOID) hWnd, 0, &Tid6); break; case ID_PRIORITY_ABOVENORMAL: // must be below but I didn't change it CheckMenuRadioItem(hMenu1,ID_PRIORITY_ABOVENORMAL,ID_PRIORITY_HIGHEST,ID_PRIORITY_ABOVENORMAL,MF_BYCOMMAND); SetThreadPriority(t1,THREAD_PRIORITY_IDLE); SetThreadPriority(t2,THREAD_PRIORITY_IDLE); SetThreadPriority(t3,THREAD_PRIORITY_IDLE); SetThreadPriority(t5,THREAD_PRIORITY_IDLE); SetThreadPriority(t6,THREAD_PRIORITY_IDLE); SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_IDLE ); break; case ID_PRIORITY_NORMAL: SetThreadPriority(t1,THREAD_PRIORITY_NORMAL); SetThreadPriority(t2,THREAD_PRIORITY_NORMAL); SetThreadPriority(t3,THREAD_PRIORITY_NORMAL); SetThreadPriority(t5,THREAD_PRIORITY_NORMAL); SetThreadPriority(t6,THREAD_PRIORITY_NORMAL); SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_NORMAL ); CheckMenuRadioItem(hMenu1,ID_PRIORITY_ABOVENORMAL,ID_PRIORITY_HIGHEST,ID_PRIORITY_NORMAL,MF_BYCOMMAND); break; case ID_PRIORITY_HIGHEST: SetThreadPriority(t1,THREAD_PRIORITY_HIGHEST); SetThreadPriority(t2,THREAD_PRIORITY_HIGHEST); SetThreadPriority(t3,THREAD_PRIORITY_HIGHEST); SetThreadPriority(t5,THREAD_PRIORITY_HIGHEST); SetThreadPriority(t6,THREAD_PRIORITY_HIGHEST); SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_HIGHEST ); CheckMenuRadioItem(hMenu1,ID_PRIORITY_ABOVENORMAL,ID_PRIORITY_HIGHEST,ID_PRIORITY_HIGHEST,MF_BYCOMMAND); break; case ID_1: sc=1; CheckMenuRadioItem(hMenu,ID_1 ,ID_6, ID_1, MF_BYCOMMAND ); break; case ID_2: sc=2; CheckMenuRadioItem(hMenu,ID_1 ,ID_6, ID_2, MF_BYCOMMAND ); break; case ID_3: sc=3; CheckMenuRadioItem(hMenu,ID_1 ,ID_6, ID_3, MF_BYCOMMAND ); break; case ID_4: sc=4; CheckMenuRadioItem(hMenu,ID_1 ,ID_6, ID_4, MF_BYCOMMAND ); break; case ID_STOP: EnableMenuItem(hMenu,ID_RESUME,MF_ENABLED); EnableMenuItem(hMenu,ID_STOP,MF_GRAYED); SuspendThread(t1); SuspendThread(t2); SuspendThread(t3); SuspendThread(t5); SuspendThread(t6); break; case ID_RESUME: EnableMenuItem(hMenu,ID_STOP,MF_ENABLED); EnableMenuItem(hMenu,ID_RESUME,MF_GRAYED); ResumeThread(t1); ResumeThread(t2); ResumeThread(t3); ResumeThread(t5); ResumeThread(t6); break; case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; case ID_PLOT_1: hDlg=CreateDialog(hInst,MAKEINTRESOURCE(IDD_LARGE), hWnd, (DLGPROC)Dialog); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_VSCROLL: if(udWnd==(HWND)lParam) { quanta = SendMessage(udWnd,UDM_GETPOS,0,0); SetTimer(hWnd,1,quanta,NULL); } break; case WM_HSCROLL: switch(LOWORD(wParam)) { case TB_TOP: case TB_BOTTOM: case TB_LINEDOWN: case TB_THUMBPOSITION: case TB_THUMBTRACK: case TB_PAGEUP: case TB_LINEUP: case TB_PAGEDOWN: if(hTrack == (HWND)lParam) { delay= SendMessage(hTrack, TBM_GETPOS, 0,0); hdc=GetDC(hWnd); wsprintf(szBuffer1,"%lu ",delay); TextOut(hdc,210,200,szBuffer1,lstrlen(szBuffer1)); ReleaseDC(hWnd,hdc); } if(hTrack1 == (HWND)lParam) { PKT_SIZE= SendMessage(hTrack1, TBM_GETPOS, 0,0); hdc=GetDC(hWnd); wsprintf(szBuffer1,"%d ",(int)PKT_SIZE); TextOut(hdc,210,265,szBuffer1,lstrlen(szBuffer1)); ReleaseDC(hWnd,hdc); } if(hTrack2 == (HWND)lParam) { delay1= SendMessage(hTrack2, TBM_GETPOS, 0,0); hdc=GetDC(hWnd); wsprintf(szBuffer1,"%d ",delay1); TextOut(hdc,210,330,szBuffer1,lstrlen(szBuffer1)); ReleaseDC(hWnd,hdc); } if(hTrack3 == (HWND)lParam) { SinkPacket= SendMessage(hTrack3, TBM_GETPOS, 0,0); hdc=GetDC(hWnd); wsprintf(szBuffer1,"%d ",SinkPacket); TextOut(hdc,210,385,szBuffer1,lstrlen(szBuffer1)); ReleaseDC(hWnd,hdc); } break; } break; case WM_TIMER: quanta1++; if(quanta1>3) quanta1=0; break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); SetBkColor(hdc,RGB(204,204,204)); RECT rt; GetClientRect(hWnd, &rt); TextOut(hdc,0,175,"Source packet sending time interval",35); TextOut(hdc,0,235,"Source Packet Size",18); TextOut(hdc,0,295,"Server Delay Value",18); TextOut(hdc,265,295,"RR Quanta:",10); TextOut(hdc,0,355,"Sink Packet Size ",18); wsprintf(szBuffer1,"%lu ",delay); TextOut(hdc,210,200,szBuffer1,lstrlen(szBuffer1)); wsprintf(szBuffer1,"%lu ",(int)PKT_SIZE); TextOut(hdc,210,265,szBuffer1,lstrlen(szBuffer1)); wsprintf(szBuffer1,"%d ",delay1); TextOut(hdc,210,330,szBuffer1,lstrlen(szBuffer1)); wsprintf(szBuffer1,"%d",SinkPacket); TextOut(hdc,210,385,szBuffer1,lstrlen(szBuffer1)); MoveToEx(hdc,50,60,NULL); LineTo(hdc,90,60); MoveToEx(hdc,130,60,NULL); LineTo(hdc,160,45); MoveToEx(hdc,130,60,NULL); LineTo(hdc,160,75); MoveToEx(hdc,560,45,NULL); LineTo(hdc,600,45); MoveToEx(hdc,560,75,NULL); LineTo(hdc,600,75); MoveToEx(hdc,130,60,NULL); LineTo(hdc,160,15); MoveToEx(hdc,130,60,NULL); LineTo(hdc,160,105); MoveToEx(hdc,560,15,NULL); LineTo(hdc,600,15); MoveToEx(hdc,560,105,NULL); LineTo(hdc,600,105); Draw10Rect(hdc,160,65); Draw10Rect(hdc,160,35); Draw10Rect(hdc,160,5); Draw10Rect(hdc,160,95); Draw(hdc,0); DrawSink(hdc,1,0); DrawSink(hdc,2,0); DrawSink(hdc,3,0); DrawSink(hdc,4,0); TextOut(hdc,632,7,"S1",2); TextOut(hdc,632,37,"S2",2); TextOut(hdc,632,67,"S3",2); TextOut(hdc,632,97,"S4",2); //DrawText(hdc,"2002-Cem KARACA",15,&rt, DT_BOTTOM | DT_RIGHT ); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; } /* A thread of execution within the process. */ DWORD WINAPI Source(LPVOID param) { HDC hdc; unsigned long poisson=0; for(;;) { if(Check2==1) pkt=nexp(PKT_SIZE); else pkt=PKT_SIZE; Stack+=(int)pkt; BytesSent+=pkt/1024; hdc=GetDC(hWnd); SetBkColor(hdc,RGB(204,204,204)); Draw(hdc,0); //wsprintf(szBuffer,"packets: %d and packet size is: %d and delay is %lu ",count,(int)pkt,poisson); //TextOut(hdc,20,20,szBuffer,lstrlen(szBuffer)); ReleaseDC(hWnd,hdc); count++; if(Check1==1) poisson =(unsigned long ) nexp(delay);else poisson=delay; // ~200 ms Sleep(poisson/2); hdc=GetDC(hWnd); SetBkColor(hdc,RGB(204,204,204)); Draw(hdc,1); PacketsSent++; Sleep(poisson/2); DrawSink(hdc,1,2); DrawSink(hdc,2,2); DrawSink(hdc,3,2); DrawSink(hdc,4,2); if(Stack>0) { int min=0; switch(sc) { case 1: wsprintf(szBuffer1,"Round Robin Selected :S%d ",rr+1); TextOut(hdc,220,135,szBuffer1,lstrlen(szBuffer1)); switch(quanta1) { case 0: q1+=(Stack/SinkPacket);q1b+=Stack;Stack=0;q1s+=q1; ResumeThread(t2); Draw10RectR(hdc,(int)q1,1); break; case 1: q2+=(Stack/SinkPacket);q2b+=Stack;Stack=0;rr=2;q2s+=q2; ResumeThread(t3); Draw10RectR(hdc,(int)q2,2); break; case 2: q3+=(Stack/SinkPacket);q3b+=Stack;Stack=0;rr=3;q3s+=q3; ResumeThread(t5); Draw10RectR(hdc,(int)q3,3); break; case 3: q4+=(Stack/SinkPacket);q4b+=Stack;Stack=0;rr=0;q4s+=q4; ResumeThread(t6); Draw10RectR(hdc,(int)q4,4); break; } break; case 2: int ran; ran=rand() %4; wsprintf(szBuffer1,"Random Selected Server #:%d ",ran+1); TextOut(hdc,220,135,szBuffer1,lstrlen(szBuffer1)); switch(ran) { case 0: q1+=(Stack/SinkPacket);q1b+=Stack;Stack=0;q1s+=q1; ResumeThread(t2); Draw10RectR(hdc,(int)q1,1); break; case 1: q2+=(Stack/SinkPacket);q2b+=Stack;Stack=0;q2s+=q2; ResumeThread(t3); Draw10RectR(hdc,(int)q2,2); break; case 2: q3+=(Stack/SinkPacket);q3b+=Stack;Stack=0;q3s+=q3; ResumeThread(t5); Draw10RectR(hdc,(int)q3,3); break; case 3: q4+=(Stack/SinkPacket);q4b+=Stack;Stack=0;q4s+=q4; ResumeThread(t6); Draw10RectR(hdc,(int)q4,4); break; } break; case 3: if(q1<=q2 && q1<=q3 && q1<=q4) min =0; if(q2<=q1 && q2<=q3 && q2<=q4) min =1; if(q3<=q1 && q3<=q2 && q3<=q4) min =2; if(q4<=q1 && q4<=q2 && q4<=q3) min =3; wsprintf(szBuffer1,"Shortest Queue Selected: S%d ",min+1); TextOut(hdc,220,135,szBuffer1,lstrlen(szBuffer1)); switch(min) { case 0: q1+=(Stack/SinkPacket);q1b+=Stack;Stack=0;q1s+=q1; ResumeThread(t2); Draw10RectR(hdc,(int)q1,1); break; case 1: q2+=(Stack/SinkPacket);q2b+=Stack;Stack=0;q2s+=q2; ResumeThread(t3); Draw10RectR(hdc,(int)q2,2); break; case 2: q3+=(Stack/SinkPacket);q3b+=Stack;Stack=0;q3s+=q3; ResumeThread(t5); Draw10RectR(hdc,(int)q3,3); break; case 3: q4+=(Stack/SinkPacket);q4b+=Stack;Stack=0;q4s+=q4; ResumeThread(t6); Draw10RectR(hdc,(int)q4,4); break; } break; case 4: wsprintf(szBuffer1,"Periodically Selected :S%d ",rr+1); TextOut(hdc,220,135,szBuffer1,lstrlen(szBuffer1)); switch(rr) { case 0: q1+=(Stack/SinkPacket);rr=1;q1b+=Stack;Stack=0;q1s+=q1; ResumeThread(t2); Draw10RectR(hdc,(int)q1,1); break; case 1: q2+=(Stack/SinkPacket);rr=2;q2b+=Stack;Stack=0;rr=2;q2s+=q2; ResumeThread(t3); Draw10RectR(hdc,(int)q2,2); break; case 2: q3+=(Stack/SinkPacket);rr=3;q3b+=Stack;Stack=0;rr=3;q3s+=q3; ResumeThread(t5); Draw10RectR(hdc,(int)q3,3); break; case 3: q4+=(Stack/SinkPacket);rr=0;q4b+=Stack;Stack=0;rr=0;q4s+=q4; ResumeThread(t6); Draw10RectR(hdc,(int)q4,4); break; } break; } } ReleaseDC(hWnd,hdc); } return 0; } /* A thread of execution within the process. */ DWORD WINAPI Queue1(LPVOID param) { HDC hdc; for(;;) { if(q1>0) { if(q1>=80) { q1L+=q1-80;q1bL+=(q1-80)*SinkPacket; } Sleep(delay1/2); hdc=GetDC(hWnd); Draw10RectG(hdc,(int)q1,1); q1--; DrawSink(hdc,1,1); ReleaseDC(hWnd,hdc); Sleep(delay1/2); } else SuspendThread(t2); } return 0; } /* A thread of execution within the process. */ DWORD WINAPI Queue2(LPVOID param) { HDC hdc; for(;;) { if(q2>0) { if(q2>=80) { q2L+=q2-80; q2bL+=(q2-80)*SinkPacket; } Sleep(delay1/2); hdc=GetDC(hWnd); Draw10RectG(hdc,(int)q2,2); q2--; DrawSink(hdc,2,1); ReleaseDC(hWnd,hdc); Sleep(delay1/2); } else SuspendThread(t3); } return 0; } /* A thread of execution within the process. */ DWORD WINAPI Queue3(LPVOID param) { HDC hdc; for(;;) { if(q3>0) { if(q3>=80) { q3L+=q3-80; q3bL+=(q3-80)*SinkPacket; } Sleep(delay1/2); hdc=GetDC(hWnd); Draw10RectG(hdc,(int)q3,3); q3--; DrawSink(hdc,3,1); ReleaseDC(hWnd,hdc); Sleep(delay1/2); } else SuspendThread(t5); } return 0; } /* A thread of execution within the process. */ DWORD WINAPI Queue4(LPVOID param) { HDC hdc; for(;;) { if(q4>0) { if(q4>=80) { q4L+=q4-80; q4bL+=(q4-80)*SinkPacket; } Sleep(delay1/2); hdc=GetDC(hWnd); Draw10RectG(hdc,(int)q4,4); q4--; DrawSink(hdc,4,1); ReleaseDC(hWnd,hdc); Sleep(delay1/2); } else SuspendThread(t6); } return 0; } double nexp(double mean ) // Returns negative exponential of mean { int i; double res; i = rand(); res=(double)i/RAND_MAX; return(-mean*log(res) ); } int Draw(HDC hdc,int status) { if(status==1) SelectObject(hdc, hRed); else SelectObject(hdc, hGreen); RECT rt; rt.left=90,rt.right=130,rt.bottom=75,rt.top=45; FillRect(hdc,&rt,NULL); FrameRect(hdc,&rt,hBlack); Ellipse(hdc,10,45,50,75); return 0; } int Draw10Rect(HDC hdc,int x,int y) { int i;RECT rect; rect.left=x,rect.right=x+401;rect.top=y,rect.bottom=y+20; FillRect(hdc,&rect,hGreen); FrameRect(hdc,&rect,hBlack); x+=5; for(i=0;i<79;i++) { MoveToEx(hdc,x,y,NULL); LineTo(hdc,x,y+20); x+=5; } return 0; } int Draw10RectR(HDC hdc,int level,int queue) { if(level>=80) level=80; int x=560,y,i;RECT rect; if(queue==1) y=5; else if(queue==2)y=35; else if(queue==3)y=65; else if(queue==4)y=95; x-=level*5; for(i=0;i<level;i++) { rect.left=x,rect.right=x+6;rect.top=y,rect.bottom=y+20; FillRect(hdc,&rect,hRed); FrameRect(hdc,&rect,hBlack); x+=5; } return 0; } int Draw10RectG(HDC hdc,int level,int queue) { int x=160,y,rev; if(queue==1) y=5; else if(queue==2) y=35; else if(queue==3) y=65; else if(queue==4) y=95; rev=80-level; if(rev>=0) { x+=rev*5; RECT rect; rect.left=x,rect.right=x+6;rect.top=y,rect.bottom=y+20; FillRect(hdc,&rect,hGreen); FrameRect(hdc,&rect,hBlack); } return 0; } int DrawSink(HDC hdc,int Source,int status) { if(status==1) SelectObject(hdc, hRed); else SelectObject(hdc, hGreen); if(Source==1) Ellipse(hdc,600,0,630,30); else if(Source==2) Ellipse(hdc,600,30,630,60); else if(Source==3)Ellipse(hdc,600,60,630,90); else if(Source==4) Ellipse(hdc,600,90,630,120); return 0; } LRESULT CALLBACK Dialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { TCHAR buffer[255]; switch (message) { case WM_INITDIALOG: SetTimer(hDlg,1,500,NULL); return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDC_BUTTON1 ) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } if (LOWORD(wParam) == IDC_BUTTON2 ) { PacketsSent=0;q1s=q2s=q3s=q4s=0; BytesSent=q1b=q2b=q3b=q4b=0; } break; case WM_TIMER: wsprintf(buffer,"%d",PacketsSent); SetDlgItemText(hDlg,IDC_STAT1,buffer); wsprintf(buffer,"%d kB",(int)(BytesSent)); SetDlgItemText(hDlg,IDC_STAT2,buffer); wsprintf(buffer,"%d",(int)(q1s-q1L)); SetDlgItemText(hDlg,IDC_STAT3,buffer); wsprintf(buffer,"%d",(int)(q2s-q2L)); SetDlgItemText(hDlg,IDC_STAT4,buffer); wsprintf(buffer,"%d",(int)(q3s-q3L)); SetDlgItemText(hDlg,IDC_STAT5,buffer); wsprintf(buffer,"%d",(int)(q4s-q4L)); SetDlgItemText(hDlg,IDC_STAT6,buffer); wsprintf(buffer,"%d",(int)q1L); SetDlgItemText(hDlg,IDC_STAT11,buffer); wsprintf(buffer,"%d",(int)q2L); SetDlgItemText(hDlg,IDC_STAT12,buffer); wsprintf(buffer,"%d",(int)q3L); SetDlgItemText(hDlg,IDC_STAT13,buffer); wsprintf(buffer,"%d",(int)q4L); SetDlgItemText(hDlg,IDC_STAT14,buffer); wsprintf(buffer,"%d",(int)q1bL/1024); SetDlgItemText(hDlg,IDC_STAT15,buffer); wsprintf(buffer,"%d",(int)q2bL/1024); SetDlgItemText(hDlg,IDC_STAT16,buffer); wsprintf(buffer,"%d",(int)q3bL/1024); SetDlgItemText(hDlg,IDC_STAT17,buffer); wsprintf(buffer,"%d",(int)q4bL/1024); SetDlgItemText(hDlg,IDC_STAT18,buffer); wsprintf(buffer,"%d kB",(int)q1b/1024); SetDlgItemText(hDlg,IDC_STAT7,buffer); wsprintf(buffer,"%d kB",(int)q2b/1024); SetDlgItemText(hDlg,IDC_STAT8,buffer); wsprintf(buffer,"%d kB",(int)q3b/1024); SetDlgItemText(hDlg,IDC_STAT9,buffer); wsprintf(buffer,"%d kB",(int)q4b/1024); SetDlgItemText(hDlg,IDC_STAT10,buffer); break; } return FALSE; }
26.614164
113
0.653393
ckaraca
acefe4779efe2322456a0e7dcea1bdb8f1078760
3,028
cpp
C++
src/ActiveBSP/src/actormsg/ActorMessageFactory.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/ActiveBSP/src/actormsg/ActorMessageFactory.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/ActiveBSP/src/actormsg/ActorMessageFactory.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
#include "actormsg/ActorMessageFactory.h" #include <iostream> #include "actormsg/instruction_envelope.h" #include "actormsg/CreateActorMessage.h" #include "actormsg/CallActorMessage.h" #include "actormsg/StopActorMessage.h" #include "actormsg/StopActorProcessMessage.h" #include "actormsg/GetFutureDataMessage.h" #include "actormsg/RegisterFutureMessage.h" #include "actormsg/ReleaseFutureMessage.h" #include "actormsg/GetResultPartsMessage.h" #include "actormsg/StoreResultMessage.h" #include "actormsg/ReleaseResultPartMessage.h" #include "actormsg/DistributeVectorMessage.h" #include "actormsg/PrefetchMessage.h" #include "actormsg/FetchMessage.h" #include "actormsg/StoreResultPartMessage.h" namespace activebsp { std::shared_ptr <ActorMessage> ActorMessageFactory::createMessage(int src, char * buf, int bufsize) { instruction_envelope_t * instruction_envelope = (instruction_envelope_t *) buf; char * cpy; switch (instruction_envelope->instruction) { case INSTRUCTION_CREATE_ACTOR: return std::make_shared<CreateActorMessage>(src, buf, bufsize); case INSTRUCTION_CALL_ACTOR: cpy = new char[bufsize]; memcpy(cpy, buf, bufsize); return std::make_shared<CallActorMessage>(src, cpy, bufsize); case INSTRUCTION_DESTROY_ACTOR: return std::make_shared<StopActorMessage>(src, buf, bufsize); case INSTRUCTION_STOP: return std::make_shared<StopActorProcessMessage>(src, buf, bufsize); case INSTRUCTION_REGISTER_FUTURE_DATA: return std::make_shared<RegisterFutureMessage>(src, buf, bufsize); case INSTRUCTION_GET_FUTURE_DATA: return std::make_shared<GetFutureDataMessage>(src, buf, bufsize); case INSTRUCTION_RELEASE_FUTURE: return std::make_shared<ReleaseFutureMessage>(src, buf, bufsize); case INSTRUCTION_GET_RESULT_PARTS: return std::make_shared<GetResultPartsMessage>(src, buf, bufsize); case INSTRUCTION_STORE_RESULT: return std::make_shared<StoreResultMessage>(src, buf, bufsize); case INSTRUCTION_RELEASE_RESULT: return std::make_shared<ReleaseResultPartMessage>(src, buf, bufsize); case INSTRUCTION_DISTRIBUTE_VECTOR: return std::make_shared<DistributeVectorMessage>(src, buf, bufsize); case INSTRUCTION_PREFETCH: return std::make_shared<PrefetchMessage>(src, buf, bufsize); case INSTRUCTION_FETCH: return std::make_shared<FetchMessage>(src, buf, bufsize); case INSTRUCTION_STORE_RESULT_PART: return std::make_shared<StoreResultPartMessage>(src, buf, bufsize); default: std::cerr << "Warning, received unknown message with instruction tag " << instruction_envelope->instruction << std::endl; return nullptr; break; } } ActorMessageFactory * ActorMessageFactory::getInstance() { if (_instance == NULL) { _instance = new ActorMessageFactory(); } return _instance; } ActorMessageFactory * ActorMessageFactory::_instance = NULL; } // namespace activebsp
32.55914
129
0.743725
fbaude
acfca67ccd3faad7d5441e1f271cc7e0fee5d87d
3,273
cpp
C++
World.cpp
goopey7/goopFramework
c1f039c8e8b2c8d7f07cad9ed4806d371c246d4e
[ "MIT" ]
null
null
null
World.cpp
goopey7/goopFramework
c1f039c8e8b2c8d7f07cad9ed4806d371c246d4e
[ "MIT" ]
null
null
null
World.cpp
goopey7/goopFramework
c1f039c8e8b2c8d7f07cad9ed4806d371c246d4e
[ "MIT" ]
null
null
null
//Copyright Sam Collier 2022 //************************************************************************************** //Heavily influenced by //Chapter 3 of SFML Game Development by Artur Moreira, Henrik V. Hansson, and Jan Haller //************************************************************************************** #include "World.h" #include "Vector.h" World::World(sf::RenderWindow& window) : window(window),spawnPos(100.f,100.f) { buildGraph(); } void World::buildGraph() { // Initialize Layers for(int i=0;i<layerCount;i++) { Node::NodePtr layer(new Node()); worldLayers[i] = layer.get(); worldGraph.attachChild(std::move(layer)); } } void World::update(const float dt) { worldGraph.update(dt); } void World::fixedUpdate(const float dt) { // Broadcast commands to sceneGraph while(!commandQueue.isEmpty()) worldGraph.onCommand(commandQueue.pop(),dt); // check dynamic vs static collisions for(int i=0;i<dynamicCollidingActors.size();i++) { for(int j=0;j<collidingActors.size();j++) { Collision::ResolveDynamicVStatic(dynamicCollidingActors[i], collidingActors[j], dt); } } worldGraph.fixedUpdate(dt); } void World::draw() { window.draw(worldGraph); } World::~World() { } CommandQueue& World::getCommandQueue() { return commandQueue; } void World::loadFromFile(const char* fileName, TextureHolder& textures, unsigned int numTextures) { using nlohmann::json; std::ifstream file(fileName); json map = json::parse(file); json layers = map["layers"]; std::map<std::string,int> tileSets; for(int i=0; i<map["tilesets"].size();i++) { tileSets[map["tilesets"].at(i)["image"]] = map["tilesets"].at(i)["firstgid"]; } std::cout << "\n===============================\n"; for(auto pair : tileSets) { std::cout << pair.first << " /// " << pair.second << '\n'; } int mapWidth = map["width"], mapHeight = map["height"]; int tileWidth = map["tilewidth"], tileHeight = map["tileheight"]; unsigned int textureID = numTextures; for(auto pair : tileSets) { textures.load(textureID++,pair.first); } for(json layer : layers) { if(!layer["data"].is_null()) { std::vector<int> layout = layer["data"]; int i = 0; for(int y = 0; y<mapHeight; y++) { for(int x = 0; x<mapWidth; x++) { if(layout[i] != 0) { std::unique_ptr<Actor> tile(new Actor(textures,this)); tile->setTexture(textureID-1); tile->setPosition(x*tileWidth,y*tileHeight); sf::IntRect texRect = sf::IntRect( (layout[i]-1)*tileWidth,0, tileWidth,tileHeight); tile->setTextureRect(texRect); addNode(&tile,Tile); } i++; } } } if(!layer["objects"].is_null()) { for(json object : layer["objects"]) { sf::FloatRect rect = sf::FloatRect(object["x"],object["y"],object["width"],object["height"]); if(object["properties"].at(0)["value"] == "block") { std::unique_ptr<Actor> colBox(new Actor(textures,this)); colBox->setPosition(0.f,0.f); colBox->setCollisionBox(sf::FloatRect(rect.left,rect.top,rect.width,rect.height)); colBox->enableCollision(true); addNode(&colBox,Object); } } } } } sf::RenderWindow* World::getWindow() { return &window; } float World::getViewScale() { return viewScale; }
22.729167
97
0.603727
goopey7
4a01147693bd6aa11235738687d4046c8d74519b
14,911
cpp
C++
Modules/LibVideo/VideoPart.cpp
alanzw/FGCG
9819ff9c543cf52bfac16655d1d30417291b5d4c
[ "Apache-2.0" ]
13
2016-10-24T11:39:12.000Z
2021-04-11T13:24:05.000Z
Modules/LibVideo/VideoPart.cpp
zhangq49/sharerender
9819ff9c543cf52bfac16655d1d30417291b5d4c
[ "Apache-2.0" ]
1
2016-12-12T01:11:02.000Z
2016-12-12T01:11:02.000Z
Modules/LibVideo/VideoPart.cpp
zhangq49/sharerender
9819ff9c543cf52bfac16655d1d30417291b5d4c
[ "Apache-2.0" ]
4
2018-06-05T03:39:06.000Z
2020-06-06T04:44:20.000Z
#include "Config.h" #include "Commonwin32.h" #include <stdio.h> #include <string.h> #include <time.h> #include <map> #include "RtspConf.h" #include "RtspContext.h" #include "Pipeline.h" #include "Encoder.h" #include "FilterRGB2YUV.h" #include "VSource.h" #include "ChannelManager.h" #include "EncoderManager.h" #include "CThread.h" #include "VideoPart.h" #include "../LibCore/Log.h" #include "../LibCore/InfoRecorder.h" const char * imagepipefmt = "image-%d"; static const char * imagepipe0 = "image-0"; const char * surfacepipefmt = "surface-%d"; const char * surfacepipe0 = "surface-0"; const char * filterpipefmt = "filter-%d"; static const char * filterpipe0 = "filter-0"; static const char * encoderpipefmt = "encoder-%d"; static const char * encoderpipe0 = "encoder-0"; HANDLE videoInitMutex = NULL; /// globals GlobalManager * GlobalManager::m_manager = NULL; GlobalManager * globalManager = NULL; bool encoderRunning = true; map<DWORD, SOCKET> threadSocketMap; SOCKET clientSocket = 0; GlobalManager::GlobalManager(){ encoderManager = NULL; channelManager = NULL; filter = NULL; rtspConf = NULL; } GlobalManager::~GlobalManager(){ if (encoderManager){ EncoderManager::ReleaseEncoderManager(encoderManager); encoderManager = NULL; } if (channelManager){ //ChannelManager::ReleaseChannelManager(); channelManager = NULL; } if (rtspConf){ delete rtspConf; rtspConf = NULL; } } NetParam::NetParam(SOCKET s){ int remoteLen = sizeof(SOCKADDR_IN); this->sock = s; getpeername(sock, (SOCKADDR *)&this->remoteAddr, &remoteLen); this->remotePort = DWORD(ntohs(remoteAddr.sin_port)); } static int Init(char * config, NetParam * net){ srand((int)time(0)); netStarted = true; if (!netStarted){ WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) return -1; else netStarted = true; } av_register_all(); avcodec_register_all(); avformat_network_init(); globalManager = GlobalManager::GetGlobalManager(); // create the channel manager globalManager->init(config); // deal with the client addr and port // accept the request from logic server return 0; } ////// the rtcpheader definition struct RTCPHeader { unsigned char vps; // version, padding, RC/SC #define RTCP_Version(hdr) (((hdr)->vps) >> 6) #define RTCP_Padding(hdr) ((((hdr)->vps) >> 5) & 0x01) #define RTCP_RC(hdr) (((hdr)->vps) & 0x1f) #define RTCP_SC(hdr) RTCP_RC(hdr) unsigned char pt; unsigned short length; } #ifdef WIN32 ; #else __attribute__((__packed__)); #endif static void SkipSpaces(const char **pp) { const char *p; p = *pp; while (*p == ' ' || *p == '\t') p++; *pp = p; } static void GetWord(char *buf, int buf_size, const char **pp) { const char *p; char *q; p = *pp; SkipSpaces(&p); q = buf; while (!isspace(*p) && *p != '\0') { if ((q - buf) < buf_size - 1) *q++ = *p; p++; } if (buf_size > 0) *q = '\0'; *pp = p; } static int handle_rtcp(RTSPContext * ctx, const char *buf, size_t buflen){ return 0; } /// the rtspserver thread proc static int channelCount = 0; DWORD WINAPI RtspServerThreadProc(LPVOID arg){ Channel * ch = (Channel *)arg; SOCKET s = ch->getClientSock(); int sinlen = sizeof(struct sockaddr_in); const char *p; char buf[8192]; char cmd[32], url[1024], protocol[32]; int rlen; struct sockaddr_in sin; RTSPContext ctx; RTSPMessageHeader header1, *header = &header1; // get the RTSPcontext for the channel channelCount++; ch->setChannelId(channelCount); RTSPConf* rtspConf = ch->getRtspConf(); ///set the context config sinlen = sizeof(sin); infoRecorder->logError("[RtspServer]: set config:%p.\n", rtspConf); getpeername(s, (struct sockaddr*) &sin, &sinlen); bzero(&ctx, sizeof(ctx)); ctx.setConf(rtspConf); if (ctx.clientInit(ch->gSources, ch->getMaxWidth(), ch->getMaxHeight()) < 0) { infoRecorder->logTrace("server initialization failed.\n"); return NULL; } bcopy(&sin, &ctx.client, sizeof(ctx.client)); ctx.state = SERVER_STATE_IDLE; // XXX: hasVideo is used to sync audio/video // This value is increased by 1 for each captured frame until it is gerater than zero // when this value is greater than zero, audio encoding then starts ... //ctx.hasVideo = -(rtspconf->video_fps>>1); // for slow encoders? ctx.hasVideo = 0; // with 'zerolatency' /// create the write mutex ctx.rtspWriteMutex = CreateMutex(NULL, FALSE, NULL); infoRecorder->logTrace("[tid %ld] client connected from %s:%d\n", ccg_gettid(), inet_ntoa(sin.sin_addr), htons(sin.sin_port)); ctx.fd = s; ChannelManager * chm = ChannelManager::GetChannelManager(); chm->mapRtspContext(ch, &ctx); ch->getEncoder()->setRTSPContext(&ctx); // register the rtsp context to encoder manager infoRecorder->logTrace("[rtspserver]: start filter thread.\n"); ch->startFilter(); do { int i, fdmax, active; fd_set rfds; struct timeval to; FD_ZERO(&rfds); FD_SET(ctx.fd, &rfds); fdmax = ctx.fd; #ifdef HOLE_PUNCHING for (int i = 0; i < 2 * ctx.streamCount; i++){ FD_SET(ctx.rtpSocket[i], &rfds); if (ctx.rtpSocket[i] > fdmax) fdmax = ctx.rtpSocket[i]; } #endif to.tv_sec = 0; to.tv_usec = 500000; if ((active = select(fdmax + 1, &rfds, NULL, NULL, &to)) < 0) { infoRecorder->logTrace("select() failed: %s\n", strerror(errno)); goto quit; } if (active == 0) { // try again! continue; } #ifdef HOLE_PUNCHING for (i = 0; i < 2 * ctx.streamCount; i++) { struct sockaddr_in xsin; #ifdef WIN32 int xsinlen = sizeof(xsin); #else socklen_t xsinlen = sizeof(xsin); #endif if (FD_ISSET(ctx.rtpSocket[i], &rfds) == 0) continue; recvfrom(ctx.rtpSocket[i], buf, sizeof(buf), 0, (struct sockaddr*) &xsin, &xsinlen); if (ctx.rtpPortChecked[i] != 0) continue; // XXX: port should not flip-flop, so check only once if (xsin.sin_addr.s_addr != ctx.client.sin_addr.s_addr) { infoRecorder->logError("RTP: client address mismatched? %u.%u.%u.%u != %u.%u.%u.%u\n", NIPQUAD(ctx.client.sin_addr.s_addr), NIPQUAD(xsin.sin_addr.s_addr)); continue; } if (xsin.sin_port != ctx.rtpPeerPort[i]) { infoRecorder->logError("RTP: client port reconfigured: %u -> %u\n", (unsigned int)ntohs(ctx.rtpPeerPort[i]), (unsigned int)ntohs(xsin.sin_port)); ctx.rtpPeerPort[i] = xsin.sin_port; } else { infoRecorder->logError("RTP: client is not under an NAT, port %d confirmed\n", (int)ntohs(ctx.rtpPeerPort[i])); } ctx.rtpPortChecked[i] = 1; } // is RTSP connection? if (FD_ISSET(ctx.fd, &rfds) == 0) continue; #endif // read commands if ((rlen = ctx.rtspGetNext(buf, sizeof(buf))) < 0) { goto quit; } // Interleaved binary data? if (buf[0] == '$') { handle_rtcp(&ctx, buf, rlen); continue; } // REQUEST line infoRecorder->logTrace("%s", buf); p = buf; GetWord(cmd, sizeof(cmd), &p); GetWord(url, sizeof(url), &p); GetWord(protocol, sizeof(protocol), &p); // check protocol if (strcmp(protocol, "RTSP/1.0") != 0) { infoRecorder->logTrace("[rtsp server]: protocol not supported.\n"); ctx.rtspReplyError(RTSP_STATUS_VERSION); goto quit; } // read headers bzero(header, sizeof(*header)); do { int myseq = -1; char mysession[sizeof(header->session_id)] = ""; if ((rlen = ctx.rtspGetNext(buf, sizeof(buf))) < 0) goto quit; if (buf[0] == '\n' || (buf[0] == '\r' && buf[1] == '\n')) break; // Special handling to CSeq & Session header // ff_rtsp_parse_line cannot handle CSeq & Session properly on Windows // any more? if (strncasecmp("CSeq: ", buf, 6) == 0) { myseq = strtol(buf + 6, NULL, 10); } if (strncasecmp("Session: ", buf, 9) == 0) { strcpy(mysession, buf + 9); } // ff_rtsp_parse_line(header, buf, NULL, NULL); // if (myseq > 0 && header->seq <= 0) { infoRecorder->logError("WARNING: CSeq fixes applied (%d->%d).\n", header->seq, myseq); header->seq = myseq; } if (mysession[0] != '\0' && header->session_id[0] == '\0') { unsigned i; for (i = 0; i < sizeof(header->session_id) - 1; i++) { if (mysession[i] == '\0' || isspace(mysession[i]) || mysession[i] == ';') break; header->session_id[i] = mysession[i]; } header->session_id[i + 1] = '\0'; infoRecorder->logError("WARNING: Session fixes applied (%s)\n", header->session_id); } } while (1); // special handle to session_id if (header->session_id != NULL) { char *p = header->session_id; while (*p != '\0') { if (*p == '\r' || *p == '\n') { *p = '\0'; break; } p++; } } // handle commands ctx.seq = header->seq; if (!strcmp(cmd, "DESCRIBE")) ctx.rtspCmdDescribe(url); else if (!strcmp(cmd, "OPTIONS")) ctx.rtspCmdOptions(url); else if (!strcmp(cmd, "SETUP")) ctx.rtspCmdSetup(url, header, ch->getChannelId()); else if (!strcmp(cmd, "PLAY")) ctx.rtspCmdPlay(url, header); else if (!strcmp(cmd, "PAUSE")) ctx.rtspCmdPause(url, header); else if (!strcmp(cmd, "TEARDOWN")) ctx.rtspCmdTeardown(url, header, 1); else ctx.rtspReplyError(RTSP_STATUS_METHOD); if (ctx.state == SERVER_STATE_TEARDOWN) { break; } } while (1); quit: ctx.state = SERVER_STATE_TEARDOWN; // closesocket(ctx.fd); #ifdef SHARE_ENCODER EncoderManager * encoderManager = globalManager->encoderManager; encoderManager->encoderUnregisterClient(&ctx); // encoder_unregister_client(&ctx); #else infoRecorder->logTrace("connection closed, checking for worker threads...\n"); // wait the other thread to finish WaitForSingleObject(ctx.vThread, INFINITE); //pthread_join(ctx.vthread, (void**)&thread_ret); #ifdef ENABLE_AUDIO WaitForSingleObject(ctx.aThread, INFINITE); //pthread_join(ctx.athread, (void**)&thread_ret); #endif /* ENABLE_AUDIO */ #endif /* SHARE_ENCODER */ // ctx.clientDeinit(); infoRecorder->logTrace("RTSP client thread terminated.\n"); // return NULL; } void DestoryAll(){ Channel::Release(); RTSPConf::Release(); //RTSPContext::Release(); Filter::Release(); pipeline::Release(); ChannelManager::Release(); EncoderManager::Release(); } DWORD WINAPI VideoServer(LPVOID param){ infoRecorder->logTrace("[VideoServer]: entner the video server.\n"); Channel * ch = (Channel *)param; RTSPConf * rtspconf = NULL; int chId = 0; char imagepipename[64]; char filterpipename[64]; char surfacepipename[64]; // create the mutex videoInitMutex = CreateMutex(NULL, FALSE, NULL); WaitForSingleObject(videoInitMutex, INFINITE); /* create the rtsp connection to client */ if (!netStarted){ // start the network service #if 0 Init(RENDERPOOL_CONFIG, netParam); #else Init(RENDERPOOL_CONFIG, NULL); #endif netStarted = true; } rtspconf = globalManager->getGlobalConfig(); // deal with request SOCKET rtspSock, rtspClientSock; struct sockaddr_in sin, csin; int csInLen = 0; if ((rtspSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ infoRecorder->logError("[video server]: ERROR: create socket failed!\n"); return -1; } do{ BOOL val = 1; setsockopt(rtspSock, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val)); } while (0); bzero(&sin, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(globalManager->getGlobalConfig()->serverport); infoRecorder->logError("[video server]: bind port:%d.\n", globalManager->getGlobalConfig()->serverport); if (bind(rtspSock, (struct sockaddr *)&sin, sizeof(sin)) < 0){ infoRecorder->logError("[VIDEO SERVER] ERROR: bind error!\n"); return -1; } infoRecorder->logError("[video server]: start to listen port.\n"); if (listen(rtspSock, 256) < 0){ infoRecorder->logError("[video server] ERROR: listen error\n"); return -1; } ReleaseMutex(videoInitMutex); atexit(DestoryAll); // accept the client to play int request = 0; do{ Log::logscreen("[video server]: wait for client...\n"); infoRecorder->logError("[video server]: wait for client...\n"); csInLen = sizeof(csin); bzero(&csin, sizeof(csin)); if ((rtspClientSock = accept(rtspSock, (struct sockaddr *)&csin, &csInLen)) < 0){ infoRecorder->logError("[VIDEO SERVER] ERROR: accept error!\n"); return -1; } Log::logscreen("[video server]: accepted a rtsp client.\n"); request++; // a new request has been accepted // tunning the sending window int sndWnd = 8388608; // 8MB if (setsockopt(rtspClientSock, SOL_SOCKET, SO_SNDBUF, &sndWnd, sizeof(sndWnd)) == 0){ infoRecorder->logError("[VIDEO SERVER] INFO: set the tcp sending buffer success\n"); } else{ infoRecorder->logError("[VIDEO SERVER] ERROR: set the tcp sending buffer failed.\n"); } // start the video thread DWORD threadId; sprintf(imagepipename, imagepipefmt, chId); sprintf(filterpipename, filterpipefmt, chId); sprintf(surfacepipename, surfacepipefmt, chId); infoRecorder->logTrace("[rtsp server]: image pipenmae:%s, surface pipename:%s, filterpipename:%s.\n", imagepipename, surfacepipename, filterpipename); // init the channel, create the encoder if (ch == NULL){ infoRecorder->logTrace("[video part]: get NULL channel in video server.\n"); } ch->setSrcPipeName(imagepipename); ch->setSurfacePipeName(surfacepipename); ch->setFilterPipeName(filterpipename); ENCODER_TYPE type = globalManager->encoderManager->getAvailableType(); // TODO // to form a cuda encoder with image source type = ENCODER_TYPE::X264_ENCODER; Encoder * encoder = globalManager->encoderManager->getEncoder(type); Filter * filter = NULL; D3DWrapper * wrapper = NULL; SOURCE_TYPE sourceType = SOURCE_TYPE::SOURCE_NONE; ch->setEncoderType(type); //encoder->setRTSPContext(globalManager->); ch->setRtspConf(rtspconf); encoder->setSrcPipeName(filterpipename); // set the encoder source pipe name ch->registerEncoder(encoder); if (type == ENCODER_TYPE::X264_ENCODER){ sourceType = SOURCE_TYPE::IMAGE; // init the filter filter = new Filter(); // register filter Filter::do_register(filterpipename, filter); //filter->init(ch->getChannelName(), "filter1"); // init the filter for the x264 encoder } else if (type == ENCODER_TYPE::CUDA_ENCODER){ sourceType = SOURCE_TYPE::SURFACE; } else { sourceType = SOURCE_TYPE::IMAGE; type = ENCODER_TYPE::X264_ENCODER; // init the filter filter = new Filter(); Filter::do_register(filterpipename, filter); //filter->init(ch->getChannelName(), "filter2"); } ch->waitForDeviceAndWindowHandle(); if (filter){ ch->setFilter(filter); } // init the channel, specifically, init the source pipe ch->init(type, sourceType); ch->setClientSock(rtspClientSock); // start the rtsp server thread Log::logscreen("[video server]: start the rtsp server thread.\n"); infoRecorder->logError("[video server]: start the rtsp server thread.\n"); HANDLE thread = chBEGINTHREADEX(NULL, 0, RtspServerThreadProc, ch, 0, &threadId); chId++; } while (1); return 0; }
27.715613
152
0.669237
alanzw
4a0781cdb0f5ff86aba1554b7b52f1bef432cbe7
45
hpp
C++
src/boost_type_traits_is_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_type_traits_is_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_type_traits_is_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/type_traits/is_volatile.hpp>
22.5
44
0.822222
miathedev
4a11437123f5049e8548df746456153d51350d63
7,423
cc
C++
plugins/events/JointEventSource.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
5
2017-07-14T19:36:51.000Z
2020-04-01T06:47:59.000Z
plugins/events/JointEventSource.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
20
2017-07-20T21:04:49.000Z
2017-10-19T19:32:38.000Z
plugins/events/JointEventSource.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015-2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <limits> #include <string> #include "JointEventSource.hh" using namespace gazebo; //////////////////////////////////////////////////////////////////////////////// JointEventSource::JointEventSource(transport::PublisherPtr _pub, physics::WorldPtr _world) :EventSource(_pub, "joint", _world), range(INVALID), isTriggered(false) { this->min = std::numeric_limits<double>::lowest(); this->max = std::numeric_limits<double>::max(); } //////////////////////////////////////////////////////////////////////////////// void JointEventSource::Load(const sdf::ElementPtr _sdf) { // Listen to the update event. This event is broadcast every // simulation iteration. this->updateConnection = event::Events::ConnectWorldUpdateBegin( boost::bind(&JointEventSource::Update, this)); EventSource::Load(_sdf); if (_sdf->HasElement("model")) { this->modelName = _sdf->Get<std::string>("model"); } else { gzerr << this->name << " is missing a model element" << std::endl; } if (_sdf->HasElement("joint")) { this->jointName = _sdf->Get<std::string>("joint"); } else { gzerr << this->name << " is missing a joint element" << std::endl; } if (_sdf->HasElement("range")) { sdf::ElementPtr rangeElem = _sdf->GetElement("range"); if (!rangeElem->HasElement("min") && !rangeElem->HasElement("max") ) { gzerr << this->name << ": <range>" << " should have a min and (or) a max element." << std::endl; } if (rangeElem->HasElement("min")) { this->min = rangeElem->Get<double>("min"); } if (rangeElem->HasElement("max")) { this->max = rangeElem->Get<double>("max"); } if (rangeElem->HasElement("type")) { std::string typeStr = rangeElem->Get<std::string>("type"); this->SetRangeFromString(typeStr); if (this->range == INVALID) { gzerr << this->name << " has an invalid \"" << typeStr << " \" range type. " << " It should be one of: \"position\"," << " \"normalized_angle\", \"velocity\" or \"applied_force\"" << std::endl; } } else { gzerr << this->name << ": range is missing a type element" << std::endl; } } else { gzerr << this->name << " is missing a range element" << std::endl; } } //////////////////////////////////////////////////////////////////////////////// void JointEventSource::Init() { this->Info(); } //////////////////////////////////////////////////////////////////////////////// void JointEventSource::SetRangeFromString(const std::string &_rangeStr) { if (_rangeStr == "position") this->range = POSITION; else if (_rangeStr == "normalized_angle") this->range = ANGLE; else if (_rangeStr == "applied_force") this->range = FORCE; else if (_rangeStr == "velocity") this->range = VELOCITY; else this->range = INVALID; } //////////////////////////////////////////////////////////////////////////////// std::string JointEventSource::RangeAsString() const { std::string rangeStr; switch (this->range) { case POSITION: rangeStr = "position"; break; case VELOCITY: rangeStr = "velocity"; break; case ANGLE: rangeStr = "normalized_angle"; break; case FORCE: rangeStr = "applied_force"; break; default: rangeStr = "invalid"; break; } return rangeStr; } //////////////////////////////////////////////////////////////////////////////// void JointEventSource::Info() const { std::stringstream ss; ss << "JointEventSource: " << this->name << " model: " << this->modelName << " joint: " << this->jointName << " range: " << this->RangeAsString() << " min: " << this->min << " max: " << this->max << " triggered: " << this->isTriggered << std::endl; gzmsg << ss.str(); } //////////////////////////////////////////////////////////////////////////////// bool JointEventSource::LookupJoint() { if (!this->model) { this->model = this->world->GetModel(this->modelName); // if the model name is not found if (!this->model) { // look for a model with a name that starts with our model name for (unsigned int i = 0; i < this->world->GetModelCount(); ++i) { physics::ModelPtr m = this->world->GetModel(i); size_t pos = m->GetName().find(this->modelName); if (pos == 0) { this->model = m; break; } } } } // if we have a model, let's look for the joint (full joint name only) if (this->model && !this->joint) { this->joint = this->model->GetJoint(this->jointName); } if (!this->model || !this->joint) { return false; } return true; } //////////////////////////////////////////////////////////////////////////////// void JointEventSource::Update() { if (!this->LookupJoint()) return; bool oldState = this->isTriggered; double value = 0; double position = this->joint->GetAngle(0).Radian(); math::Angle a = this->joint->GetAngle(0); // get a value between -PI and PI a.Normalize(); double angle = a.Radian(); double force = this->joint->GetForce(0); double velocity = this->joint->GetVelocity(0); switch (this->range) { case POSITION: { value = position; break; } case VELOCITY: { value = velocity; break; } case ANGLE: { value = angle; break; } case FORCE: { value = force; break; } default: // we can't do anything useful. Hopefully the error message during load // has attracted the attention of the user. return; } // check if the state has changed bool currentState = value >= this->min && value <= this->max; if (oldState != currentState) { this->isTriggered = currentState; std::string json = "{"; if (currentState) { json += "\"state\":\"in_range\","; } else { json += "\"state\":\"out_of_range\","; } json += "\"joint\":\"" + this->jointName + "\", "; json += "\"position\":\"" + std::to_string(position) + "\", "; json += "\"velocity\":\"" + std::to_string(velocity) + "\", "; json += "\"force\":\"" + std::to_string(force) + "\", "; if (this->range == ANGLE) json += "\"angle\":\"" + std::to_string(angle) + "\", "; json += "\"range\":\"" + this->RangeAsString() + "\", "; json += "\"min\":\"" + std::to_string(this->min) + "\", "; json += "\"max\":\"" + std::to_string(this->max) + "\", "; json += "\"value\":\"" + std::to_string(value) + "\", "; json += "\"model\":\"" + this->modelName + "\""; json += "}"; this->Emit(json); } }
26.510714
80
0.5227
otamachan
4a1c9ff4d1e64ff7640dfac693f12102ff66ed14
2,606
hpp
C++
include/binapi/errors.hpp
ihsanturk/binapi
8d5589d84fc0085b1d2739fed29dc901a5e7ad6c
[ "Apache-2.0" ]
98
2020-08-08T13:12:25.000Z
2022-03-26T14:47:02.000Z
include/binapi/errors.hpp
ihsanturk/binapi
8d5589d84fc0085b1d2739fed29dc901a5e7ad6c
[ "Apache-2.0" ]
55
2020-08-29T13:00:59.000Z
2022-02-12T13:05:26.000Z
include/binapi/errors.hpp
ihsanturk/binapi
8d5589d84fc0085b1d2739fed29dc901a5e7ad6c
[ "Apache-2.0" ]
48
2020-11-05T14:11:58.000Z
2022-03-27T23:51:18.000Z
// ---------------------------------------------------------------------------- // Apache License // Version 2.0, January 2004 // http://www.apache.org/licenses/ // // This file is part of binapi(https://github.com/niXman/binapi) project. // // Copyright (c) 2019-2021 niXman (github dot nixman dog pm.me). All rights reserved. // ---------------------------------------------------------------------------- #ifndef __binapi__errors_hpp #define __binapi__errors_hpp #include <string> #include <utility> namespace flatjson { struct fjson; } // ns flatjson namespace binapi { namespace rest { /*************************************************************************************************/ // https://github.com/binance/binance-spot-api-docs/blob/master/errors.md enum class e_error: int { OK = 0 ,UNKNOWN = -1000 ,DISCONNECTED = -1001 ,UNAUTHORIZED = -1002 ,TOO_MANY_REQUESTS = -1003 ,UNEXPECTED_RESP = -1006 ,TIMEOUT = -1007 ,UNKNOWN_ORDER_COMPOSITION = -1014 ,TOO_MANY_ORDERS = -1015 ,SERVICE_SHUTTING_DOWN = -1016 ,UNSUPPORTED_OPERATION = -1020 ,INVALID_TIMESTAMP = -1021 ,INVALID_SIGNATURE = -1022 ,ILLEGAL_CHARS = -1100 ,TOO_MANY_PARAMETERS = -1101 ,MANDATORY_PARAM_EMPTY_OR_MALFORMED = -1102 ,UNKNOWN_PARAM = -1103 ,UNREAD_PARAMETERS = -1104 ,PARAM_EMPTY = -1105 ,PARAM_NOT_REQUIRED = -1106 ,BAD_PRECISION = -1111 ,NO_DEPTH = -1112 ,TIF_NOT_REQUIRED = -1114 ,INVALID_TIF = -1115 ,INVALID_ORDER_TYPE = -1116 ,INVALID_SIDE = -1117 ,EMPTY_NEW_CL_ORD_ID = -1118 ,EMPTY_ORG_CL_ORD_ID = -1119 ,BAD_INTERVAL = -1120 ,BAD_SYMBOL = -1121 ,INVALID_LISTEN_KEY = -1125 ,MORE_THAN_XX_HOURS = -1127 ,OPTIONAL_PARAMS_BAD_COMBO = -1128 ,INVALID_PARAMETER = -1130 ,NEW_ORDER_REJECTED = -2010 ,CANCEL_REJECTED = -2011 ,NO_SUCH_ORDER = -2013 ,BAD_API_KEY_FMT = -2014 ,REJECTED_MBX_KEY = -2015 ,NO_TRADING_WINDOW = -2016 }; const char* e_error_to_string(e_error v); const char* e_error_to_string(int v); inline bool e_error_equal(int v, e_error err) { return v == static_cast<int>(err); } /*************************************************************************************************/ bool is_api_error(const flatjson::fjson &json); std::pair<int, std::string> construct_error(const flatjson::fjson &json); /*************************************************************************************************/ } // ns rest } // ns binapi #endif // __binapi__errors_hpp
29.280899
99
0.550269
ihsanturk
4a1ce07e2059057824a62d5cf0726202dff0848f
40,177
cxx
C++
MUON/MUONmapping/AliMpDCSNamer.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
MUON/MUONmapping/AliMpDCSNamer.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
2
2016-11-25T08:40:56.000Z
2019-10-11T12:29:29.000Z
MUON/MUONmapping/AliMpDCSNamer.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMpDCSNamer.h" #include "AliCodeTimer.h" #include "AliLog.h" #include "AliMpArea.h" #include "AliMpDEIterator.h" #include "AliMpDEManager.h" #include "AliMpHelper.h" #include "AliMpMotifMap.h" #include "AliMpMotifPosition.h" #include "AliMpSector.h" #include "AliMpSegmentation.h" #include "AliMpSlat.h" #include "AliMpConstants.h" #include <Riostream.h> #include <TMap.h> #include <TObjArray.h> #include <TObjString.h> #include <TString.h> #include <TSystem.h> #include <cassert> //----------------------------------------------------------------------------- /// \class AliMpDCSNamer /// /// A utility class to manage DCS aliases names, in particular the /// two conventions used to number the detection elements within a detector. /// /// \author: Laurent Aphecetche and Diego Stocco, Subatech //----------------------------------------------------------------------------- using std::cout; using std::endl; /// \cond CLASSIMP ClassImp(AliMpDCSNamer) /// \endcond const char* AliMpDCSNamer::fgkDCSChannelSt345Pattern[] = { "MchHvLvLeft/Chamber%02dLeft/Slat%02d.actual.vMon", "MchHvLvRight/Chamber%02dRight/Slat%02d.actual.vMon" }; const char* AliMpDCSNamer::fgkDCSChannelSt12Pattern[] = { "MchHvLvLeft/Chamber%02dLeft/Quad%dSect%d.actual.vMon", "MchHvLvRight/Chamber%02dRight/Quad%dSect%d.actual.vMon" }; const char* AliMpDCSNamer::fgkDCSQuadrantPattern[] = { "MchHvLvLeft/Chamber%02dLeft/Quad%d", "MchHvLvRight/Chamber%02dRight/Quad%d" }; const char* AliMpDCSNamer::fgkDCSChamberPattern[] = { "MchHvLvLeft/Chamber%02dLeft", "MchHvLvRight/Chamber%02dRight" }; const char* AliMpDCSNamer::fgkDCSMCHLVGroupPattern[] = { "MchHvLvLeft/Chamber%02dLeft/Group%d%s.MeasurementSenseVoltage", "MchHvLvRight/Chamber%02dRight/Group%d%s.MeasurementSenseVoltage" }; const char* AliMpDCSNamer::fgkDCSSideTrackerName[] = { "Left", "Right" }; const char* AliMpDCSNamer::fgkDCSSwitchSt345Pattern = "MchDE%04dsw%d.inValue"; const char* AliMpDCSNamer::fgkDCSChannelTriggerPatternRead[] = {"MTR_%3sSIDE_MT%2i_RPC%i_HV.%14s", "MTR_%2sSIDE_MT%2i_RPC%i_HV.%14s"}; const char* AliMpDCSNamer::fgkDCSChannelTriggerPattern[] = {"MTR_%3sSIDE_MT%2i_RPC%i_HV.%s", "MTR_%2sSIDE_MT%2i_RPC%i_HV.%s"}; const char* AliMpDCSNamer::fgkDCSSideTriggerName[] = { "OUT", "IN" }; const char* AliMpDCSNamer::fgkDCSMeasureName[] = { "vEff", "actual.iMon" }; const char* AliMpDCSNamer::fgkDetectorName[] = { "TRACKER", "TRIGGER" }; //_____________________________________________________________________________ AliMpDCSNamer::AliMpDCSNamer(): fDetector(-1) { SetDetector("TRACKER"); /// default ctor } //_____________________________________________________________________________ AliMpDCSNamer::AliMpDCSNamer(const char* detName): fDetector(-1) { /// ctor taking the detector name as argument (either trigger or tracker) SetDetector(detName); } //_____________________________________________________________________________ AliMpDCSNamer::~AliMpDCSNamer() { /// dtor } //_____________________________________________________________________________ Bool_t AliMpDCSNamer::SetDetector(const char* detName) { /// Set the detector type /// \param detName = tracker, trigger TString sDetName(detName); Bool_t isOk(kTRUE); sDetName.ToUpper(); if(sDetName.Contains(fgkDetectorName[kTrackerDet])) fDetector = kTrackerDet; else if(sDetName.Contains(fgkDetectorName[kTriggerDet])) fDetector = kTriggerDet; else { AliWarning("Detector name must be either tracker or trigger. Default tracker selected"); isOk = kFALSE; } return isOk; } //_____________________________________________________________________________ void AliMpDCSNamer::AliasesAsLdif(const char* ldiffile) const { /// Export the aliases in LDIF format ofstream out(ldiffile); TObjArray* a = CompactAliases(); TIter next(a); TObjString* s; // Some header. host name and port probably not up to date. TString detName = (fDetector == kTriggerDet) ? "MTR" : "MCH"; out << "#" << detName.Data() << " config" << endl << "dn: det=" << detName.Data() <<",o=alice,dc=cern,dc=ch" << endl << "objectClass: AliShuttleDetector" << endl << "det: " << detName.Data() << endl << "StrictRunOrder: 1" << endl << "responsible: aphecetc@in2p3.fr" << endl << "DCSHost: aldcs053.cern.ch" << endl << "DCSPort: 4242" <<endl; while ( ( s = (TObjString*)(next()) ) ) { out << "DCSalias: " << s->String().Data() << endl; } out.close(); delete a; } //_____________________________________________________________________________ TObjArray* AliMpDCSNamer::CompactAliases() const { /// Generate a compact list of aliases, for Shuttle test /// This one is completely hand-made, in contrast with GenerateAliases() /// method TObjArray* a = new TObjArray; a->SetOwner(kTRUE); switch(fDetector){ case kTrackerDet: // St 12 (DCS HV Channels) a->Add(new TObjString("MchHvLvRight/Chamber[00..03]Right/Quad0Sect[0..2].actual.vMon")); a->Add(new TObjString("MchHvLvLeft/Chamber[00..03]Left/Quad1Sect[0..2].actual.vMon")); a->Add(new TObjString("MchHvLvLeft/Chamber[00..03]Left/Quad2Sect[0..2].actual.vMon")); a->Add(new TObjString("MchHvLvRight/Chamber[00..03]Right/Quad3Sect[0..2].actual.vMon")); // St345 (DCS HV Channels) a->Add(new TObjString("MchHvLvRight/Chamber[04..09]Right/Slat[00..08].actual.vMon")); a->Add(new TObjString("MchHvLvLeft/Chamber[04..09]Left/Slat[00..08].actual.vMon")); a->Add(new TObjString("MchHvLvRight/Chamber[06..09]Right/Slat[09..12].actual.vMon")); a->Add(new TObjString("MchHvLvLeft/Chamber[06..09]Left/Slat[09..12].actual.vMon")); // (LV groups) // St12 have 4 LV groups a->Add(new TObjString("MchHvLvLeft/Chamber[01..10]Left/Group[1..4]dig.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvLeft/Chamber[01..10]Left/Group[1..4]ann.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvLeft/Chamber[01..10]Left/Group[1..4]anp.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[01..10]Right/Group[1..4]dig.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[01..10]Right/Group[1..4]ann.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[01..10]Right/Group[1..4]anp.MeasurementSenseVoltage")); // St3 has 5 LV groups a->Add(new TObjString("MchHvLvLeft/Chamber[05..06]Left/Group[5..5]dig.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvLeft/Chamber[05..06]Left/Group[5..5]ann.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvLeft/Chamber[05..06]Left/Group[5..5]anp.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[05..06]Right/Group[5..5]dig.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[05..06]Right/Group[5..5]ann.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[05..06]Right/Group[5..5]anp.MeasurementSenseVoltage")); // St4-5 have 7 LV groups a->Add(new TObjString("MchHvLvLeft/Chamber[07..10]Left/Group[5..7]dig.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvLeft/Chamber[07..10]Left/Group[5..7]ann.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvLeft/Chamber[07..10]Left/Group[5..7]anp.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[07..10]Right/Group[5..7]dig.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[07..10]Right/Group[5..7]ann.MeasurementSenseVoltage")); a->Add(new TObjString("MchHvLvRight/Chamber[07..10]Right/Group[5..7]anp.MeasurementSenseVoltage")); break; case kTriggerDet: a->Add(new TObjString("MTR_OUTSIDE_MT[11..12]Right/RPC[1..9]_HV.imon")); a->Add(new TObjString("MTR_OUTSIDE_MT[21..22]Right/RPC[1..9]_HV.imon")); a->Add(new TObjString("MTR_INSIDE_MT[11..12]Right/RPC[1..9]_HV.imon")); a->Add(new TObjString("MTR_INSIDE_MT[21..22]Right/RPC[1..9]_HV.imon")); a->Add(new TObjString("MTR_OUTSIDE_MT[11..12]Right/RPC[1..9]_HV.vmon")); a->Add(new TObjString("MTR_OUTSIDE_MT[21..22]Right/RPC[1..9]_HV.vmon")); a->Add(new TObjString("MTR_INSIDE_MT[11..12]Right/RPC[1..9]_HV.vmon")); a->Add(new TObjString("MTR_INSIDE_MT[21..22]Right/RPC[1..9]_HV.vmon")); } if(fDetector == kTrackerDet){ // St345 (DCS Switches) AliMpDEIterator it; it.First(); while (!it.IsDone()) { Int_t detElemId = it.CurrentDEId(); if ( AliMpDEManager::GetStationType(detElemId) == AliMp::kStation345 ) { a->Add(new TObjString(Form("MchDE%04dsw[0..%d].inValue",detElemId,NumberOfPCBs(detElemId)-1))); } it.Next(); } } return a; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::DCS2DE(Int_t chId, Int_t side, Int_t dcsNumber) const { /// Convert DCS Tracker "slat number" (old convention) to DE (new) convention. /// /// \param chamberId : chamber number (starting at 0) /// \param side : 0 for Left, 1 for Right /// \param dcsNumber : slat number in DCS convention /// /// note that dcsNumber should be >=0 and < number of DEs/2 in chamber Int_t de(-1); Int_t chamberId = chId; if(fDetector == kTrackerDet){ // Tracker Int_t nofDE = AliMpDEManager::GetNofDEInChamber(chamberId); Int_t half = nofDE/2; dcsNumber = half - dcsNumber; Int_t quarter = nofDE/4; Int_t threeQuarter = half + quarter; if ( side == 0 ) // left { de = threeQuarter + 1 - dcsNumber; } else if ( side == 1 ) // right { if ( dcsNumber <= quarter ) { de = dcsNumber + threeQuarter; } else { de = dcsNumber - quarter - 1; } } } else { // Trigger if ( chId < 19 ) chamberId = chId - 1; else chamberId = chId - 9; Int_t nofDE = AliMpDEManager::GetNofDEInChamber(chamberId); if ( side == 0 ) // left -> Outside { de = 14 - dcsNumber; } else if ( side == 1 ) // right -> Inside { if (nofDE>0) de = (13 + dcsNumber) % nofDE; } } return (chamberId+1)*100 + de; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::DetElemId2DCS(Int_t detElemId, Int_t& side, Int_t &chId) const { /// Convert DE to DCS "slat number" /// @see DCS2DE CheckConsistency(detElemId); Int_t chamberId = AliMpDEManager::GetChamberId(detElemId); if ( chamberId < 0 ) { AliDebug(1,Form("DetElemId %d invalid",detElemId)); return -1; } Int_t dcsNumber = (detElemId-(chamberId+1)*100); switch ( AliMpDEManager::GetStationType(detElemId) ) { case AliMp::kStation12: { chId = chamberId; switch (dcsNumber) { case 0: case 3: side = 1; // right break; case 1: case 2: side = 0; // left default: break; } } break; case AliMp::kStation345: { chId = chamberId; Int_t nofDE = AliMpDEManager::GetNofDEInChamber(chamberId); Int_t quarter = nofDE/4; Int_t half = nofDE/2; Int_t threeQuarter = half + quarter; side = -1; if ( dcsNumber <= quarter ) { dcsNumber += quarter + 1 ; side = 1; // right } else if ( dcsNumber <= threeQuarter ) { dcsNumber = ( threeQuarter - dcsNumber + 1 ); side = 0; // left } else if ( dcsNumber > threeQuarter ) { dcsNumber = dcsNumber - threeQuarter; side = 1; // right } else { AliFatal("oups"); } // dcs convention change : numbering from top, not from bottom dcsNumber = half-dcsNumber; } break; case AliMp::kStationTrigger: { if (chamberId < AliMpConstants::NofChambers()-2) chId = chamberId + 1; else chId = 23 + chamberId - AliMpConstants::NofChambers(); Int_t nofDE = AliMpDEManager::GetNofDEInChamber(chamberId); if ( dcsNumber >=5 && dcsNumber <= 13 ) { side = 0; dcsNumber = 14 - dcsNumber; } else { side = 1; if (nofDE>0) dcsNumber = (5 + dcsNumber) % nofDE; } AliDebug(10, Form("detElemId %i -> MT%i_side%i_L%i", detElemId, chId, side, dcsNumber)); } break; default: break; } return dcsNumber; } //_____________________________________________________________________________ TString AliMpDCSNamer::DCSNameFromAlias(const char* dcsAlias) const { /// Convert a (possibly partial) aliasname to a name (only for MCH HV) TString salias(dcsAlias); if ( !salias.Contains("MchHvLv") ) return dcsAlias; // not MCH if ( salias.Contains("Group")) return dcsAlias; // not MCH HV (but LV) Int_t quadrantNumber(-1); Int_t chamberNumber(-1); Int_t side(-1); if ( salias.Contains("Left")) side = 0; if ( salias.Contains("Right")) side = 1; if ( side < 0 ) return ""; TString channelName; if ( salias.Contains("Slat") ) { Int_t slatNumber(-1); sscanf(salias.Data(),fgkDCSChannelSt345Pattern[side],&chamberNumber,&slatNumber); ++chamberNumber; ++slatNumber; channelName = TString::Format(fgkDCSChannelSt345Pattern[side],chamberNumber,slatNumber); } else if ( salias.Contains("Sect") ) { Int_t sectorNumber(-1); sscanf(salias.Data(),fgkDCSChannelSt12Pattern[side],&chamberNumber,&quadrantNumber,&sectorNumber); ++chamberNumber; ++quadrantNumber; ++sectorNumber; channelName = TString::Format(fgkDCSChannelSt12Pattern[side],chamberNumber,quadrantNumber,sectorNumber); } else if ( salias.Contains("Quad") ) { sscanf(salias.Data(),fgkDCSQuadrantPattern[side],&chamberNumber,&quadrantNumber); ++chamberNumber; ++quadrantNumber; channelName = TString::Format(fgkDCSQuadrantPattern[side],chamberNumber,quadrantNumber); } else if ( salias.Contains("Chamber") ) { sscanf(salias.Data(),fgkDCSChamberPattern[side],&chamberNumber); ++chamberNumber; channelName = TString::Format(fgkDCSChamberPattern[side],chamberNumber); } if ( TString(dcsAlias).Contains("iMon") ) { channelName.ReplaceAll("vMon","iMon"); } return channelName; } //_____________________________________________________________________________ TString AliMpDCSNamer::DCSAliasFromName(const char* dcsName) const { /// Convert a (possibly partial) dcsname to an alias (only for MCH HV) TString sname(dcsName); if ( !sname.Contains("MchHvLv") ) return dcsName; if ( sname.Contains("Group")) return dcsName; // not MCH HV (but LV) Int_t quadrantNumber(-1); Int_t chamberNumber(-1); Int_t side(-1); if ( sname.Contains("Left")) side = 0; if ( sname.Contains("Right")) side = 1; if ( side < 0 ) return ""; TString channelName; if ( sname.Contains("Slat") ) { Int_t slatNumber(-1); sscanf(sname.Data(),fgkDCSChannelSt345Pattern[side],&chamberNumber,&slatNumber); --chamberNumber; --slatNumber; channelName = TString::Format(fgkDCSChannelSt345Pattern[side],chamberNumber,slatNumber); } else if ( sname.Contains("Sect") ) { Int_t sectorNumber(-1); sscanf(sname.Data(),fgkDCSChannelSt12Pattern[side],&chamberNumber,&quadrantNumber,&sectorNumber); --chamberNumber; --quadrantNumber; --sectorNumber; channelName = TString::Format(fgkDCSChannelSt12Pattern[side],chamberNumber,quadrantNumber,sectorNumber); } else if ( sname.Contains("Quad") ) { sscanf(sname.Data(),fgkDCSQuadrantPattern[side],&chamberNumber,&quadrantNumber); --chamberNumber; --quadrantNumber; channelName = TString::Format(fgkDCSQuadrantPattern[side],chamberNumber,quadrantNumber); } else if ( sname.Contains("Chamber") ) { sscanf(sname.Data(),fgkDCSChamberPattern[side],&chamberNumber); --chamberNumber; channelName = TString::Format(fgkDCSChamberPattern[side],chamberNumber); } if ( TString(dcsName).Contains("iMon") ) { channelName.ReplaceAll("vMon","iMon"); } return channelName; } //_____________________________________________________________________________ Bool_t AliMpDCSNamer::DecodeDCSMCHLVAlias(const char* dcsAlias, Int_t*& detElemId, Int_t& numberOfDetectionElements, AliMp::PlaneType& planeType ) const { /// Decode a MCH LV dcs alias in order to get : /// - the list of detection elements powered by this LV (between 1 for St 1-2 and max 4 DEs for St345 per LV group) /// - the plane type powered by this LV (only for St 1 and 2) TString salias(dcsAlias); detElemId = 0x0; planeType = AliMp::kBendingPlane; if (!salias.Contains("Group")) { // not a MCH LV alias return kFALSE; } Int_t side(-1); if ( salias.Contains("Left")) { side = 0; } else if ( salias.Contains("Right")) { side = 1; } else { AliError(Form("unexpected alias=%s",salias.Data())); return kFALSE; } Bool_t left = ( side == 0 ); Int_t chamberNumber, groupNumber; TString voltageType; sscanf(salias.Data(),fgkDCSMCHLVGroupPattern[side],&chamberNumber,&groupNumber,&voltageType[0]); if ( chamberNumber >= 1 && chamberNumber <= 4 ) { Int_t deOffset = 0; if ( groupNumber == 1 ) { if ( left ) { deOffset = 1; planeType = AliMp::kBendingPlane; } else { deOffset = 0; planeType = AliMp::kNonBendingPlane; } } else if ( groupNumber == 2 ) { if ( left ) { deOffset = 2; planeType = AliMp::kNonBendingPlane; } else { deOffset = 3; planeType = AliMp::kBendingPlane; } } else if ( groupNumber == 3 ) { if ( left ) { deOffset = 1; planeType = AliMp::kNonBendingPlane; } else { deOffset = 0; planeType = AliMp::kBendingPlane; } } else if ( groupNumber == 4 ) { if ( left ) { deOffset = 2; planeType = AliMp::kBendingPlane; } else { deOffset = 3; planeType = AliMp::kNonBendingPlane; } } else { AliError(Form("Got incorrect group number=%d from alias=%s",groupNumber,salias.Data())); return kFALSE; } numberOfDetectionElements=1; detElemId = new Int_t[numberOfDetectionElements]; detElemId[0] = chamberNumber*100 + deOffset; } else if ( chamberNumber >= 5 && chamberNumber <= 10 ) { Int_t* dcsSlatNumber(0x0); if ( chamberNumber >= 5 && chamberNumber <= 6 ) { if ( groupNumber == 1 ) { numberOfDetectionElements=3; dcsSlatNumber=new Int_t[numberOfDetectionElements]; dcsSlatNumber[0]=1; dcsSlatNumber[1]=2; dcsSlatNumber[2]=3; } else if ( groupNumber == 5 ) { numberOfDetectionElements=3; dcsSlatNumber=new Int_t[numberOfDetectionElements]; dcsSlatNumber[0]=7; dcsSlatNumber[1]=8; dcsSlatNumber[2]=9; } else if ( groupNumber > 1 && groupNumber < 5 ) { numberOfDetectionElements=1; dcsSlatNumber=new Int_t[numberOfDetectionElements]; dcsSlatNumber[0]=groupNumber+2; } else { AliError(Form("Got incorrect group number=%d from alias=%s",groupNumber,salias.Data())); return kFALSE; } } else if ( chamberNumber >= 7 ) { if ( groupNumber == 1 ) { numberOfDetectionElements=4; dcsSlatNumber=new Int_t[numberOfDetectionElements]; dcsSlatNumber[0]=1; dcsSlatNumber[1]=2; dcsSlatNumber[2]=3; dcsSlatNumber[3]=4; } else if ( groupNumber == 7 ) { numberOfDetectionElements=4; dcsSlatNumber=new Int_t[numberOfDetectionElements]; dcsSlatNumber[0]=10; dcsSlatNumber[1]=11; dcsSlatNumber[2]=12; dcsSlatNumber[3]=13; } else if ( groupNumber > 1 && groupNumber < 7 ) { numberOfDetectionElements=1; dcsSlatNumber=new Int_t[numberOfDetectionElements]; dcsSlatNumber[0]=groupNumber+3; } else { AliError(Form("Got incorrect group number=%d from alias=%s",groupNumber,salias.Data())); return kFALSE; } } detElemId = new Int_t[numberOfDetectionElements]; for ( int i = 0; i < numberOfDetectionElements; ++i ) { detElemId[i] = DCS2DE(chamberNumber-1,side,dcsSlatNumber[i]-1); } } else { AliError(Form("Got an invalid chamberNumber=%d from alias=%s",chamberNumber,salias.Data())); return kFALSE; } return kTRUE; } //_____________________________________________________________________________ TString AliMpDCSNamer::DCSMCHLVAliasName(Int_t detElemId, Int_t voltageType, AliMp::PlaneType planeType) const { TString voltage; if ( voltageType == -1 ) { voltage = "ann"; } else if ( voltageType == 0 ) { voltage = "dig"; } else if ( voltageType == 1 ) { voltage = "anp"; } if ( !voltage.Length() ) { AliError(Form("Incorrect voltageType=%d. Expected -1,0 or 1.",voltageType)); return ""; } Int_t chamberId = AliMpDEManager::GetChamberId(detElemId); if ( chamberId < 0 ) { AliError(Form("Got an incorrect chamberId=%d from detElemId=%d",chamberId,detElemId)); return ""; } Int_t stationId = 1 + chamberId / 2; Int_t side(-1); Int_t cham; Int_t dcsNumber = DetElemId2DCS(detElemId, side, cham); Int_t group(0); switch (AliMpDEManager::GetStationType(detElemId)) { case AliMp::kStation12: { // For Chamber 1 to 4 Left the relationship between DCS GUI names and groups is: // Quad2B --> Group3 = DE x01 Non Bending // Quad2F --> Group1 = DE x01 Bending // Quad3B --> Group4 = DE x02 Bending // Quad3F --> Group2 = DE x02 Non Bending // for Chamber 1 to 4 Right the relationship is: // Quad1B --> Group3 = DE x00 Bending // Quad1F --> Group1 = DE x00 Non Bending // Quad4B --> Group4 = DE x03 Non Bending // Quad4F --> Group2 = DE x03 Bending // where x = 1,2,3,4 // and Quad#B = Back = towards IP = cath1 // while Quad#F = Front = towards muon trigger = cath0 // Int_t remnant = detElemId % 100; switch (remnant) { case 0: // DE x00 group = ( planeType == AliMp::kBendingPlane ) ? 3 : 1; break; case 1: // DE x01 group = ( planeType == AliMp::kBendingPlane ) ? 1 : 3; break; case 2: // DE x02 group = ( planeType == AliMp::kBendingPlane ) ? 4 : 2; break; case 3: // DE x03 group = ( planeType == AliMp::kBendingPlane ) ? 2 : 4; break; default: AliFatal(""); break; } } break; case AliMp::kStation345: { Int_t dcsSlatNumber = 1 + dcsNumber; if ( stationId == 3 ) { switch (dcsSlatNumber) { case 1: case 2: case 3: group = 1; break; case 4: case 5: case 6: group = dcsSlatNumber - 2; break; case 7: case 8: case 9: group = 5; break; default: break; } } else { switch (dcsSlatNumber) { case 1: case 2: case 3: case 4: group = 1; break; case 5: case 6: case 7: case 8: case 9: group = dcsSlatNumber - 3; break; case 10: case 11: case 12: case 13: group = 7; break; default: break; } } } break; default: break; } if ( group == 0 ) { AliError(Form("Could not get LV group id for detection element %d",detElemId)); return ""; } TString aliasName; aliasName.Form(fgkDCSMCHLVGroupPattern[side],chamberId+1,group,voltage.Data()); return aliasName; } //_____________________________________________________________________________ TString AliMpDCSNamer::DCSAliasName(Int_t detElemId, Int_t sector, Int_t dcsMeasure) const { /// Return the alias name of the DCS Channel for a given DCS area /// \param detElemId /// \param sector = 0,1 or 2 for St12, and is unused for st345 and trigger /// \param dcsMeasure = kDCSHV, kDCSI Int_t chamberId = AliMpDEManager::GetChamberId(detElemId); if ( chamberId < 0 ) return ""; Int_t side(-1), chId(-1); Int_t dcsNumber = DetElemId2DCS(detElemId,side,chId); TString aliasName; switch (AliMpDEManager::GetStationType(detElemId)) { case AliMp::kStation12: aliasName.Form(fgkDCSChannelSt12Pattern[side],chamberId,dcsNumber,sector); break; case AliMp::kStation345: aliasName.Form(fgkDCSChannelSt345Pattern[side],chamberId,dcsNumber); break; case AliMp::kStationTrigger: return TString::Format(fgkDCSChannelTriggerPattern[side],fgkDCSSideTriggerName[side],chId,dcsNumber,fgkDCSMeasureName[dcsMeasure]); break; default: return ""; break; } if ( dcsMeasure == AliMpDCSNamer::kDCSI ) { aliasName.ReplaceAll("vMon","iMon"); } return aliasName; } //_____________________________________________________________________________ TString AliMpDCSNamer::DCSSwitchAliasName(Int_t detElemId, Int_t pcbNumber) const { /// Return the alias name of the DCS Switch for a given PCB /// within a slat of St345 if (AliMpDEManager::GetStationType(detElemId) == AliMp::kStation345) { return TString::Format(fgkDCSSwitchSt345Pattern,detElemId,pcbNumber); } return ""; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::DCSIndexFromDCSAlias(const char* dcsAlias) const { /// Converts the dcs alias to a hv index /// /// dcsAlias has one of the following 3 forms : /// /// MchHvLv[Left|Right]/Chamber##[Left|Right]/Chamber##[Left|Right]Slat##.actual.vMon /// /// MchHvLv[Left|Right]/Chamber##[Left|Right]/Chamber##[Left|Right]Quad#Sect#.actual.vMon /// /// MchDE####dsw#.inValue TString sDcsAlias(dcsAlias); Int_t de(-1); Int_t sw(-1); int side(-1); if ( sDcsAlias.Contains("Left") ) { side = 0; } else if ( sDcsAlias.Contains("Right") ) { side = 1; } else { /// it's a switch sscanf(sDcsAlias.Data(),fgkDCSSwitchSt345Pattern,&de,&sw); return sw; } int n1(-1); int n3(-1); int n4(-1); if ( sDcsAlias.Contains("Quad") ) { sscanf(sDcsAlias.Data(),fgkDCSChannelSt12Pattern[side],&n1,&n3,&n4); return n4; } return -2; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::DetElemIdFromDCSAlias(const char* dcsAlias) const { /// Converts the dcs alias to a detection element identifier /// /// dcsAlias has one of the following forms : /// /// MchHvLv[Left|Right]/Chamber##[Left|Right]/Chamber##[Left|Right]Slat##.actual.vMon /// /// MchHvLv[Left|Right]/Chamber##[Left|Right]/Chamber##[Left|Right]Quad#Sect#.actual.vMon /// /// MTR_Side[OUTSIDE|INSIDE]_MTChamber##_RPC#_HV.Type[actual.iMon|vEff] AliDebug(1,Form("dcsAlias=%s",dcsAlias)); TString sDcsAlias(dcsAlias); int side(-1); const char** sideName = (fDetector == kTriggerDet) ? fgkDCSSideTriggerName : fgkDCSSideTrackerName; for(Int_t iside=0; iside<2; iside++){ if ( sDcsAlias.Contains(sideName[iside]) ) { side = iside; break; } } if(side<0) return -2; int n1(-1); int n3(-1); int n4(-1); char type[15]; char cside[4]; int detElemId(-1); if ( sDcsAlias.Contains("Slat") ) { sscanf(sDcsAlias.Data(),fgkDCSChannelSt345Pattern[side],&n1,&n3); detElemId = DCS2DE(n1,side,n3); AliDebug(1,Form("Slat side=%d n1=%d n3=%d de=%d",side,n1,n3,detElemId)); } else if ( sDcsAlias.Contains("Quad") ) { sscanf(sDcsAlias.Data(),fgkDCSChannelSt12Pattern[side],&n1,&n3,&n4); detElemId = 100*(n1+1) + n3; AliDebug(1,Form("Quad side=%d n1=%d n3=%d n4=%d de=%d",side,n1,n3,n4,detElemId)); } else if ( sDcsAlias.Contains("MT") ) { sscanf(sDcsAlias.Data(),fgkDCSChannelTriggerPatternRead[side],cside,&n1,&n3,type); detElemId = DCS2DE(n1,side,n3); AliDebug(1,Form("Slat side=%d n1=%d n3=%d de=%d",side,n1,n3,detElemId)); } else { return -3; } if ( !AliMpDEManager::IsValidDetElemId(detElemId) ) { AliError(Form("Invalid aliasName %s",dcsAlias)); return -1; } return detElemId; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::DCSvariableFromDCSAlias(const char* dcsAlias) const { /// Get DCS variable from an alias (trigger) TString sDcsAlias(dcsAlias); Int_t dcsMeasurement = -1; for(Int_t iMeas=0; iMeas<kNDCSMeas; iMeas++){ if ( sDcsAlias.Contains(fgkDCSMeasureName[iMeas]) ) { dcsMeasurement = iMeas; break; } } return dcsMeasurement; } //_____________________________________________________________________________ TObjArray* AliMpDCSNamer::GenerateAliases(const char* pattern) const { /// Generate DCS alias names, for MUON Tracker High and Low Voltage systems /// or for MUON Trigger HV and current system. /// /// For MCH we first generate 188 aliases of HV DCS channels : /// /// St 1 ch 1 : 12 channels /// ch 2 : 12 channels /// St 2 ch 3 : 12 channels /// ch 4 : 12 channels /// St 3 ch 5 : 18 channels /// ch 6 : 18 channels /// St 4 ch 7 : 26 channels /// ch 8 : 26 channels /// St 5 ch 9 : 26 channels /// ch 10 : 26 channels /// /// then 600 aliases of DCS switches (only for St345) : 1 switch per PCB. /// /// and finally 324 LV groups (108 per voltage x 3 voltages) /// /// St 1 ch 1 left or right : 4 groups /// ch 2 left or right : 4 groups /// St 2 ch 3 left or right : 4 groups /// ch 4 left or right : 4 groups /// St 3 ch 5 left or right : 5 groups /// ch 6 left or right : 5 groups /// St 4 ch 7 left or right : 7 groups /// ch 8 left or right : 7 groups /// St 5 ch 9 left or right : 7 groups /// ch 10 left or right : 7 groups /// /// Returns a TObjArray of TObjString(=alias name) TObjArray* aliases = new TObjArray; aliases->SetOwner(kTRUE); Int_t nMeasures = (fDetector == kTriggerDet) ? kNDCSMeas : 1; for(Int_t iMeas=0; iMeas<nMeasures; iMeas++){ AliMpDEIterator it; it.First(); Int_t voltageType[] = { -1,0,1 }; while (!it.IsDone()) { Int_t detElemId = it.CurrentDEId(); switch (fDetector){ case kTrackerDet: { switch ( AliMpDEManager::GetStationType(detElemId) ) { case AliMp::kStation12: { for ( int sector = 0; sector < 3; ++sector) { // HV voltage aliases->Add(new TObjString(DCSAliasName(detElemId,sector))); // HV current aliases->Add(new TObjString(DCSAliasName(detElemId,sector,AliMpDCSNamer::kDCSI))); } AliMp::PlaneType planeType[] = { AliMp::kBendingPlane, AliMp::kNonBendingPlane }; // LV groups, one per voltage (analog negative, digital, analog positive) // per plane (bending / non-bending) for ( int pt = 0; pt < 2; ++pt ) { for ( int i = 0; i < 3; ++i ) { TString name = DCSMCHLVAliasName(detElemId,voltageType[i],planeType[pt]); aliases->Add(new TObjString(name)); } } } break; case AliMp::kStation345: { // HV voltage aliases->Add(new TObjString(DCSAliasName(detElemId))); // HV current aliases->Add(new TObjString(DCSAliasName(detElemId,0,AliMpDCSNamer::kDCSI))); // HV switches for ( Int_t i = 0; i < NumberOfPCBs(detElemId); ++i ) { aliases->Add(new TObjString(DCSSwitchAliasName(detElemId,i))); } // LV groups, one per voltage (analog negative, digital, analog positive) for ( int i = 0; i < 3; ++i ) { TString name = DCSMCHLVAliasName(detElemId,voltageType[i]); // for Station345 some detection elements share the same voltage group, // so we must insure we're not adding the same one several times if (!aliases->FindObject(name)) { aliases->Add(new TObjString(name)); } } } break; default: break; } } break; case kTriggerDet: { switch ( AliMpDEManager::GetStationType(detElemId) ) { case AliMp::kStationTrigger: AliDebug(10,Form("Current DetElemId %i",detElemId)); aliases->Add(new TObjString(DCSAliasName(detElemId,0,iMeas))); break; default: break; } } break; } it.Next(); } // loop on detElemId } // Loop on measurement type if (pattern && strlen(pattern)>0) { // remove aliases not containing the input pattern TObjArray* tmp = new TObjArray; tmp->SetOwner(kTRUE); for ( Int_t i = 0; i <= aliases->GetLast(); ++i ) { TString name = static_cast<TObjString*>(aliases->At(i))->String(); if (name.Contains(pattern)) { tmp->Add(new TObjString(name.Data())); } } delete aliases; aliases = tmp; } return aliases; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::ManuId2Index(Int_t detElemId, Int_t manuId) const { /// Convert (de,manu) to hv index, depending on the station AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId); if ( stationType == AliMp::kStation345 ) { return ManuId2PCBIndex(detElemId,manuId); } else if ( stationType == AliMp::kStation12 ) { return ManuId2Sector(detElemId,manuId); } return -1; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::ManuId2PCBIndex(Int_t detElemId, Int_t manuId) const { /// Returns the index of PCB (within a St345 slat) for a given manu number. /// Returns -1 if (detElemId,manuId) is incorrect AliCodeTimerAuto("",0) const AliMpSlat* slat = AliMpSegmentation::Instance()->GetSlatByElectronics(detElemId, manuId); if ( ! slat ) return -1; return slat->FindPCBIndexByMotifPositionID(manuId); } //_____________________________________________________________________________ Int_t AliMpDCSNamer::ManuId2Sector(Int_t detElemId, Int_t manuId) const { /// Return the DCS-sector number (within a St12 quadrant) for a given manu number. AliCodeTimerAuto("",0) const AliMpSector* sector = AliMpSegmentation::Instance()->GetSectorByElectronics(detElemId, manuId); if ( ! sector ) return -1; const AliMpMotifMap* motifMap = sector->GetMotifMap(); const AliMpMotifPosition* motifPos = motifMap->FindMotifPosition(manuId); Double_t lowerLeftX = motifPos->GetPositionX()-motifPos->GetDimensionX(); Double_t x = lowerLeftX*10.0; // cm -> mm Int_t isector(-1); AliMq::Station12Type stationType = AliMpDEManager::GetStation12Type(detElemId); if ( stationType == AliMq::kStation1 ) { if ( x < -10 ) AliFatal(""); if ( x < 291.65 ) isector = 0; else if ( x < 585.65 ) isector = 1; else if ( x < 879.65 ) isector = 2; } else { if ( x < -140 ) AliFatal(""); if ( x < 283.75 ) isector = 0; else if ( x < 606.25 ) isector = 1; else if ( x < 1158.75 ) isector = 2; } return isector; } //_____________________________________________________________________________ Int_t AliMpDCSNamer::NumberOfPCBs(Int_t detElemId) const { /// Returns the number of PCB in a given detection element /// Only works for St345 AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId); if ( stationType != AliMp::kStation345 ) { return 0; } else { const AliMpSlat* slat = AliMpSegmentation::Instance()->GetSlat(detElemId, AliMp::kCath0); return slat->GetSize(); } } //_____________________________________________________________________________ Bool_t AliMpDCSNamer::CheckConsistency(Int_t detElemId) const { // /// Check that the required detElemId either belongs to tracker or trigger /// consistently with the initial definition of the namer // Bool_t isConsistent(kFALSE); TString requestInfo; switch(AliMpDEManager::GetStationType(detElemId)) { case AliMp::kStation12: case AliMp::kStation345: if (fDetector == kTrackerDet) isConsistent = kTRUE; requestInfo = "TRACKER"; break; case AliMp::kStationTrigger: if (fDetector == kTriggerDet) isConsistent = kTRUE; requestInfo = "TRIGGER"; break; default: break; } if(!isConsistent) AliWarning(Form("Requesting information for %s station but class initialized for %s",requestInfo.Data(), fgkDetectorName[fDetector])); return isConsistent; } //_____________________________________________________________________________ Bool_t AliMpDCSNamer::TestMCHLV() const { /// Circular test of DCSMCHLVAliasName and DecodeDCSMCHLVAlias methods TObjArray* aliases = GenerateAliases("Group"); const char* voltageTypeName[] = { "ann","dig","anp"}; Int_t voltageType[] = { -1,0,1 }; Int_t n(0); for ( Int_t iv = 0; iv < 3; ++iv ) { for ( Int_t i = 0; i < aliases->GetEntries(); ++i ) { TString dcsAlias = static_cast<TObjString*>(aliases->At(i))->String(); if ( !dcsAlias.Contains(voltageTypeName[iv])) continue; Int_t* detElemId(0x0); Int_t numberOfDetectionElements(0); AliMp::PlaneType planeType; Bool_t ok = DecodeDCSMCHLVAlias(dcsAlias.Data(), detElemId, numberOfDetectionElements, planeType); if (!ok) { AliError(Form("Could not decode alias=%s",dcsAlias.Data())); delete[] detElemId; return kFALSE; } for ( Int_t id = 0; id < numberOfDetectionElements; ++id ) { TString check = DCSMCHLVAliasName(detElemId[id], voltageType[iv], planeType); if (check!=dcsAlias) { AliError(Form("%s != %s",check.Data(),dcsAlias.Data())); return kFALSE; } else { ++n; } } delete[] detElemId; } } delete aliases; AliInfo(Form("%d aliases successfully tested",n)); return kTRUE; }
28.555082
154
0.628693
AllaMaevskaya
4a223e946c69a9c86ebec7bc698ab08eecee5863
2,834
cpp
C++
core/model/src/model_membranes_t.cpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
4
2019-07-18T15:05:09.000Z
2020-03-14T09:50:07.000Z
core/model/src/model_membranes_t.cpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
328
2019-06-30T12:03:01.000Z
2020-10-05T15:56:35.000Z
core/model/src/model_membranes_t.cpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
1
2019-06-08T22:47:14.000Z
2019-06-08T22:47:14.000Z
#include "catch_wrapper.hpp" #include "sme/model_membranes.hpp" #include <QImage> using namespace sme; TEST_CASE("SBML membranes", "[core/model/membranes][core/model][core][model][membranes]") { SECTION("ModelMembranes") { SECTION("No image") { model::ModelMembranes m; REQUIRE(m.getIds().isEmpty()); REQUIRE(m.getNames().isEmpty()); REQUIRE(m.getMembranes().empty()); REQUIRE(m.getIdColourPairs().empty()); } SECTION("Image with 2 compartments, 1 membrane") { QImage img(3, 3, QImage::Format_RGB32); QRgb col0 = qRgb(0, 255, 0); QRgb col1 = qRgb(123, 123, 0); img.fill(col1); img.setPixel(1, 1, col0); img = img.convertToFormat(QImage::Format_Indexed8); std::vector<std::unique_ptr<geometry::Compartment>> compartments; compartments.push_back( std::make_unique<geometry::Compartment>("c0", img, col0)); compartments.push_back( std::make_unique<geometry::Compartment>("c1", img, col1)); QStringList names{"c0 name", "c1 name"}; model::ModelMembranes ms; ms.updateCompartmentImage(img); REQUIRE(ms.getIds().isEmpty()); REQUIRE(ms.getMembranes().empty()); REQUIRE(ms.getNames().isEmpty()); // set name is no-op if not found ms.setName("dontexist", "new name"); REQUIRE(ms.getNames().isEmpty()); ms.setHasUnsavedChanges(false); ms.updateCompartments(compartments); ms.setHasUnsavedChanges(true); REQUIRE(ms.getIds().size() == 1); REQUIRE(ms.getMembranes().size() == 1); REQUIRE(ms.getNames().isEmpty()); ms.setHasUnsavedChanges(false); ms.updateCompartmentNames(names); ms.setHasUnsavedChanges(true); REQUIRE(ms.getIds().size() == 1); REQUIRE(ms.getIds()[0] == "c1_c0_membrane"); REQUIRE(ms.getNames().size() == 1); REQUIRE(ms.getNames()[0] == "c1 name <-> c0 name"); ms.setHasUnsavedChanges(false); // setting name to same value is a no-op ms.setName("c1_c0_membrane", "c1 name <-> c0 name"); REQUIRE(ms.getHasUnsavedChanges() == false); // but setting a new name is an unsaved change ms.setName("c1_c0_membrane", "mem"); REQUIRE(ms.getHasUnsavedChanges() == true); REQUIRE(ms.getIdColourPairs().size() == 1); REQUIRE(ms.getIdColourPairs()[0].first == "c1_c0_membrane"); REQUIRE(ms.getIdColourPairs()[0].second == std::pair<QRgb, QRgb>{col1, col0}); REQUIRE(ms.getMembranes().size() == 1); const auto &m = ms.getMembranes()[0]; REQUIRE(m.getId() == "c1_c0_membrane"); REQUIRE(m.getCompartmentA()->getId() == "c1"); REQUIRE(m.getCompartmentB()->getId() == "c0"); REQUIRE(m.getImage().size() == img.size()); REQUIRE(m.getIndexPairs().size() == 4); } } }
39.361111
73
0.618207
lkeegan
4a28de0b33ad19c26eb6c52af2ab095a80f8d847
2,805
cpp
C++
src/gui/Utils.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
4
2021-01-28T17:39:38.000Z
2022-02-11T20:13:46.000Z
src/gui/Utils.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
null
null
null
src/gui/Utils.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
3
2021-02-22T21:22:30.000Z
2022-01-10T19:32:12.000Z
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. ******************************************************************************/ #include <gui/Utils.h> #include <sim/sim_Languages.h> //////////////////////////////////////////////////////////////////////////////// int Utils::read( const QDomElement &node, Text *text ) { if ( !node.isNull() ) { QDomElement textNode = node.firstChildElement( "text" ); while ( !textNode.isNull() ) { std::string str = textNode.text().toStdString(); if ( str.length() > 0 ) { std::string lang = textNode.attribute( "lang" ).toStdString(); int index = sim::Languages::instance()->getIndexByCode( lang ); if ( index >= 0 ) { text->set( index, str ); } } textNode = textNode.nextSiblingElement( "text" ); } return SIM_SUCCESS; } return SIM_FAILURE; } //////////////////////////////////////////////////////////////////////////////// void Utils::m2ftin( double len_m, int *len_ft, int *len_in ) { double temp_ft = Convert::m2ft( len_m ); *len_ft = floor( temp_ft ); *len_in = floor( 12.0 * ( temp_ft - *len_ft ) + 0.5 ); if ( *len_in == 12 ) { *len_ft += 1; *len_in = 0; } } //////////////////////////////////////////////////////////////////////////////// QString Utils::m2ftin( double len_m ) { int len_ft = 0; int len_in = 0; m2ftin( len_m, &len_ft, &len_in ); return QString::number( len_ft ) + " ft " + QString::number( len_in ) + " in"; }
32.241379
82
0.535116
marek-cel
4a30a7ee66085ecf15308102494dd1365d325a44
1,285
cpp
C++
Dot++/src/lexer/TokenizerStatesPack.cpp
SenorAgosto/Dot-pp
21491dc17deb8c287bda93d27bb3d9c58844f3db
[ "BSD-4-Clause" ]
null
null
null
Dot++/src/lexer/TokenizerStatesPack.cpp
SenorAgosto/Dot-pp
21491dc17deb8c287bda93d27bb3d9c58844f3db
[ "BSD-4-Clause" ]
1
2017-01-15T04:49:51.000Z
2017-01-15T04:53:08.000Z
Dot++/src/lexer/TokenizerStatesPack.cpp
SenorAgosto/Dot-pp
21491dc17deb8c287bda93d27bb3d9c58844f3db
[ "BSD-4-Clause" ]
null
null
null
#include <Dot++/lexer/TokenizerStatesPack.hpp> #include <Dot++/Exceptions.hpp> #include <Dot++/lexer/TokenizerState.hpp> namespace dot_pp { namespace lexer { const TokenizerStateInterface& TokenizerStatesPack::operator[](const TokenizerState state) const { // ordered by frequency of use switch(state) { case TokenizerState::Init: return init_; case TokenizerState::StringLiteral: return stringLiteral_; case TokenizerState::StringLiteralEscape: return stringLiteralEscape_; case TokenizerState::HashLineComment: return hashLineComment_; case TokenizerState::BeginSlashLineComment: return beginSlashLine_; case TokenizerState::SlashLineComment: return slashLineComment_; case TokenizerState::MultiLineComment: return multiLineComment_; case TokenizerState::EndMultiLineComment: return endMultiLineComment_; case TokenizerState::MultiLineEscape: return multiLineEscape_; case TokenizerState::Error: return error_; default: break; }; throw UnknownTokenizerState(state); } }}
37.794118
100
0.631128
SenorAgosto
4a315a8c163ec35139dfcbcb5bb782d1450167ee
8,142
cpp
C++
asidorov_task_1/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
1
2018-03-04T21:28:20.000Z
2018-03-04T21:28:20.000Z
asidorov_task_1/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
asidorov_task_1/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
/** * func_memory.cpp - the module implementing the concept of * programer-visible memory space accesing via memory address. * @author Alexander Titov <alexander.igorevich.titov@gmail.com> * @author Alexey Sidorov <alexey.s.sidorov@gmail.com> * Copyright 2012 uArchSim iLab project */ // Generic C #include <math.h> // Generic C++ #include <algorithm> #include <iostream> #include <string> #include <sstream> // uArchSim modules #include <func_memory.h> using namespace std; FuncMemory::FuncMemory( const char* executable_file_name, uint64 addr_bits, uint64 page_num_bits, uint64 offset_bits) { assert( executable_file_name != NULL && addr_bits && page_num_bits && offset_bits && ( addr_bits > page_num_bits + offset_bits)); this->addr_bits = addr_bits; this->set_num_bits = addr_bits - page_num_bits - offset_bits; this->page_num_bits = page_num_bits; this->offset_bits = offset_bits; this->addr_size = ( uint64) 1 << this->addr_bits; this->sets_array_size = ( uint64) 1 << this->set_num_bits; this->set_size = ( uint64) 1 << this->page_num_bits; this->page_size = ( uint64) 1 << this->offset_bits; this->sets_array = new uint8**[ this->sets_array_size]; for ( uint64 index = 0; index < this->sets_array_size; ++index) this->sets_array[ index] = NULL; vector< ElfSection> sections_array; ElfSection::getAllElfSections( executable_file_name, sections_array); for ( uint64 section_index = 0; section_index < sections_array.size(); ++section_index) { if ( !strcmp( sections_array[ section_index].name, ".text")) this->start_pc = sections_array[ section_index].start_addr; for ( uint64 content_index = 0, curr_addr = sections_array[ section_index].start_addr; content_index < sections_array[ section_index].size; ++content_index, ++curr_addr) { this->write( ( uint64) sections_array[ section_index].content[ content_index], curr_addr, 1); } } } FuncMemory::~FuncMemory() { for ( uint64 set_index = 0; set_index < this->sets_array_size; ++set_index) { if ( this->sets_array[ set_index] == NULL) continue; for ( uint64 page_index = 0; page_index < this->set_size; ++page_index) { if ( this->sets_array[ set_index][ page_index] == NULL) continue; delete [] this->sets_array[ set_index][ page_index]; } delete [] this->sets_array[ set_index]; } delete [] this->sets_array; } uint64 FuncMemory::startPC() const { return this->start_pc; } uint64 FuncMemory::takeLeastBits( uint64 number, uint64 bits_number) const { return number & ( ( (uint64) 1 << bits_number) - 1); } void FuncMemory::decodeAddress( uint64 address, uint64* set_index, uint64* page_index, uint64* offset) const { *offset = this->takeLeastBits( address, this->offset_bits); address >>= this->offset_bits; *page_index = this->takeLeastBits( address, this->page_num_bits); address >>= this->page_num_bits; *set_index = this->takeLeastBits( address, this->set_num_bits); } uint64 FuncMemory::read( uint64 addr, unsigned short num_of_bytes) const { assert( num_of_bytes); uint64 set_index; uint64 page_index; uint64 offset; stringstream ss; ss << hex; for ( uint64 counter = 0, curr_addr = addr + num_of_bytes - 1; counter < num_of_bytes; --curr_addr, ++counter) { this->decodeAddress( curr_addr, &set_index, &page_index, &offset); assert( set_index < this->sets_array_size && page_index < this->set_size && offset < this->page_size && this->sets_array[ set_index] != NULL && this->sets_array[ set_index][ page_index] != NULL); ss.width( 2); ss.fill( '0'); ss << (uint16) this->sets_array[ set_index][ page_index][ offset]; } uint64 result; ss >> result; return result; } void FuncMemory::write( uint64 value, uint64 addr, unsigned short num_of_bytes) { assert( num_of_bytes); uint64 set_index; uint64 page_index; uint64 offset; uint64 bits_number = 8; while (value && num_of_bytes) { this->decodeAddress( addr, &set_index, &page_index, &offset); assert( set_index < this->sets_array_size && page_index < this->set_size && offset < this->page_size); if ( this->sets_array[ set_index] == NULL) { this->sets_array[ set_index] = new uint8*[ this->set_size]; for ( uint64 index = 0; index < this->set_size; ++index) { if (index == page_index) { this->sets_array[ set_index][ index] = new uint8[ this->page_size]; } else { this->sets_array[ set_index][ index] = NULL; } } } else if ( this->sets_array[ set_index][ page_index] == NULL) { this->sets_array[ set_index][ page_index] = new uint8[ this->page_size]; } this->sets_array[ set_index][ page_index][ offset] = (uint8) this->takeLeastBits( value, bits_number); value >>= bits_number; ++addr; --num_of_bytes; } while (num_of_bytes) { this->decodeAddress( addr, &set_index, &page_index, &offset); assert( set_index < this->sets_array_size && page_index < this->set_size && offset < this->page_size); if ( this->sets_array[ set_index] == NULL) { this->sets_array[ set_index] = new uint8*[ this->set_size]; for ( uint64 index = 0; index < this->set_size; ++index) { if (index == page_index) { this->sets_array[ set_index][ index] = new uint8[ this->page_size]; } else { this->sets_array[ set_index][ index] = NULL; } } } else if ( this->sets_array[ set_index][ page_index] == NULL) { this->sets_array[ set_index][ page_index] = new uint8[ this->page_size]; } this->sets_array[ set_index][ page_index][ offset] = (uint8) 0; ++addr; --num_of_bytes; } } string FuncMemory::dump( string indent) const { ostringstream oss; oss << hex; for ( uint64 set_index = 0; set_index < this->sets_array_size; ++set_index) { oss << indent << "Dump set #" << set_index << endl; if ( this->sets_array[ set_index] == NULL) { oss << indent << "There is no data" << endl; continue; } for ( uint64 page_index = 0; page_index < this->set_size; ++page_index) { oss << indent << "Dump page #" << page_index << endl; if ( this->sets_array[ set_index][ page_index] == NULL) { oss << indent << "There is no data" << endl; continue; } for ( uint64 offset = 0; offset < this->page_size; ++offset) { oss << hex; oss.width( 2); oss.fill( '0'); oss << indent << "offset == " << offset << ", value == " << (uint16) this->sets_array[ set_index][ page_index][ offset] << endl; } } } return oss.str(); }
30.380597
110
0.532916
MIPT-ILab
4a31d347a29bc79489137a343e1e96641b71f3cd
1,589
cpp
C++
src/d3d11/d3d11_cuda.cpp
oashnic/dxvk
78ef4cfd92cb7f448292aaca83091914ab271257
[ "Zlib" ]
8,148
2017-10-29T10:51:20.000Z
2022-03-31T12:52:51.000Z
src/d3d11/d3d11_cuda.cpp
oashnic/dxvk
78ef4cfd92cb7f448292aaca83091914ab271257
[ "Zlib" ]
2,270
2017-12-04T12:08:13.000Z
2022-03-31T19:56:41.000Z
src/d3d11/d3d11_cuda.cpp
oashnic/dxvk
78ef4cfd92cb7f448292aaca83091914ab271257
[ "Zlib" ]
732
2017-11-28T13:08:15.000Z
2022-03-31T21:05:59.000Z
#include "d3d11_cuda.h" namespace dxvk { CubinShaderWrapper::CubinShaderWrapper(const Rc<dxvk::DxvkDevice>& dxvkDevice, VkCuModuleNVX cuModule, VkCuFunctionNVX cuFunction, VkExtent3D blockDim) : m_dxvkDevice(dxvkDevice), m_module(cuModule), m_function(cuFunction), m_blockDim(blockDim) { }; CubinShaderWrapper::~CubinShaderWrapper() { VkDevice vkDevice = m_dxvkDevice->handle(); m_dxvkDevice->vkd()->vkDestroyCuFunctionNVX(vkDevice, m_function, nullptr); m_dxvkDevice->vkd()->vkDestroyCuModuleNVX(vkDevice, m_module, nullptr); }; HRESULT STDMETHODCALLTYPE CubinShaderWrapper::QueryInterface(REFIID riid, void **ppvObject) { if (riid == __uuidof(IUnknown)) { *ppvObject = ref(this); return S_OK; } Logger::warn("CubinShaderWrapper::QueryInterface: Unknown interface query"); Logger::warn(str::format(riid)); return E_NOINTERFACE; } void CubinShaderLaunchInfo::insertResource(ID3D11Resource* pResource, DxvkAccessFlags access) { auto img = GetCommonTexture(pResource); auto buf = GetCommonBuffer(pResource); if (img) insertUniqueResource(images, img->GetImage(), access); if (buf) insertUniqueResource(buffers, buf->GetBuffer(), access); } template<typename T> void CubinShaderLaunchInfo::insertUniqueResource(std::vector<std::pair<T, DxvkAccessFlags>>& list, const T& resource, DxvkAccessFlags access) { for (auto& entry : list) { if (entry.first == resource) { entry.second.set(access); return; } } list.push_back({ resource, access }); } }
30.557692
153
0.708622
oashnic
4a3701e4e52d48ce7af0916791d17873ad8f3681
1,396
hpp
C++
include/X-GS/SceneManager.hpp
iPruch/X-GS
ac43b91735a048216f60c49a9b43d6edd6d5e35e
[ "Zlib" ]
1
2015-01-04T22:17:25.000Z
2015-01-04T22:17:25.000Z
include/X-GS/SceneManager.hpp
iPruch/X-GS
ac43b91735a048216f60c49a9b43d6edd6d5e35e
[ "Zlib" ]
null
null
null
include/X-GS/SceneManager.hpp
iPruch/X-GS
ac43b91735a048216f60c49a9b43d6edd6d5e35e
[ "Zlib" ]
null
null
null
#ifndef XGS_SCENEMANAGER_HPP #define XGS_SCENEMANAGER_HPP #include <SFML/System/NonCopyable.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Window/Event.hpp> #include <X-GS/Time.hpp> #include <X-GS/Scene.hpp> #include <X-GS/Entity.hpp> //#include <X-GS/Scenes/ScenesIdentifiers.hpp> #include <map> #include "ScenesIdentifiers.hpp" namespace xgs { class SceneManager : private sf::NonCopyable { // Methods public: explicit SceneManager(sf::RenderWindow& window); ~SceneManager(); template <typename T> void registerScene(Scenes::ID stateID); void loadScene(Scenes::ID sceneID); void update(const HiResDuration& dt); void render(); void handleEvent(const sf::Event& event); private: Scene::ScenePtr createScene(Scenes::ID sceneID); void switchScene(); // Variables (member / properties) private: sf::RenderWindow& mWindow; Scene::ScenePtr mCurrentScene; Scenes::ID mNextScene; bool mSceneChangeRequest; std::map<Scenes::ID, std::function<Scene::ScenePtr()>> mFactories; }; // Template implementation template <typename T> void SceneManager::registerScene(Scenes::ID sceneID) { mFactories[sceneID] = [this] () { return Scene::ScenePtr(new T(mWindow, *this)); }; } } // namespace xgs #endif // XGS_SCENEMANAGER_HPP
22.885246
68
0.670487
iPruch
4a3b1cd0a59a840a8602740f222e342bed64a5d2
4,528
cpp
C++
Development/Source/Renderers/Generic/GNRenderer.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
24
2019-10-28T07:01:48.000Z
2022-03-04T16:10:39.000Z
Development/Source/Renderers/Generic/GNRenderer.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
8
2020-04-22T19:42:45.000Z
2021-04-30T16:28:32.000Z
Development/Source/Renderers/Generic/GNRenderer.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
6
2019-09-22T14:44:15.000Z
2021-04-01T20:04:29.000Z
/* NAME: GNRenderer.c DESCRIPTION: Quesa generic renderer. COPYRIGHT: Copyright (c) 1999-2004, Quesa Developers. All rights reserved. For the current release of Quesa, please see: <https://github.com/jwwalker/Quesa> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: o Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. o 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. o Neither the name of Quesa 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. ___________________________________________________________________________ */ //============================================================================= // Include files //----------------------------------------------------------------------------- #include "GNPrefix.h" #include "GNRenderer.h" //============================================================================= // Public functions //----------------------------------------------------------------------------- // GNRenderer_StartFrame : Start a frame. //----------------------------------------------------------------------------- TQ3Status GNRenderer_StartFrame(TQ3ViewObject theView, void *instanceData, TQ3DrawContextObject theDrawContext) { #pragma unused(theView) #pragma unused(instanceData) #pragma unused(theDrawContext) // We're done return(kQ3Success); } //============================================================================= // GNRenderer_EndFrame : End a frame. //----------------------------------------------------------------------------- TQ3Status GNRenderer_EndFrame(TQ3ViewObject theView, void *instanceData, TQ3DrawContextObject theDrawContext) { #pragma unused(theView) #pragma unused(instanceData) #pragma unused(theDrawContext) // We're done return(kQ3Success); } //============================================================================= // GNRenderer_StartPass : Start a pass. //----------------------------------------------------------------------------- TQ3Status GNRenderer_StartPass(TQ3ViewObject theView, void *instanceData, TQ3CameraObject theCamera, TQ3GroupObject theLights) { #pragma unused(theView) #pragma unused(instanceData) #pragma unused(theCamera) #pragma unused(theLights) // We're done return(kQ3Success); } //============================================================================= // GNRenderer_EndPass : End a pass. //----------------------------------------------------------------------------- TQ3ViewStatus GNRenderer_EndPass(TQ3ViewObject theView, void *instanceData) { #pragma unused(theView) #pragma unused(instanceData) // We're done return(kQ3ViewStatusDone); } //============================================================================= // GNRenderer_Cancel: Cancel a pass. //----------------------------------------------------------------------------- void GNRenderer_Cancel(TQ3ViewObject theView, void *instanceData) { #pragma unused(theView) #pragma unused(instanceData) }
29.789474
80
0.541078
h-haris
6657e39ca442608118acd560386f9d3636df14b2
2,896
cpp
C++
src/geometry.cpp
srinivasyadav18/octotiger
4d93c50fe345a081b7985ecb4cb698d16c121565
[ "BSL-1.0" ]
35
2016-11-17T22:35:11.000Z
2022-01-24T19:07:36.000Z
src/geometry.cpp
srinivasyadav18/octotiger
4d93c50fe345a081b7985ecb4cb698d16c121565
[ "BSL-1.0" ]
123
2016-11-17T21:29:25.000Z
2022-03-03T21:40:04.000Z
src/geometry.cpp
srinivasyadav18/octotiger
4d93c50fe345a081b7985ecb4cb698d16c121565
[ "BSL-1.0" ]
10
2018-11-28T18:17:42.000Z
2022-01-25T12:52:37.000Z
// Copyright (c) 2019 AUTHORS // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef GEOMETRY_CPP_ #define GEOMETRY_CPP_ #include "octotiger/geometry.hpp" #include "octotiger/defs.hpp" #include <array> namespace geo { direction face::to_direction() const { direction dir; switch (i) { case FXM: dir.set(-1, 0, 0); break; case FXP: dir.set(+1, 0, 0); break; case FYM: dir.set(0, -1, 0); break; case FYP: dir.set(0, +1, 0); break; case FZM: dir.set(0, 0, -1); break; case FZP: dir.set(0, 0, +1); break; default: dir = -1; break; } return dir; } std::array<face, face::count() / NDIM> face::dimension_subset(const dimension& d) { std::array<face, _count / NDIM> a; switch (d.i) { case XDIM: a = { { 0,1}}; break; case YDIM: a = { { 2,3}}; break; case ZDIM: a = { { 4,5}}; break; default: a = { {}}; assert(false); } return a; } quadrant octant::get_quadrant(const dimension& d) const { quadrant q; switch (d.i) { case XDIM: q.i = i >> 1; break; case YDIM: q.i = (i & 1) | ((i >> 1) & 2); break; case ZDIM: q.i = i & 3; break; default: q.i = -1; assert(false); } return q; } std::array<octant, octant::count() / 2> octant::face_subset(const face& f) { std::array<octant, octant::count() / 2> a; switch (f.i) { case FXM: a = { { 0,2,4,6}}; break; case FXP: a = { { 1,3,5,7}}; break; case FYM: a = { { 0,1,4,5}}; break; case FYP: a = { { 2,3,6,7}}; break; case FZM: a = { { 0,1,2,3}}; break; case FZP: a = { { 4,5,6,7}}; break; default: a = { {}}; assert(false); } return a; } octant quadrant::get_octant_on_face(const face& f) const { octant o; const dimension d = f.get_dimension(); const side s = f.get_side(); switch (d.i) { case XDIM: o.i = (i << 1) | s.i; break; case YDIM: o.i = ((i << 1) & 4) | (s.i << 1) | (i & 1); break; case ZDIM: o.i = (i & 3) | (s.i << 2); break; default: o.i = -1; assert(false); } return o; } } integer get_boundary_size(std::array<integer, NDIM>& lb, std::array<integer, NDIM>& ub, const geo::direction& dir, const geo::side& side, integer inx, integer bw, integer use_bw) { integer hsize, size; size = 0; integer nx = 2 * bw + inx; if( use_bw < 0 ) { use_bw = bw; } const integer off = (side == OUTER) ? use_bw : 0; hsize = 1; for (auto& d : geo::dimension::full_set()) { auto this_dir = dir[d]; if (this_dir == 0) { lb[d] = bw; ub[d] = nx - bw; } else if (this_dir < 0) { lb[d] = bw - off; // ub[d] = 2 * bw - off; ub[d] = lb[d] + use_bw; } else /*if (this_dir > 0) */{ ub[d] = nx - bw + off; lb[d] = ub[d] - use_bw; } const integer width = ub[d] - lb[d]; hsize *= width; } size += hsize; return size; } #endif /* GEOMETRY_CPP_ */
17.551515
114
0.559047
srinivasyadav18
667521ae887b43bdf8ca24cd354fa62b0e10ce3c
2,069
hpp
C++
include/nanorange/algorithm/rotate.hpp
nyarlathotep-prog/NanoRange
ae170b7ad3213c40d788e649d2ffc1d774892098
[ "BSL-1.0" ]
null
null
null
include/nanorange/algorithm/rotate.hpp
nyarlathotep-prog/NanoRange
ae170b7ad3213c40d788e649d2ffc1d774892098
[ "BSL-1.0" ]
null
null
null
include/nanorange/algorithm/rotate.hpp
nyarlathotep-prog/NanoRange
ae170b7ad3213c40d788e649d2ffc1d774892098
[ "BSL-1.0" ]
3
2018-08-27T16:57:03.000Z
2018-09-15T14:54:14.000Z
// nanorange/algorithm/rotate.hpp // // Copyright (c) 2018 Tristan Brindle (tcbrindle 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) #ifndef NANORANGE_ALGORITHM_ROTATE_HPP_INCLUDED #define NANORANGE_ALGORITHM_ROTATE_HPP_INCLUDED #include <nanorange/ranges.hpp> #include <nanorange/view/subrange.hpp> NANO_BEGIN_NAMESPACE namespace detail { struct rotate_fn { private: template <typename I, typename S> static constexpr subrange<I> impl(I first, I middle, S last) { if (first == middle) { auto ret = next(first, last); return {ret, ret}; } if (middle == last) { return {first, middle}; } I next = middle; do { nano::iter_swap(first++, next++); if (first == middle) { middle = next; } } while (next != last); I ret = first; next = middle; while (next != last) { nano::iter_swap(first++, next++); if (first == middle) { middle = next; } else if (next == last) { next = middle; } } return {std::move(ret), std::move(next)}; } public: template <typename I, typename S> constexpr std::enable_if_t< ForwardIterator<I> && Sentinel<S, I> && Permutable<I>, subrange<I>> operator()(I first, I middle, S last) const { return rotate_fn::impl(std::move(first), std::move(middle), std::move(last)); } template <typename Rng> constexpr std::enable_if_t< ForwardRange<Rng> && Permutable<iterator_t<Rng>>, safe_subrange_t<Rng>> operator()(Rng&& rng, iterator_t<Rng> middle) const { return rotate_fn::impl(nano::begin(rng), std::move(middle), nano::end(rng)); } }; } // namespace detail NANO_INLINE_VAR(detail::rotate_fn, rotate) NANO_END_NAMESPACE #endif
24.630952
85
0.57709
nyarlathotep-prog
66763c225c32956b043394176393c0721c80a34d
4,933
cpp
C++
skse64/Hooks_SaveLoad.cpp
Acro748/CBPCSSE
fabd56ce8f8ac10cde17325f0bd61ecc8cbcda20
[ "MIT" ]
13
2020-06-06T09:08:55.000Z
2022-01-22T12:21:21.000Z
skse64/Hooks_SaveLoad.cpp
Erstori/SkyrimPriority-Mod
50a5adeb78766fba25d4f28626621e9df38df4ba
[ "MIT" ]
1
2020-09-08T19:38:55.000Z
2020-09-08T19:38:55.000Z
skse64/Hooks_SaveLoad.cpp
Erstori/SkyrimPriority-Mod
50a5adeb78766fba25d4f28626621e9df38df4ba
[ "MIT" ]
4
2020-06-05T12:32:58.000Z
2022-01-15T00:17:44.000Z
#include "Hooks_SaveLoad.h" #include "skse64_common/SafeWrite.h" #include "skse64_common/Utilities.h" #include "skse64_common/BranchTrampoline.h" #include "Serialization.h" #include "GlobalLocks.h" #include "GameData.h" #include "GameMenus.h" #include "PapyrusVM.h" #include "PluginManager.h" void BGSSaveLoadManager::SaveGame_Hook(UInt64 *unk0) { const char *saveName = reinterpret_cast<const char *>(unk0[0xBB0 / 8]); // Game actually does this, we may as well do the same if (!saveName) saveName = ""; #ifdef DEBUG _MESSAGE("Executing BGSSaveLoadManager::SaveGame_Hook. saveName: %s", saveName); #endif Serialization::SetSaveName(saveName); PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_SaveGame, (void*)saveName, strlen(saveName), NULL); CALL_MEMBER_FN(this, SaveGame_HookTarget)(unk0); Serialization::SetSaveName(NULL); #ifdef DEBUG _MESSAGE("Executed BGSSaveLoadManager::SaveGame_Hook."); #endif } bool BGSSaveLoadManager::LoadGame_Hook(UInt64 *unk0, UInt32 unk1, UInt32 unk2, void *unk3) { const char *saveName = reinterpret_cast<const char *>(unk0[0xBB0 / 8]); // Game actually does this, we may as well do the same if (!saveName) saveName = ""; #ifdef DEBUG _MESSAGE("Executing BGSSaveLoadManager::LoadGame_Hook. saveName: %s", saveName); #endif g_loadGameLock.Enter(); Serialization::SetSaveName(saveName); PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_PreLoadGame, (void*)saveName, strlen(saveName), NULL); bool result = CALL_MEMBER_FN(this, LoadGame_HookTarget)(unk0, unk1, unk2, unk3); PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_PostLoadGame, (void*)result, 1, NULL); Serialization::SetSaveName(NULL); g_loadGameLock.Leave(); // Clear invalid handles in OnUpdate event registration list UInt32 enableClearRegs = 0; if(GetConfigOption_UInt32("General", "ClearInvalidRegistrations", &enableClearRegs)) { if(enableClearRegs) { UInt32 count = (*g_skyrimVM)->ClearInvalidRegistrations(); if (count > 0) _MESSAGE("ClearInvalidRegistrations: Removed %d invalid OnUpdate registration(s)", count); } } #ifdef DEBUG _MESSAGE("Executed BGSSaveLoadManager::LoadGame_Hook."); #endif return result; } bool s_requestedSave = false; bool s_requestedLoad = false; std::string s_reqSaveName; std::string s_reqLoadName; void BGSSaveLoadManager::RequestSave(const char * name) { s_requestedSave = true; s_reqSaveName = name; } void BGSSaveLoadManager::RequestLoad(const char * name) { s_requestedLoad = true; s_reqLoadName = name; } void BGSSaveLoadManager::ProcessEvents_Hook(void) { CALL_MEMBER_FN(this, ProcessEvents_Internal)(); // wants both? gets nothing. if(s_requestedSave && s_requestedLoad) _MESSAGE("BGSSaveLoadManager: save and load requested in the same frame, ignoring both"); else if(s_requestedSave) Save(s_reqSaveName.c_str()); else if(s_requestedLoad) Load(s_reqLoadName.c_str()); s_requestedSave = false; s_requestedLoad = false; s_reqSaveName.clear(); s_reqLoadName.clear(); } void BGSSaveLoadManager::DeleteSavegame_Hook(const char * saveNameIn, UInt32 unk1) { std::string saveName = saveNameIn; PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_DeleteGame, (void*)saveName.c_str(), strlen(saveName.c_str()), NULL); CALL_MEMBER_FN(this, DeleteSavegame)(saveNameIn, unk1); Serialization::HandleDeleteSave(saveName); } UInt8 TESQuest::NewGame_Hook(UInt8 * unk1, UInt8 unk2) { UInt8 ret = CALL_MEMBER_FN(this, NewGame_Internal)(unk1, unk2); PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_NewGame, (void*)this, sizeof(void*), NULL); return ret; } RelocAddr <uintptr_t> SaveGame_HookTarget_Enter(0x00586DE0 + 0x18B); RelocAddr <uintptr_t> SaveGame2_HookTarget_Enter(0x005875F0 + 0x138); RelocAddr <uintptr_t> LoadGame_HookTarget_Enter(0x0058AE30 + 0x26C); RelocAddr <uintptr_t> ProcessEvents_Enter(0x005B2FF0 + 0x7F); RelocAddr <uintptr_t> NewGame_Enter(0x008A20E0 + 0x59); RelocAddr <uintptr_t> DeleteSaveGame_Enter(0x005794C0 + 0x77); RelocAddr <uintptr_t> DeleteSaveGame_Enter2(0x00579590 + 0x17); void Hooks_SaveLoad_Commit(void) { // Load & Save g_branchTrampoline.Write5Call(SaveGame_HookTarget_Enter, GetFnAddr(&BGSSaveLoadManager::SaveGame_Hook)); g_branchTrampoline.Write5Call(SaveGame2_HookTarget_Enter, GetFnAddr(&BGSSaveLoadManager::SaveGame_Hook)); g_branchTrampoline.Write5Call(LoadGame_HookTarget_Enter, GetFnAddr(&BGSSaveLoadManager::LoadGame_Hook)); g_branchTrampoline.Write5Call(ProcessEvents_Enter, GetFnAddr(&BGSSaveLoadManager::ProcessEvents_Hook)); // New Game g_branchTrampoline.Write5Call(NewGame_Enter, GetFnAddr(&TESQuest::NewGame_Hook)); // Delete savegame g_branchTrampoline.Write5Call(DeleteSaveGame_Enter, GetFnAddr(&BGSSaveLoadManager::DeleteSavegame_Hook)); g_branchTrampoline.Write5Call(DeleteSaveGame_Enter2, GetFnAddr(&BGSSaveLoadManager::DeleteSavegame_Hook)); }
32.886667
138
0.785931
Acro748
66788d1c5c7cc5bd89a477d0c828481b0f0d9d8c
1,447
cc
C++
src/search_local/index_storage/cache/hb_feature.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/search_local/index_storage/cache/hb_feature.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/search_local/index_storage/cache/hb_feature.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
/* * ===================================================================================== * * Filename: hb_feature.cc * * Description: hotbackup method release. * * Version: 1.0 * Created: 09/08/2020 10:02:05 PM * Revision: none * Compiler: gcc * * Author: Norton, yangshuang68@jd.com * Company: JD.com, Inc. * * ===================================================================================== */ #include <string.h> #include <stdio.h> #include <errno.h> #include "hb_feature.h" #include "global.h" DTC_USING_NAMESPACE HBFeature::HBFeature() : _hb_info(NULL), _handle(INVALID_HANDLE) { memset(_errmsg, 0, sizeof(_errmsg)); } HBFeature::~HBFeature() { } int HBFeature::Init(time_t tMasterUptime) { _handle = M_CALLOC(sizeof(HB_FEATURE_INFO_T)); if (INVALID_HANDLE == _handle) { snprintf(_errmsg, sizeof(_errmsg), "init hb_feature fail, %s", M_ERROR()); return -ENOMEM; } _hb_info = M_POINTER(HB_FEATURE_INFO_T, _handle); _hb_info->master_up_time = tMasterUptime; _hb_info->slave_up_time = 0; return 0; } int HBFeature::Attach(MEM_HANDLE_T handle) { if (INVALID_HANDLE == handle) { snprintf(_errmsg, sizeof(_errmsg), "attach hb feature failed, memory handle = 0"); return -1; } _handle = handle; _hb_info = M_POINTER(HB_FEATURE_INFO_T, _handle); return 0; } void HBFeature::Detach(void) { _hb_info = NULL; _handle = INVALID_HANDLE; }
20.671429
88
0.587422
jdisearch
667ecdb4aa83ec5647baf99ef9fa710f9347057a
2,914
hpp
C++
include/libTAU/kademlia/rpc_manager.hpp
Tau-Coin/libTAU
2e8cace4195faa75b6a75c0ce02496346936bc79
[ "BSL-1.0", "BSD-3-Clause" ]
6
2021-08-16T17:27:10.000Z
2022-01-12T09:18:02.000Z
include/libTAU/kademlia/rpc_manager.hpp
Tau-Coin/libTAU
2e8cace4195faa75b6a75c0ce02496346936bc79
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
include/libTAU/kademlia/rpc_manager.hpp
Tau-Coin/libTAU
2e8cace4195faa75b6a75c0ce02496346936bc79
[ "BSL-1.0", "BSD-3-Clause" ]
3
2022-01-03T03:06:54.000Z
2022-03-11T03:15:32.000Z
/* Copyright (c) 2006-2017, 2019-2020, Arvid Norberg Copyright (c) 2015, Thomas Yuan Copyright (c) 2016-2017, Steven Siloti Copyright (c) 2016, Alden Torres All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #ifndef RPC_MANAGER_HPP #define RPC_MANAGER_HPP #include <unordered_map> #include <cstdint> #include <libTAU/socket.hpp> #include <libTAU/time.hpp> #include <libTAU/kademlia/node_id.hpp> #include <libTAU/kademlia/observer.hpp> #include <libTAU/aux_/listen_socket_handle.hpp> #include <libTAU/aux_/pool.hpp> namespace libTAU { struct entry; namespace aux { struct session_settings; } } namespace libTAU { namespace dht { struct settings; struct dht_logger; struct socket_manager; struct TORRENT_EXTRA_EXPORT null_observer : observer { null_observer(std::shared_ptr<traversal_algorithm> a , udp::endpoint const& ep, node_id const& id) : observer(std::move(a), ep, id) {} void reply(msg const&) override { flags |= flag_done; } }; class routing_table; class TORRENT_EXTRA_EXPORT rpc_manager { public: rpc_manager(node_id const& our_id , aux::session_settings const& settings , routing_table& table , aux::listen_socket_handle sock , socket_manager* sock_man , dht_logger* log); ~rpc_manager(); void unreachable(udp::endpoint const& ep); // returns true if the node needs a refresh // if so, id is assigned the node id to refresh bool incoming(msg const&, node_id* id); time_duration tick(); bool invoke(entry& e, udp::endpoint const& target , observer_ptr o, bool discard_response = false); void add_our_id(entry& e); #if TORRENT_USE_ASSERTS size_t allocation_size() const; #endif #if TORRENT_USE_INVARIANT_CHECKS void check_invariant() const; #endif template <typename T, typename... Args> std::shared_ptr<T> allocate_observer(Args&&... args) { void* ptr = allocate_observer(); if (ptr == nullptr) return std::shared_ptr<T>(); auto deleter = [this](observer* o) { TORRENT_ASSERT(o->m_in_use); o->~observer(); free_observer(o); }; return std::shared_ptr<T>(new (ptr) T(std::forward<Args>(args)...), deleter); } int num_allocated_observers() const { return m_allocated_observers; } int num_invoked_requests() const { return m_invoked_requests; } void update_node_id(node_id const& id) { m_our_id = id; } private: void* allocate_observer(); void free_observer(void* ptr); mutable lt::aux::pool m_pool_allocator; std::unordered_multimap<std::uint16_t, observer_ptr> m_transactions; aux::listen_socket_handle m_sock; socket_manager* m_sock_man; #ifndef TORRENT_DISABLE_LOGGING dht_logger* m_log; #endif aux::session_settings const& m_settings; routing_table& m_table; node_id m_our_id; std::uint32_t m_allocated_observers:31; std::int64_t m_invoked_requests; std::uint32_t m_destructing:1; }; } // namespace dht } // namespace libTAU #endif
22.765625
80
0.74571
Tau-Coin
667ff961092b42586ada40c0221036a46def61ea
698
cpp
C++
src/Astar-3D/list.cpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
9
2021-09-04T15:14:57.000Z
2022-03-29T04:34:13.000Z
src/Astar-3D/list.cpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
null
null
null
src/Astar-3D/list.cpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
4
2021-09-29T11:32:54.000Z
2022-03-06T05:24:33.000Z
#include "Astar-3D/list.h" NodeList::NodeList(void) { } NodeList::~NodeList(void) { } bool NodeList::find(int x, int y) { std::list<Node>::iterator iter = List.end(); for(; iter != List.begin(); --iter) { if((iter->i == x) && (iter->j == y)) { return true; } } if((iter->i == x) && (iter->j == y)) { return true; } return false; } std::list<Node>::iterator NodeList::find_i(int x, int y) { std::list<Node>::iterator iter = List.begin(); for(iter = List.begin(); iter != List.end(); ++iter) { if((iter->i == x) && (iter->j == y)) { break; } } return iter; }
15.511111
56
0.465616
dabinkim-LGOM
66815ad5cc91d384bcc57fb4e047955f66ad71d5
1,070
hpp
C++
Sources/Uis/UiPanel.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Uis/UiPanel.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Uis/UiPanel.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
#pragma once #include "Guis/Gui.hpp" #include "Uis/UiObject.hpp" #include "UiScrollBar.hpp" namespace acid { class ACID_EXPORT UiPanel : public UiObject { public: enum class Resize { None, Left, Top, Right, Bottom }; explicit UiPanel(UiObject *parent, const UiBound &rectangle = UiBound(Vector2f(0.0f, 0.0f), UiReference::Centre, UiAspect::Position | UiAspect::Size), const Colour &colour = Colour::White, const Resize &resize = Resize::None, const BitMask<ScrollBar> &scrollBars = ScrollBar::Vertical | ScrollBar::Horizontal); void UpdateObject() override; UiObject &GetContent() { return m_content; } const BitMask<ScrollBar> &GetScrollBars() const { return m_scrollBars; } void SetScrollBars(const BitMask<ScrollBar> &scrollBars) { m_scrollBars = scrollBars; } private: void SetScissor(UiObject *object, const bool &checkSize = false); Gui m_background; UiObject m_content; UiObject m_resizeHandle; Resize m_resize; UiScrollBar m_scrollX; UiScrollBar m_scrollY; BitMask<ScrollBar> m_scrollBars; Vector2f m_min; Vector2f m_max; }; }
23.26087
161
0.751402
liuping1997
668c04dec1fe1dee72957b89136ea4c585ec9953
78,809
cc
C++
src/ros/src/security/include/modules/localization/proto/localization.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
1
2018-05-25T07:20:17.000Z
2018-05-25T07:20:17.000Z
src/ros/src/security/include/modules/localization/proto/localization.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
null
null
null
src/ros/src/security/include/modules/localization/proto/localization.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: modules/localization/proto/localization.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "modules/localization/proto/localization.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace apollo { namespace localization { class UncertaintyDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Uncertainty> { } _Uncertainty_default_instance_; class LocalizationEstimateDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<LocalizationEstimate> { } _LocalizationEstimate_default_instance_; class LocalizationStatusDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<LocalizationStatus> { } _LocalizationStatus_default_instance_; namespace protobuf_modules_2flocalization_2fproto_2flocalization_2eproto { namespace { ::google::protobuf::Metadata file_level_metadata[3]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1]; } // namespace PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField const TableStruct::entries[] = { {0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0}, }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField const TableStruct::aux[] = { ::google::protobuf::internal::AuxillaryParseTableField(), }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const TableStruct::schema[] = { { NULL, NULL, 0, -1, -1, false }, { NULL, NULL, 0, -1, -1, false }, { NULL, NULL, 0, -1, -1, false }, }; const ::google::protobuf::uint32 TableStruct::offsets[] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Uncertainty, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Uncertainty, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Uncertainty, position_std_dev_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Uncertainty, orientation_std_dev_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Uncertainty, linear_velocity_std_dev_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Uncertainty, linear_acceleration_std_dev_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Uncertainty, angular_velocity_std_dev_), 0, 1, 2, 3, 4, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationEstimate, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationEstimate, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationEstimate, header_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationEstimate, pose_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationEstimate, uncertainty_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationEstimate, measurement_time_), 0, 1, 2, 3, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationStatus, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationStatus, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationStatus, header_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationStatus, fusion_status_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationStatus, gnss_status_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationStatus, lidar_status_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LocalizationStatus, measurement_time_), 0, 1, 2, 4, 3, }; static const ::google::protobuf::internal::MigrationSchema schemas[] = { { 0, 10, sizeof(Uncertainty)}, { 15, 24, sizeof(LocalizationEstimate)}, { 28, 38, sizeof(LocalizationStatus)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&_Uncertainty_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_LocalizationEstimate_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_LocalizationStatus_default_instance_), }; namespace { void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "modules/localization/proto/localization.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3); } } // namespace void TableStruct::Shutdown() { _Uncertainty_default_instance_.Shutdown(); delete file_level_metadata[0].reflection; _LocalizationEstimate_default_instance_.Shutdown(); delete file_level_metadata[1].reflection; _LocalizationStatus_default_instance_.Shutdown(); delete file_level_metadata[2].reflection; } void TableStruct::InitDefaultsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::internal::InitProtobufDefaults(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fheader_2eproto::InitDefaults(); ::apollo::localization::protobuf_modules_2flocalization_2fproto_2fpose_2eproto::InitDefaults(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fgeometry_2eproto::InitDefaults(); _Uncertainty_default_instance_.DefaultConstruct(); _LocalizationEstimate_default_instance_.DefaultConstruct(); _LocalizationStatus_default_instance_.DefaultConstruct(); _Uncertainty_default_instance_.get_mutable()->position_std_dev_ = const_cast< ::apollo::common::Point3D*>( ::apollo::common::Point3D::internal_default_instance()); _Uncertainty_default_instance_.get_mutable()->orientation_std_dev_ = const_cast< ::apollo::common::Point3D*>( ::apollo::common::Point3D::internal_default_instance()); _Uncertainty_default_instance_.get_mutable()->linear_velocity_std_dev_ = const_cast< ::apollo::common::Point3D*>( ::apollo::common::Point3D::internal_default_instance()); _Uncertainty_default_instance_.get_mutable()->linear_acceleration_std_dev_ = const_cast< ::apollo::common::Point3D*>( ::apollo::common::Point3D::internal_default_instance()); _Uncertainty_default_instance_.get_mutable()->angular_velocity_std_dev_ = const_cast< ::apollo::common::Point3D*>( ::apollo::common::Point3D::internal_default_instance()); _LocalizationEstimate_default_instance_.get_mutable()->header_ = const_cast< ::apollo::common::Header*>( ::apollo::common::Header::internal_default_instance()); _LocalizationEstimate_default_instance_.get_mutable()->pose_ = const_cast< ::apollo::localization::Pose*>( ::apollo::localization::Pose::internal_default_instance()); _LocalizationEstimate_default_instance_.get_mutable()->uncertainty_ = const_cast< ::apollo::localization::Uncertainty*>( ::apollo::localization::Uncertainty::internal_default_instance()); _LocalizationStatus_default_instance_.get_mutable()->header_ = const_cast< ::apollo::common::Header*>( ::apollo::common::Header::internal_default_instance()); } void InitDefaults() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] = { "\n-modules/localization/proto/localizatio" "n.proto\022\023apollo.localization\032!modules/co" "mmon/proto/header.proto\032%modules/localiz" "ation/proto/pose.proto\032#modules/common/p" "roto/geometry.proto\"\244\002\n\013Uncertainty\0220\n\020p" "osition_std_dev\030\001 \001(\0132\026.apollo.common.Po" "int3D\0223\n\023orientation_std_dev\030\002 \001(\0132\026.apo" "llo.common.Point3D\0227\n\027linear_velocity_st" "d_dev\030\003 \001(\0132\026.apollo.common.Point3D\022;\n\033l" "inear_acceleration_std_dev\030\004 \001(\0132\026.apoll" "o.common.Point3D\0228\n\030angular_velocity_std" "_dev\030\005 \001(\0132\026.apollo.common.Point3D\"\267\001\n\024L" "ocalizationEstimate\022%\n\006header\030\001 \001(\0132\025.ap" "ollo.common.Header\022\'\n\004pose\030\002 \001(\0132\031.apoll" "o.localization.Pose\0225\n\013uncertainty\030\003 \001(\013" "2 .apollo.localization.Uncertainty\022\030\n\020me" "asurement_time\030\004 \001(\001\"\200\002\n\022LocalizationSta" "tus\022%\n\006header\030\001 \001(\0132\025.apollo.common.Head" "er\0228\n\rfusion_status\030\002 \001(\0162!.apollo.local" "ization.MeasureState\0226\n\013gnss_status\030\003 \001(" "\0162!.apollo.localization.MeasureState\0227\n\014" "lidar_status\030\004 \001(\0162!.apollo.localization" ".MeasureState\022\030\n\020measurement_time\030\005 \001(\001*" "@\n\014MeasureState\022\r\n\tNOT_VALID\020\000\022\016\n\nNOT_ST" "ABLE\020\001\022\006\n\002OK\020\002\022\t\n\005VALID\020\003" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 985); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "modules/localization/proto/localization.proto", &protobuf_RegisterTypes); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fheader_2eproto::AddDescriptors(); ::apollo::localization::protobuf_modules_2flocalization_2fproto_2fpose_2eproto::AddDescriptors(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fgeometry_2eproto::AddDescriptors(); ::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_modules_2flocalization_2fproto_2flocalization_2eproto const ::google::protobuf::EnumDescriptor* MeasureState_descriptor() { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::file_level_enum_descriptors[0]; } bool MeasureState_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: return true; default: return false; } } // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Uncertainty::kPositionStdDevFieldNumber; const int Uncertainty::kOrientationStdDevFieldNumber; const int Uncertainty::kLinearVelocityStdDevFieldNumber; const int Uncertainty::kLinearAccelerationStdDevFieldNumber; const int Uncertainty::kAngularVelocityStdDevFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Uncertainty::Uncertainty() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.localization.Uncertainty) } Uncertainty::Uncertainty(const Uncertainty& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_position_std_dev()) { position_std_dev_ = new ::apollo::common::Point3D(*from.position_std_dev_); } else { position_std_dev_ = NULL; } if (from.has_orientation_std_dev()) { orientation_std_dev_ = new ::apollo::common::Point3D(*from.orientation_std_dev_); } else { orientation_std_dev_ = NULL; } if (from.has_linear_velocity_std_dev()) { linear_velocity_std_dev_ = new ::apollo::common::Point3D(*from.linear_velocity_std_dev_); } else { linear_velocity_std_dev_ = NULL; } if (from.has_linear_acceleration_std_dev()) { linear_acceleration_std_dev_ = new ::apollo::common::Point3D(*from.linear_acceleration_std_dev_); } else { linear_acceleration_std_dev_ = NULL; } if (from.has_angular_velocity_std_dev()) { angular_velocity_std_dev_ = new ::apollo::common::Point3D(*from.angular_velocity_std_dev_); } else { angular_velocity_std_dev_ = NULL; } // @@protoc_insertion_point(copy_constructor:apollo.localization.Uncertainty) } void Uncertainty::SharedCtor() { _cached_size_ = 0; ::memset(&position_std_dev_, 0, reinterpret_cast<char*>(&angular_velocity_std_dev_) - reinterpret_cast<char*>(&position_std_dev_) + sizeof(angular_velocity_std_dev_)); } Uncertainty::~Uncertainty() { // @@protoc_insertion_point(destructor:apollo.localization.Uncertainty) SharedDtor(); } void Uncertainty::SharedDtor() { if (this != internal_default_instance()) { delete position_std_dev_; } if (this != internal_default_instance()) { delete orientation_std_dev_; } if (this != internal_default_instance()) { delete linear_velocity_std_dev_; } if (this != internal_default_instance()) { delete linear_acceleration_std_dev_; } if (this != internal_default_instance()) { delete angular_velocity_std_dev_; } } void Uncertainty::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Uncertainty::descriptor() { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Uncertainty& Uncertainty::default_instance() { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::InitDefaults(); return *internal_default_instance(); } Uncertainty* Uncertainty::New(::google::protobuf::Arena* arena) const { Uncertainty* n = new Uncertainty; if (arena != NULL) { arena->Own(n); } return n; } void Uncertainty::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.localization.Uncertainty) if (_has_bits_[0 / 32] & 31u) { if (has_position_std_dev()) { GOOGLE_DCHECK(position_std_dev_ != NULL); position_std_dev_->::apollo::common::Point3D::Clear(); } if (has_orientation_std_dev()) { GOOGLE_DCHECK(orientation_std_dev_ != NULL); orientation_std_dev_->::apollo::common::Point3D::Clear(); } if (has_linear_velocity_std_dev()) { GOOGLE_DCHECK(linear_velocity_std_dev_ != NULL); linear_velocity_std_dev_->::apollo::common::Point3D::Clear(); } if (has_linear_acceleration_std_dev()) { GOOGLE_DCHECK(linear_acceleration_std_dev_ != NULL); linear_acceleration_std_dev_->::apollo::common::Point3D::Clear(); } if (has_angular_velocity_std_dev()) { GOOGLE_DCHECK(angular_velocity_std_dev_ != NULL); angular_velocity_std_dev_->::apollo::common::Point3D::Clear(); } } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool Uncertainty::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.localization.Uncertainty) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .apollo.common.Point3D position_std_dev = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_position_std_dev())); } else { goto handle_unusual; } break; } // optional .apollo.common.Point3D orientation_std_dev = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_orientation_std_dev())); } else { goto handle_unusual; } break; } // optional .apollo.common.Point3D linear_velocity_std_dev = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_linear_velocity_std_dev())); } else { goto handle_unusual; } break; } // optional .apollo.common.Point3D linear_acceleration_std_dev = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_linear_acceleration_std_dev())); } else { goto handle_unusual; } break; } // optional .apollo.common.Point3D angular_velocity_std_dev = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(42u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_angular_velocity_std_dev())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.localization.Uncertainty) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.localization.Uncertainty) return false; #undef DO_ } void Uncertainty::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.localization.Uncertainty) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .apollo.common.Point3D position_std_dev = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->position_std_dev_, output); } // optional .apollo.common.Point3D orientation_std_dev = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->orientation_std_dev_, output); } // optional .apollo.common.Point3D linear_velocity_std_dev = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, *this->linear_velocity_std_dev_, output); } // optional .apollo.common.Point3D linear_acceleration_std_dev = 4; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->linear_acceleration_std_dev_, output); } // optional .apollo.common.Point3D angular_velocity_std_dev = 5; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, *this->angular_velocity_std_dev_, output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.localization.Uncertainty) } ::google::protobuf::uint8* Uncertainty::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.localization.Uncertainty) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .apollo.common.Point3D position_std_dev = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *this->position_std_dev_, deterministic, target); } // optional .apollo.common.Point3D orientation_std_dev = 2; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->orientation_std_dev_, deterministic, target); } // optional .apollo.common.Point3D linear_velocity_std_dev = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 3, *this->linear_velocity_std_dev_, deterministic, target); } // optional .apollo.common.Point3D linear_acceleration_std_dev = 4; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *this->linear_acceleration_std_dev_, deterministic, target); } // optional .apollo.common.Point3D angular_velocity_std_dev = 5; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 5, *this->angular_velocity_std_dev_, deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.localization.Uncertainty) return target; } size_t Uncertainty::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.localization.Uncertainty) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } if (_has_bits_[0 / 32] & 31u) { // optional .apollo.common.Point3D position_std_dev = 1; if (has_position_std_dev()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->position_std_dev_); } // optional .apollo.common.Point3D orientation_std_dev = 2; if (has_orientation_std_dev()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->orientation_std_dev_); } // optional .apollo.common.Point3D linear_velocity_std_dev = 3; if (has_linear_velocity_std_dev()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->linear_velocity_std_dev_); } // optional .apollo.common.Point3D linear_acceleration_std_dev = 4; if (has_linear_acceleration_std_dev()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->linear_acceleration_std_dev_); } // optional .apollo.common.Point3D angular_velocity_std_dev = 5; if (has_angular_velocity_std_dev()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->angular_velocity_std_dev_); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Uncertainty::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.localization.Uncertainty) GOOGLE_DCHECK_NE(&from, this); const Uncertainty* source = ::google::protobuf::internal::DynamicCastToGenerated<const Uncertainty>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.localization.Uncertainty) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.localization.Uncertainty) MergeFrom(*source); } } void Uncertainty::MergeFrom(const Uncertainty& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.localization.Uncertainty) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 31u) { if (cached_has_bits & 0x00000001u) { mutable_position_std_dev()->::apollo::common::Point3D::MergeFrom(from.position_std_dev()); } if (cached_has_bits & 0x00000002u) { mutable_orientation_std_dev()->::apollo::common::Point3D::MergeFrom(from.orientation_std_dev()); } if (cached_has_bits & 0x00000004u) { mutable_linear_velocity_std_dev()->::apollo::common::Point3D::MergeFrom(from.linear_velocity_std_dev()); } if (cached_has_bits & 0x00000008u) { mutable_linear_acceleration_std_dev()->::apollo::common::Point3D::MergeFrom(from.linear_acceleration_std_dev()); } if (cached_has_bits & 0x00000010u) { mutable_angular_velocity_std_dev()->::apollo::common::Point3D::MergeFrom(from.angular_velocity_std_dev()); } } } void Uncertainty::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.localization.Uncertainty) if (&from == this) return; Clear(); MergeFrom(from); } void Uncertainty::CopyFrom(const Uncertainty& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.localization.Uncertainty) if (&from == this) return; Clear(); MergeFrom(from); } bool Uncertainty::IsInitialized() const { return true; } void Uncertainty::Swap(Uncertainty* other) { if (other == this) return; InternalSwap(other); } void Uncertainty::InternalSwap(Uncertainty* other) { std::swap(position_std_dev_, other->position_std_dev_); std::swap(orientation_std_dev_, other->orientation_std_dev_); std::swap(linear_velocity_std_dev_, other->linear_velocity_std_dev_); std::swap(linear_acceleration_std_dev_, other->linear_acceleration_std_dev_); std::swap(angular_velocity_std_dev_, other->angular_velocity_std_dev_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Uncertainty::GetMetadata() const { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Uncertainty // optional .apollo.common.Point3D position_std_dev = 1; bool Uncertainty::has_position_std_dev() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Uncertainty::set_has_position_std_dev() { _has_bits_[0] |= 0x00000001u; } void Uncertainty::clear_has_position_std_dev() { _has_bits_[0] &= ~0x00000001u; } void Uncertainty::clear_position_std_dev() { if (position_std_dev_ != NULL) position_std_dev_->::apollo::common::Point3D::Clear(); clear_has_position_std_dev(); } const ::apollo::common::Point3D& Uncertainty::position_std_dev() const { // @@protoc_insertion_point(field_get:apollo.localization.Uncertainty.position_std_dev) return position_std_dev_ != NULL ? *position_std_dev_ : *::apollo::common::Point3D::internal_default_instance(); } ::apollo::common::Point3D* Uncertainty::mutable_position_std_dev() { set_has_position_std_dev(); if (position_std_dev_ == NULL) { position_std_dev_ = new ::apollo::common::Point3D; } // @@protoc_insertion_point(field_mutable:apollo.localization.Uncertainty.position_std_dev) return position_std_dev_; } ::apollo::common::Point3D* Uncertainty::release_position_std_dev() { // @@protoc_insertion_point(field_release:apollo.localization.Uncertainty.position_std_dev) clear_has_position_std_dev(); ::apollo::common::Point3D* temp = position_std_dev_; position_std_dev_ = NULL; return temp; } void Uncertainty::set_allocated_position_std_dev(::apollo::common::Point3D* position_std_dev) { delete position_std_dev_; position_std_dev_ = position_std_dev; if (position_std_dev) { set_has_position_std_dev(); } else { clear_has_position_std_dev(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.Uncertainty.position_std_dev) } // optional .apollo.common.Point3D orientation_std_dev = 2; bool Uncertainty::has_orientation_std_dev() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Uncertainty::set_has_orientation_std_dev() { _has_bits_[0] |= 0x00000002u; } void Uncertainty::clear_has_orientation_std_dev() { _has_bits_[0] &= ~0x00000002u; } void Uncertainty::clear_orientation_std_dev() { if (orientation_std_dev_ != NULL) orientation_std_dev_->::apollo::common::Point3D::Clear(); clear_has_orientation_std_dev(); } const ::apollo::common::Point3D& Uncertainty::orientation_std_dev() const { // @@protoc_insertion_point(field_get:apollo.localization.Uncertainty.orientation_std_dev) return orientation_std_dev_ != NULL ? *orientation_std_dev_ : *::apollo::common::Point3D::internal_default_instance(); } ::apollo::common::Point3D* Uncertainty::mutable_orientation_std_dev() { set_has_orientation_std_dev(); if (orientation_std_dev_ == NULL) { orientation_std_dev_ = new ::apollo::common::Point3D; } // @@protoc_insertion_point(field_mutable:apollo.localization.Uncertainty.orientation_std_dev) return orientation_std_dev_; } ::apollo::common::Point3D* Uncertainty::release_orientation_std_dev() { // @@protoc_insertion_point(field_release:apollo.localization.Uncertainty.orientation_std_dev) clear_has_orientation_std_dev(); ::apollo::common::Point3D* temp = orientation_std_dev_; orientation_std_dev_ = NULL; return temp; } void Uncertainty::set_allocated_orientation_std_dev(::apollo::common::Point3D* orientation_std_dev) { delete orientation_std_dev_; orientation_std_dev_ = orientation_std_dev; if (orientation_std_dev) { set_has_orientation_std_dev(); } else { clear_has_orientation_std_dev(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.Uncertainty.orientation_std_dev) } // optional .apollo.common.Point3D linear_velocity_std_dev = 3; bool Uncertainty::has_linear_velocity_std_dev() const { return (_has_bits_[0] & 0x00000004u) != 0; } void Uncertainty::set_has_linear_velocity_std_dev() { _has_bits_[0] |= 0x00000004u; } void Uncertainty::clear_has_linear_velocity_std_dev() { _has_bits_[0] &= ~0x00000004u; } void Uncertainty::clear_linear_velocity_std_dev() { if (linear_velocity_std_dev_ != NULL) linear_velocity_std_dev_->::apollo::common::Point3D::Clear(); clear_has_linear_velocity_std_dev(); } const ::apollo::common::Point3D& Uncertainty::linear_velocity_std_dev() const { // @@protoc_insertion_point(field_get:apollo.localization.Uncertainty.linear_velocity_std_dev) return linear_velocity_std_dev_ != NULL ? *linear_velocity_std_dev_ : *::apollo::common::Point3D::internal_default_instance(); } ::apollo::common::Point3D* Uncertainty::mutable_linear_velocity_std_dev() { set_has_linear_velocity_std_dev(); if (linear_velocity_std_dev_ == NULL) { linear_velocity_std_dev_ = new ::apollo::common::Point3D; } // @@protoc_insertion_point(field_mutable:apollo.localization.Uncertainty.linear_velocity_std_dev) return linear_velocity_std_dev_; } ::apollo::common::Point3D* Uncertainty::release_linear_velocity_std_dev() { // @@protoc_insertion_point(field_release:apollo.localization.Uncertainty.linear_velocity_std_dev) clear_has_linear_velocity_std_dev(); ::apollo::common::Point3D* temp = linear_velocity_std_dev_; linear_velocity_std_dev_ = NULL; return temp; } void Uncertainty::set_allocated_linear_velocity_std_dev(::apollo::common::Point3D* linear_velocity_std_dev) { delete linear_velocity_std_dev_; linear_velocity_std_dev_ = linear_velocity_std_dev; if (linear_velocity_std_dev) { set_has_linear_velocity_std_dev(); } else { clear_has_linear_velocity_std_dev(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.Uncertainty.linear_velocity_std_dev) } // optional .apollo.common.Point3D linear_acceleration_std_dev = 4; bool Uncertainty::has_linear_acceleration_std_dev() const { return (_has_bits_[0] & 0x00000008u) != 0; } void Uncertainty::set_has_linear_acceleration_std_dev() { _has_bits_[0] |= 0x00000008u; } void Uncertainty::clear_has_linear_acceleration_std_dev() { _has_bits_[0] &= ~0x00000008u; } void Uncertainty::clear_linear_acceleration_std_dev() { if (linear_acceleration_std_dev_ != NULL) linear_acceleration_std_dev_->::apollo::common::Point3D::Clear(); clear_has_linear_acceleration_std_dev(); } const ::apollo::common::Point3D& Uncertainty::linear_acceleration_std_dev() const { // @@protoc_insertion_point(field_get:apollo.localization.Uncertainty.linear_acceleration_std_dev) return linear_acceleration_std_dev_ != NULL ? *linear_acceleration_std_dev_ : *::apollo::common::Point3D::internal_default_instance(); } ::apollo::common::Point3D* Uncertainty::mutable_linear_acceleration_std_dev() { set_has_linear_acceleration_std_dev(); if (linear_acceleration_std_dev_ == NULL) { linear_acceleration_std_dev_ = new ::apollo::common::Point3D; } // @@protoc_insertion_point(field_mutable:apollo.localization.Uncertainty.linear_acceleration_std_dev) return linear_acceleration_std_dev_; } ::apollo::common::Point3D* Uncertainty::release_linear_acceleration_std_dev() { // @@protoc_insertion_point(field_release:apollo.localization.Uncertainty.linear_acceleration_std_dev) clear_has_linear_acceleration_std_dev(); ::apollo::common::Point3D* temp = linear_acceleration_std_dev_; linear_acceleration_std_dev_ = NULL; return temp; } void Uncertainty::set_allocated_linear_acceleration_std_dev(::apollo::common::Point3D* linear_acceleration_std_dev) { delete linear_acceleration_std_dev_; linear_acceleration_std_dev_ = linear_acceleration_std_dev; if (linear_acceleration_std_dev) { set_has_linear_acceleration_std_dev(); } else { clear_has_linear_acceleration_std_dev(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.Uncertainty.linear_acceleration_std_dev) } // optional .apollo.common.Point3D angular_velocity_std_dev = 5; bool Uncertainty::has_angular_velocity_std_dev() const { return (_has_bits_[0] & 0x00000010u) != 0; } void Uncertainty::set_has_angular_velocity_std_dev() { _has_bits_[0] |= 0x00000010u; } void Uncertainty::clear_has_angular_velocity_std_dev() { _has_bits_[0] &= ~0x00000010u; } void Uncertainty::clear_angular_velocity_std_dev() { if (angular_velocity_std_dev_ != NULL) angular_velocity_std_dev_->::apollo::common::Point3D::Clear(); clear_has_angular_velocity_std_dev(); } const ::apollo::common::Point3D& Uncertainty::angular_velocity_std_dev() const { // @@protoc_insertion_point(field_get:apollo.localization.Uncertainty.angular_velocity_std_dev) return angular_velocity_std_dev_ != NULL ? *angular_velocity_std_dev_ : *::apollo::common::Point3D::internal_default_instance(); } ::apollo::common::Point3D* Uncertainty::mutable_angular_velocity_std_dev() { set_has_angular_velocity_std_dev(); if (angular_velocity_std_dev_ == NULL) { angular_velocity_std_dev_ = new ::apollo::common::Point3D; } // @@protoc_insertion_point(field_mutable:apollo.localization.Uncertainty.angular_velocity_std_dev) return angular_velocity_std_dev_; } ::apollo::common::Point3D* Uncertainty::release_angular_velocity_std_dev() { // @@protoc_insertion_point(field_release:apollo.localization.Uncertainty.angular_velocity_std_dev) clear_has_angular_velocity_std_dev(); ::apollo::common::Point3D* temp = angular_velocity_std_dev_; angular_velocity_std_dev_ = NULL; return temp; } void Uncertainty::set_allocated_angular_velocity_std_dev(::apollo::common::Point3D* angular_velocity_std_dev) { delete angular_velocity_std_dev_; angular_velocity_std_dev_ = angular_velocity_std_dev; if (angular_velocity_std_dev) { set_has_angular_velocity_std_dev(); } else { clear_has_angular_velocity_std_dev(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.Uncertainty.angular_velocity_std_dev) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int LocalizationEstimate::kHeaderFieldNumber; const int LocalizationEstimate::kPoseFieldNumber; const int LocalizationEstimate::kUncertaintyFieldNumber; const int LocalizationEstimate::kMeasurementTimeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 LocalizationEstimate::LocalizationEstimate() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.localization.LocalizationEstimate) } LocalizationEstimate::LocalizationEstimate(const LocalizationEstimate& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_header()) { header_ = new ::apollo::common::Header(*from.header_); } else { header_ = NULL; } if (from.has_pose()) { pose_ = new ::apollo::localization::Pose(*from.pose_); } else { pose_ = NULL; } if (from.has_uncertainty()) { uncertainty_ = new ::apollo::localization::Uncertainty(*from.uncertainty_); } else { uncertainty_ = NULL; } measurement_time_ = from.measurement_time_; // @@protoc_insertion_point(copy_constructor:apollo.localization.LocalizationEstimate) } void LocalizationEstimate::SharedCtor() { _cached_size_ = 0; ::memset(&header_, 0, reinterpret_cast<char*>(&measurement_time_) - reinterpret_cast<char*>(&header_) + sizeof(measurement_time_)); } LocalizationEstimate::~LocalizationEstimate() { // @@protoc_insertion_point(destructor:apollo.localization.LocalizationEstimate) SharedDtor(); } void LocalizationEstimate::SharedDtor() { if (this != internal_default_instance()) { delete header_; } if (this != internal_default_instance()) { delete pose_; } if (this != internal_default_instance()) { delete uncertainty_; } } void LocalizationEstimate::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* LocalizationEstimate::descriptor() { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const LocalizationEstimate& LocalizationEstimate::default_instance() { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::InitDefaults(); return *internal_default_instance(); } LocalizationEstimate* LocalizationEstimate::New(::google::protobuf::Arena* arena) const { LocalizationEstimate* n = new LocalizationEstimate; if (arena != NULL) { arena->Own(n); } return n; } void LocalizationEstimate::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.localization.LocalizationEstimate) if (_has_bits_[0 / 32] & 7u) { if (has_header()) { GOOGLE_DCHECK(header_ != NULL); header_->::apollo::common::Header::Clear(); } if (has_pose()) { GOOGLE_DCHECK(pose_ != NULL); pose_->::apollo::localization::Pose::Clear(); } if (has_uncertainty()) { GOOGLE_DCHECK(uncertainty_ != NULL); uncertainty_->::apollo::localization::Uncertainty::Clear(); } } measurement_time_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear(); } bool LocalizationEstimate::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.localization.LocalizationEstimate) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .apollo.common.Header header = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_header())); } else { goto handle_unusual; } break; } // optional .apollo.localization.Pose pose = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_pose())); } else { goto handle_unusual; } break; } // optional .apollo.localization.Uncertainty uncertainty = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_uncertainty())); } else { goto handle_unusual; } break; } // optional double measurement_time = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(33u)) { set_has_measurement_time(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &measurement_time_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.localization.LocalizationEstimate) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.localization.LocalizationEstimate) return false; #undef DO_ } void LocalizationEstimate::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.localization.LocalizationEstimate) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->header_, output); } // optional .apollo.localization.Pose pose = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->pose_, output); } // optional .apollo.localization.Uncertainty uncertainty = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, *this->uncertainty_, output); } // optional double measurement_time = 4; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(4, this->measurement_time(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.localization.LocalizationEstimate) } ::google::protobuf::uint8* LocalizationEstimate::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.localization.LocalizationEstimate) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *this->header_, deterministic, target); } // optional .apollo.localization.Pose pose = 2; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->pose_, deterministic, target); } // optional .apollo.localization.Uncertainty uncertainty = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 3, *this->uncertainty_, deterministic, target); } // optional double measurement_time = 4; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(4, this->measurement_time(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.localization.LocalizationEstimate) return target; } size_t LocalizationEstimate::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.localization.LocalizationEstimate) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } if (_has_bits_[0 / 32] & 15u) { // optional .apollo.common.Header header = 1; if (has_header()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->header_); } // optional .apollo.localization.Pose pose = 2; if (has_pose()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->pose_); } // optional .apollo.localization.Uncertainty uncertainty = 3; if (has_uncertainty()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->uncertainty_); } // optional double measurement_time = 4; if (has_measurement_time()) { total_size += 1 + 8; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void LocalizationEstimate::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.localization.LocalizationEstimate) GOOGLE_DCHECK_NE(&from, this); const LocalizationEstimate* source = ::google::protobuf::internal::DynamicCastToGenerated<const LocalizationEstimate>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.localization.LocalizationEstimate) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.localization.LocalizationEstimate) MergeFrom(*source); } } void LocalizationEstimate::MergeFrom(const LocalizationEstimate& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.localization.LocalizationEstimate) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 15u) { if (cached_has_bits & 0x00000001u) { mutable_header()->::apollo::common::Header::MergeFrom(from.header()); } if (cached_has_bits & 0x00000002u) { mutable_pose()->::apollo::localization::Pose::MergeFrom(from.pose()); } if (cached_has_bits & 0x00000004u) { mutable_uncertainty()->::apollo::localization::Uncertainty::MergeFrom(from.uncertainty()); } if (cached_has_bits & 0x00000008u) { measurement_time_ = from.measurement_time_; } _has_bits_[0] |= cached_has_bits; } } void LocalizationEstimate::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.localization.LocalizationEstimate) if (&from == this) return; Clear(); MergeFrom(from); } void LocalizationEstimate::CopyFrom(const LocalizationEstimate& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.localization.LocalizationEstimate) if (&from == this) return; Clear(); MergeFrom(from); } bool LocalizationEstimate::IsInitialized() const { return true; } void LocalizationEstimate::Swap(LocalizationEstimate* other) { if (other == this) return; InternalSwap(other); } void LocalizationEstimate::InternalSwap(LocalizationEstimate* other) { std::swap(header_, other->header_); std::swap(pose_, other->pose_); std::swap(uncertainty_, other->uncertainty_); std::swap(measurement_time_, other->measurement_time_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata LocalizationEstimate::GetMetadata() const { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // LocalizationEstimate // optional .apollo.common.Header header = 1; bool LocalizationEstimate::has_header() const { return (_has_bits_[0] & 0x00000001u) != 0; } void LocalizationEstimate::set_has_header() { _has_bits_[0] |= 0x00000001u; } void LocalizationEstimate::clear_has_header() { _has_bits_[0] &= ~0x00000001u; } void LocalizationEstimate::clear_header() { if (header_ != NULL) header_->::apollo::common::Header::Clear(); clear_has_header(); } const ::apollo::common::Header& LocalizationEstimate::header() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationEstimate.header) return header_ != NULL ? *header_ : *::apollo::common::Header::internal_default_instance(); } ::apollo::common::Header* LocalizationEstimate::mutable_header() { set_has_header(); if (header_ == NULL) { header_ = new ::apollo::common::Header; } // @@protoc_insertion_point(field_mutable:apollo.localization.LocalizationEstimate.header) return header_; } ::apollo::common::Header* LocalizationEstimate::release_header() { // @@protoc_insertion_point(field_release:apollo.localization.LocalizationEstimate.header) clear_has_header(); ::apollo::common::Header* temp = header_; header_ = NULL; return temp; } void LocalizationEstimate::set_allocated_header(::apollo::common::Header* header) { delete header_; header_ = header; if (header) { set_has_header(); } else { clear_has_header(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.LocalizationEstimate.header) } // optional .apollo.localization.Pose pose = 2; bool LocalizationEstimate::has_pose() const { return (_has_bits_[0] & 0x00000002u) != 0; } void LocalizationEstimate::set_has_pose() { _has_bits_[0] |= 0x00000002u; } void LocalizationEstimate::clear_has_pose() { _has_bits_[0] &= ~0x00000002u; } void LocalizationEstimate::clear_pose() { if (pose_ != NULL) pose_->::apollo::localization::Pose::Clear(); clear_has_pose(); } const ::apollo::localization::Pose& LocalizationEstimate::pose() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationEstimate.pose) return pose_ != NULL ? *pose_ : *::apollo::localization::Pose::internal_default_instance(); } ::apollo::localization::Pose* LocalizationEstimate::mutable_pose() { set_has_pose(); if (pose_ == NULL) { pose_ = new ::apollo::localization::Pose; } // @@protoc_insertion_point(field_mutable:apollo.localization.LocalizationEstimate.pose) return pose_; } ::apollo::localization::Pose* LocalizationEstimate::release_pose() { // @@protoc_insertion_point(field_release:apollo.localization.LocalizationEstimate.pose) clear_has_pose(); ::apollo::localization::Pose* temp = pose_; pose_ = NULL; return temp; } void LocalizationEstimate::set_allocated_pose(::apollo::localization::Pose* pose) { delete pose_; pose_ = pose; if (pose) { set_has_pose(); } else { clear_has_pose(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.LocalizationEstimate.pose) } // optional .apollo.localization.Uncertainty uncertainty = 3; bool LocalizationEstimate::has_uncertainty() const { return (_has_bits_[0] & 0x00000004u) != 0; } void LocalizationEstimate::set_has_uncertainty() { _has_bits_[0] |= 0x00000004u; } void LocalizationEstimate::clear_has_uncertainty() { _has_bits_[0] &= ~0x00000004u; } void LocalizationEstimate::clear_uncertainty() { if (uncertainty_ != NULL) uncertainty_->::apollo::localization::Uncertainty::Clear(); clear_has_uncertainty(); } const ::apollo::localization::Uncertainty& LocalizationEstimate::uncertainty() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationEstimate.uncertainty) return uncertainty_ != NULL ? *uncertainty_ : *::apollo::localization::Uncertainty::internal_default_instance(); } ::apollo::localization::Uncertainty* LocalizationEstimate::mutable_uncertainty() { set_has_uncertainty(); if (uncertainty_ == NULL) { uncertainty_ = new ::apollo::localization::Uncertainty; } // @@protoc_insertion_point(field_mutable:apollo.localization.LocalizationEstimate.uncertainty) return uncertainty_; } ::apollo::localization::Uncertainty* LocalizationEstimate::release_uncertainty() { // @@protoc_insertion_point(field_release:apollo.localization.LocalizationEstimate.uncertainty) clear_has_uncertainty(); ::apollo::localization::Uncertainty* temp = uncertainty_; uncertainty_ = NULL; return temp; } void LocalizationEstimate::set_allocated_uncertainty(::apollo::localization::Uncertainty* uncertainty) { delete uncertainty_; uncertainty_ = uncertainty; if (uncertainty) { set_has_uncertainty(); } else { clear_has_uncertainty(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.LocalizationEstimate.uncertainty) } // optional double measurement_time = 4; bool LocalizationEstimate::has_measurement_time() const { return (_has_bits_[0] & 0x00000008u) != 0; } void LocalizationEstimate::set_has_measurement_time() { _has_bits_[0] |= 0x00000008u; } void LocalizationEstimate::clear_has_measurement_time() { _has_bits_[0] &= ~0x00000008u; } void LocalizationEstimate::clear_measurement_time() { measurement_time_ = 0; clear_has_measurement_time(); } double LocalizationEstimate::measurement_time() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationEstimate.measurement_time) return measurement_time_; } void LocalizationEstimate::set_measurement_time(double value) { set_has_measurement_time(); measurement_time_ = value; // @@protoc_insertion_point(field_set:apollo.localization.LocalizationEstimate.measurement_time) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int LocalizationStatus::kHeaderFieldNumber; const int LocalizationStatus::kFusionStatusFieldNumber; const int LocalizationStatus::kGnssStatusFieldNumber; const int LocalizationStatus::kLidarStatusFieldNumber; const int LocalizationStatus::kMeasurementTimeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 LocalizationStatus::LocalizationStatus() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.localization.LocalizationStatus) } LocalizationStatus::LocalizationStatus(const LocalizationStatus& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_header()) { header_ = new ::apollo::common::Header(*from.header_); } else { header_ = NULL; } ::memcpy(&fusion_status_, &from.fusion_status_, reinterpret_cast<char*>(&lidar_status_) - reinterpret_cast<char*>(&fusion_status_) + sizeof(lidar_status_)); // @@protoc_insertion_point(copy_constructor:apollo.localization.LocalizationStatus) } void LocalizationStatus::SharedCtor() { _cached_size_ = 0; ::memset(&header_, 0, reinterpret_cast<char*>(&lidar_status_) - reinterpret_cast<char*>(&header_) + sizeof(lidar_status_)); } LocalizationStatus::~LocalizationStatus() { // @@protoc_insertion_point(destructor:apollo.localization.LocalizationStatus) SharedDtor(); } void LocalizationStatus::SharedDtor() { if (this != internal_default_instance()) { delete header_; } } void LocalizationStatus::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* LocalizationStatus::descriptor() { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const LocalizationStatus& LocalizationStatus::default_instance() { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::InitDefaults(); return *internal_default_instance(); } LocalizationStatus* LocalizationStatus::New(::google::protobuf::Arena* arena) const { LocalizationStatus* n = new LocalizationStatus; if (arena != NULL) { arena->Own(n); } return n; } void LocalizationStatus::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.localization.LocalizationStatus) if (has_header()) { GOOGLE_DCHECK(header_ != NULL); header_->::apollo::common::Header::Clear(); } if (_has_bits_[0 / 32] & 30u) { ::memset(&fusion_status_, 0, reinterpret_cast<char*>(&lidar_status_) - reinterpret_cast<char*>(&fusion_status_) + sizeof(lidar_status_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool LocalizationStatus::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.localization.LocalizationStatus) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .apollo.common.Header header = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_header())); } else { goto handle_unusual; } break; } // optional .apollo.localization.MeasureState fusion_status = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::localization::MeasureState_IsValid(value)) { set_fusion_status(static_cast< ::apollo::localization::MeasureState >(value)); } else { mutable_unknown_fields()->AddVarint(2, value); } } else { goto handle_unusual; } break; } // optional .apollo.localization.MeasureState gnss_status = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::localization::MeasureState_IsValid(value)) { set_gnss_status(static_cast< ::apollo::localization::MeasureState >(value)); } else { mutable_unknown_fields()->AddVarint(3, value); } } else { goto handle_unusual; } break; } // optional .apollo.localization.MeasureState lidar_status = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::localization::MeasureState_IsValid(value)) { set_lidar_status(static_cast< ::apollo::localization::MeasureState >(value)); } else { mutable_unknown_fields()->AddVarint(4, value); } } else { goto handle_unusual; } break; } // optional double measurement_time = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(41u)) { set_has_measurement_time(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &measurement_time_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.localization.LocalizationStatus) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.localization.LocalizationStatus) return false; #undef DO_ } void LocalizationStatus::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.localization.LocalizationStatus) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->header_, output); } // optional .apollo.localization.MeasureState fusion_status = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 2, this->fusion_status(), output); } // optional .apollo.localization.MeasureState gnss_status = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 3, this->gnss_status(), output); } // optional .apollo.localization.MeasureState lidar_status = 4; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 4, this->lidar_status(), output); } // optional double measurement_time = 5; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->measurement_time(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.localization.LocalizationStatus) } ::google::protobuf::uint8* LocalizationStatus::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.localization.LocalizationStatus) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *this->header_, deterministic, target); } // optional .apollo.localization.MeasureState fusion_status = 2; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 2, this->fusion_status(), target); } // optional .apollo.localization.MeasureState gnss_status = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 3, this->gnss_status(), target); } // optional .apollo.localization.MeasureState lidar_status = 4; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 4, this->lidar_status(), target); } // optional double measurement_time = 5; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->measurement_time(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.localization.LocalizationStatus) return target; } size_t LocalizationStatus::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.localization.LocalizationStatus) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } if (_has_bits_[0 / 32] & 31u) { // optional .apollo.common.Header header = 1; if (has_header()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->header_); } // optional .apollo.localization.MeasureState fusion_status = 2; if (has_fusion_status()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->fusion_status()); } // optional .apollo.localization.MeasureState gnss_status = 3; if (has_gnss_status()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->gnss_status()); } // optional double measurement_time = 5; if (has_measurement_time()) { total_size += 1 + 8; } // optional .apollo.localization.MeasureState lidar_status = 4; if (has_lidar_status()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->lidar_status()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void LocalizationStatus::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.localization.LocalizationStatus) GOOGLE_DCHECK_NE(&from, this); const LocalizationStatus* source = ::google::protobuf::internal::DynamicCastToGenerated<const LocalizationStatus>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.localization.LocalizationStatus) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.localization.LocalizationStatus) MergeFrom(*source); } } void LocalizationStatus::MergeFrom(const LocalizationStatus& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.localization.LocalizationStatus) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 31u) { if (cached_has_bits & 0x00000001u) { mutable_header()->::apollo::common::Header::MergeFrom(from.header()); } if (cached_has_bits & 0x00000002u) { fusion_status_ = from.fusion_status_; } if (cached_has_bits & 0x00000004u) { gnss_status_ = from.gnss_status_; } if (cached_has_bits & 0x00000008u) { measurement_time_ = from.measurement_time_; } if (cached_has_bits & 0x00000010u) { lidar_status_ = from.lidar_status_; } _has_bits_[0] |= cached_has_bits; } } void LocalizationStatus::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.localization.LocalizationStatus) if (&from == this) return; Clear(); MergeFrom(from); } void LocalizationStatus::CopyFrom(const LocalizationStatus& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.localization.LocalizationStatus) if (&from == this) return; Clear(); MergeFrom(from); } bool LocalizationStatus::IsInitialized() const { return true; } void LocalizationStatus::Swap(LocalizationStatus* other) { if (other == this) return; InternalSwap(other); } void LocalizationStatus::InternalSwap(LocalizationStatus* other) { std::swap(header_, other->header_); std::swap(fusion_status_, other->fusion_status_); std::swap(gnss_status_, other->gnss_status_); std::swap(measurement_time_, other->measurement_time_); std::swap(lidar_status_, other->lidar_status_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata LocalizationStatus::GetMetadata() const { protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2flocalization_2fproto_2flocalization_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // LocalizationStatus // optional .apollo.common.Header header = 1; bool LocalizationStatus::has_header() const { return (_has_bits_[0] & 0x00000001u) != 0; } void LocalizationStatus::set_has_header() { _has_bits_[0] |= 0x00000001u; } void LocalizationStatus::clear_has_header() { _has_bits_[0] &= ~0x00000001u; } void LocalizationStatus::clear_header() { if (header_ != NULL) header_->::apollo::common::Header::Clear(); clear_has_header(); } const ::apollo::common::Header& LocalizationStatus::header() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationStatus.header) return header_ != NULL ? *header_ : *::apollo::common::Header::internal_default_instance(); } ::apollo::common::Header* LocalizationStatus::mutable_header() { set_has_header(); if (header_ == NULL) { header_ = new ::apollo::common::Header; } // @@protoc_insertion_point(field_mutable:apollo.localization.LocalizationStatus.header) return header_; } ::apollo::common::Header* LocalizationStatus::release_header() { // @@protoc_insertion_point(field_release:apollo.localization.LocalizationStatus.header) clear_has_header(); ::apollo::common::Header* temp = header_; header_ = NULL; return temp; } void LocalizationStatus::set_allocated_header(::apollo::common::Header* header) { delete header_; header_ = header; if (header) { set_has_header(); } else { clear_has_header(); } // @@protoc_insertion_point(field_set_allocated:apollo.localization.LocalizationStatus.header) } // optional .apollo.localization.MeasureState fusion_status = 2; bool LocalizationStatus::has_fusion_status() const { return (_has_bits_[0] & 0x00000002u) != 0; } void LocalizationStatus::set_has_fusion_status() { _has_bits_[0] |= 0x00000002u; } void LocalizationStatus::clear_has_fusion_status() { _has_bits_[0] &= ~0x00000002u; } void LocalizationStatus::clear_fusion_status() { fusion_status_ = 0; clear_has_fusion_status(); } ::apollo::localization::MeasureState LocalizationStatus::fusion_status() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationStatus.fusion_status) return static_cast< ::apollo::localization::MeasureState >(fusion_status_); } void LocalizationStatus::set_fusion_status(::apollo::localization::MeasureState value) { assert(::apollo::localization::MeasureState_IsValid(value)); set_has_fusion_status(); fusion_status_ = value; // @@protoc_insertion_point(field_set:apollo.localization.LocalizationStatus.fusion_status) } // optional .apollo.localization.MeasureState gnss_status = 3; bool LocalizationStatus::has_gnss_status() const { return (_has_bits_[0] & 0x00000004u) != 0; } void LocalizationStatus::set_has_gnss_status() { _has_bits_[0] |= 0x00000004u; } void LocalizationStatus::clear_has_gnss_status() { _has_bits_[0] &= ~0x00000004u; } void LocalizationStatus::clear_gnss_status() { gnss_status_ = 0; clear_has_gnss_status(); } ::apollo::localization::MeasureState LocalizationStatus::gnss_status() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationStatus.gnss_status) return static_cast< ::apollo::localization::MeasureState >(gnss_status_); } void LocalizationStatus::set_gnss_status(::apollo::localization::MeasureState value) { assert(::apollo::localization::MeasureState_IsValid(value)); set_has_gnss_status(); gnss_status_ = value; // @@protoc_insertion_point(field_set:apollo.localization.LocalizationStatus.gnss_status) } // optional .apollo.localization.MeasureState lidar_status = 4; bool LocalizationStatus::has_lidar_status() const { return (_has_bits_[0] & 0x00000010u) != 0; } void LocalizationStatus::set_has_lidar_status() { _has_bits_[0] |= 0x00000010u; } void LocalizationStatus::clear_has_lidar_status() { _has_bits_[0] &= ~0x00000010u; } void LocalizationStatus::clear_lidar_status() { lidar_status_ = 0; clear_has_lidar_status(); } ::apollo::localization::MeasureState LocalizationStatus::lidar_status() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationStatus.lidar_status) return static_cast< ::apollo::localization::MeasureState >(lidar_status_); } void LocalizationStatus::set_lidar_status(::apollo::localization::MeasureState value) { assert(::apollo::localization::MeasureState_IsValid(value)); set_has_lidar_status(); lidar_status_ = value; // @@protoc_insertion_point(field_set:apollo.localization.LocalizationStatus.lidar_status) } // optional double measurement_time = 5; bool LocalizationStatus::has_measurement_time() const { return (_has_bits_[0] & 0x00000008u) != 0; } void LocalizationStatus::set_has_measurement_time() { _has_bits_[0] |= 0x00000008u; } void LocalizationStatus::clear_has_measurement_time() { _has_bits_[0] &= ~0x00000008u; } void LocalizationStatus::clear_measurement_time() { measurement_time_ = 0; clear_has_measurement_time(); } double LocalizationStatus::measurement_time() const { // @@protoc_insertion_point(field_get:apollo.localization.LocalizationStatus.measurement_time) return measurement_time_; } void LocalizationStatus::set_measurement_time(double value) { set_has_measurement_time(); measurement_time_ = value; // @@protoc_insertion_point(field_set:apollo.localization.LocalizationStatus.measurement_time) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace localization } // namespace apollo // @@protoc_insertion_point(global_scope)
38.275376
130
0.733381
Kurinkitos
668c6105db6299be100652f110badf0c1fe5f560
50,411
cpp
C++
server/Server/Obj/Obj_Human_Attributes.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
3
2018-06-19T21:37:38.000Z
2021-07-31T21:51:40.000Z
server/Server/Obj/Obj_Human_Attributes.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
null
null
null
server/Server/Obj/Obj_Human_Attributes.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
13
2015-01-30T17:45:06.000Z
2022-01-06T02:29:34.000Z
#include "stdafx.h" /////////////////////////////////////////////////////////////////////////////// // 文件名:Obj_Human_Attributes.cpp // 功能说明:角色层属性 // // 修改记录: // // // /////////////////////////////////////////////////////////////////////////////// #include "Type.h" #include "GameDefine.h" #include "GameDefine2.h" #include "GameDefine_Attr.h" #include "Obj_Human.h" #include "LogicManager.h" #include "GameTable.h" #include "Config.h" using namespace Combat_Module::Skill_Module; using namespace MenPai_Module; //////////////////////////////////////////////////////////////////////////////// //角色属性部分 //Strike point INT Obj_Human::GetMaxStrikePoint(VOID) { if(TRUE==GetMaxStrikePointDirtyFlag()) { INT nValue=GetBaseMaxStrikePoint()+GetMaxStrikePointRefix(); nValue>MAX_STRIKE_POINT?nValue=MAX_STRIKE_POINT:NULL; SetIntAttr(CharIntAttrs_T::ATTR_MAX_STRIKE_POINT, nValue); ClearMaxStrikePointDirtyFlag(); if(GetStrikePoint()>nValue) SetStrikePoint(nValue); } return GetIntAttr(CharIntAttrs_T::ATTR_MAX_STRIKE_POINT); } INT Obj_Human::GetMaxRage(VOID) { if(TRUE==GetMaxRageDirtyFlag()) { INT nValue=GetBaseMaxRage()+GetMaxRageRefix(); nValue>MAX_RAGE?nValue=MAX_RAGE:NULL; SetIntAttr(CharIntAttrs_T::ATTR_MAX_RAGE, nValue); ClearMaxRageDirtyFlag(); if(GetRage()>nValue) SetRage(nValue); } return GetIntAttr(CharIntAttrs_T::ATTR_MAX_RAGE); } //Attr1: Str INT Obj_Human::GetStr(VOID) { if(TRUE==GetStrDirtyFlag()) { INT nItemValue = 0; _ITEM_EFFECT* pIE = ItemEffect(IATTRIBUTE_STR) ; Assert( pIE ) ; if( pIE->IsActive() ) { nItemValue= pIE->m_Attr.m_Value ; } INT nValue=GetBaseStr()+GetStrRefix()+nItemValue; SetIntAttr(CharIntAttrs_T::ATTR_STR, nValue); ClearStrDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_STR); } INT Obj_Human::GetBaseStr(VOID) { return m_DB.GetDBAttrLvl1(CATTR_LEVEL1_STR); } VOID Obj_Human::SetBaseStr(INT const nValue) { m_DB.SetDBAttrLvl1(CATTR_LEVEL1_STR, nValue); MarkStrDirtyFlag(); MarkAttackPhysicsDirtyFlag(); } //Attr1: Spr INT Obj_Human::GetSpr(VOID) { if(TRUE==GetSprDirtyFlag()) { INT nItemValue = 0; _ITEM_EFFECT* pIE = ItemEffect(IATTRIBUTE_SPR) ; Assert( pIE ) ; if( pIE->IsActive() ) { nItemValue= pIE->m_Attr.m_Value ; } INT nValue=GetBaseSpr()+GetSprRefix()+nItemValue; SetIntAttr(CharIntAttrs_T::ATTR_SPR, nValue); ClearSprDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_SPR); } INT Obj_Human::GetBaseSpr(VOID) { return m_DB.GetDBAttrLvl1(CATTR_LEVEL1_SPR); } VOID Obj_Human::SetBaseSpr(INT const nValue) { m_DB.SetDBAttrLvl1(CATTR_LEVEL1_SPR, nValue); MarkSprDirtyFlag(); MarkAttackMagicDirtyFlag(); } //Attr1: Con INT Obj_Human::GetCon(VOID) { if(TRUE==GetConDirtyFlag()) { INT nItemValue = 0; _ITEM_EFFECT* pIE = ItemEffect(IATTRIBUTE_CON) ; Assert( pIE ) ; if( pIE->IsActive() ) { nItemValue= pIE->m_Attr.m_Value ; } INT nValue=GetBaseCon()+GetConRefix()+nItemValue; SetIntAttr(CharIntAttrs_T::ATTR_CON, nValue); ClearConDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_CON); } INT Obj_Human::GetBaseCon(VOID) { return m_DB.GetDBAttrLvl1(CATTR_LEVEL1_CON); } VOID Obj_Human::SetBaseCon(INT const nValue) { m_DB.SetDBAttrLvl1(CATTR_LEVEL1_CON, nValue); MarkConDirtyFlag(); MarkMaxHPDirtyFlag(); MarkHPRegenerateDirtyFlag(); MarkDefencePhysicsDirtyFlag(); } //Attr1: Int INT Obj_Human::GetInt(VOID) { if(TRUE==GetIntDirtyFlag()) { INT nItemValue = 0; _ITEM_EFFECT* pIE = ItemEffect(IATTRIBUTE_INT) ; Assert( pIE ) ; if( pIE->IsActive() ) { nItemValue= pIE->m_Attr.m_Value ; } INT nValue=GetBaseInt()+GetIntRefix()+nItemValue; SetIntAttr(CharIntAttrs_T::ATTR_INT, nValue); ClearIntDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_INT); } INT Obj_Human::GetBaseInt(VOID) { return m_DB.GetDBAttrLvl1(CATTR_LEVEL1_INT); } VOID Obj_Human::SetBaseInt(INT const nValue) { m_DB.SetDBAttrLvl1(CATTR_LEVEL1_INT, nValue); MarkIntDirtyFlag(); MarkMaxMPDirtyFlag(); MarkMPRegenerateDirtyFlag(); MarkDefenceMagicDirtyFlag(); } //Attr1: Dex INT Obj_Human::GetDex(VOID) { if(TRUE==GetDexDirtyFlag()) { INT nItemValue = 0; _ITEM_EFFECT* pIE = ItemEffect(IATTRIBUTE_DEX) ; Assert( pIE ) ; if( pIE->IsActive() ) { nItemValue= pIE->m_Attr.m_Value ; } INT nValue=GetBaseDex()+GetDexRefix()+nItemValue; SetIntAttr(CharIntAttrs_T::ATTR_DEX, nValue); ClearDexDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_DEX); } INT Obj_Human::GetBaseDex(VOID) { return m_DB.GetDBAttrLvl1(CATTR_LEVEL1_DEX); } VOID Obj_Human::SetBaseDex(INT const nValue) { m_DB.SetDBAttrLvl1(CATTR_LEVEL1_DEX, nValue); MarkDexDirtyFlag(); MarkHitDirtyFlag(); MarkMissDirtyFlag(); MarkCriticalDirtyFlag(); } //HP INT Obj_Human::GetMaxHP(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetMaxHPDirtyFlag()) { INT nBaseAttr=GetBaseMaxHP(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_POINT_MAXHP); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //装备对属性的百分比影响 pIE = ItemEffect(IATTRIBUTE_RATE_MAXHP); Assert( pIE ) ; if( pIE->IsActive() ) { nItemRateRefix = Float2Int((nBaseAttr*(pIE->m_Attr.m_Value))/100.0f); } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetMaxHPRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_MAX_HP, nValue); ClearMaxHPDirtyFlag(); if(GetHP()>nValue) SetHP(nValue); } return GetIntAttr(CharIntAttrs_T::ATTR_MAX_HP); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseMaxHP(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseMaxHP]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitMaxHP(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetMaxHPConRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetMaxHPLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetCon()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseMaxHP(INT const nHp) { // forbiden modify this attribute } INT Obj_Human::GetHPRegenerate(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetMaxMPDirtyFlag()) { INT nBaseAttr=GetBaseHPRegenerate(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_RESTORE_HP); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetHPRegenerateRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix; SetIntAttr(CharIntAttrs_T::ATTR_HP_REGENERATE, nValue); ClearHPRegenerateDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_HP_REGENERATE); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseHPRegenerate(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseHPRegenerate]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitHPRegenerate(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetHPRegenerateConRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetHPRegenerateLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetCon()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseHPRegenerate(INT const nValue) {// forbiden modify this attribute } //MP INT Obj_Human::GetMaxMP(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetMaxMPDirtyFlag()) { INT nBaseAttr=GetBaseMaxMP(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_POINT_MAXMP); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //装备对属性的百分比影响 pIE = ItemEffect(IATTRIBUTE_RATE_MAXMP); Assert( pIE ) ; if( pIE->IsActive() ) { nItemRateRefix = Float2Int((nBaseAttr*(pIE->m_Attr.m_Value))/100.0f); } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetMaxMPRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_MAX_MP, nValue); ClearMaxMPDirtyFlag(); if(GetMP()>nValue) SetMP(nValue); } return GetIntAttr(CharIntAttrs_T::ATTR_MAX_MP); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseMaxMP(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseMaxMP]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitMaxMP(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetMaxMPIntRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetMaxMPLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetInt()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseMaxMp(INT const nMp) {// forbiden modify this attribute } INT Obj_Human::GetMPRegenerate(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetMPRegenerateDirtyFlag()) { INT nBaseAttr=GetBaseMPRegenerate(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_RESTORE_MP); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetMPRegenerateRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_MP_REGENERATE, nValue); ClearMPRegenerateDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_MP_REGENERATE); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseMPRegenerate(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseMPRegenerate]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitMPRegenerate(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetMPRegenerateIntRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetMPRegenerateLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetInt()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseMPRegenerate(INT const nValue) {// forbiden modify this attribute } const _CAMP_DATA *Obj_Human::GetBaseCampData(VOID)const { return m_DB.GetDBCampData(); } VOID Obj_Human::SetBaseCampData(const _CAMP_DATA *pCampData) { m_DB.SetDBCampData(pCampData); } //CampID INT Obj_Human::GetCampID(VOID) { if(TRUE==GetCampIDDirtyFlag()) { INT nValue=GetCampIDRefix(); if(INVALID_ID==nValue) { nValue=GetBaseCampID(); } SetIntAttr(CharIntAttrs_T::ATTR_CAMP, nValue); ClearCampIDDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_CAMP); } INT Obj_Human::GetBaseCampID(VOID) const { HumanDB * pDB=(HumanDB *)&m_DB; return pDB->GetDBCampData()->m_nCampID; } VOID Obj_Human::SetBaseCampID(INT const nID) { _CAMP_DATA stCampData = *(m_DB.GetDBCampData()); stCampData.m_nCampID = nID; m_DB.SetDBCampData(&stCampData); MarkCampIDDirtyFlag(); } //modelID INT Obj_Human::GetBaseModelID(VOID) const { return INVALID_ID; //Need modify } VOID Obj_Human::SetBaseModelID(INT const nID) { // forbiden modify this attribute } // Alive flag, wraped in ObjCharacter // In Combat flag, wraped in ObjCharacter // Can move flag, wraped in ObjCharacter // Can Action flag, wraped in ObjCharacter // Unbreakable flag, wraped in ObjCharacter BOOL Obj_Human::IsUnbreakable(VOID) { return (this->Obj_Character::IsUnbreakable())||IsGod()||IsHaveChangeSceneFlag(); } // Attr2: Move Speed, wraped in ObjCharacter FLOAT Obj_Human::GetMoveSpeed(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if( __GetTeamFollowFlag() ) { if ( GetTeamInfo()->IsLeader()==FALSE ) { return __GetTeamFollowSpeed(); } } if(TRUE==GetMoveSpeedDirtyFlag()) { INT nBaseAttr=GetBaseMoveSpeed(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_SPEED_RATE); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetMoveSpeedRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_MOVE_SPEED, nValue); ClearMoveSpeedDirtyFlag(); } FLOAT fMoveSpeed = GetIntAttr(CharIntAttrs_T::ATTR_MOVE_SPEED) / 10.f; //LM修改 ENUM_MOVE_MODE eMoveMode = GetMoveMode(); if(eMoveMode == MOVE_MODE_HOBBLE) {//变成基础速度的50% fMoveSpeed = fMoveSpeed*0.5f; } else if(eMoveMode == MOVE_MODE_RUN) {//变成基础速度的150% fMoveSpeed = fMoveSpeed*1.5f; } else if (eMoveMode == MOVE_MODE_SPRINT) {//变成基础速度的500% fMoveSpeed = fMoveSpeed*5.0f; } return fMoveSpeed; __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseMoveSpeed(VOID) { return g_Config.m_ConfigInfo.m_DefaultMoveSpeed; } VOID Obj_Human::SetBaseMoveSpeed(INT const nValue) {// forbiden modify this attribute } // Attr2: Attack Speed INT Obj_Human::GetAttackSpeed(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetAttackSpeedDirtyFlag()) { INT nBaseAttr=GetBaseAttackSpeed(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_ATTACK_SPEED); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetAttackSpeedRefix(); nValue = nBaseAttr-nImpactAndSkillRefix-nItemPointRefix; nValue<0?nValue=0:NULL; if(400<nValue) { nValue = 400; } if(25>=nValue) { nValue = 25; } SetIntAttr(CharIntAttrs_T::ATTR_ATTACK_SPEED, nValue); ClearAttackSpeedDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_ATTACK_SPEED); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseAttackSpeed(VOID) { //return g_Config.m_ConfigInfo.m_DefaultAttackSpeed; return BASE_ATTACK_SPEED; //use 100 as base cooldown and other actiontime refix; } VOID Obj_Human::SetBaseAttackSpeed(INT const nValue) {// forbiden modify this attribute } // Attr2: Miss INT Obj_Human::GetMiss(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetMissDirtyFlag()) { INT nBaseAttr=GetBaseMiss(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nItemBasePointRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备的基础点数影响 pIE = ItemEffect(IATTRIBUTE_BASE_MISS); Assert(pIE); if(pIE->IsActive()) { nItemBasePointRefix= pIE->m_Attr.m_Value; } // passive Skill refix start // ... // passive skill refix end ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_MISS); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetMissRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix+nItemBasePointRefix; SetIntAttr(CharIntAttrs_T::ATTR_MISS, nValue); ClearMissDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_MISS); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseMiss(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseMiss]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitMiss(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetMissDexRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetMissLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetDex()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseMiss(INT const nValue) {// forbiden modify this attribute } // Attr2 Hit INT Obj_Human::GetHit(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetHitDirtyFlag()) { INT nBaseAttr=GetBaseHit(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_HIT); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetHitRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_HIT, nValue); ClearHitDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_HIT); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseHit(VOID) { //门派 INT nMenPaiID = GetMenPai(); MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseHit]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitHit(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetHitDexRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetHitLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetDex()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseHit(INT const nValue) {// forbiden modify this attribute } // Attr2 Critical INT Obj_Human::GetCritical(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetCriticalDirtyFlag()) { INT nBaseAttr=GetBaseCritical(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_2ATTACK_RATE); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetCriticalRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_CRITICAL, nValue); ClearCriticalDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_CRITICAL); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseCritical(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseCritical]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitCritical(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetCriticalDexRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetCriticalLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetDex()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseCritical(INT const nValue) {// forbiden modify this attribute } // Attr2: Attack and Defence power physics INT Obj_Human::GetAttackPhysics(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetAttackPhysicsDirtyFlag()) { INT nBaseAttr=GetBaseAttackPhysics(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nItemBasePointRefix=0; INT nItemBaseRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备的基础点数影响 pIE = ItemEffect(IATTRIBUTE_BASE_ATTACK_P); Assert(pIE); if(pIE->IsActive()) { nItemBasePointRefix= pIE->m_Attr.m_Value; } // passive Skill refix start // ... // passive skill refix end ////////////////////////////////////////////////////////////////////// //装备的基础百分率影响 pIE = ItemEffect(IATTRIBUTE_RATE_ATTACK_EP); Assert(pIE); if(pIE->IsActive()) { nItemBaseRateRefix= Float2Int((nItemBasePointRefix*(pIE->m_Attr.m_Value))/100.0f); } ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_ATTACK_P); Assert(pIE); if(pIE->IsActive()) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //装备对属性的百分比影响 pIE = ItemEffect(IATTRIBUTE_RATE_ATTACK_P); Assert(pIE) ; if(pIE->IsActive()) { nItemRateRefix = Float2Int((nBaseAttr*(pIE->m_Attr.m_Value))/100.0f); } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetAttackPhysicsRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix+nItemBasePointRefix+nItemBaseRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_ATTACK_PHY, nValue); ClearAttackPhysicsDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_ATTACK_PHY); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseAttackPhysics(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseAttackPhysics]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitAttackPhysics(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetAttackPhysicsStrRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetAttackPhysicsLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetStr()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseAttackPhysics(INT const nValue) {// forbiden modify this attribute } INT Obj_Human::GetDefencePhysics(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetDefencePhysicsDirtyFlag()) { INT nBaseAttr=GetBaseDefencePhysics(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nItemBasePointRefix=0; INT nItemBaseRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备的基础点数影响 pIE = ItemEffect(IATTRIBUTE_BASE_DEFENCE_P); Assert(pIE); if(pIE->IsActive()) { nItemBasePointRefix= pIE->m_Attr.m_Value; } // passive Skill refix start // ... // passive skill refix end ////////////////////////////////////////////////////////////////////// //装备的基础百分率影响 pIE = ItemEffect(IATTRIBUTE_RATE_DEFENCE_EP); Assert(pIE); if(pIE->IsActive()) { nItemBaseRateRefix= Float2Int((nItemBasePointRefix*(pIE->m_Attr.m_Value))/100.0f); } ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_DEFENCE_P); Assert(pIE); if(pIE->IsActive()) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //装备对属性的百分比影响 pIE = ItemEffect(IATTRIBUTE_RATE_DEFENCE_P); Assert(pIE); if(pIE->IsActive()) { nItemRateRefix = Float2Int((nBaseAttr*(pIE->m_Attr.m_Value))/100.0f); } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetDefencePhysicsRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix+nItemBasePointRefix+nItemBaseRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_DEFENCE_PHY, nValue); ClearDefencePhysicsDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_DEFENCE_PHY); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseDefencePhysics(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseDefencePhysics]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitDefencePhysics(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetDefencePhysicsConRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetDefencePhysicsLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetCon()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseDefencePhysics(INT const nValue) {// forbiden modify this attribute } // Attr2: Attack and Defence power of Magic INT Obj_Human::GetAttackMagic(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetAttackMagicDirtyFlag()) { INT nBaseAttr=GetBaseAttackMagic(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nItemBasePointRefix=0; INT nItemBaseRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备的基础点数影响 pIE = ItemEffect(IATTRIBUTE_BASE_ATTACK_M); Assert(pIE); if(pIE->IsActive()) { nItemBasePointRefix= pIE->m_Attr.m_Value; } // passive Skill refix start // ... // passive skill refix end ////////////////////////////////////////////////////////////////////// //装备的基础百分率影响 pIE = ItemEffect(IATTRIBUTE_RATE_ATTACK_EM); Assert(pIE); if(pIE->IsActive()) { nItemBaseRateRefix= Float2Int((nItemBasePointRefix*(pIE->m_Attr.m_Value))/1000.0f); } ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_ATTACK_M); Assert(pIE); if(pIE->IsActive()) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //装备对属性的百分比影响 pIE = ItemEffect(IATTRIBUTE_RATE_ATTACK_M); Assert(pIE) ; if(pIE->IsActive()) { nItemRateRefix = Float2Int((nBaseAttr*(pIE->m_Attr.m_Value))/1000.0f); } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetAttackMagicRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix+nItemBasePointRefix+nItemBaseRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_ATTACK_MAGIC, nValue); ClearAttackMagicDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_ATTACK_MAGIC); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseAttackMagic(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseAttackMagic]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitAttackMagic(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetAttackMagicSprRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetAttackMagicLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetSpr()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseAttackMagic(INT const nValue) {// forbiden modify this attribute } INT Obj_Human::GetDefenceMagic(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetDefenceMagicDirtyFlag()) { INT nBaseAttr=GetBaseDefenceMagic(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nItemBasePointRefix=0; INT nItemBaseRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备的基础点数影响 pIE = ItemEffect(IATTRIBUTE_BASE_DEFENCE_M); Assert(pIE); if(pIE->IsActive()) { nItemBasePointRefix= pIE->m_Attr.m_Value; } // passive Skill refix start // ... // passive skill refix end ////////////////////////////////////////////////////////////////////// //装备的基础百分率影响 pIE = ItemEffect(IATTRIBUTE_RATE_DEFENCE_EM); Assert(pIE); if(pIE->IsActive()) { nItemBaseRateRefix= Float2Int((nItemBasePointRefix*(pIE->m_Attr.m_Value))/1000.0f); } ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_DEFENCE_M); Assert(pIE); if(pIE->IsActive()) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //装备对属性的百分比影响 pIE = ItemEffect(IATTRIBUTE_RATE_DEFENCE_M); Assert(pIE); if(pIE->IsActive()) { nItemRateRefix = Float2Int((nBaseAttr*(pIE->m_Attr.m_Value))/100.0f); } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetDefenceMagicRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix+nItemBasePointRefix+nItemBaseRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_DEFENCE_MAGIC, nValue); ClearDefenceMagicDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_DEFENCE_MAGIC); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseDefenceMagic(VOID) { //门派 INT nMenPaiID = GetMenPai() ; MenPai_T const* pMenPaiLogic = g_MenPaiLogicList.GetLogicById(nMenPaiID); if(NULL == pMenPaiLogic) { AssertEx(FALSE,"[Obj_Human::GetBaseDefenceMagic]: Can't not find MenPai Logic!"); return 0; } //初始属性值 INT nInitAttr = pMenPaiLogic->GetInitDefenceMagic(); //一级属性对该属性的影响系数 INT nAttrLevel1Refix = pMenPaiLogic->GetDefenceMagicIntRefix(); //等级对该属性的影响系数 INT nLevelRefix = pMenPaiLogic->GetDefenceMagicLevelRefix(); //计算基础基础属性 INT nBase = nInitAttr+GetInt()*nAttrLevel1Refix+GetLevel()*nLevelRefix; nBase=Float2Int((nBase)/100.0f); //表里面的数值都是乘了100的,计算后应该修正回去 0<=nBase?NULL:nBase=0; return nBase; } VOID Obj_Human::SetBaseDefenceMagic(INT const nValue) {// forbiden modify this attribute } // Attr2: Attack and Defence power of Cold INT Obj_Human::GetAttackCold(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetAttackColdDirtyFlag()) { INT nBaseAttr=GetBaseAttackCold(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_COLD_ATTACK); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetAttackColdRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_ATTACK_COLD, nValue); ClearAttackColdDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_ATTACK_COLD); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseAttackCold(VOID) { return 0; } VOID Obj_Human::SetBaseAttackCold(INT const nValue) {// forbiden modify this attribute } INT Obj_Human::GetDefenceCold(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetResistColdDirtyFlag()) { INT nBaseAttr=GetBaseDefenceCold(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_COLD_RESIST); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetDefenceColdRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_RESIST_COLD, nValue); ClearResistColdDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_RESIST_COLD); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseDefenceCold(VOID) { return 0; } VOID Obj_Human::SetBaseDefenceCold(INT const nValue) {// forbiden modify this attribute } // Attr2: Attack and Defence power of Fire INT Obj_Human::GetAttackFire(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetAttackFireDirtyFlag()) { INT nBaseAttr=GetBaseAttackFire(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_FIRE_ATTACK); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetAttackFireRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_ATTACK_FIRE, nValue); ClearAttackFireDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_ATTACK_FIRE); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseAttackFire(VOID) { return 0; } VOID Obj_Human::SetBaseAttackFire(INT const nValue) {// forbiden modify this attribute } INT Obj_Human::GetDefenceFire(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetResistFireDirtyFlag()) { INT nBaseAttr=GetBaseDefenceFire(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_FIRE_RESIST); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetDefenceFireRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_RESIST_FIRE, nValue); ClearResistFireDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_RESIST_FIRE); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseDefenceFire(VOID) { return 0; } VOID Obj_Human::SetBaseDefenceFire(INT const nValue) {// forbiden modify this attribute } // Attr2: Attack and Defence power of Light INT Obj_Human::GetAttackLight(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetAttackLightDirtyFlag()) { INT nBaseAttr=GetBaseAttackLight(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_LIGHT_ATTACK); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetAttackLightRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_ATTACK_LIGHT, nValue); ClearAttackLightDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_ATTACK_LIGHT); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseAttackLight(VOID) { return 0; } VOID Obj_Human::SetBaseAttackLight(INT const nValue) {// forbiden modify this attribute } INT Obj_Human::GetDefenceLight(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetResistLightDirtyFlag()) { INT nBaseAttr=GetBaseDefenceLight(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_LIGHT_RESIST); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetDefenceLightRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_RESIST_LIGHT, nValue); ClearResistLightDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_RESIST_LIGHT); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseDefenceLight(VOID) { return 0; } VOID Obj_Human::SetBaseDefenceLight(INT const nValue) {// forbiden modify this attribute } // Attr2: Attack and Defence power of Poison INT Obj_Human::GetAttackPoison(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetAttackPoisonDirtyFlag()) { INT nBaseAttr=GetBaseAttackPoison(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_POISON_ATTACK); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetAttackPoisonRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_ATTACK_POISON, nValue); ClearAttackPoisonDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_ATTACK_POISON); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseAttackPoison(VOID) { return 0; } VOID Obj_Human::SetBaseAttackPoison(INT const nValue) {// forbiden modify this attribute } INT Obj_Human::GetDefencePoison(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetResistPoisonDirtyFlag()) { INT nBaseAttr=GetBaseDefencePoison(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_POISON_RESIST); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetDefencePoisonRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_RESIST_POISON, nValue); ClearResistPoisonDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_RESIST_POISON); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseDefencePoison(VOID) { return 0; } VOID Obj_Human::SetBaseDefencePoison(INT const nValue) {// forbiden modify this attribute } // Attr2 Reduce Slower Duration INT Obj_Human::GetReduceSlowerDuration(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetReduceSlowerDurationDirtyFlag()) { INT nBaseAttr=0; INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_COLD_TIME); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetReduceSlowerDurationRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_REDUCE_SLOWER_DURATION, nValue); ClearReduceSlowerDurationDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_REDUCE_SLOWER_DURATION); __LEAVE_FUNCTION return 0; } // Attr2 Reduce Weaken Duration INT Obj_Human::GetReduceWeakenDuration(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetReduceWeakenDurationDirtyFlag()) { INT nBaseAttr=0; INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_FIRE_TIME); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetReduceWeakenDurationRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_REDUCE_WEAKEN_DURATION, nValue); ClearReduceWeakenDurationDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_REDUCE_WEAKEN_DURATION); __LEAVE_FUNCTION return 0; } // Attr2 Reduce Faint Duration INT Obj_Human::GetReduceFaintDuration(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetReduceFaintDurationDirtyFlag()) { INT nBaseAttr=0; INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_LIGHT_TIME); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetReduceFaintDurationRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_REDUCE_FAINT_DURATION, nValue); ClearReduceFaintDurationDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_REDUCE_FAINT_DURATION); __LEAVE_FUNCTION return 0; } // Attr2 Reduce Poisoned Duration INT Obj_Human::GetReducePoisonedDuration(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetReducePoisonedDurationDirtyFlag()) { INT nBaseAttr=0; INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //装备对属性的点数影响 pIE = ItemEffect(IATTRIBUTE_POISON_TIME); Assert( pIE ); if( pIE->IsActive() ) { nItemPointRefix= pIE->m_Attr.m_Value; } ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetReducePoisonedDurationRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_REDUCE_POISONED_DURATION, nValue); ClearReducePoisonedDurationDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_REDUCE_POISONED_DURATION); __LEAVE_FUNCTION return 0; } // Attr2 VisionRange INT Obj_Human::GetVisionRange(VOID) { __ENTER_FUNCTION _ITEM_EFFECT* pIE=NULL; if(TRUE==GetVisionRangeDirtyFlag()) { INT nBaseAttr=GetBaseVisionRange(); INT nImpactAndSkillRefix=0; INT nItemPointRefix=0; INT nItemRateRefix=0; INT nValue=0; ////////////////////////////////////////////////////////////////////// //技能和效果对属性的影响 nImpactAndSkillRefix=GetVisionRangeRefix(); nValue = nBaseAttr+nImpactAndSkillRefix+nItemPointRefix+nItemRateRefix; SetIntAttr(CharIntAttrs_T::ATTR_VISION_RANGE, nValue); ClearVisionRangeDirtyFlag(); } return GetIntAttr(CharIntAttrs_T::ATTR_VISION_RANGE); __LEAVE_FUNCTION return 0; } INT Obj_Human::GetBaseVisionRange(VOID) { //return g_MonsterAttrExTbl.Get(UINT MonsterType, UINT AttrEx); return BASE_VISION_RANGE; } VOID Obj_Human::SetBaseVisionRange(INT const nValue) {// forbiden modify this attribute }
30.060227
118
0.583345
viticm
668e16ec932688e4ec10b529b7ffc0059c0db6b1
706
hpp
C++
include/SorghumFactory/LeafSegment.hpp
edisonlee0212/RayMLVQ
d040a068691799bdf82e7a0b394309efabc570d2
[ "BSD-3-Clause" ]
null
null
null
include/SorghumFactory/LeafSegment.hpp
edisonlee0212/RayMLVQ
d040a068691799bdf82e7a0b394309efabc570d2
[ "BSD-3-Clause" ]
null
null
null
include/SorghumFactory/LeafSegment.hpp
edisonlee0212/RayMLVQ
d040a068691799bdf82e7a0b394309efabc570d2
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <sorghum_factory_export.h> using namespace UniEngine; namespace SorghumFactory { class SORGHUM_FACTORY_API LeafSegment { public: glm::vec3 m_position; glm::vec3 m_front; glm::vec3 m_up; glm::quat m_rotation; float m_surfacePush = 0.0f; float m_leafHalfWidth; float m_theta; float m_radius; float m_leftHeightFactor = 1.0f; float m_rightHeightFactor = 1.0f; bool m_isLeaf; LeafSegment(glm::vec3 position, glm::vec3 up, glm::vec3 front, float leafHalfWidth, float theta, bool isLeaf, float surfacePush, float leftHeightFactor = 1.0f, float rightHeightFactor = 1.0f); glm::vec3 GetPoint(float angle); }; } // namespace PlantFactory
28.24
79
0.726629
edisonlee0212
668f60498fa51815bfe41dd43db626a08913ed85
970
cpp
C++
problems/chapter14/miiitomi/floyd_warshall.cpp
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
1
2021-07-07T15:46:58.000Z
2021-07-07T15:46:58.000Z
problems/chapter14/miiitomi/floyd_warshall.cpp
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
5
2021-06-05T14:16:41.000Z
2021-07-10T07:08:28.000Z
problems/chapter14/miiitomi/floyd_warshall.cpp
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; typedef long long ll; const ll INF = (1LL << 60); int main() { int N, M; cin >> N >> M; vector<vector<ll>> dp(N, vector<ll>(N, INF)); for (int e = 0; e < M; e++) { int a, b; ll w; cin >> a >> b >> w; dp[a][b] = w; } for (int v = 0; v < N; v++) dp[v][v] = 0; for (int k = 0; k < N; k++) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]); } } } for (int v = 0; v < N; v++) { if (dp[v][v] < 0) { cout << "Negatibve cycle exists!" << endl; return 0; } } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (j) cout << " "; if (dp[i][j] < INF/2) cout << dp[i][j]; else cout << "INF"; } cout << endl; } }
21.086957
62
0.350515
tokuma09
669330195d1eb88c32b35178800feb914ec6a183
6,765
cpp
C++
pelican/server/test/src/StreamDataBufferTest.cpp
pelican/pelican
834ae2e5d0e58009500286eb7f7891611d02b50c
[ "BSD-3-Clause" ]
3
2015-10-11T07:30:59.000Z
2016-06-03T04:27:40.000Z
pelican/server/test/src/StreamDataBufferTest.cpp
pelican/pelican
834ae2e5d0e58009500286eb7f7891611d02b50c
[ "BSD-3-Clause" ]
null
null
null
pelican/server/test/src/StreamDataBufferTest.cpp
pelican/pelican
834ae2e5d0e58009500286eb7f7891611d02b50c
[ "BSD-3-Clause" ]
2
2016-05-09T09:52:38.000Z
2019-05-17T06:08:24.000Z
#include "server/test/StreamDataBufferTest.h" #include "server/DataManager.h" #include "comms/StreamData.h" #include "server/StreamDataBuffer.h" #include "server/ServiceDataBuffer.h" #include "server/WritableData.h" #include "server/LockedData.h" #include "server/LockableStreamData.h" #include "utility/Config.h" #include <QtCore/QCoreApplication> namespace pelican { CPPUNIT_TEST_SUITE_REGISTRATION( StreamDataBufferTest ); // class StreamDataBufferTest StreamDataBufferTest::StreamDataBufferTest() : CppUnit::TestFixture(), _dataManager(0) { int ac = 0; _app = new QCoreApplication(ac, NULL); } StreamDataBufferTest::~StreamDataBufferTest() { delete _app; } void StreamDataBufferTest::setUp() { Config config; _dataManager = new DataManager(&config); } void StreamDataBufferTest::tearDown() { delete _dataManager; } void StreamDataBufferTest::test_getNext() { { // Use case: // getNext called on an empty buffer // expect to return an invalid LockedData object StreamDataBuffer b("test"); b.setDataManager(_dataManager); LockedData data("test"); b.getNext(data); CPPUNIT_ASSERT( ! data.isValid() ); } { // Use case: // getNext called on an non-empty buffer // expect to return an valid LockedData object StreamDataBuffer b("test"); b.setDataManager(_dataManager); b.getWritable(100); _app->processEvents(); LockedData data("test"); b.getNext(data); CPPUNIT_ASSERT( data.isValid() ); // Use Case: // Make a second call to getNext() whilst data exists but locked // Expect to return an invalid object LockedData data2("test2"); b.getNext(data2); CPPUNIT_ASSERT( ! data2.isValid() ); } } void StreamDataBufferTest::test_getWritable() { QByteArray data1("data1"); { // Use case: // getWritable() called with no service data // Expect a valid object with no associate data. StreamDataBuffer buffer("test"); buffer.setDataManager(_dataManager); WritableData data = buffer.getWritable(data1.size()); CPPUNIT_ASSERT( data.isValid() ); data.write(data1.data(),data1.size()); CPPUNIT_ASSERT( data.isValid() ); CPPUNIT_ASSERT_EQUAL(0, static_cast<LockableStreamData*>(data.data())->associateData().size() ); } // Setup data manager with a service data buffer for remaining test cases ServiceDataBuffer* serveBuffer = new ServiceDataBuffer("test"); QString service1("Service1"); _dataManager->setServiceDataBuffer(service1,serveBuffer); { // Use case: // getWritable() called with service data supported, but no data // expect valid object with no associate data StreamDataBuffer b("test"); b.setDataManager(_dataManager); WritableData data = b.getWritable(data1.size()); CPPUNIT_ASSERT( data.isValid() ); data.write(data1.data(),data1.size()); CPPUNIT_ASSERT( data.isValid() ); CPPUNIT_ASSERT_EQUAL(0, static_cast<LockableStreamData*>(data.data())->associateData().size() ); } // inject some data into the service buffer for remaining tests serveBuffer->getWritable(1); _app->processEvents(); { // Use case: // getWritable() called with service data supported, with data // expect valid object with associate data StreamDataBuffer b("test"); b.setDataManager(_dataManager); WritableData data = b.getWritable(data1.size()); CPPUNIT_ASSERT( data.isValid() ); data.write(data1.data(),data1.size()); CPPUNIT_ASSERT( data.isValid() ); CPPUNIT_ASSERT_EQUAL(1, static_cast<LockableStreamData*>(data.data())->associateData().size() ); } } void StreamDataBufferTest::test_getWritableStreams() { using namespace std; bool verbose = false; if (verbose) cout << endl; // Use case: // Multiple calls to getWritable() simulating filling of a stream buffer. // Expect: unique data pointers to be returned. { size_t dataSize = 8; StreamDataBuffer buffer("test"); buffer.setDataManager(_dataManager); { WritableData dataChunk = buffer.getWritable(dataSize); void* dataPtr = dataChunk.data()->dataChunk()->ptr(); double value = 1; dataChunk.write(&value, 8, 0); if (verbose) cout << "[1] dataPtr = " << dataPtr << endl; } CPPUNIT_ASSERT_EQUAL(1, buffer._serveQueue.size()); { WritableData dataChunk = buffer.getWritable(dataSize); void* dataPtr = dataChunk.data()->dataChunk()->ptr(); double value = 2; dataChunk.write(&value, 8, 0); if (verbose) cout << "[2] dataPtr = " << dataPtr << endl; } CPPUNIT_ASSERT_EQUAL(2, buffer._serveQueue.size()); { WritableData dataChunk = buffer.getWritable(dataSize); void* dataPtr = dataChunk.data()->dataChunk()->ptr(); double value = 3; dataChunk.write(&value, 8, 0); if (verbose) cout << "[3] dataPtr = " << dataPtr << endl; } CPPUNIT_ASSERT_EQUAL(3, buffer._serveQueue.size()); CPPUNIT_ASSERT_EQUAL(0, buffer._emptyQueue.size()); { LockedData data("test"); buffer.getNext(data); static_cast<LockableStreamData*>(data.object())->served() = true; } CPPUNIT_ASSERT_EQUAL(2, buffer._serveQueue.size()); CPPUNIT_ASSERT_EQUAL(1, buffer._emptyQueue.size()); { LockedData data("test"); buffer.getNext(data); static_cast<LockableStreamData*>(data.object())->served() = true; } CPPUNIT_ASSERT_EQUAL(1, buffer._serveQueue.size()); CPPUNIT_ASSERT_EQUAL(2, buffer._emptyQueue.size()); { LockedData data("test"); buffer.getNext(data); static_cast<LockableStreamData*>(data.object())->served() = true; } CPPUNIT_ASSERT_EQUAL(0, buffer._serveQueue.size()); CPPUNIT_ASSERT_EQUAL(3, buffer._emptyQueue.size()); { WritableData dataChunk = buffer.getWritable(dataSize); void* dataPtr = dataChunk.data()->dataChunk()->ptr(); double value = 4; dataChunk.write(&value, 8, 0); if (verbose) cout << "[4] dataPtr = " << dataPtr << endl; } CPPUNIT_ASSERT_EQUAL(1, buffer._serveQueue.size()); CPPUNIT_ASSERT_EQUAL(2, buffer._emptyQueue.size()); } if (verbose) cout << endl; } } // namespace pelican
33.161765
104
0.619069
pelican
6696f91b4ccd2d1e8a8809169df75c6b9cb1fee5
5,599
cpp
C++
src/3DSMax/rendutil.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
1
2018-12-20T19:31:02.000Z
2018-12-20T19:31:02.000Z
src/3DSMax/rendutil.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
src/3DSMax/rendutil.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
//*************************************************************************** // rise3dsmax - [rendutil.cpp] Sample Plugin Renderer for 3D Studio MAX. // // By Christer Janson - Kinetix // // Description: // Utilitiy functions // //*************************************************************************** #include "pch.h" #include "maxincl.h" #include "rise3dsmax.h" #include "rendutil.h" //*************************************************************************** // Since Matrix3::NoScale() was not implemented in Max SDK 1.0, // here's a manual implementation //*************************************************************************** void RemoveScaling(Matrix3 &m) { for (int i=0; i<3; i++) m.SetRow(i,Normalize(m.GetRow(i))); } //*************************************************************************** // Helper function to see if the face is 'facing' our way. //*************************************************************************** int isFacing(Point3& p0, Point3& p1, Point3& p2 , int projType) { if (projType==PROJ_PERSPECTIVE) { FLOAT t0,t1,t2,d; t0 = p1.y*p2.z - p1.z*p2.y; t1 = p2.y*p0.z - p2.z*p0.y; t2 = p0.y*p1.z - p0.z*p1.y; d = -(p0.x*t0 + p1.x*t1 + p2.x*t2); return((d<0.0)?0:1); } else { float d = (p1.x-p0.x)*(p2.y-p0.y) - (p2.x-p0.x)*(p1.y-p0.y); return((d<0.0)?0:1); } } //*************************************************************************** // Calculate the determinant // Thanks to Ruediger Hoefert, Absolute Software //*************************************************************************** static float det2x2( float a, float b, float c, float d ) { float ans; ans = a * d - b * c; return ans; } //*************************************************************************** // // float = det3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3 ) // // calculate the determinant of a 3x3 matrix // in the form // // | a1, b1, c1 | // | a2, b2, c2 | // | a3, b3, c3 | // // Thanks to Ruediger Hoefert, Absolute Software //*************************************************************************** static float det3x3( Point3 a,Point3 b,Point3 c ) { float a1, a2, a3, b1, b2, b3, c1, c2, c3; float ans; a1 = a.x ; a2 = a.y ; a3 = a.z ; b1 = b.x ; b2 = b.y ; b3 = b.z ; c1 = c.x ; c2 = c.y ; c3 = c.z ; ans = a1 * det2x2( b2, b3, c2, c3 ) - b1 * det2x2( a2, a3, c2, c3 ) + c1 * det2x2( a2, a3, b2, b3 ); return ans; } //*************************************************************************** // Given three points in space forming a triangle (p0,p1,p2), // and a fourth point in the plane of that triangle, returns the // barycentric coords of that point relative to the triangle. // Thanks to Ruediger Hoefert, Absolute Software //*************************************************************************** Point3 CalcBaryCoords(Point3 p0, Point3 p1, Point3 p2, Point3 p) { Point3 tpos[3]; Point3 cpos; Point3 bary; tpos[0] = p0; tpos[1] = p1; tpos[2] = p2; cpos = p; /* S.304 Curves+Surfaces for Computer aided design: u + v + w = 1 area(p,b,c) area(a,p,c) area(a,b,p) u = -----------, v = -----------, w = -----------, area(a,b,c) area(a,b,c) area(a,b,c) ax bx cx area(a,b,c) = 0.5 * ay by cy az bz cz */ float area_abc, area_pbc, area_apc, area_abp; area_abc= det3x3(tpos[0],tpos[1],tpos[2]); area_abc=1.0f/area_abc; area_pbc =det3x3(cpos ,tpos[1],tpos[2]); area_apc =det3x3(tpos[0],cpos ,tpos[2]); area_abp =det3x3(tpos[0],tpos[1],cpos ); bary.x = area_pbc *area_abc ; bary.y = area_apc *area_abc ; bary.z = area_abp *area_abc ; return bary; } //*************************************************************************** // This is cut directly from the SDK documentation. // This is how UV coords are generated for face mapped materials //*************************************************************************** static Point3 basic_tva[3] = { Point3(0.0,0.0,0.0),Point3(1.0,0.0,0.0),Point3(1.0,1.0,0.0) }; static Point3 basic_tvb[3] = { Point3(1.0,1.0,0.0),Point3(0.0,1.0,0.0),Point3(0.0,0.0,0.0) }; static int nextpt[3] = {1,2,0}; static int prevpt[3] = {2,0,1}; void MakeFaceUV(Face *f, Point3 *tv) { int na,nhid,i; Point3 *basetv; /* make the invisible edge be 2->0 */ nhid = 2; if (!(f->flags&EDGE_A)) nhid=0; else if (!(f->flags&EDGE_B)) nhid = 1; else if (!(f->flags&EDGE_C)) nhid = 2; na = 2-nhid; basetv = (f->v[prevpt[nhid]]<f->v[nhid]) ? basic_tva : basic_tvb; for (i=0; i<3; i++) { tv[i] = basetv[na]; na = nextpt[na]; } } //*************************************************************************** // Utility function to convert a Color to a BMM_Color_64 structure //*************************************************************************** BMM_Color_64 colTo64(Color c) { BMM_Color_64 bc; // Clamp the colors c.ClampMinMax(); bc.r = (WORD)(c.r * 65535.0); bc.g = (WORD)(c.g * 65535.0); bc.b = (WORD)(c.b * 65535.0); return bc; } //*************************************************************************** // Determine is the node has negative scaling. // This is used for mirrored objects for example. They have a negative scale // so when calculating the normal we take the vertices counter clockwise. // If we don't compensate for this the objects will be 'inverted' //*************************************************************************** BOOL TMNegParity(Matrix3 &m) { return (DotProd(CrossProd(m.GetRow(0),m.GetRow(1)),m.GetRow(2))<0.0)?1:0; }
27.717822
77
0.450795
aravindkrishnaswamy
66997d67e0e4622ef15cd621769a53788238e675
5,308
cpp
C++
engine/Engine.UI.GDI/src/ui/gdi/Canvas.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
null
null
null
engine/Engine.UI.GDI/src/ui/gdi/Canvas.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
10
2018-03-20T21:32:16.000Z
2018-04-23T19:42:59.000Z
engine/Engine.UI.GDI/src/ui/gdi/Canvas.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
null
null
null
#include "ghuigdipch.h" #include "Canvas.h" #include "ui/gdi/Shape.h" namespace Ghurund::UI::GDI { Status Canvas::init(HWND hwnd) { this->hwnd = hwnd; BufferedPaintInit(); pen = new Gdiplus::Pen(Gdiplus::Color()); brush = new Gdiplus::SolidBrush(Gdiplus::Color()); colorMatrixEffect = new Gdiplus::ColorMatrixEffect(); colorMatrix = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f }; matrix = new Gdiplus::Matrix(); return Status::OK; } void Canvas::uninit() { BufferedPaintUnInit(); delete matrix; delete colorMatrixEffect; delete pen; delete brush; } void Canvas::beginPaint() { if (bitmap) { graphics = Gdiplus::Graphics::FromImage(bitmap); } else { hdc = GetDC(hwnd);// BeginPaint(hwnd, &ps); RECT rc; GetClientRect(hwnd, &rc); HDC memdc; hbuff = BeginBufferedPaint(hdc, &rc, BPBF_COMPATIBLEBITMAP, NULL, &memdc); graphics = Gdiplus::Graphics::FromHDC(memdc); } graphics->SetSmoothingMode(Gdiplus::SmoothingMode::SmoothingModeAntiAlias); graphics->SetTextRenderingHint(Gdiplus::TextRenderingHint::TextRenderingHintAntiAlias); } void Canvas::endPaint() { if (!bitmap) { EndBufferedPaint(hbuff, TRUE); ReleaseDC(hwnd, hdc); //EndPaint(hwnd, &ps); } delete graphics; graphics = nullptr; } void Canvas::drawRect(float x, float y, float width, float height, const Color& color, float thickness, IStrokeStyle* strokeStyle) { this->color.SetValue(color); if (strokeStyle) pen->SetDashStyle(((StrokeStyle*)strokeStyle)->get()); pen->SetWidth(thickness); pen->SetColor(this->color); graphics->DrawRectangle(pen, Gdiplus::RectF(x - 0.5f, y - 0.5f, width, height)); } void Canvas::fillRect(float x, float y, float width, float height, const Color& color) { this->color.SetValue(color); brush->SetColor(this->color); graphics->FillRectangle(brush, Gdiplus::RectF(x - 0.5f, y - 0.5f, width, height)); } void Canvas::drawShape(Ghurund::UI::Shape& shape, const Color& color, float thickness) { this->color.SetValue(color); pen->SetWidth(thickness); pen->SetColor(this->color); graphics->DrawPath(pen, ((Ghurund::UI::GDI::Shape&)shape).Path); } void Canvas::drawLine(float x1, float y1, float x2, float y2, const Color& color, float thickness, IStrokeStyle* strokeStyle) { this->color.SetValue(color); if (strokeStyle) pen->SetDashStyle(((StrokeStyle*)strokeStyle)->get()); pen->SetWidth(thickness); pen->SetColor(this->color); path.Reset(); path.AddLine(Gdiplus::PointF(x1 - 0.5f, y1 - 0.5f), Gdiplus::PointF(x2 - 0.5f, y2 - 0.5f)); graphics->DrawPath(pen, &path); } void Canvas::drawImage(Bitmap& bitmapImage, const FloatRect& dst, float alpha) { //D2D1_RECT_F d = { dst.left, dst.top, dst.right, dst.bottom }; //deviceContext->DrawBitmap(bitmapImage, d, alpha); } void Canvas::drawImage(Bitmap& bitmapImage, const FloatRect& dst, const Color& color, float alpha) { /*tintEffect->SetInput(0, bitmapImage); D2D1_MATRIX_5X4_F matrix = D2D1::Matrix5x4F(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, color.A * alpha, color.R, color.G, color.B, 0); tintEffect->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX, matrix); deviceContext->DrawImage(tintEffect.Get(), D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC);*/ } void Canvas::drawImage(Bitmap& bitmapImage, const FloatRect& src, const FloatRect& dst, float alpha) { /*D2D1_RECT_F s = {src.left, src.top, src.right, src.bottom}; D2D1_RECT_F d = { dst.left, dst.top, dst.right, dst.bottom }; deviceContext->DrawBitmap(bitmapImage, d, alpha, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC, s);*/ } void Canvas::drawImage(Bitmap& bitmapImage, const FloatRect& src, const FloatRect& dst, const Color& color, float alpha) { /*tintEffect->SetInput(0, bitmapImage); D2D1_MATRIX_5X4_F matrix = D2D1::Matrix5x4F(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, color.A * alpha, color.R, color.G, color.B, 0); tintEffect->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX, matrix); deviceContext->DrawImage(tintEffect.Get(), D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC);*/ } void Canvas::drawImage(VectorImage& svgDocument) { //deviceContext->DrawSvgDocument(&svgDocument); } /*void Canvas::drawShadow(ID2D1Bitmap1* bitmapImage, float radius, const Color& color) { /*shadowEffect->SetInput(0, bitmapImage); shadowEffect->SetValue(D2D1_SHADOW_PROP_COLOR, D2D_VECTOR_4F(color.R, color.G, color.B, color.A)); shadowEffect->SetValue(D2D1_SHADOW_PROP_BLUR_STANDARD_DEVIATION, radius); deviceContext->DrawImage(shadowEffect.Get(), D2D1_INTERPOLATION_MODE_LINEAR);* / }*/ }
41.795276
144
0.620008
Kartikeyapan598
669c5ad9e7393878c9e4f0a96edfe9207a74bd12
395
cpp
C++
src/Token.cpp
UberDever/go_compiler
4a5087b0b7813d17dcb654f9b68f92fb0226bc82
[ "MIT" ]
null
null
null
src/Token.cpp
UberDever/go_compiler
4a5087b0b7813d17dcb654f9b68f92fb0226bc82
[ "MIT" ]
null
null
null
src/Token.cpp
UberDever/go_compiler
4a5087b0b7813d17dcb654f9b68f92fb0226bc82
[ "MIT" ]
1
2021-12-16T07:42:27.000Z
2021-12-16T07:42:27.000Z
// // Created by uberdever on 30.05.2020. // #include "../include/Token.hpp" #include <utility> string Token::tokenTypes[(int)TOKEN_TYPE::END + 1] = {"Identifier", "Keyword", "Operator", "Literal", "Number"}; Token::Token(const string &_lex, TOKEN_TYPE _type) { lex = _lex; type = _type; } Token::Token(string _lex) { lex = std::move(_lex); type = TOKEN_TYPE::IDENTIFIER; }
19.75
112
0.643038
UberDever
66a59fc5880c168584b0a29129ddbe220fc0eefd
4,368
cpp
C++
shape.cpp
amatveiakin/area-measurement
8228d6e10c93d98ac0d2a94d315bacc67df69b31
[ "MIT" ]
null
null
null
shape.cpp
amatveiakin/area-measurement
8228d6e10c93d98ac0d2a94d315bacc67df69b31
[ "MIT" ]
null
null
null
shape.cpp
amatveiakin/area-measurement
8228d6e10c93d98ac0d2a94d315bacc67df69b31
[ "MIT" ]
1
2021-08-18T05:54:50.000Z
2021-08-18T05:54:50.000Z
#include <QLineF> #include "shape.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Helpers double segmentLenght(QPointF a, QPointF b) { return QLineF(a, b).length(); } void assertPolygonIsClosed(QPolygonF polygon) { ASSERT_RETURN(polygon.isEmpty() || polygon.first() == polygon.last()); } bool testSegmentsCross(QPointF a, QPointF b, QPointF c, QPointF d) { return QLineF(a, b).intersect(QLineF(c, d), 0) == QLineF::BoundedIntersection; } bool isSelfintersectingPolygon(QPolygonF polygon) { assertPolygonIsClosed(polygon); int n = polygon.size() - 1; // cut off last vertex for (int i1 = 0; i1 < n; i1++) { int i2 = (i1 + 1) % n; for (int j1 = 0; j1 < n; j1++) { int j2 = (j1 + 1) % n; if (i1 != j1 && i1 != j2 && i2 != j1 && testSegmentsCross(polygon[i1], polygon[i2], polygon[j1], polygon[j2])) return true; } } return false; } double triangleSignedArea(QPointF a, QPointF b, QPointF c) { QPointF p = b - a; QPointF q = c - a; return (p.x() * q.y() - p.y() * q.x()) / 2.0; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Shape Shape::Shape(ShapeType shapeType) : vertices_(), type_(shapeType), isFinished_(false) { } bool Shape::addPoint(QPointF newPoint) { ASSERT_RETURN_V(!isFinished_, true); if (!vertices_.isEmpty() && newPoint == vertices_.back()) return false; vertices_.append(newPoint); switch (type_) { case SEGMENT: case RECTANGLE: ASSERT_RETURN_V(vertices_.size() <= 2, true); isFinished_ = (vertices_.size() == 2); return isFinished_; case POLYLINE: case CLOSED_POLYLINE: case POLYGON: return false; } ERROR_RETURN_V(true); } void Shape::finish() { ASSERT_RETURN(!vertices_.empty()); isFinished_ = true; } void Shape::scale(double factor) { for (int i = 0; i < vertices_.size(); ++i) vertices_[i] *= factor; } void Shape::dragVertex(int iVertex, QPointF newPos) { switch (type_) { case SEGMENT: case POLYLINE: case CLOSED_POLYLINE: case POLYGON: vertices_[iVertex] = newPos; break; case RECTANGLE: ASSERT_RETURN(vertices_.size() == 2); switch (iVertex) { case 0: vertices_[0] = newPos; break; case 1: vertices_[0].ry() = newPos.y(); vertices_[1].rx() = newPos.x(); break; case 2: vertices_[1] = newPos; break; case 3: vertices_[0].rx() = newPos.x(); vertices_[1].ry() = newPos.y(); break; default: ERROR_RETURN(); } break; } } QPolygonF Shape::vertices() const { QPolygonF result = vertices_; switch (type_) { case SEGMENT: case POLYLINE: case CLOSED_POLYLINE: case POLYGON: break; case RECTANGLE: if (result.size() == 2) { result = QPolygonF(QRectF(result[0], result[1])); result.pop_back(); } break; } return result; } QPolygonF Shape::polygon() const { QPolygonF result = vertices_; switch (type_) { case SEGMENT: case POLYLINE: break; case CLOSED_POLYLINE: case POLYGON: result.append(result.first()); break; case RECTANGLE: if (result.size() == 2) result = QPolygonF(QRectF(result[0], result[1])); break; } return result; } ShapeCorrectness Shape::correctness() const { switch (type_) { case SEGMENT: case POLYLINE: case CLOSED_POLYLINE: case RECTANGLE: return VALID_SHAPE; case POLYGON: return isSelfintersectingPolygon(polygon()) ? SELF_INTERSECTING_POLYGON : VALID_SHAPE; } ERROR_RETURN_V(VALID_SHAPE); } double Shape::length() const { ASSERT_RETURN_V(dimensionality() == SHAPE_1D, 0.); QPolygonF p = polygon(); double result = 0.; for (int i = 0; i < p.size() - 1; i++) result += segmentLenght(p[i], p[i + 1]); return result; } double Shape::area() const { ASSERT_RETURN_V(dimensionality() == SHAPE_2D, 0.); QPolygonF p = polygon(); assertPolygonIsClosed(p); double result = 0.; for (int i = 1; i < p.size() - 2; i++) result += triangleSignedArea(p[0], p[i], p[i + 1]); return qAbs(result); }
22.4
140
0.563645
amatveiakin
66a78e564d4dc0814fb58c36e6a580c4928d629a
839
hpp
C++
src/rotating_plane.hpp
fdekruijff/Tesseract-LED-Cube
70a9ce4d44517714966b2a62e8fb6c4a950f8407
[ "BSL-1.0" ]
null
null
null
src/rotating_plane.hpp
fdekruijff/Tesseract-LED-Cube
70a9ce4d44517714966b2a62e8fb6c4a950f8407
[ "BSL-1.0" ]
null
null
null
src/rotating_plane.hpp
fdekruijff/Tesseract-LED-Cube
70a9ce4d44517714966b2a62e8fb6c4a950f8407
[ "BSL-1.0" ]
null
null
null
/// Copyright Floris de Kruijff 2018. /// Distributed under the Boost Software License, Version 1.0. /// (See accompanying file LICENSE.txt or copy at /// https://www.boost.org/LICENSE.txt) /// @file #ifndef ROTATING_PLANE_HPP #define ROTATING_PLANE_HPP #include "vector.hpp" #include "cube.hpp" #include "animation.hpp" /// @class rotating_plane /// @author Floris de Kruijff /// @date 25-06-2018 /// @file rotating_plane.hpp /// @brief rotating plane class decleration /// @details /// The rotating plane class is a simple demonstration of a 2D plane rotating in 3D space. class rotating_plane : public animation { public: rotating_plane( const cube &c, int frame_delay ); void draw( hwlib::pin_in &interrupt = hwlib::pin_in_dummy ) override; }; #endif // ROTATING_PLANE_HPP
28.931034
91
0.688915
fdekruijff
66a8e5be070e40d668ff9e225a11c3e9b36a3360
3,848
cpp
C++
ndt_eval/src/pointcloud_handler.cpp
JHenriksson86/ndt_2d
ff26d1b68a89098184381c937f79bc1460bf660a
[ "MIT" ]
1
2020-08-12T14:15:20.000Z
2020-08-12T14:15:20.000Z
ndt_eval/src/pointcloud_handler.cpp
JHenriksson86/ndt_2d
ff26d1b68a89098184381c937f79bc1460bf660a
[ "MIT" ]
1
2021-01-05T04:36:50.000Z
2021-01-05T07:30:23.000Z
ndt_eval/src/pointcloud_handler.cpp
JHenriksson86/ndt_2d
ff26d1b68a89098184381c937f79bc1460bf660a
[ "MIT" ]
1
2020-08-08T11:26:11.000Z
2020-08-08T11:26:11.000Z
#include "ndt_eval/pointcloud_handler.h" namespace ndt2d { PointCloudHandler::PointCloudHandler(std::string frame) : cloud_(new pcl::PointCloud<pcl::PointXYZ>) { this->frame_ = frame; this->stamp_ = ""; } PointCloudHandler::PointCloudHandler( const sensor_msgs::PointCloud2& pc2_message, std::string frame) : cloud_(new pcl::PointCloud<pcl::PointXYZ>) { pcl::PCLPointCloud2 pcl_pc2; pcl_conversions::toPCL(pc2_message, pcl_pc2); pcl::fromPCLPointCloud2(pcl_pc2, *cloud_); this->frame_ = frame; this->stamp_ = ""; } PointCloudHandler::~PointCloudHandler(){} int PointCloudHandler::getNumberOfPoints() const { return cloud_->size(); } void PointCloudHandler::loadPCD(std::string pcd_path) { cloud_->clear(); pcl::PCDReader reader; ROS_DEBUG_STREAM("Loading pcd from: " << pcd_path); if (reader.read(pcd_path, *cloud_) < 0) { PCL_ERROR ("Couldn't read file test_pcd.pcd \n"); } } void PointCloudHandler::setStamp(const std::string& stamp) { this->stamp_ = stamp; } const std::string& PointCloudHandler::getStamp() const { return stamp_; } sensor_msgs::PointCloud2 PointCloudHandler::getPointCloud2Message( bool reduced, double grid_size) const { ROS_DEBUG("PointCloudHandler::getPointCloud2Message(reduced = %d, grid_size = %.2f)", reduced, grid_size); if(!reduced) { return pclToPC2(*cloud_); } pcl::PointCloud<pcl::PointXYZ>::Ptr filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); downsampleCloud(grid_size, cloud_, *filtered_cloud); return pclToPC2(*filtered_cloud); } sensor_msgs::PointCloud2 PointCloudHandler::getPointCloud2Message( const geometry_msgs::Transform& transform, bool reduced, double grid_size) const { ROS_DEBUG("PointCloudHandler::getPointCloud2Message(const geometry_msgs::Transform& transform)"); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud; if(reduced) { cloud = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>); downsampleCloud(grid_size, cloud_, *cloud); } else { cloud = cloud_; } Eigen::Affine3d transformation = Eigen::Affine3d::Identity(); TransformHandler::transformMessageToEigenTransform(transform, transformation); pcl::PointCloud<pcl::PointXYZ>::Ptr transformed_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::transformPointCloud(*cloud, *transformed_cloud, transformation); ROS_DEBUG_STREAM("Transforming point cloud with translation:\n" << transformation.translation() << "\nrotation:\n" << transformation.rotation()); return pclToPC2(*transformed_cloud); } Eigen::MatrixXd PointCloudHandler::getPointMatrix(bool reduced, double grid_size) const { if(!reduced) { return cloud_->getMatrixXfMap(3,4,0).cast<double>(); } pcl::PointCloud<pcl::PointXYZ>::Ptr filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); downsampleCloud(grid_size, cloud_, *filtered_cloud); return filtered_cloud->getMatrixXfMap(3,4,0).cast<double>(); } sensor_msgs::PointCloud2 PointCloudHandler::pclToPC2(const PointCloud& pcl_cloud) const { sensor_msgs::PointCloud2 ros_cloud; pcl::toROSMsg(pcl_cloud, ros_cloud); ros_cloud.header.frame_id = frame_; ros::Time time_stamp; if(stamp_.compare("") != 0) time_stamp.fromSec(std::stod(stamp_)); else time_stamp.fromSec(0.0); ros_cloud.header.stamp = time_stamp; return ros_cloud; } void PointCloudHandler::downsampleCloud(double grid_size,PointCloud::Ptr input_cloud, PointCloud& output_cloud) const { pcl::VoxelGrid<pcl::PointXYZ> filter; filter.setInputCloud(input_cloud); filter.setLeafSize(grid_size, grid_size, grid_size); filter.filter(output_cloud); } };
29.829457
119
0.696206
JHenriksson86
66a914fa67e9030cc0c647cde04960546f536dfc
4,319
cpp
C++
common/merging_result_storage.cpp
abadona/qsimscan
3ae8524d7f97a0586ed3b283c49d28c298a3f558
[ "MIT" ]
10
2015-11-20T00:19:13.000Z
2021-02-25T10:33:14.000Z
common/merging_result_storage.cpp
abadona/qsimscan
3ae8524d7f97a0586ed3b283c49d28c298a3f558
[ "MIT" ]
1
2016-08-24T07:09:42.000Z
2016-08-24T07:09:42.000Z
common/merging_result_storage.cpp
abadona/qsimscan
3ae8524d7f97a0586ed3b283c49d28c298a3f558
[ "MIT" ]
1
2020-03-10T03:02:24.000Z
2020-03-10T03:02:24.000Z
////////////////////////////////////////////////////////////////////////////// //// This software module is developed by SciDM (Scientific Data Management) in 1998-2015 //// //// This program is free software; you can redistribute, reuse, //// or modify it with no restriction, under the terms of the MIT License. //// //// This program is distributed in the hope that it will be useful, //// but WITHOUT ANY WARRANTY; without even the implied warranty of //// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. //// //// For any questions please contact Denis Kaznadzey at dkaznadzey@yahoo.com ////////////////////////////////////////////////////////////////////////////// #include "merging_result_storage.h" MergingResultStorage::MergingResultStorage (SimMergerBase& merger, unsigned capacity, unsigned res_per_target) : AlignResultStorage (capacity), merger_ (merger), res_per_target_ (res_per_target), accum_no_ (0), cur_sid_ (-1), tot_merged_ (0) { } bool MergingResultStorage::add_result (longlong qid, longlong sid, bool reverse, float al_score, int score, float chi2, double evalue, double bitscore, int q_auto_score, int t_auto_score, int batch_no, BATCH* batches, const char* binsubj, QWORD subjid, DWORD subjlen) { if (cur_sid_ != sid) { // flush (binsubj); cur_sid_ = sid; } AlignResult r (sid, reverse, al_score, score, chi2, evalue, bitscore, q_auto_score, t_auto_score, batch_no, batches, binsubj, subjid, subjlen); if (reverse) accum_rev_ [qid].push_back (r); else accum_fwd_ [qid].push_back (r); accum_no_ ++; return true; } struct AlignResultWrapper { const AlignResult* align_; longlong query_; AlignResultWrapper () : align_ (NULL), query_ (0) { } AlignResultWrapper (const AlignResult& align, longlong query) : align_ (&align), query_ (query) { } AlignResultWrapper (const AlignResultWrapper& oth) : align_ (oth.align_), query_ (oth.query_) { } AlignResultWrapper& operator = (const AlignResultWrapper& oth) { align_ = oth.align_; query_ = oth.query_; } bool operator < (const AlignResultWrapper& other) const { return *align_ < *(other.align_); } bool operator == (const AlignResultWrapper& other) const { return *align_ == *(other.align_); } }; typedef PQueue <AlignResultWrapper> ARWQueue; void MergingResultStorage::flush (const char* tseq) { if (!accum_no_) return; QryResults::iterator qi; ARWQueue besthits (res_per_target_); for (qi = accum_fwd_.begin (); qi != accum_fwd_.end (); qi ++) { ARVect& alignments = (*qi).second; merger_.merge (alignments, tseq); for (ARVect::iterator ri = alignments.begin (); ri != alignments.end (); ri ++) { if (res_per_target_) besthits.push (AlignResultWrapper (*ri, (*qi).first)); else AlignResultStorage::add_result ((*qi).first, *ri); ++ tot_merged_; } } for (qi = accum_rev_.begin (); qi != accum_rev_.end (); qi ++) { ARVect& alignments = (*qi).second; merger_.merge (alignments, tseq); for (ARVect::iterator ri = alignments.begin (); ri != alignments.end (); ri ++) { if (res_per_target_) besthits.push (AlignResultWrapper (*ri, (*qi).first)); else AlignResultStorage::add_result ((*qi).first, *ri); ++ tot_merged_; } } if (res_per_target_) { const ARWQueue::ElemVec& wrappers = besthits.data (); for (unsigned pp = 0, sent = besthits.size (); pp != sent; ++pp) { const AlignResultWrapper& wrapper = wrappers [pp]; AlignResultStorage::add_result (wrapper.query_, *wrapper.align_); } } clear_accum (); } void MergingResultStorage::clear_accum () { QryResults::iterator ii; for (ii = accum_fwd_.begin (); ii != accum_fwd_.end (); ii ++) (*ii).second.clear (); for (ii = accum_rev_.begin (); ii != accum_rev_.end (); ii ++) (*ii).second.clear (); accum_no_ = 0; } bool MergingResultStorage::reset () { clear_accum (); return AlignResultStorage::reset (); }
30.415493
267
0.59875
abadona
66aa6c8ee2670c58c83c68e167642a6a957918c6
15,989
cpp
C++
webkit/WebCore/html/HTMLLinkElement.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/html/HTMLLinkElement.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/html/HTMLLinkElement.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2003, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2009 Rob Buis (rwlbuis@gmail.com) * Copyright (c) 2010 ACCESS CO., LTD. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "HTMLLinkElement.h" #include "CSSHelper.h" #include "CachedCSSStyleSheet.h" #include "DNS.h" #include "DocLoader.h" #include "Document.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "FrameTree.h" #include "HTMLNames.h" #include "MappedAttribute.h" #include "MediaList.h" #include "MediaQueryEvaluator.h" #include "Page.h" #include "ScriptEventListener.h" #include "Settings.h" #include <wtf/StdLibExtras.h> namespace WebCore { using namespace HTMLNames; HTMLLinkElement::HTMLLinkElement(const QualifiedName& qName, Document *doc, bool createdByParser) : HTMLElement(qName, doc) , m_cachedSheet(0) , m_disabledState(0) , m_loading(false) , m_alternate(false) , m_isStyleSheet(false) , m_isIcon(false) , m_isDNSPrefetch(false) , m_createdByParser(createdByParser) { ASSERT(hasTagName(linkTag)); } HTMLLinkElement::~HTMLLinkElement() { if (m_cachedSheet) { m_cachedSheet->removeClient(this); if (m_loading && !isDisabled() && !isAlternate()) document()->removePendingSheet(); } } void HTMLLinkElement::setDisabledState(bool _disabled) { int oldDisabledState = m_disabledState; m_disabledState = _disabled ? 2 : 1; if (oldDisabledState != m_disabledState) { // If we change the disabled state while the sheet is still loading, then we have to // perform three checks: if (isLoading()) { // Check #1: If the sheet becomes disabled while it was loading, and if it was either // a main sheet or a sheet that was previously enabled via script, then we need // to remove it from the list of pending sheets. if (m_disabledState == 2 && (!m_alternate || oldDisabledState == 1)) document()->removePendingSheet(); // Check #2: An alternate sheet becomes enabled while it is still loading. if (m_alternate && m_disabledState == 1) document()->addPendingSheet(); // Check #3: A main sheet becomes enabled while it was still loading and // after it was disabled via script. It takes really terrible code to make this // happen (a double toggle for no reason essentially). This happens on // virtualplastic.net, which manages to do about 12 enable/disables on only 3 // sheets. :) if (!m_alternate && m_disabledState == 1 && oldDisabledState == 2) document()->addPendingSheet(); // If the sheet is already loading just bail. return; } // Load the sheet, since it's never been loaded before. if (!m_sheet && m_disabledState == 1) process(); else document()->updateStyleSelector(); // Update the style selector. } } StyleSheet* HTMLLinkElement::sheet() const { return m_sheet.get(); } void HTMLLinkElement::parseMappedAttribute(MappedAttribute *attr) { if (attr->name() == relAttr) { tokenizeRelAttribute(attr->value(), m_isStyleSheet, m_alternate, m_isIcon, m_isDNSPrefetch); process(); } else if (attr->name() == hrefAttr) { m_url = document()->completeURL(deprecatedParseURL(attr->value())); process(); } else if (attr->name() == typeAttr) { m_type = attr->value(); process(); } else if (attr->name() == mediaAttr) { m_media = attr->value().string().lower(); process(); } else if (attr->name() == disabledAttr) { setDisabledState(!attr->isNull()); } else if (attr->name() == onbeforeloadAttr) setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, attr)); else { if (attr->name() == titleAttr && m_sheet) m_sheet->setTitle(attr->value()); HTMLElement::parseMappedAttribute(attr); } } void HTMLLinkElement::tokenizeRelAttribute(const AtomicString& rel, bool& styleSheet, bool& alternate, bool& icon, bool& dnsPrefetch) { styleSheet = false; icon = false; alternate = false; dnsPrefetch = false; if (equalIgnoringCase(rel, "stylesheet")) styleSheet = true; else if (equalIgnoringCase(rel, "icon") || equalIgnoringCase(rel, "shortcut icon")) icon = true; else if (equalIgnoringCase(rel, "dns-prefetch")) dnsPrefetch = true; else if (equalIgnoringCase(rel, "alternate stylesheet") || equalIgnoringCase(rel, "stylesheet alternate")) { styleSheet = true; alternate = true; } else { // Tokenize the rel attribute and set bits based on specific keywords that we find. String relString = rel.string(); relString.replace('\n', ' '); Vector<String> list; relString.split(' ', list); Vector<String>::const_iterator end = list.end(); for (Vector<String>::const_iterator it = list.begin(); it != end; ++it) { if (equalIgnoringCase(*it, "stylesheet")) styleSheet = true; else if (equalIgnoringCase(*it, "alternate")) alternate = true; else if (equalIgnoringCase(*it, "icon")) icon = true; } } } void HTMLLinkElement::process() { if (!inDocument()) return; String type = m_type.lower(); // IE extension: location of small icon for locationbar / bookmarks // We'll record this URL per document, even if we later only use it in top level frames if (m_isIcon && m_url.isValid() && !m_url.isEmpty()) document()->setIconURL(m_url.string(), type); #if 1 // modified at webkit.org trunk r63622 if (m_isDNSPrefetch && document()->isDNSPrefetchEnabled() && m_url.isValid() && !m_url.isEmpty()) #else if (m_isDNSPrefetch && m_url.isValid() && !m_url.isEmpty()) #endif prefetchDNS(m_url.host()); bool acceptIfTypeContainsTextCSS = document()->page() && document()->page()->settings() && document()->page()->settings()->treatsAnyTextCSSLinkAsStylesheet(); // Stylesheet // This was buggy and would incorrectly match <link rel="alternate">, which has a different specified meaning. -dwh if (m_disabledState != 2 && (m_isStyleSheet || (acceptIfTypeContainsTextCSS && type.contains("text/css"))) && document()->frame() && m_url.isValid()) { // also, don't load style sheets for standalone documents String charset = getAttribute(charsetAttr); if (charset.isEmpty() && document()->frame()) charset = document()->frame()->loader()->encoding(); if (m_cachedSheet) { if (m_loading) document()->removePendingSheet(); m_cachedSheet->removeClient(this); m_cachedSheet = 0; } if (!dispatchBeforeLoadEvent(m_url)) return; m_loading = true; // Add ourselves as a pending sheet, but only if we aren't an alternate // stylesheet. Alternate stylesheets don't hold up render tree construction. if (!isAlternate()) document()->addPendingSheet(); m_cachedSheet = document()->docLoader()->requestCSSStyleSheet(m_url, charset); if (m_cachedSheet) m_cachedSheet->addClient(this); else { // The request may have been denied if (for example) the stylesheet is local and the document is remote. m_loading = false; if (!isAlternate()) document()->removePendingSheet(); } } else if (m_sheet) { // we no longer contain a stylesheet, e.g. perhaps rel or type was changed m_sheet = 0; document()->updateStyleSelector(); } } void HTMLLinkElement::insertedIntoDocument() { HTMLElement::insertedIntoDocument(); document()->addStyleSheetCandidateNode(this, m_createdByParser); process(); } void HTMLLinkElement::removedFromDocument() { HTMLElement::removedFromDocument(); document()->removeStyleSheetCandidateNode(this); // FIXME: It's terrible to do a synchronous update of the style selector just because a <style> or <link> element got removed. if (document()->renderer()) document()->updateStyleSelector(); } void HTMLLinkElement::finishParsingChildren() { m_createdByParser = false; HTMLElement::finishParsingChildren(); } #if PLATFORM(WKC) static String* gSlashKHTMLFixesDotCss = 0; static String* gMediaWikiKHTMLFixesStyleSheet = 0; #endif #if 1 // modified at webkit.org trunk r53607 void HTMLLinkElement::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet* sheet) #else void HTMLLinkElement::setCSSStyleSheet(const String& url, const String& charset, const CachedCSSStyleSheet* sheet) #endif { #if 1 // modified at webkit.org trunk r53607 m_sheet = CSSStyleSheet::create(this, href, baseURL, charset); #else m_sheet = CSSStyleSheet::create(this, url, charset); #endif bool strictParsing = !document()->inCompatMode(); bool enforceMIMEType = strictParsing; bool needsSiteSpecificQuirks = document()->page() && document()->page()->settings()->needsSiteSpecificQuirks(); // Check to see if we should enforce the MIME type of the CSS resource in strict mode. // Running in iWeb 2 is one example of where we don't want to - <rdar://problem/6099748> if (enforceMIMEType && document()->page() && !document()->page()->settings()->enforceCSSMIMETypeInStrictMode()) enforceMIMEType = false; #if defined(BUILDING_ON_TIGER) || defined(BUILDING_ON_LEOPARD) if (enforceMIMEType && needsSiteSpecificQuirks) { // Covers both http and https, with or without "www." #if 1 // modified at webkit.org trunk r53607 if (baseURL.string().contains("mcafee.com/japan/", false)) #else if (url.contains("mcafee.com/japan/", false)) #endif enforceMIMEType = false; } #endif String sheetText = sheet->sheetText(enforceMIMEType); m_sheet->parseString(sheetText, strictParsing); if (strictParsing && needsSiteSpecificQuirks) { // Work around <https://bugs.webkit.org/show_bug.cgi?id=28350>. #if PLATFORM(WKC) if (!gSlashKHTMLFixesDotCss) { gSlashKHTMLFixesDotCss = new String("/KHTMLFixes.css"); } const String& slashKHTMLFixesDotCss = *gSlashKHTMLFixesDotCss; if (!gMediaWikiKHTMLFixesStyleSheet) { gMediaWikiKHTMLFixesStyleSheet = new String("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n"); } String& mediaWikiKHTMLFixesStyleSheet = *gMediaWikiKHTMLFixesStyleSheet; #else DEFINE_STATIC_LOCAL(const String, slashKHTMLFixesDotCss, ("/KHTMLFixes.css")); DEFINE_STATIC_LOCAL(const String, mediaWikiKHTMLFixesStyleSheet, ("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n")); #endif // There are two variants of KHTMLFixes.css. One is equal to mediaWikiKHTMLFixesStyleSheet, // while the other lacks the second trailing newline. #if 1 // modified at webkit.org trunk r53607 if (baseURL.string().endsWith(slashKHTMLFixesDotCss) && !sheetText.isNull() && mediaWikiKHTMLFixesStyleSheet.startsWith(sheetText) #else if (url.endsWith(slashKHTMLFixesDotCss) && !sheetText.isNull() && mediaWikiKHTMLFixesStyleSheet.startsWith(sheetText) #endif && sheetText.length() >= mediaWikiKHTMLFixesStyleSheet.length() - 1) { ASSERT(m_sheet->length() == 1); ExceptionCode ec; m_sheet->deleteRule(0, ec); } } m_sheet->setTitle(title()); RefPtr<MediaList> media = MediaList::createAllowingDescriptionSyntax(m_media); m_sheet->setMedia(media.get()); m_loading = false; m_sheet->checkLoaded(); } bool HTMLLinkElement::isLoading() const { if (m_loading) return true; if (!m_sheet) return false; return static_cast<CSSStyleSheet *>(m_sheet.get())->isLoading(); } bool HTMLLinkElement::sheetLoaded() { if (!isLoading() && !isDisabled() && !isAlternate()) { document()->removePendingSheet(); return true; } return false; } bool HTMLLinkElement::isURLAttribute(Attribute *attr) const { return attr->name() == hrefAttr; } bool HTMLLinkElement::disabled() const { return !getAttribute(disabledAttr).isNull(); } void HTMLLinkElement::setDisabled(bool disabled) { setAttribute(disabledAttr, disabled ? "" : 0); } String HTMLLinkElement::charset() const { return getAttribute(charsetAttr); } void HTMLLinkElement::setCharset(const String& value) { setAttribute(charsetAttr, value); } KURL HTMLLinkElement::href() const { return document()->completeURL(getAttribute(hrefAttr)); } void HTMLLinkElement::setHref(const String& value) { setAttribute(hrefAttr, value); } String HTMLLinkElement::hreflang() const { return getAttribute(hreflangAttr); } void HTMLLinkElement::setHreflang(const String& value) { setAttribute(hreflangAttr, value); } String HTMLLinkElement::media() const { return getAttribute(mediaAttr); } void HTMLLinkElement::setMedia(const String& value) { setAttribute(mediaAttr, value); } String HTMLLinkElement::rel() const { return getAttribute(relAttr); } void HTMLLinkElement::setRel(const String& value) { setAttribute(relAttr, value); } String HTMLLinkElement::rev() const { return getAttribute(revAttr); } void HTMLLinkElement::setRev(const String& value) { setAttribute(revAttr, value); } String HTMLLinkElement::target() const { return getAttribute(targetAttr); } void HTMLLinkElement::setTarget(const String& value) { setAttribute(targetAttr, value); } String HTMLLinkElement::type() const { return getAttribute(typeAttr); } void HTMLLinkElement::setType(const String& value) { setAttribute(typeAttr, value); } void HTMLLinkElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const { HTMLElement::addSubresourceAttributeURLs(urls); // Favicons are handled by a special case in LegacyWebArchive::create() if (m_isIcon) return; if (!m_isStyleSheet) return; // Append the URL of this link element. addSubresourceURL(urls, href()); // Walk the URLs linked by the linked-to stylesheet. if (StyleSheet* styleSheet = const_cast<HTMLLinkElement*>(this)->sheet()) styleSheet->addSubresourceStyleURLs(urls); } #if PLATFORM(WKC) void HTMLLinkElement::deleteSharedInstance() { delete gSlashKHTMLFixesDotCss; delete gMediaWikiKHTMLFixesStyleSheet; } void HTMLLinkElement::resetVariables() { gSlashKHTMLFixesDotCss = 0; gMediaWikiKHTMLFixesStyleSheet = 0; } #endif }
32.497967
191
0.666708
s1rcheese
66ac633fd7fcb1d8bfe7c6202d278966761c7f11
25,124
cpp
C++
Source/ComponentMesh.cpp
project-3-bcn-2019/Project-Atlas
16ae881cec41d17a168d10f2f9cd2cf9207b2855
[ "MIT" ]
1
2019-02-21T13:35:35.000Z
2019-02-21T13:35:35.000Z
Source/ComponentMesh.cpp
project-3-bcn-2019/Kuroko-Engine
16ae881cec41d17a168d10f2f9cd2cf9207b2855
[ "MIT" ]
1
2019-03-01T15:18:28.000Z
2019-03-01T15:18:28.000Z
Source/ComponentMesh.cpp
project-3-bcn-2019/Project-Atlas
16ae881cec41d17a168d10f2f9cd2cf9207b2855
[ "MIT" ]
null
null
null
#include "ComponentMesh.h" #include "ComponentTransform.h" #include "Transform.h" #include "GameObject.h" #include "ModuleScene.h" #include "ModuleShaders.h" #include "Application.h" #include "ComponentAABB.h" #include "ComponentBone.h" #include "Material.h" #include "ModuleImporter.h" #include "ModuleUI.h" #include "FileSystem.h" #include "glew-2.1.0\include\GL\glew.h" #include "ModuleCamera3D.h" #include "Camera.h" #include "Applog.h" #include "ModuleResourcesManager.h" #include "ModuleRenderer3D.h" #include "ResourceMesh.h" #include "ResourceTexture.h" #include "ResourceBone.h" #include "ResourceShader.h" std::string openFileWID(bool isfile = false); ComponentMesh::ComponentMesh(JSON_Object * deff, GameObject* parent): Component(parent, MESH) { is_active = json_object_get_boolean(deff, "active"); std::string path; // Load mesh from own file format //std::string mesh_name = json_object_get_string(deff, "mesh_name"); // Mesh name not used for now primitive_type = primitiveString2PrimitiveType(json_object_get_string(deff, "primitive_type")); if(primitive_type == Primitive_None){ // TODO: Store the color of the meshes // ASSIGNING RESOURCE const char* parent3dobject = json_object_get_string(deff, "Parent3dObject"); if (App->is_game && !App->debug_game) { setMeshResourceId(App->resources->getResourceUuid(json_object_get_string(deff, "mesh_name"), R_MESH)); } else if (parent3dobject) // Means that is being loaded from a scene mesh_resource_uuid = App->resources->getMeshResourceUuid(parent3dobject, json_object_get_string(deff, "mesh_name")); else // Means it is being loaded from a 3dObject binary mesh_resource_uuid = json_object_get_number(deff, "mesh_resource_uuid"); App->resources->assignResource(mesh_resource_uuid); } JSON_Array* bones = json_object_get_array(deff, "bones"); if (bones != nullptr) //There are stored bones { for (int i = 0; i < json_array_get_count(bones); ++i) { JSON_Object* bone = json_array_get_object(bones, i); bones_names.push_back(json_object_get_string(bone, "bone_name")); } } mat = new Material(); // ASSIGNING RESOURCE const char* diffuse_path = json_object_dotget_string(deff, "material.diffuse"); uint diffuse_resource = 0; if (diffuse_path) { // Means that is being loaded from a scene if (strcmp(diffuse_path, "missing reference") != 0) { if (!App->is_game || App->debug_game) diffuse_resource = App->resources->getResourceUuid(diffuse_path); else { std::string d_path = diffuse_path; App->fs.getFileNameFromPath(d_path); diffuse_resource = App->resources->getTextureResourceUuid(d_path.c_str()); } } } else // Means it is being loaded from a 3dObject binary diffuse_resource = json_object_dotget_number(deff, "material.diffuse_resource_uuid"); const char* vertex_path = json_object_dotget_string(deff, "vertex_shader"); uint vertex_resource = 0; if (vertex_path) { // Means that is being loaded from a scene if (!App->is_game || App->debug_game) vertex_resource = App->resources->getResourceUuid(vertex_path); else { std::string s_path = vertex_path; App->fs.getFileNameFromPath(s_path); vertex_resource = App->resources->getShaderResourceUuid(s_path.c_str()); } } //else // Means it is being loaded from a 3dObject binary // vertex_resource = json_object_dotget_number(deff, "material.diffuse_resource_uuid"); const char* fragment_path = json_object_dotget_string(deff, "fragment_shader"); uint fragment_resource = 0; if (fragment_path) { // Means that is being loaded from a scene if (!App->is_game || App->debug_game) fragment_resource = App->resources->getResourceUuid(fragment_path); else { std::string d_path = fragment_path; App->fs.getFileNameFromPath(d_path); fragment_resource = App->resources->getShaderResourceUuid(d_path.c_str()); } } if(diffuse_resource != 0){ App->resources->assignResource(diffuse_resource); mat->setTextureResource(DIFFUSE, diffuse_resource); } if (vertex_resource != 0 && fragment_resource != 0) { App->resources->assignResource(vertex_resource); App->resources->assignResource(fragment_resource); //first we look for an existent program uint ShaderID = App->shaders->GetShaderProgramByResources(vertex_resource, fragment_resource); if (ShaderID != 0) { mat->setShaderProgram(ShaderID); } else //if we can't find a program we create a new one { ShaderProgram* shader_program = new ShaderProgram(); shader_program->shaderUUIDS.push_back(vertex_resource); shader_program->shaderUUIDS.push_back(fragment_resource); if (App->shaders->CompileProgramFromResources(shader_program)) { App->shaders->shader_programs.push_back(shader_program); } else { //if there is any compiling error we will use the default shader that will be always loaded RELEASE(shader_program) } } } } ComponentMesh::~ComponentMesh() { // Deassign all the components that the element had if it is deleted if(primitive_type == Primitive_None) App->resources->deasignResource(mesh_resource_uuid); delete mat; } void ComponentMesh::Draw() { if (mat) { if (mat->translucent) { App->renderer3D->translucentMeshes.push(this); return; } } App->renderer3D->opaqueMeshes.push_back(this); } void ComponentMesh::DrawSelected() { App->renderer3D->selected_meshes_to_draw.push_back(this); } void ComponentMesh::Render() const { if (Mesh* mesh_from_resource = getMeshFromResource()) { OBB* obb = ((ComponentAABB*)getParent()->getComponent(C_AABB))->getOBB(); if (App->camera->current_camera->frustumCull(*obb)) { ComponentTransform* transform = nullptr; float4x4 view_mat = float4x4::identity; if (transform = (ComponentTransform*)getParent()->getComponent(TRANSFORM)) { GLfloat matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, matrix); view_mat.Set((float*)matrix); glMatrixMode(GL_MODELVIEW_MATRIX); glLoadMatrixf((GLfloat*)(transform->global->getMatrix().Transposed() * view_mat).v); } if (draw_normals || App->scene->global_normals) mesh_from_resource->DrawNormals(); if (wireframe || App->scene->global_wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); Skining(); mesh_from_resource->Draw(mat); //Descoment to use shader render /*ComponentAnimation* animation = nullptr; animation = (ComponentAnimation*)getParent()->getComponent(ANIMATION); mesh_from_resource->MaxDrawFunctionTest(mat, animation,*transform->global->getMatrix().Transposed().v);*/ if (transform) glLoadMatrixf((GLfloat*)view_mat.v); } } } void ComponentMesh::RenderSelected() const { if (Mesh* mesh_from_resource = getMeshFromResource()) { OBB* obb = ((ComponentAABB*)getParent()->getComponent(C_AABB))->getOBB(); if (App->camera->current_camera->frustumCull(*obb)) { ComponentTransform* transform = nullptr; float4x4 view_mat = float4x4::identity; if (transform = (ComponentTransform*)getParent()->getComponent(TRANSFORM)) { GLfloat matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, matrix); view_mat.Set((float*)matrix); glMatrixMode(GL_MODELVIEW_MATRIX); glLoadMatrixf((GLfloat*)(transform->global->getMatrix().Transposed() * view_mat).v); } glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); Mesh* mesh_from_resource = getMeshFromResource(); mesh_from_resource->Draw(mat, true); //Descoment to use shader render /*ComponentAnimation* animation = nullptr; animation = (ComponentAnimation*)getParent()->getComponent(ANIMATION); mesh_from_resource->MaxDrawFunctionTest(nullptr,animation,*transform->global->getMatrix().Transposed().v, true);*/ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (transform) glLoadMatrixf((GLfloat*)view_mat.v); } } } bool ComponentMesh::Update(float dt) { if (components_bones.size() == 0 && parent->getParent() != nullptr && bones_names.size() > 0) { setMeshResourceId(mesh_resource_uuid); } return true; } bool ComponentMesh::DrawInspector(int id) { std::string tag; tag = "Mesh##" + std::to_string(id); if (ImGui::CollapsingHeader(tag.c_str())) { static bool wireframe_enabled; static bool mesh_active; static bool draw_normals; wireframe_enabled = getWireframe(); draw_normals = getDrawNormals(); mesh_active = isActive(); if (ImGui::Checkbox("Active## mesh_active", &mesh_active)) { setActive(mesh_active); App->scene->AskAutoSaveScene(); } if (mesh_active) { ResourceMesh* R_mesh = (ResourceMesh*)App->resources->getResource(getMeshResource()); ImGui::Text("Resource: %s", (R_mesh != nullptr) ? R_mesh->asset.c_str() : "None"); if (ImGui::Checkbox("Wireframe", &wireframe_enabled)) setWireframe(wireframe_enabled); ImGui::SameLine(); if (ImGui::Checkbox("Draw normals", &draw_normals)) setDrawNormals(draw_normals); if (!getMesh()) { static bool add_mesh_menu = false; if (ImGui::Button("Add mesh")) { add_mesh_menu = true; } if (add_mesh_menu) { std::list<resource_deff> mesh_res; App->resources->getMeshResourceList(mesh_res); ImGui::Begin("Mesh selector", &add_mesh_menu); for (auto it = mesh_res.begin(); it != mesh_res.end(); it++) { resource_deff mesh_deff = (*it); if (ImGui::MenuItem(mesh_deff.asset.c_str())) { App->resources->deasignResource(getMeshResource()); App->resources->assignResource(mesh_deff.uuid); setMeshResourceId(mesh_deff.uuid); add_mesh_menu = false; break; } } ImGui::End(); } } if (Mesh* mesh = getMesh()) { if (ImGui::TreeNode("Mesh Options")) { uint vert_num, poly_count; bool has_normals, has_colors, has_texcoords; if (ImGui::Button("Remove mesh")) { App->resources->deasignResource(getMeshResource()); setMeshResourceId(0); } mesh->getData(vert_num, poly_count, has_normals, has_colors, has_texcoords); ImGui::Text("vertices: %d, poly count: %d, ", vert_num, poly_count); ImGui::Text(has_normals ? "normals: Yes," : "normals: No,"); ImGui::Text(has_colors ? "colors: Yes," : "colors: No,"); ImGui::Text(has_texcoords ? "tex coords: Yes" : "tex coords: No"); ImGui::TreePop(); } } if (ImGui::TreeNode("Material")) { if (Material* material = getMaterial()) { ImGui::Checkbox("translucent", &material->translucent); static int preview_size = 128; ImGui::Text("Id: %d", material->getId()); ImGui::SameLine(); /*if (ImGui::Button("remove material")) { delete c_mesh->getMaterial(); c_mesh->setMaterial(nullptr); ImGui::TreePop(); return true; }*/ ImGui::Text("Preview size"); ImGui::SameLine(); if (ImGui::Button("64")) preview_size = 64; ImGui::SameLine(); if (ImGui::Button("128")) preview_size = 128; ImGui::SameLine(); if (ImGui::Button("256")) preview_size = 256; if (ImGui::TreeNode("diffuse")) { Texture* texture = nullptr; if (ResourceTexture* tex_res = (ResourceTexture*)App->resources->getResource(material->getTextureResource(DIFFUSE))) texture = tex_res->texture; ImGui::Image(texture ? (void*)texture->getGLid() : (void*)App->gui->ui_textures[NO_TEXTURE]->getGLid(), ImVec2(preview_size, preview_size)); ImGui::SameLine(); int w = 0; int h = 0; if (texture) texture->getSize(w, h); ImGui::Text("texture data: \n x: %d\n y: %d", w, h); //if (ImGui::Button("Load checkered##Dif: Load checkered")) // material->setCheckeredTexture(DIFFUSE); //ImGui::SameLine() if (ImGui::Button("Load(from asset folder)##Dif: Load")) { std::string texture_path = openFileWID(); uint new_resource = App->resources->getResourceUuid(texture_path.c_str()); if (new_resource != 0) { App->resources->assignResource(new_resource); App->resources->deasignResource(material->getTextureResource(DIFFUSE)); material->setTextureResource(DIFFUSE, new_resource); } } ImGui::TreePop(); } if (ImGui::TreeNode("shader program")) { if (material->getShaderProgram()) { ImGui::Text("Vertex:"); ImGui::SameLine(); ResourceShader* vertex_shader = (ResourceShader*)App->resources->getResource(material->getShaderProgram()->shaderUUIDS[0]); std::string vertex_name; if (vertex_shader) { vertex_name = vertex_shader->asset; App->fs.getFileNameFromPath(vertex_name); } else { vertex_name = "NONE"; } ImGui::PushItemWidth(200.0f); ImGui::PushID("Vertex Shader"); if (ImGui::BeginCombo("", vertex_name.c_str())) { std::list<resource_deff> vertex_Sahders; App->resources->getShaderResourceList(vertex_Sahders); for (std::list<resource_deff>::iterator v_it = vertex_Sahders.begin(); v_it != vertex_Sahders.end(); ++v_it) { Shader* shader = nullptr; if (shader=((ResourceShader*)App->resources->getResource((*v_it).uuid))->shaderObject) { bool selected = false; if (shader->type == VERTEX) { if (ImGui::Selectable(shader->name.c_str(), &selected)) { /*change the shader and recompile the shader program*/ } } } } ImGui::EndCombo(); } ImGui::PopID(); ImGui::PopItemWidth(); ImGui::Text("Fragment:"); ImGui::SameLine(); ResourceShader* fragment_shader = (ResourceShader*)App->resources->getResource(material->getShaderProgram()->shaderUUIDS[1]); std::string fragment_name; if (fragment_shader) { fragment_name = fragment_shader->asset; App->fs.getFileNameFromPath(fragment_name); } else { fragment_name = "NONE"; } ImGui::PushItemWidth(200.0f); ImGui::PushID("Fragment Shader"); if (ImGui::BeginCombo("", fragment_name.c_str())) { std::list<resource_deff> fragment_Sahders; App->resources->getShaderResourceList(fragment_Sahders); for (std::list<resource_deff>::iterator v_it = fragment_Sahders.begin(); v_it != fragment_Sahders.end(); ++v_it) { Shader* shader = nullptr; if (shader = ((ResourceShader*)App->resources->getResource((*v_it).uuid))->shaderObject) { bool selected = false; if (shader->type == FRAGMENT) { if (ImGui::Selectable(shader->name.c_str(), &selected)) { /*change the shader and recompile the shader program*/ } } } } ImGui::EndCombo(); } ImGui::PopID(); ImGui::PopItemWidth(); } ImGui::TreePop(); } if (ImGui::TreeNode("ambient (feature not avaliable yet)")) { //ImGui::Image(material->getTexture(AMBIENT) ? (void*)material->getTexture(AMBIENT)->getGLid() : (void*)ui_textures[NO_TEXTURE]->getGLid(), ImVec2(preview_size, preview_size)); //if (ImGui::Button("Load checkered##Amb: Load checkered")) // material->setCheckeredTexture(AMBIENT); //ImGui::SameLine(); //if (ImGui::Button("Load##Amb: Load")) //{ // std::string texture_path = openFileWID(); // if (Texture* tex = (Texture*)App->importer->Import(texture_path.c_str(), I_TEXTURE)) // c_mesh->getMaterial()->setTexture(AMBIENT, tex); //} ImGui::TreePop(); } if (ImGui::TreeNode("normals (feature not avaliable yet)")) { //ImGui::Image(material->getTexture(NORMALS) ? (void*)material->getTexture(NORMALS)->getGLid() : (void*)ui_textures[NO_TEXTURE]->getGLid(), ImVec2(preview_size, preview_size)); //if (ImGui::Button("Load checkered##Nor: Load checkered")) // material->setCheckeredTexture(NORMALS); //ImGui::SameLine(); //if (ImGui::Button("Load##Nor: Load")) //{ // std::string texture_path = openFileWID(); // if (Texture* tex = (Texture*)App->importer->Import(texture_path.c_str(), I_TEXTURE)) // c_mesh->getMaterial()->setTexture(NORMALS, tex); //} ImGui::TreePop(); } if (ImGui::TreeNode("lightmap (feature not avaliable yet)")) { //ImGui::Image(material->getTexture(LIGHTMAP) ? (void*)material->getTexture(LIGHTMAP)->getGLid() : (void*)ui_textures[NO_TEXTURE]->getGLid(), ImVec2(preview_size, preview_size)); //if (ImGui::Button("Load checkered##Lgm: Load checkered")) // material->setCheckeredTexture(LIGHTMAP); //ImGui::SameLine(); //if (ImGui::Button("Load##Lgm: Load")) //{ // std::string texture_path = openFileWID(); // if (Texture* tex = (Texture*)App->importer->Import(texture_path.c_str(), I_TEXTURE)) // c_mesh->getMaterial()->setTexture(LIGHTMAP, tex); //} ImGui::TreePop(); } } else { ImGui::TextWrapped("No material assigned!"); if (getMesh()) { static bool draw_colorpicker = false; static Color reference_color = getMesh()->tint_color; static GameObject* last_selected = getParent(); std::string label = getParent()->getName() + " color picker"; if (last_selected != getParent()) reference_color = getMesh()->tint_color; ImGui::SameLine(); if (ImGui::ColorButton((label + "button").c_str(), ImVec4(getMesh()->tint_color.r, getMesh()->tint_color.g, getMesh()->tint_color.b, getMesh()->tint_color.a))) draw_colorpicker = !draw_colorpicker; if (draw_colorpicker) App->gui->DrawColorPickerWindow(label.c_str(), (Color*)&getMesh()->tint_color, &draw_colorpicker, (Color*)&reference_color); else reference_color = getMesh()->tint_color; last_selected = getParent(); } if (ImGui::Button("Add material")) { Material* mat = new Material(); setMaterial(mat); } } ImGui::TreePop(); } if (ImGui::TreeNode("Connected Bones")) { ImGui::Text("Num Bones: %d", components_bones.size()); ImGui::TreePop(); } } ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(1.f, 0.f, 0.f, 1.f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1.f, 0.2f, 0.f, 1.f)); if (ImGui::Button("Remove##Remove mesh")) { ImGui::PopStyleColor(); ImGui::PopStyleColor(); return false; } ImGui::PopStyleColor(); ImGui::PopStyleColor(); } return true; } Mesh* ComponentMesh::getMesh() const { Mesh* ret = nullptr; ResourceMesh* mesh_resource = nullptr; if (primitive_type == Primitive_None) { mesh_resource = (ResourceMesh*)App->resources->getResource(mesh_resource_uuid); if(mesh_resource) ret = mesh_resource->mesh; } else { mesh_resource = (ResourceMesh*)App->resources->getPrimitiveMeshResource(primitive_type); ret = mesh_resource->mesh; } return ret; } void ComponentMesh::setMeshResourceId(uint _mesh_resource_uuid) { App->resources->deasignResource(mesh_resource_uuid); mesh_resource_uuid = _mesh_resource_uuid; App->resources->assignResource(mesh_resource_uuid); ((ComponentAABB*)getParent()->getComponent(C_AABB))->Reload(); components_bones.clear(); for (int i = 0; i < bones_names.size(); ++i) { GameObject* GO = parent->getAbsoluteParent()->getChild(bones_names[i].c_str(), true); if (GO != nullptr) { Component* bone = GO->getComponent(BONE); if (bone != nullptr) { components_bones.push_back(bone->getUUID()); } } } } PrimitiveTypes ComponentMesh::primitiveString2PrimitiveType(std::string primitive_type_string) { PrimitiveTypes ret = Primitive_None; // Just for security if (primitive_type_string == "CUBE") ret = Primitive_Cube; else if (primitive_type_string == "PLANE") ret = Primitive_Plane; else if (primitive_type_string == "SPHERE") ret = Primitive_Sphere; else if (primitive_type_string == "CYLINDER") ret = Primitive_Cylinder; return ret; } std::string ComponentMesh::PrimitiveType2primitiveString(PrimitiveTypes type) { std::string ret = "NONE"; switch (type) { case Primitive_Cube: ret = "CUBE"; break; case Primitive_Plane: ret = "PLANE"; break; case Primitive_Sphere: ret = "SPHERE"; break; case Primitive_Cylinder: ret = "CYLINDER"; break; } return ret; } void ComponentMesh::Skining() const { ResourceMesh* mesh = (ResourceMesh*)App->resources->getResource(mesh_resource_uuid); if (mesh != nullptr && components_bones.size() > 0 && parent->getParent() != nullptr && bones_names.size() > 0) { float3* vertices = new float3[mesh->mesh->getNumVertices()]; memset(vertices, 0, sizeof(float)*mesh->mesh->getNumVertices() * 3); bool hasBones = false; for (int i = 0; i < components_bones.size(); i++) { GameObject* absoluteParent = parent->getAbsoluteParent(); ComponentBone* bone = (ComponentBone*)absoluteParent->getChildComponent(components_bones[i]); if (bone != nullptr) { ResourceBone* rBone = (ResourceBone*)App->resources->getResource(bone->getBoneResource()); if (rBone != nullptr) { hasBones = true; //float4x4 boneTransform = ((ComponentTransform*)bone->getParent()->getComponent(TRANSFORM))->global->getMatrix()*rBone->Offset; float4x4 boneTransform = ((ComponentTransform*)parent->getComponent(TRANSFORM))->global->getMatrix().Inverted()*((ComponentTransform*)bone->getParent()->getComponent(TRANSFORM))->global->getMatrix()*rBone->Offset; for (int j = 0; j < rBone->numWeights; j++) { uint VertexIndex = rBone->weights[j].VertexID; if (VertexIndex >= mesh->mesh->getNumVertices()) continue; float3 startingVertex(mesh->mesh->getVertices()[VertexIndex]); float3 movementWeight = boneTransform.TransformPos(mesh->mesh->getVertices()[VertexIndex] + mesh->mesh->getCentroid()); /*vertices[VertexIndex].x += movementWeight.x*rBone->weights[j].weight; vertices[VertexIndex].y += movementWeight.y*rBone->weights[j].weight; vertices[VertexIndex].z += movementWeight.z*rBone->weights[j].weight;*/ vertices[VertexIndex] += movementWeight * rBone->weights[j].weight; } } } } if (hasBones) mesh->mesh->setMorphedVertices(vertices); else mesh->mesh->setMorphedVertices(nullptr); mesh->mesh->updateVRAM(); } } void ComponentMesh::Save(JSON_Object* config) { // Determine the type of the mesh // Component has two strings, one for mesh name, and another for diffuse texture name json_object_set_string(config, "type", "mesh"); json_object_set_boolean(config, "active", is_active); if(mesh_resource_uuid != 0){ //json_object_set_number(config, "mesh_resource_uuid", mesh_resource_uuid); ResourceMesh* res_mesh = (ResourceMesh*)App->resources->getResource(mesh_resource_uuid); if(res_mesh){ json_object_set_string(config, "mesh_name", res_mesh->asset.c_str()); json_object_set_string(config, "Parent3dObject", res_mesh->Parent3dObject.c_str()); } else { json_object_set_string(config, "mesh_name", "missing reference"); json_object_set_string(config, "Parent3dObject", "missing reference"); } } json_object_set_string(config, "primitive_type", PrimitiveType2primitiveString(primitive_type).c_str()); if (mat) { //If it has a material and a diffuse texture ResourceTexture* res_diff = (ResourceTexture*)App->resources->getResource(mat->getTextureResource(DIFFUSE)); if(res_diff) json_object_dotset_string(config, "material.diffuse",res_diff->asset.c_str()); else json_object_dotset_string(config, "material.diffuse", "missing_reference"); if (mat->getShaderProgramID() != 0) { ShaderProgram* shader = mat->getShaderProgram(); if (shader) { ResourceShader* vertex = (ResourceShader*)App->resources->getResource(shader->shaderUUIDS[0]); if(vertex) json_object_dotset_string(config, "vertex_shader", vertex->asset.c_str()); ResourceShader* fragment = (ResourceShader*)App->resources->getResource(shader->shaderUUIDS[1]); if(fragment) json_object_dotset_string(config, "fragment_shader", fragment->asset.c_str()); } } } if (components_bones.size() > 0) //If it has any bone { JSON_Value* bones = json_value_init_array(); for (int i = 0; i < components_bones.size(); ++i) { JSON_Value* bone = json_value_init_object(); json_object_set_string(json_object(bone), "bone_name", bones_names[i].c_str()); json_array_append_value(json_array(bones), bone); } json_object_set_value(config, "bones", bones); } } Mesh * ComponentMesh::getMeshFromResource() const { ResourceMesh* mesh_resource = nullptr; Mesh* mesh = nullptr; if (primitive_type == Primitive_None) { mesh_resource = (ResourceMesh*)App->resources->getResource(mesh_resource_uuid); if (mesh_resource) mesh = mesh_resource->mesh; } else { mesh_resource = (ResourceMesh*)App->resources->getPrimitiveMeshResource(primitive_type); mesh = mesh_resource->mesh; } return mesh; }
31.762326
218
0.674773
project-3-bcn-2019
66af23788672a99d7178347aff100b85ac474684
454
cpp
C++
src/statistics.cpp
JulianNeeleman/kattis
035c1113ffb397c2d8538af8ba16b7ee4160393d
[ "MIT" ]
null
null
null
src/statistics.cpp
JulianNeeleman/kattis
035c1113ffb397c2d8538af8ba16b7ee4160393d
[ "MIT" ]
1
2017-05-16T15:57:29.000Z
2017-05-17T19:43:56.000Z
src/statistics.cpp
JulianNeeleman/kattis
035c1113ffb397c2d8538af8ba16b7ee4160393d
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <set> #include <vector> #include <climits> using namespace std; int main() { int n; int t = 1; while(cin >> n) { int minv = INT_MAX, maxv = -INT_MAX; for(int i = 0; i < n; i++) { int v; cin >> v; minv = min(minv, v); maxv = max(maxv, v); } cout << "Case " << t << ": " << minv << " " << maxv << " " << (maxv - minv) << endl; t++; } return 0; }
17.461538
86
0.522026
JulianNeeleman
66b55ad571caf6501a6c506b9c45f0083456ad41
3,171
cpp
C++
library/andy/points_wrapper.cpp
kwikius/tinyspline
0649081f6d6afb525c78036c458c4d6725787964
[ "MIT" ]
null
null
null
library/andy/points_wrapper.cpp
kwikius/tinyspline
0649081f6d6afb525c78036c458c4d6725787964
[ "MIT" ]
null
null
null
library/andy/points_wrapper.cpp
kwikius/tinyspline
0649081f6d6afb525c78036c458c4d6725787964
[ "MIT" ]
null
null
null
#include "points_wrapper.hpp" quan::three_d::vect<tsReal> get_result(tsDeBoorNet const & net) { assert(net.dim == 3U); return { net.result[0],net.result[1],net.result[2]}; } void interpolate(ts_points_wrapper const & points,tsBSpline & spline) { assert(ts_bspline_interpolate_cubic(points.get_points(), points.get_num_points() / 3, 3, &spline) == TS_SUCCESS); } void interpolate(std::vector<quan::three_d::vect<tsReal> > const & vect,tsBSpline & spline) { ts_points_wrapper points(vect); interpolate(points,spline); } /* evaluate the spline at u where u is between 0 and 1 */ quan::three_d::vect<tsReal> evaluate(tsBSpline const & spline,tsReal const & u) { tsDeBoorNet spline_net; assert(ts_bspline_evaluate(&spline, u, &spline_net)== TS_SUCCESS); auto const p = get_result(spline_net); ts_deboornet_free(&spline_net); return p; } namespace { void set_point(tsReal * pt, quan::three_d::vect<tsReal> const & vect) { pt[0] = vect.x; pt[1] = vect.y; pt[2] = vect.z; } tsReal* convert_to_ts_bspline_points(std::vector<quan::three_d::vect<tsReal> > const & points_in) { std::size_t const size = points_in.size(); tsReal* arr = new tsReal [3 * size]; for (size_t i = 0U; i < size; ++i){ set_point(&arr[3 *i],points_in[i]); } return arr; } } ts_points_wrapper::ts_points_wrapper(size_t num_points) :m_points{ new tsReal [num_points] } ,m_num_points{num_points}{} ts_points_wrapper::ts_points_wrapper(ts_points_wrapper const & in) : m_points{ new tsReal [in.m_num_points] } ,m_num_points{in.m_num_points} { for ( size_t i = 0U; i < m_num_points; ++i){ m_points[i] = in.m_points[i]; } } ts_points_wrapper::ts_points_wrapper(std::vector<quan::three_d::vect<tsReal> > const & vect) : m_points{convert_to_ts_bspline_points(vect)},m_num_points{vect.size() * 3}{} ts_points_wrapper::ts_points_wrapper(ts_points_wrapper && temp): m_points{temp.get_points()}, m_num_points{temp.get_num_points()} { temp.null_points(); } ts_points_wrapper::~ts_points_wrapper() { if (m_points != nullptr){ delete [] m_points;} } ts_points_wrapper & ts_points_wrapper::operator = (ts_points_wrapper const & temp) { if ( m_num_points != temp.m_num_points){ delete [] m_points; m_points = new tsReal [temp.m_num_points]; m_num_points = temp.m_num_points; } for (size_t i = 0U; i < m_num_points; ++i){ m_points[i] = temp.m_points[i]; } return *this; } ts_points_wrapper & ts_points_wrapper::operator = (std::vector<quan::three_d::vect<tsReal> > const & vect) { auto const vect_num_points = vect.size() * 3; if ( m_num_points != vect_num_points){ delete [] m_points; m_points = new tsReal [vect_num_points]; m_num_points = vect_num_points; } for (size_t i = 0U; i < m_num_points/3; ++i){ //m_points[i] = temp.m_points[i]; set_point(&m_points[3 *i],vect[i]); } return *this; } ts_points_wrapper & ts_points_wrapper::operator = (ts_points_wrapper && temp) { if (m_points != nullptr){ delete [] m_points;} m_num_points = temp.m_num_points; m_points = temp.move_points(); return *this; }
27.815789
129
0.681173
kwikius
66b5ef652eff040f99faf378f61af2fed84a5c54
1,111
hpp
C++
lib/include/fabtex/anchor.hpp
HenryAWE/FabulaeTextile
41c3b2796154b138e606ce1976e3024c3c1c89a5
[ "MIT-0", "MIT" ]
1
2022-02-04T02:14:24.000Z
2022-02-04T02:14:24.000Z
lib/include/fabtex/anchor.hpp
HenryAWE/FabulaeTextile
41c3b2796154b138e606ce1976e3024c3c1c89a5
[ "MIT-0", "MIT" ]
null
null
null
lib/include/fabtex/anchor.hpp
HenryAWE/FabulaeTextile
41c3b2796154b138e606ce1976e3024c3c1c89a5
[ "MIT-0", "MIT" ]
null
null
null
#pragma once #include <optional> #include <string> #include <fabtex/vector.hpp> namespace fabtex { class anchor { public: typedef vec<2, float> vector_type; anchor(std::string name_, vector_type position_, std::optional<std::string> target_ = std::nullopt) noexcept : m_name(std::move(name_)), m_position(position_), m_target(std::move(target_)) {} anchor(const anchor&) = default; anchor& operator=(const anchor&) = default; // getters & setters const std::string& name() const noexcept { return m_name; } void name(std::string name) { m_name.swap(name); } const vector_type& position() const noexcept { return m_position; } void position(vector_type new_position) { m_position = new_position; } const std::optional<std::string>& target() const noexcept { return m_target; } void target(std::optional<std::string> new_target) { m_target = std::move(new_target); } private: std::string m_name; vector_type m_position; std::optional<std::string> m_target; }; }
31.742857
116
0.643564
HenryAWE
66b7180b9fe0c0094148be3a6cc45721e5dee91c
901
hpp
C++
test/unit/bnf/test_rule.hpp
alandefreitas/http_proto
dc64cbdd44048a2c06671282b736f7edacb39a42
[ "BSL-1.0" ]
6
2021-11-17T03:23:50.000Z
2021-11-25T15:58:02.000Z
test/unit/bnf/test_rule.hpp
alandefreitas/http_proto
dc64cbdd44048a2c06671282b736f7edacb39a42
[ "BSL-1.0" ]
6
2021-11-17T16:13:52.000Z
2022-01-31T04:17:47.000Z
test/unit/bnf/test_rule.hpp
samd2/http_proto
486729f1a68b7611f143e18c7bae8df9b908e9aa
[ "BSL-1.0" ]
3
2021-11-17T03:01:12.000Z
2021-11-17T14:14:45.000Z
// // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.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/CPPAlliance/http_proto // #ifndef BOOST_HTTP_PROTO_TEST_RULE_HPP #define BOOST_HTTP_PROTO_TEST_RULE_HPP #include <boost/http_proto/bnf/algorithm.hpp> #include <boost/http_proto/string_view.hpp> #include "test_suite.hpp" namespace boost { namespace http_proto { namespace bnf { namespace test { template<class T> void bad(string_view s) { BOOST_TEST_THROWS( validate<T>(s), std::exception); BOOST_TEST(! is_valid<T>(s)); } template<class T> void good(string_view s) { BOOST_TEST_NO_THROW( validate<T>(s)); BOOST_TEST(is_valid<T>(s)); } } // test } // bnf } // http_proto } // boost #endif
18.770833
79
0.710322
alandefreitas
66b71de0dc96f658d2c1451c79e8f27ceab7a038
307
cc
C++
LuoGu/1403.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:10.000Z
2017-10-12T13:49:10.000Z
LuoGu/1403.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
null
null
null
LuoGu/1403.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:38.000Z
2017-10-12T13:49:38.000Z
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> using std::cin; using std::cout; using std::cerr; const char El = 10; int n; int main() { long long ans = 0; cin >> n; for (int i = 1; i <= n; ++i) ans += (long long)n / i; cout << ans << El; return 0; }
12.791667
57
0.557003
DesZou
66bd33468aa99e05e061e564a97de65b0ed255b9
12,240
cpp
C++
src/NowPlaying.cpp
khanhas/nowplaying-node
6d4455d6ab196866ad409635f6db3fd15cc96251
[ "MIT" ]
14
2018-05-27T22:01:35.000Z
2022-03-05T19:05:33.000Z
src/NowPlaying.cpp
khanhas/nowplaying-node
6d4455d6ab196866ad409635f6db3fd15cc96251
[ "MIT" ]
null
null
null
src/NowPlaying.cpp
khanhas/nowplaying-node
6d4455d6ab196866ad409635f6db3fd15cc96251
[ "MIT" ]
5
2018-06-06T03:14:37.000Z
2021-10-11T17:52:29.000Z
#include "NowPlaying.h" #include "Player.h" #include "PlayerAIMP.h" #include "PlayerCAD.h" #include "PlayerITunes.h" #include "PlayerSpotify.h" #include "PlayerWLM.h" #include "PlayerWMP.h" #include "PlayerWinamp.h" HINSTANCE g_Instance = nullptr; using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::Persistent; using v8::Value; enum PlayerName { WLM, AIMP, CAD, FOOBAR, ITUNES, MEDIAMONKEY, SPOTIFY, WINAMP, WMP }; int GetInt(Isolate *isolate, Local<Object> &obj, LPCSTR key, int defVal) { Local<Value> val = obj->Get(v8::String::NewFromUtf8(isolate, key)); return val->IsUndefined() ? defVal : (int)val->ToInteger()->Value(); } bool GetBoolean(Isolate *isolate, Local<Object> &obj, LPCSTR key, bool defVal) { Local<Value> val = obj->Get(v8::String::NewFromUtf8(isolate, key)); return val->IsUndefined() ? defVal : val->ToBoolean()->Value(); } Persistent<Function> NowPlaying::constructor; NowPlaying::NowPlaying(Player *player, std::wstring playerPath) : _player(player), trackCount(0), trackChanged(false), playerPath(playerPath) {} NowPlaying::~NowPlaying() { delete _player; } void NowPlaying::New(const FBVALUE &args) { Isolate *isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Invoked as constructor: `new NowPlaying(...)` if (args[0]->IsUndefined()) { args.GetReturnValue().Set(v8::Undefined(isolate)); return; } Player *player = nullptr; Local<Object> setting = args[0].As<Object>(); int playerName = GetInt(isolate, setting, "player", 0); switch (playerName) { case PlayerName::AIMP: { player = PlayerAIMP::Create(); break; } case PlayerName::CAD: { player = PlayerCAD::Create(); break; } case PlayerName::FOOBAR: { HWND fooWindow = FindWindow(L"foo_rainmeter_class", nullptr); if (fooWindow) { const WCHAR *error = L"Your foobar2000 plugin is out of date.\n\n" L"Do you want to update the plugin now?"; if (MessageBox(nullptr, error, L"nowplaying-node", MB_YESNO | MB_ICONINFORMATION | MB_TOPMOST) == IDYES) { ShellExecute(nullptr, L"open", L"http://github.com/poiru/foo-cad#readme", nullptr, nullptr, SW_SHOWNORMAL); } } player = PlayerCAD::Create(); break; } case PlayerName::ITUNES: { player = PlayerITunes::Create(); break; } case PlayerName::MEDIAMONKEY: { player = PlayerWinamp::Create(WA_MEDIAMONKEY); break; } case PlayerName::SPOTIFY: { player = PlayerSpotify::Create(); break; } case PlayerName::WINAMP: { player = PlayerWinamp::Create(WA_WINAMP); break; } case PlayerName::WMP: { player = PlayerWMP::Create(); break; } default: { player = PlayerWLM::Create(); if (playerName != PlayerName::WLM) { printf("Invalid player option. Fallback to WLM."); } } } player->m_fetchCover = GetBoolean(isolate, setting, "fetchCover", false); Local<Value> playerPathVal = setting->Get(v8::String::NewFromUtf8(isolate, "playerPath")); std::wstring playerPath; if (!playerPathVal->IsUndefined()) { uint16_t buffer[MAX_PATH]; playerPathVal->ToString()->Write(buffer, 0, -1, 4); playerPath = (LPCWSTR)buffer; } NowPlaying *np = new NowPlaying(player, playerPath); np->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } } void NowPlaying::Update(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->UpdateMeasure(); } void NowPlaying::GetState(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Integer::New(args.GetIsolate(), np->_player->GetState())); } void NowPlaying::GetArtist(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); uint16_t *coverted = (uint16_t *)np->_player->GetArtist(); args.GetReturnValue().Set( v8::String::NewFromTwoByte(args.GetIsolate(), coverted)); } void NowPlaying::GetAlbum(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); uint16_t *coverted = (uint16_t *)np->_player->GetAlbum(); args.GetReturnValue().Set( v8::String::NewFromTwoByte(args.GetIsolate(), coverted)); } void NowPlaying::GetTitle(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); uint16_t *coverted = (uint16_t *)np->_player->GetTitle(); args.GetReturnValue().Set( v8::String::NewFromTwoByte(args.GetIsolate(), coverted)); } void NowPlaying::GetGenre(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); uint16_t *coverted = (uint16_t *)np->_player->GetGenre(); args.GetReturnValue().Set( v8::String::NewFromTwoByte(args.GetIsolate(), coverted)); } void NowPlaying::GetCoverPath(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); uint16_t *coverted = (uint16_t *)np->_player->GetCoverPath(); args.GetReturnValue().Set( v8::String::NewFromTwoByte(args.GetIsolate(), coverted)); } void NowPlaying::GetFilePath(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); uint16_t *coverted = (uint16_t *)np->_player->GetFilePath(); args.GetReturnValue().Set( v8::String::NewFromTwoByte(args.GetIsolate(), coverted)); } void NowPlaying::GetProgress(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); double value = (double)np->_player->GetPosition() * 100.0 / (double)np->_player->GetDuration(); args.GetReturnValue().Set(v8::Number::New(args.GetIsolate(), value)); } void NowPlaying::GetDuration(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Integer::New(args.GetIsolate(), np->_player->GetDuration())); } void NowPlaying::GetPosition(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Integer::New(args.GetIsolate(), np->_player->GetPosition())); } void NowPlaying::GetRating(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Integer::New(args.GetIsolate(), np->_player->GetRating())); } void NowPlaying::GetVolume(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Integer::New(args.GetIsolate(), np->_player->GetVolume())); } void NowPlaying::GetNumber(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Integer::New(args.GetIsolate(), np->_player->GetNumber())); } void NowPlaying::GetYear(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Integer::New(args.GetIsolate(), np->_player->GetYear())); } void NowPlaying::GetShuffle(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Boolean::New(args.GetIsolate(), np->_player->GetShuffle())); } void NowPlaying::GetRepeat(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Boolean::New(args.GetIsolate(), np->_player->GetRepeat())); } void NowPlaying::GetStatus(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); args.GetReturnValue().Set( v8::Boolean::New(args.GetIsolate(), np->_player->IsInitialized())); } void NowPlaying::Pause(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->Pause(); } void NowPlaying::Play(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->Play(); } void NowPlaying::Stop(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->Stop(); } void NowPlaying::Next(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->Next(); } void NowPlaying::Previous(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->Previous(); } void NowPlaying::SetPosition(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); if (args[0]->IsNumber()) { int val = (int)args[0]->ToInteger()->Value(); np->_player->SetPosition(val); } } void NowPlaying::SetRating(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); if (args[0]->IsNumber()) { int val = (int)args[0]->ToInteger()->Value(); np->_player->SetRating(val); } } void NowPlaying::SetVolume(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); if (args[0]->IsNumber()) { int val = (int)args[0]->ToInteger()->Value(); np->_player->SetVolume(val); } } void NowPlaying::SetShuffle(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); if (args[0]->IsBoolean()) { bool val = args[0]->ToBoolean()->Value(); np->_player->SetShuffle(val); } } void NowPlaying::SetRepeat(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); if (args[0]->IsBoolean()) { bool val = args[0]->ToBoolean()->Value(); np->_player->SetRepeat(val); } } void NowPlaying::OpenPlayer(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->OpenPlayer(np->playerPath); } void NowPlaying::ClosePlayer(const FBVALUE &args) { NowPlaying *np = ObjectWrap::Unwrap<NowPlaying>(args.This()); np->_player->ClosePlayer(); } void NowPlaying::Init(Local<Object> exports) { Isolate *isolate = exports->GetIsolate(); // Prepare constructor template Local<FUNCTIONTEMPLATE> tpl = FUNCTIONTEMPLATE::New(isolate, New); tpl->SetClassName(v8::String::NewFromUtf8(isolate, "NowPlaying")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "update", Update); NODE_SET_PROTOTYPE_METHOD(tpl, "getState", GetState); NODE_SET_PROTOTYPE_METHOD(tpl, "getArtist", GetArtist); NODE_SET_PROTOTYPE_METHOD(tpl, "getAlbum", GetAlbum); NODE_SET_PROTOTYPE_METHOD(tpl, "getTitle", GetTitle); NODE_SET_PROTOTYPE_METHOD(tpl, "getGenre", GetGenre); NODE_SET_PROTOTYPE_METHOD(tpl, "getCoverPath", GetCoverPath); NODE_SET_PROTOTYPE_METHOD(tpl, "getFilePath", GetFilePath); NODE_SET_PROTOTYPE_METHOD(tpl, "getDuration", GetDuration); NODE_SET_PROTOTYPE_METHOD(tpl, "getPosition", GetPosition); NODE_SET_PROTOTYPE_METHOD(tpl, "getProgress", GetProgress); NODE_SET_PROTOTYPE_METHOD(tpl, "getRating", GetRating); NODE_SET_PROTOTYPE_METHOD(tpl, "getVolume", GetVolume); NODE_SET_PROTOTYPE_METHOD(tpl, "getNumber", GetNumber); NODE_SET_PROTOTYPE_METHOD(tpl, "getYear", GetYear); NODE_SET_PROTOTYPE_METHOD(tpl, "getShuffle", GetShuffle); NODE_SET_PROTOTYPE_METHOD(tpl, "getRepeat", GetRepeat); NODE_SET_PROTOTYPE_METHOD(tpl, "getStatus", GetStatus); NODE_SET_PROTOTYPE_METHOD(tpl, "pause", Pause); NODE_SET_PROTOTYPE_METHOD(tpl, "play", Play); NODE_SET_PROTOTYPE_METHOD(tpl, "stop", Stop); NODE_SET_PROTOTYPE_METHOD(tpl, "next", Next); NODE_SET_PROTOTYPE_METHOD(tpl, "previous", Previous); NODE_SET_PROTOTYPE_METHOD(tpl, "setPosition", SetPosition); NODE_SET_PROTOTYPE_METHOD(tpl, "setRating", SetRating); NODE_SET_PROTOTYPE_METHOD(tpl, "setVolume", SetVolume); NODE_SET_PROTOTYPE_METHOD(tpl, "setShuffle", SetShuffle); NODE_SET_PROTOTYPE_METHOD(tpl, "setRepeat", SetRepeat); NODE_SET_PROTOTYPE_METHOD(tpl, "openPlayer", OpenPlayer); NODE_SET_PROTOTYPE_METHOD(tpl, "closePlayer", ClosePlayer); constructor.Reset(isolate, tpl->GetFunction()); exports->Set(v8::String::NewFromUtf8(isolate, "NowPlaying"), tpl->GetFunction()); }
33.905817
80
0.686275
khanhas
66bd9221ab5d0c6bc1afbd775f6405900558f219
53
hpp
C++
src/boost_spirit_home_classic_core_parser.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_spirit_home_classic_core_parser.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_spirit_home_classic_core_parser.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/spirit/home/classic/core/parser.hpp>
26.5
52
0.792453
miathedev
66c070de507f1d95476be1904a8e85e8ed96846e
118
hpp
C++
sdl/CMakeConfig.hpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/CMakeConfig.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/CMakeConfig.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
#ifndef LW__CMAKECONFIG_HPP #define LW__CMAKECONFIG_HPP #define PROJECT_SOURCE_DIR "/Users/graehl/c/hyp/sdl" #endif
16.857143
52
0.822034
sdl-research
66c1f01d9bd7b7dc562d4035d4d3c0238822530b
2,457
cc
C++
16/main.cc
buyno/CodingInterview2
9765010e3e8aa96df5cc0456f616fd764a4385a8
[ "Apache-2.0" ]
null
null
null
16/main.cc
buyno/CodingInterview2
9765010e3e8aa96df5cc0456f616fd764a4385a8
[ "Apache-2.0" ]
null
null
null
16/main.cc
buyno/CodingInterview2
9765010e3e8aa96df5cc0456f616fd764a4385a8
[ "Apache-2.0" ]
null
null
null
// 数值的整数次方,不考虑大数 #include <assert.h> #include <stdio.h> #include <iostream> using namespace std; // double power(int base, int component) // { // if (base == 0) // return 0; // if (component == 0) // return 1; // if (base != 0 && component < 0) // { // component = -component; // double res = 1; // for (int i = 1; i <= component; i++) // { // res = res * base; // } // return 1 / res; // } // double res = 1; // for (int i = 1; i <= component; i++) // { // res = res * base; // } // return res; // } double power(int x, int n) { if (x == 0) { return 0; } if (n == 0) { return 1; } int negative = 0; if (n < 0) { negative = 1; n = -n; } int index = 1; double tmp = x; while (index * 2 < n) { tmp = tmp * tmp; index *= 2; } for (int i = 0; i < n - index; i++) { tmp *= x; } if (negative == 1) { return 1 / tmp; } return tmp; } class Solution { public: double myPow(double x, int n) { if (n == 0) { return 1; } //+- int positive = 1; long temp; if (n < 0) { positive = 0; temp = n; temp = -temp; //直接取反会越界 } else { temp = n; } if (temp == 1) { return positive ? x : 1.0 / x; } double result = 1; result = myPow(x, temp / 2); result *= result; if (temp % 2) { result *= x; } // cout << (positive ? result : 1.0 / result) << endl; return positive ? result : 1.0 / result; } }; int main() { // assert(power(2, 3) == 8); // assert(power(2, 0) == 1); // assert(power(2, -1) == 0.5); // assert(power(0, 3) == 0); // assert(power(0, -1) == 0); // assert(power(0, 0) == 0); // assert(power(-2, 0) == 1); // assert(power(-2, 3) == -8); // assert(power(-2, -2) == 0.25); Solution s; assert(s.myPow(2, 3) == 8); assert(s.myPow(2, -3) == 1.0 / 8); // cout << 1.0 / 8 << endl; assert(s.myPow(2, 10) == 1024); assert(s.myPow(0.5, 2) == 0.25); assert(s.myPow(123, 0) == 1); assert(s.myPow(1, 200) == 1); assert(s.myPow(1, -2147483648) == 1); }
20.139344
62
0.393162
buyno
66c5a897bb68a4e087ea09b4b5d6fe3ab72eb017
16,514
cpp
C++
fmm.cpp
rioyokotalab/gemsfmm
f27a8cbd122c4e507eb4a3272a5b925512a13100
[ "MIT" ]
8
2016-03-02T10:29:41.000Z
2022-01-07T15:59:16.000Z
fmm.cpp
rioyokotalab/gemsfmm
f27a8cbd122c4e507eb4a3272a5b925512a13100
[ "MIT" ]
3
2020-07-09T22:04:29.000Z
2021-02-28T12:50:58.000Z
fmm.cpp
rioyokotalab/gemsfmm
f27a8cbd122c4e507eb4a3272a5b925512a13100
[ "MIT" ]
10
2015-09-30T17:50:51.000Z
2021-12-20T20:42:12.000Z
#include "fmm.h" // Dynamically allocate memory for non-empty boxes void FmmSystem::allocate() { int i,j; particleOffset = new int* [2]; for( i=0; i<2; i++ ) particleOffset[i] = new int [numBoxIndexLeaf]; boxIndexMask = new int [numBoxIndexFull]; boxIndexFull = new int [numBoxIndexTotal]; levelOffset = new int [maxLevel]; numInteraction = new int [numBoxIndexLeaf]; interactionList = new int [numBoxIndexLeaf][maxM2LInteraction]; boxOffsetStart = new int [numBoxIndexLeaf]; boxOffsetEnd = new int [numBoxIndexLeaf]; factorial = new float [4*numExpansion2]; Lnm = new std::complex<double> [numBoxIndexLeaf][numCoefficients]; LnmOld = new std::complex<double> [numBoxIndexLeaf][numCoefficients]; Mnm = new std::complex<double> [numBoxIndexTotal][numCoefficients]; Ynm = new std::complex<double> [4*numExpansion2]; Dnm = new std::complex<double>** [2*numRelativeBox]; for( i=0; i<2*numRelativeBox; i++ ) { Dnm[i] = new std::complex<double>* [numExpansions]; for( j=0; j<numExpansions; j++ ) Dnm[i][j] = new std::complex<double> [numExpansion2]; } } // Free memory corresponding to allocate() void FmmSystem::deallocate() { int i,j; for( i=0; i<2; i++ ) delete[] particleOffset[i]; delete[] particleOffset; delete[] boxIndexMask; delete[] boxIndexFull; delete[] levelOffset; delete[] numInteraction; delete[] interactionList; delete[] boxOffsetStart; delete[] boxOffsetEnd; delete[] mortonIndex; delete[] sortValue; delete[] sortIndex; delete[] sortValueBuffer; delete[] sortIndexBuffer; delete[] factorial; delete[] Lnm; delete[] LnmOld; delete[] Mnm; delete[] Ynm; for( i=0; i<2*numRelativeBox; i++ ) { for( j=0; j<numExpansions; j++ ) delete[] Dnm[i][j]; delete[] Dnm[i]; } delete[] Dnm; } // Calculate range of FMM domain from particle positions void FmmSystem::setDomainSize(int numParticles) { int i; float xmin,xmax,ymin,ymax,zmin,zmax; // Initialize the minimum and maximum values xmin = 1000000; xmax = -1000000; ymin = 1000000; ymax = -1000000; zmin = 1000000; zmax = -1000000; // Calculate the minimum and maximum of particle positions for( i=0; i<numParticles; i++ ) { xmin = std::min(xmin,bodyPos[i].x); xmax = std::max(xmax,bodyPos[i].x); ymin = std::min(ymin,bodyPos[i].y); ymax = std::max(ymax,bodyPos[i].y); zmin = std::min(zmin,bodyPos[i].z); zmax = std::max(zmax,bodyPos[i].z); } boxMin.x = xmin; boxMin.y = ymin; boxMin.z = zmin; // Calculat the domain size rootBoxSize = 0; rootBoxSize = std::max(rootBoxSize,xmax-xmin); rootBoxSize = std::max(rootBoxSize,ymax-ymin); rootBoxSize = std::max(rootBoxSize,zmax-zmin); rootBoxSize *= 1.00001; // Keep particle on the edge from falling out } // Calculate leaf level optimally from tabulated theshold values of numParticles void FmmSystem::setOptimumLevel(int numParticles) { // float level_switch[6]={2e4,1.7e5,1.3e6,1e7,7e7,5e8}; // cpu-tree // float level_switch[6]={1.3e4,1e5,7e5,5e6,3e7,1.5e8}; // cpu-fmm // float level_switch[6]={1e5,5e5,5e6,3e7,2e8,1.5e9}; // gpu-tree float level_switch[6]={1e5,7e5,7e6,5e7,3e8,2e9}; // gpu-fmm maxLevel = 1; if( numParticles < level_switch[0] ) { maxLevel += 1; } else if( numParticles < level_switch[1] ) { maxLevel += 2; } else if( numParticles < level_switch[2] ) { maxLevel += 3; } else if( numParticles < level_switch[3] ) { maxLevel += 4; } else if( numParticles < level_switch[4] ) { maxLevel += 5; } else if( numParticles < level_switch[5] ) { maxLevel += 6; } else { maxLevel += 7; } printf("level : %d\n",maxLevel); numBoxIndexFull = 1 << 3*maxLevel; } // Generate Morton index from particle coordinates void FmmSystem::morton(int numParticles) { int i,j,nx,ny,nz,boxIndex; float boxSize; boxSize = rootBoxSize/(1 << maxLevel); for( j=0; j<numParticles; j++ ) { nx = int((bodyPos[j].x-boxMin.x)/boxSize); ny = int((bodyPos[j].y-boxMin.y)/boxSize); nz = int((bodyPos[j].z-boxMin.z)/boxSize); if( nx >= (1 << maxLevel) ) nx--; if( ny >= (1 << maxLevel) ) ny--; if( nz >= (1 << maxLevel) ) nz--; boxIndex = 0; for( i=0; i<maxLevel; i++ ) { boxIndex += nx%2 << (3*i+1); nx >>= 1; boxIndex += ny%2 << (3*i); ny >>= 1; boxIndex += nz%2 << (3*i+2); nz >>= 1; } mortonIndex[j] = boxIndex; } } // Generate Morton index for a box center to use in M2L translation void FmmSystem::morton1(vec3<int> boxIndex3D, int& boxIndex, int numLevel) { int i,nx,ny,nz; boxIndex = 0; for( i=0; i<numLevel; i++ ) { nx = boxIndex3D.x%2; boxIndex3D.x >>= 1; boxIndex += nx*(1 << (3*i+1)); ny = boxIndex3D.y%2; boxIndex3D.y >>= 1; boxIndex += ny*(1 << (3*i)); nz = boxIndex3D.z%2; boxIndex3D.z >>= 1; boxIndex += nz*(1 << (3*i+2)); } } // Returns 3D box index from Morton index void FmmSystem::unmorton(int boxIndex, vec3<int>& boxIndex3D) { int i,j,k,n,mortonIndex3D[3]; for( i=0; i<3; i++ ) mortonIndex3D[i] = 0; n = boxIndex; k = 0; i = 0; while( n != 0 ) { j = 2-k; mortonIndex3D[j] += (n%2)*(1 << i); n >>= 1; k = (k+1)%3; if( k == 0 ) i++; } boxIndex3D.x = mortonIndex3D[1]; boxIndex3D.y = mortonIndex3D[2]; boxIndex3D.z = mortonIndex3D[0]; } // Prepare for binning particles by first sorting the Morton index void FmmSystem::sort(int numParticles) { int i; for( i=0; i<numBoxIndexFull; i++ ) sortIndexBuffer[i] = 0; for( i=0; i<numParticles; i++ ) sortIndexBuffer[sortValue[i]]++; for( i=1; i<numBoxIndexFull; i++ ) sortIndexBuffer[i] += sortIndexBuffer[i-1]; for( i=numParticles-1; i>=0; i-- ) { sortIndexBuffer[sortValue[i]]--; sortValueBuffer[sortIndexBuffer[sortValue[i]]] = sortValue[i]; sortIndex[sortIndexBuffer[sortValue[i]]] = i; } for( i=0; i<numParticles; i++ ) sortValue[i] = sortValueBuffer[i]; } // Sort the particles according to the previously sorted Morton index void FmmSystem::sortParticles(int& numParticles) { int i; permutation = new int [numParticles]; morton(numParticles); for( i=0; i<numParticles; i++ ) { sortValue[i] = mortonIndex[i]; sortIndex[i] = i; } sort(numParticles); for( i=0; i<numParticles; i++ ) { permutation[i] = sortIndex[i]; } vec4<float> *sortBuffer; sortBuffer = new vec4<float> [numParticles]; for( i=0; i<numParticles; i++ ) { sortBuffer[i] = bodyPos[permutation[i]]; } for( i=0; i<numParticles; i++ ) { bodyPos[i] = sortBuffer[i]; } delete[] sortBuffer; } // Unsorting particles upon exit (optional) void FmmSystem::unsortParticles(int& numParticles) { int i; vec3<float> *sortBuffer; sortBuffer = new vec3<float> [numParticles]; for( i=0; i<numParticles; i++ ) { sortBuffer[permutation[i]] = bodyAccel[i]; } for( i=0; i<numParticles; i++ ) { bodyAccel[i] = sortBuffer[i]; } delete[] sortBuffer; vec4<float> *sortBuffer2; sortBuffer2 = new vec4<float> [numParticles]; for( i=0; i<numParticles; i++ ) { sortBuffer2[permutation[i]] = bodyPos[i]; } for( i=0; i<numParticles; i++ ) { bodyPos[i] = sortBuffer2[i]; } delete[] sortBuffer2; delete[] permutation; } // Estimate storage requirements adaptively to skip empty boxes void FmmSystem::countNonEmptyBoxes(int numParticles) { int i,currentIndex,numLevel; morton(numParticles); for( i=0; i<numParticles; i++ ) { sortValue[i] = mortonIndex[i]; sortIndex[i] = i; } sort(numParticles); // Count non-empty boxes at leaf level numBoxIndexLeaf = 0; // counter currentIndex = -1; for( i=0; i<numParticles; i++ ) { if( sortValue[i] != currentIndex ) { numBoxIndexLeaf++; currentIndex = sortValue[i]; } } // Count non-empty boxes for all levels numBoxIndexTotal = numBoxIndexLeaf; for( numLevel=maxLevel-1; numLevel>=2; numLevel-- ) { currentIndex = -1; for( i=0; i<numParticles; i++ ) { if( sortValue[i]/(1 << 3*(maxLevel-numLevel)) != currentIndex ) { numBoxIndexTotal++; currentIndex = sortValue[i]/(1 << 3*(maxLevel-numLevel)); } } } } // Obtain two-way link list between non-empty and full box indices, and offset of particle index void FmmSystem::getBoxData(int numParticles, int& numBoxIndex) { int i,currentIndex; morton(numParticles); numBoxIndex = 0; currentIndex = -1; for( i=0; i<numBoxIndexFull; i++ ) boxIndexMask[i] = -1; for( i=0; i<numParticles; i++ ) { if( mortonIndex[i] != currentIndex ) { boxIndexMask[mortonIndex[i]] = numBoxIndex; boxIndexFull[numBoxIndex] = mortonIndex[i]; particleOffset[0][numBoxIndex] = i; if( numBoxIndex > 0 ) particleOffset[1][numBoxIndex-1] = i-1; currentIndex = mortonIndex[i]; numBoxIndex++; } } particleOffset[1][numBoxIndex-1] = numParticles-1; } // Propagate non-empty/full link list to parent boxes void FmmSystem::getBoxDataOfParent(int& numBoxIndex, int numLevel, int treeOrFMM) { int i,numBoxIndexOld,currentIndex,boxIndex; levelOffset[numLevel-1] = levelOffset[numLevel]+numBoxIndex; numBoxIndexOld = numBoxIndex; numBoxIndex = 0; currentIndex = -1; for( i=0; i<numBoxIndexFull; i++ ) boxIndexMask[i] = -1; for( i=0; i<numBoxIndexOld; i++ ) { boxIndex = i+levelOffset[numLevel]; if( currentIndex != boxIndexFull[boxIndex]/8 ) { currentIndex = boxIndexFull[boxIndex]/8; boxIndexMask[currentIndex] = numBoxIndex; boxIndexFull[numBoxIndex+levelOffset[numLevel-1]] = currentIndex; if( treeOrFMM == 0 ) { particleOffset[0][numBoxIndex] = particleOffset[0][i]; if( numBoxIndex > 0 ) particleOffset[1][numBoxIndex-1] = particleOffset[0][i]-1; } numBoxIndex++; } } if( treeOrFMM == 0 ) particleOffset[1][numBoxIndex-1] = particleOffset[1][numBoxIndexOld-1]; } // Recalculate non-empty box index for current level void FmmSystem::getBoxIndexMask(int numBoxIndex, int numLevel) { int i,boxIndex; for( i=0; i<numBoxIndexFull; i++ ) boxIndexMask[i] = -1; for( i=0; i<numBoxIndex; i++ ) { boxIndex = i+levelOffset[numLevel-1]; boxIndexMask[boxIndexFull[boxIndex]] = i; } } // Calculate the interaction list for P2P and M2L void FmmSystem::getInteractionList(int numBoxIndex, int numLevel, int interactionType) { int jxmin,jxmax,jymin,jymax,jzmin,jzmax,ii,ib,jj,jb,ix,iy,iz,jx,jy,jz,boxIndex; int ixp,iyp,izp,jxp,jyp,jzp; vec3<int> boxIndex3D; // Initialize the minimum and maximum values jxmin = 1000000; jxmax = -1000000; jymin = 1000000; jymax = -1000000; jzmin = 1000000; jzmax = -1000000; // Calculate the minimum and maximum of boxIndex3D for( jj=0; jj<numBoxIndex; jj++ ) { jb = jj+levelOffset[numLevel-1]; unmorton(boxIndexFull[jb],boxIndex3D); jxmin = std::min(jxmin,boxIndex3D.x); jxmax = std::max(jxmax,boxIndex3D.x); jymin = std::min(jymin,boxIndex3D.y); jymax = std::max(jymax,boxIndex3D.y); jzmin = std::min(jzmin,boxIndex3D.z); jzmax = std::max(jzmax,boxIndex3D.z); } // P2P if( interactionType == 0 ) { for( ii=0; ii<numBoxIndex; ii++ ) { ib = ii+levelOffset[numLevel-1]; numInteraction[ii] = 0; unmorton(boxIndexFull[ib],boxIndex3D); ix = boxIndex3D.x; iy = boxIndex3D.y; iz = boxIndex3D.z; for( jx=std::max(ix-1,jxmin); jx<=std::min(ix+1,jxmax); jx++ ) { for( jy=std::max(iy-1,jymin); jy<=std::min(iy+1,jymax); jy++ ) { for( jz=std::max(iz-1,jzmin); jz<=std::min(iz+1,jzmax); jz++ ) { boxIndex3D.x = jx; boxIndex3D.y = jy; boxIndex3D.z = jz; morton1(boxIndex3D,boxIndex,numLevel); jj = boxIndexMask[boxIndex]; if( jj != -1 ) { interactionList[ii][numInteraction[ii]] = jj; numInteraction[ii]++; } } } } } // M2L at level 2 } else if( interactionType == 1 ) { for( ii=0; ii<numBoxIndex; ii++ ) { ib = ii+levelOffset[numLevel-1]; numInteraction[ii] = 0; unmorton(boxIndexFull[ib],boxIndex3D); ix = boxIndex3D.x; iy = boxIndex3D.y; iz = boxIndex3D.z; for( jj=0; jj<numBoxIndex; jj++ ) { jb = jj+levelOffset[numLevel-1]; unmorton(boxIndexFull[jb],boxIndex3D); jx = boxIndex3D.x; jy = boxIndex3D.y; jz = boxIndex3D.z; if( jx < ix-1 || ix+1 < jx || jy < iy-1 || iy+1 < jy || jz < iz-1 || iz+1 < jz ) { interactionList[ii][numInteraction[ii]] = jj; numInteraction[ii]++; } } } // M2L at lower levels } else if( interactionType == 2 ) { for( ii=0; ii<numBoxIndex; ii++ ) { ib = ii+levelOffset[numLevel-1]; numInteraction[ii] = 0; unmorton(boxIndexFull[ib],boxIndex3D); ix = boxIndex3D.x; iy = boxIndex3D.y; iz = boxIndex3D.z; ixp = (ix+2)/2; iyp = (iy+2)/2; izp = (iz+2)/2; for( jxp=ixp-1; jxp<=ixp+1; jxp++ ) { for( jyp=iyp-1; jyp<=iyp+1; jyp++ ) { for( jzp=izp-1; jzp<=izp+1; jzp++ ) { for( jx=std::max(2*jxp-2,jxmin); jx<=std::min(2*jxp-1,jxmax); jx++ ) { for( jy=std::max(2*jyp-2,jymin); jy<=std::min(2*jyp-1,jymax); jy++ ) { for( jz=std::max(2*jzp-2,jzmin); jz<=std::min(2*jzp-1,jzmax); jz++ ) { if( jx < ix-1 || ix+1 < jx || jy < iy-1 || iy+1 < jy || jz < iz-1 || iz+1 < jz ) { boxIndex3D.x = jx; boxIndex3D.y = jy; boxIndex3D.z = jz; morton1(boxIndex3D,boxIndex,numLevel); jj = boxIndexMask[boxIndex]; if( jj != -1 ) { interactionList[ii][numInteraction[ii]] = jj; numInteraction[ii]++; } } } } } } } } } } } // Main part of the FMM/treecode void FmmSystem::fmmMain(int numParticles, int treeOrFMM){ int i,numLevel,numBoxIndex,numBoxIndexOld; FmmKernel kernel; log_time(0); for( i=0; i<9; i++ ) t[i] = 0; mortonIndex = new int [numParticles]; sortValue = new int [numParticles]; sortIndex = new int [numParticles]; sortValueBuffer = new int [numParticles]; sortIndexBuffer = new int [numParticles]; setDomainSize(numParticles); setOptimumLevel(numParticles); log_time(7); sortParticles(numParticles); log_time(6); countNonEmptyBoxes(numParticles); allocate(); numLevel = maxLevel; levelOffset[numLevel-1] = 0; kernel.precalc(); getBoxData(numParticles,numBoxIndex); // P2P getInteractionList(numBoxIndex,numLevel,0); for( i=0; i<numParticles; i++ ) { bodyAccel[i].x = 0; bodyAccel[i].y = 0; bodyAccel[i].z = 0; } log_time(7); kernel.p2p(numBoxIndex); log_time(0); numLevel = maxLevel; // P2M kernel.p2m(numBoxIndex); log_time(1); if(maxLevel > 2) { for( numLevel=maxLevel-1; numLevel>=2; numLevel-- ) { if( treeOrFMM == 0 ) { // M2P at lower levels getInteractionList(numBoxIndex,numLevel+1,2); log_time(7); kernel.m2p(numBoxIndex,numLevel+1); log_time(3); } // M2M numBoxIndexOld = numBoxIndex; getBoxDataOfParent(numBoxIndex,numLevel,treeOrFMM); log_time(7); kernel.m2m(numBoxIndex,numBoxIndexOld,numLevel); log_time(2); } numLevel = 2; } else { getBoxIndexMask(numBoxIndex,numLevel); } if( treeOrFMM == 0 ) { // M2P at level 2 getInteractionList(numBoxIndex,numLevel,1); log_time(7); kernel.m2p(numBoxIndex,numLevel); log_time(3); } else { // M2L at level 2 getInteractionList(numBoxIndex,numLevel,1); log_time(7); kernel.m2l(numBoxIndex,numLevel); log_time(3); // L2L if( maxLevel > 2 ) { for( numLevel=3; numLevel<=maxLevel; numLevel++ ) { numBoxIndex = levelOffset[numLevel-2]-levelOffset[numLevel-1]; log_time(7); kernel.l2l(numBoxIndex,numLevel); log_time(4); getBoxIndexMask(numBoxIndex,numLevel); // M2L at lower levels getInteractionList(numBoxIndex,numLevel,2); log_time(7); kernel.m2l(numBoxIndex,numLevel); log_time(3); } numLevel = maxLevel; } // L2P log_time(7); kernel.l2p(numBoxIndex); log_time(5); } unsortParticles(numParticles); deallocate(); log_time(7); }
27.386401
100
0.613419
rioyokotalab
66cb942809d9646146bd64971e86f3b9af84a997
1,059
hpp
C++
src/util/error.hpp
GLorieul/FluidBoxPublic
a026e16cf5c6efc606832a9f5bdac3738e0062e3
[ "MIT" ]
null
null
null
src/util/error.hpp
GLorieul/FluidBoxPublic
a026e16cf5c6efc606832a9f5bdac3738e0062e3
[ "MIT" ]
null
null
null
src/util/error.hpp
GLorieul/FluidBoxPublic
a026e16cf5c6efc606832a9f5bdac3738e0062e3
[ "MIT" ]
null
null
null
#ifndef UTIL_ERROR___HPP #define UTIL_ERROR___HPP namespace fb { class Distance; class Field; [[noreturn]] void raiseError(const std::string file, const int lineNb, const std::string functionName, const std::string message); void assume(const std::string file, const int lineNb, const std::string functionName, bool proposition, const std::string messageIfFalse=""); void assume_isNotThreeDimensional(const std::string file, const int lineNb, const std::string functionName, const Field& field); void assume_gridIsIsotropic(const std::string file, const int lineNb, const std::string functionName, const Distance& gridSpacing); void assume_shareTheSameDomain(const std::string file, const int lineNb, const std::string functionName, const Field& A, const Field& B); void assume_shareTheSameAnchor(const std::string file, const int lineNb, const std::string functionName, const Field& A, const Field& B); } #endif
33.09375
80
0.685552
GLorieul
66d3251f23ba6a2cc9723e16e6394877711bf6f2
446
cpp
C++
tests/EmuTest.cpp
ammubhave/emu
ff9501719f3cc53207a8931d85c19d24c86dccdc
[ "MIT" ]
null
null
null
tests/EmuTest.cpp
ammubhave/emu
ff9501719f3cc53207a8931d85c19d24c86dccdc
[ "MIT" ]
null
null
null
tests/EmuTest.cpp
ammubhave/emu
ff9501719f3cc53207a8931d85c19d24c86dccdc
[ "MIT" ]
null
null
null
// #define CATCH_CONFIG_MAIN // #include <catch2/catch_all.hpp> // using namespace Catch; // TEST_CASE("Quick check", "[main]") { // std::vector<double> values{1, 2., 3.}; // auto [mean, moment] = std::make_tuple(2.0, 5); // REQUIRE(mean == 2.0); // REQUIRE(moment == Approx(4.666666)); // } #include "gtest/gtest.h" // int main(int argc, char **argv) { // ::testing::InitGoogleTest(&argc, argv); // return RUN_ALL_TESTS(); // }
22.3
51
0.607623
ammubhave
202d6fb2e8af1224572f81f6738983c8b8536d35
13,558
cpp
C++
src/tokens/tokendb.cpp
Chellit/Chellit
7d804cfc64b4e91234b68f14b82f12c752eb6aae
[ "MIT" ]
2
2021-02-01T08:29:18.000Z
2021-06-28T23:45:28.000Z
src/tokens/tokendb.cpp
Chellit/Chellit
7d804cfc64b4e91234b68f14b82f12c752eb6aae
[ "MIT" ]
null
null
null
src/tokens/tokendb.cpp
Chellit/Chellit
7d804cfc64b4e91234b68f14b82f12c752eb6aae
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2019 The Raven Core developers // Copyright (c) 2020 The Chellit Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util.h> #include <consensus/params.h> #include <script/ismine.h> #include <tinyformat.h> #include "tokendb.h" #include "tokens.h" #include "validation.h" #include <boost/thread.hpp> static const char TOKEN_FLAG = 'T'; static const char TOKEN_ADDRESS_QUANTITY_FLAG = 'B'; static const char ADDRESS_TOKEN_QUANTITY_FLAG = 'C'; static const char MY_TOKEN_FLAG = 'M'; static const char BLOCK_TOKEN_UNDO_DATA = 'U'; static const char MEMPOOL_REISSUED_TX = 'Z'; static size_t MAX_DATABASE_RESULTS = 50000; CTokensDB::CTokensDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "tokens", nCacheSize, fMemory, fWipe) { } bool CTokensDB::WriteTokenData(const CNewToken &token, const int nHeight, const uint256& blockHash) { CDatabasedTokenData data(token, nHeight, blockHash); return Write(std::make_pair(TOKEN_FLAG, token.strName), data); } bool CTokensDB::WriteTokenAddressQuantity(const std::string &tokenName, const std::string &address, const CAmount &quantity) { return Write(std::make_pair(TOKEN_ADDRESS_QUANTITY_FLAG, std::make_pair(tokenName, address)), quantity); } bool CTokensDB::WriteAddressTokenQuantity(const std::string &address, const std::string &tokenName, const CAmount& quantity) { return Write(std::make_pair(ADDRESS_TOKEN_QUANTITY_FLAG, std::make_pair(address, tokenName)), quantity); } bool CTokensDB::ReadTokenData(const std::string& strName, CNewToken& token, int& nHeight, uint256& blockHash) { CDatabasedTokenData data; bool ret = Read(std::make_pair(TOKEN_FLAG, strName), data); if (ret) { token = data.token; nHeight = data.nHeight; blockHash = data.blockHash; } return ret; } bool CTokensDB::ReadTokenAddressQuantity(const std::string& tokenName, const std::string& address, CAmount& quantity) { return Read(std::make_pair(TOKEN_ADDRESS_QUANTITY_FLAG, std::make_pair(tokenName, address)), quantity); } bool CTokensDB::ReadAddressTokenQuantity(const std::string &address, const std::string &tokenName, CAmount& quantity) { return Read(std::make_pair(ADDRESS_TOKEN_QUANTITY_FLAG, std::make_pair(address, tokenName)), quantity); } bool CTokensDB::EraseTokenData(const std::string& tokenName) { return Erase(std::make_pair(TOKEN_FLAG, tokenName)); } bool CTokensDB::EraseMyTokenData(const std::string& tokenName) { return Erase(std::make_pair(MY_TOKEN_FLAG, tokenName)); } bool CTokensDB::EraseTokenAddressQuantity(const std::string &tokenName, const std::string &address) { return Erase(std::make_pair(TOKEN_ADDRESS_QUANTITY_FLAG, std::make_pair(tokenName, address))); } bool CTokensDB::EraseAddressTokenQuantity(const std::string &address, const std::string &tokenName) { return Erase(std::make_pair(ADDRESS_TOKEN_QUANTITY_FLAG, std::make_pair(address, tokenName))); } bool EraseAddressTokenQuantity(const std::string &address, const std::string &tokenName); bool CTokensDB::WriteBlockUndoTokenData(const uint256& blockhash, const std::vector<std::pair<std::string, CBlockTokenUndo> >& tokenUndoData) { return Write(std::make_pair(BLOCK_TOKEN_UNDO_DATA, blockhash), tokenUndoData); } bool CTokensDB::ReadBlockUndoTokenData(const uint256 &blockhash, std::vector<std::pair<std::string, CBlockTokenUndo> > &tokenUndoData) { // If it exists, return the read value. if (Exists(std::make_pair(BLOCK_TOKEN_UNDO_DATA, blockhash))) return Read(std::make_pair(BLOCK_TOKEN_UNDO_DATA, blockhash), tokenUndoData); // If it doesn't exist, we just return true because we don't want to fail just because it didn't exist in the db return true; } bool CTokensDB::WriteReissuedMempoolState() { return Write(MEMPOOL_REISSUED_TX, mapReissuedTokens); } bool CTokensDB::ReadReissuedMempoolState() { mapReissuedTokens.clear(); mapReissuedTx.clear(); // If it exists, return the read value. bool rv = Read(MEMPOOL_REISSUED_TX, mapReissuedTokens); if (rv) { for (auto pair : mapReissuedTokens) mapReissuedTx.insert(std::make_pair(pair.second, pair.first)); } return rv; } bool CTokensDB::LoadTokens() { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(std::make_pair(TOKEN_FLAG, std::string())); // Load tokens while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, std::string> key; if (pcursor->GetKey(key) && key.first == TOKEN_FLAG) { CDatabasedTokenData data; if (pcursor->GetValue(data)) { ptokensCache->Put(data.token.strName, data); pcursor->Next(); // Loaded enough from database to have in memory. // No need to load everything if it is just going to be removed from the cache if (ptokensCache->Size() == (ptokensCache->MaxSize() / 2)) break; } else { return error("%s: failed to read token", __func__); } } else { break; } } if (fTokenIndex) { std::unique_ptr<CDBIterator> pcursor3(NewIterator()); pcursor3->Seek(std::make_pair(TOKEN_ADDRESS_QUANTITY_FLAG, std::make_pair(std::string(), std::string()))); // Load mapTokenAddressAmount while (pcursor3->Valid()) { boost::this_thread::interruption_point(); std::pair<char, std::pair<std::string, std::string> > key; // <Token Name, Address> -> Quantity if (pcursor3->GetKey(key) && key.first == TOKEN_ADDRESS_QUANTITY_FLAG) { CAmount value; if (pcursor3->GetValue(value)) { ptokens->mapTokensAddressAmount.insert( std::make_pair(std::make_pair(key.second.first, key.second.second), value)); if (ptokens->mapTokensAddressAmount.size() > MAX_CACHE_TOKENS_SIZE) break; pcursor3->Next(); } else { return error("%s: failed to read my address quantity from database", __func__); } } else { break; } } } return true; } bool CTokensDB::TokenDir(std::vector<CDatabasedTokenData>& tokens, const std::string filter, const size_t count, const long start) { FlushStateToDisk(); std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(std::make_pair(TOKEN_FLAG, std::string())); auto prefix = filter; bool wildcard = prefix.back() == '*'; if (wildcard) prefix.pop_back(); size_t skip = 0; if (start >= 0) { skip = start; } else { // compute table size for backwards offset long table_size = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, std::string> key; if (pcursor->GetKey(key) && key.first == TOKEN_FLAG) { if (prefix == "" || (wildcard && key.second.find(prefix) == 0) || (!wildcard && key.second == prefix)) { table_size += 1; } } pcursor->Next(); } skip = table_size + start; pcursor->SeekToFirst(); } size_t loaded = 0; size_t offset = 0; // Load tokens while (pcursor->Valid() && loaded < count) { boost::this_thread::interruption_point(); std::pair<char, std::string> key; if (pcursor->GetKey(key) && key.first == TOKEN_FLAG) { if (prefix == "" || (wildcard && key.second.find(prefix) == 0) || (!wildcard && key.second == prefix)) { if (offset < skip) { offset += 1; } else { CDatabasedTokenData data; if (pcursor->GetValue(data)) { tokens.push_back(data); loaded += 1; } else { return error("%s: failed to read token", __func__); } } } pcursor->Next(); } else { break; } } return true; } bool CTokensDB::AddressDir(std::vector<std::pair<std::string, CAmount> >& vecTokenAmount, int& totalEntries, const bool& fGetTotal, const std::string& address, const size_t count, const long start) { FlushStateToDisk(); std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(std::make_pair(ADDRESS_TOKEN_QUANTITY_FLAG, std::make_pair(address, std::string()))); if (fGetTotal) { totalEntries = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, std::pair<std::string, std::string> > key; if (pcursor->GetKey(key) && key.first == ADDRESS_TOKEN_QUANTITY_FLAG && key.second.first == address) { totalEntries++; } pcursor->Next(); } return true; } size_t skip = 0; if (start >= 0) { skip = start; } else { // compute table size for backwards offset long table_size = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, std::pair<std::string, std::string> > key; if (pcursor->GetKey(key) && key.first == ADDRESS_TOKEN_QUANTITY_FLAG && key.second.first == address) { table_size += 1; } pcursor->Next(); } skip = table_size + start; pcursor->SeekToFirst(); } size_t loaded = 0; size_t offset = 0; // Load tokens while (pcursor->Valid() && loaded < count && loaded < MAX_DATABASE_RESULTS) { boost::this_thread::interruption_point(); std::pair<char, std::pair<std::string, std::string> > key; if (pcursor->GetKey(key) && key.first == ADDRESS_TOKEN_QUANTITY_FLAG && key.second.first == address) { if (offset < skip) { offset += 1; } else { CAmount amount; if (pcursor->GetValue(amount)) { vecTokenAmount.emplace_back(std::make_pair(key.second.second, amount)); loaded += 1; } else { return error("%s: failed to Address Token Quanity", __func__); } } pcursor->Next(); } else { break; } } return true; } // Can get to total count of addresses that belong to a certain token_name, or get you the list of all address that belong to a certain token_name bool CTokensDB::TokenAddressDir(std::vector<std::pair<std::string, CAmount> >& vecAddressAmount, int& totalEntries, const bool& fGetTotal, const std::string& tokenName, const size_t count, const long start) { FlushStateToDisk(); std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(std::make_pair(TOKEN_ADDRESS_QUANTITY_FLAG, std::make_pair(tokenName, std::string()))); if (fGetTotal) { totalEntries = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, std::pair<std::string, std::string> > key; if (pcursor->GetKey(key) && key.first == TOKEN_ADDRESS_QUANTITY_FLAG && key.second.first == tokenName) { totalEntries += 1; } pcursor->Next(); } return true; } size_t skip = 0; if (start >= 0) { skip = start; } else { // compute table size for backwards offset long table_size = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, std::pair<std::string, std::string> > key; if (pcursor->GetKey(key) && key.first == TOKEN_ADDRESS_QUANTITY_FLAG && key.second.first == tokenName) { table_size += 1; } pcursor->Next(); } skip = table_size + start; pcursor->SeekToFirst(); } size_t loaded = 0; size_t offset = 0; // Load tokens while (pcursor->Valid() && loaded < count && loaded < MAX_DATABASE_RESULTS) { boost::this_thread::interruption_point(); std::pair<char, std::pair<std::string, std::string> > key; if (pcursor->GetKey(key) && key.first == TOKEN_ADDRESS_QUANTITY_FLAG && key.second.first == tokenName) { if (offset < skip) { offset += 1; } else { CAmount amount; if (pcursor->GetValue(amount)) { vecAddressAmount.emplace_back(std::make_pair(key.second.second, amount)); loaded += 1; } else { return error("%s: failed to Token Address Quanity", __func__); } } pcursor->Next(); } else { break; } } return true; } bool CTokensDB::TokenDir(std::vector<CDatabasedTokenData>& tokens) { return CTokensDB::TokenDir(tokens, "*", MAX_SIZE, 0); }
34.411168
206
0.595442
Chellit
203221d063fc1bdbca5e6208eaf06afeec9cc2df
86
cpp
C++
source/Transcript_variationOutput.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,315
2015-01-07T02:03:15.000Z
2022-03-30T09:48:17.000Z
source/Transcript_variationOutput.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,429
2015-01-08T00:09:17.000Z
2022-03-31T08:12:14.000Z
source/Transcript_variationOutput.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
495
2015-01-23T20:00:45.000Z
2022-03-31T13:24:50.000Z
#include "Transcript.h" void Transcript::variationOutput(Variation &Var) { // };
12.285714
48
0.686047
Gavin-Lijy
2032c8b44f78d33488b39a374f827e7e177801ca
1,779
cpp
C++
Code/Source/Algorithms/SurfaceFeatures/Local/LocalPca.cpp
sidch/Thea
d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7
[ "BSD-3-Clause" ]
77
2016-11-06T17:25:54.000Z
2022-03-29T16:30:34.000Z
Code/Source/Algorithms/SurfaceFeatures/Local/LocalPca.cpp
sidch/Thea
d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7
[ "BSD-3-Clause" ]
1
2017-04-22T16:47:04.000Z
2017-04-22T16:47:04.000Z
Code/Source/Algorithms/SurfaceFeatures/Local/LocalPca.cpp
sidch/Thea
d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7
[ "BSD-3-Clause" ]
20
2015-10-17T20:38:50.000Z
2022-02-18T09:56:27.000Z
//============================================================================ // // This file is part of the Thea toolkit. // // This software is distributed under the BSD license, as detailed in the // accompanying LICENSE.txt file. Portions are derived from other works: // their respective licenses and copyright information are reproduced in // LICENSE.txt and/or in the relevant source files. // // Author: Siddhartha Chaudhuri // First version: 2014 // //============================================================================ #include "LocalPca.hpp" #include "../../IntersectionTester.hpp" #include "../../PcaN.hpp" #include <functional> namespace Thea { namespace Algorithms { namespace SurfaceFeatures { namespace Local { LocalPca::LocalPca(PointSet3 const * surf_) : surf(surf_) { alwaysAssertM(surf_, "LocalPca: Cannot construct with a null surface"); } Vector3 LocalPca::LocalPcaFunctor::getPcaFeatures(Vector3 * eigenvectors) const { Real eval[3]; Vector3 evec[3]; PcaN<Vector3, 3>::compute(nbd_pts.begin(), nbd_pts.end(), eval, evec); // returns ordered by decreasing eigenvalue if (eigenvectors) { eigenvectors[0] = evec[0]; eigenvectors[1] = evec[1]; eigenvectors[2] = evec[2]; } return Vector3(eval[0], eval[1], eval[2]); } Vector3 LocalPca::compute(Vector3 const & position, Vector3 * eigenvectors, Real nbd_radius) const { if (nbd_radius < 0) nbd_radius = 0.1f; nbd_radius *= surf->getScale(); Ball3 range(position, nbd_radius); func.reset(); const_cast<PointSet3::SampleBvh &>(surf->getBvh()).processRangeUntil<IntersectionTester>(range, std::ref(func)); return func.getPcaFeatures(eigenvectors); } } // namespace Local } // namespace SurfaceFeatures } // namespace Algorithms } // namespace Thea
26.552239
117
0.6543
sidch
20343513957ce74bbc1729a6936323cb01c2fe57
8,451
cpp
C++
src/mason/FlyCam.cpp
paulhoux/mason
5c505e14fa4b4e043818d2ddbd75149cf10f50ab
[ "BSD-2-Clause" ]
null
null
null
src/mason/FlyCam.cpp
paulhoux/mason
5c505e14fa4b4e043818d2ddbd75149cf10f50ab
[ "BSD-2-Clause" ]
null
null
null
src/mason/FlyCam.cpp
paulhoux/mason
5c505e14fa4b4e043818d2ddbd75149cf10f50ab
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2015, The Cinder Project This code is intended to be used with the Cinder C++ library, http://libcinder.org 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. 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. */ #include "mason/FlyCam.h" #include "cinder/app/AppBase.h" #include "cinder/Log.h" using namespace ci; using namespace std; namespace mason { FlyCam::FlyCam() : mCamera( nullptr ), mWindowSize( 640, 480 ), mEnabled( true ) { } FlyCam::FlyCam( CameraPersp *camera, const app::WindowRef &window, const EventOptions &options ) : mCamera( camera ), mInitialCam( *camera ), mWindowSize( 640, 480 ), mEnabled( true ) { connect( window, options ); } FlyCam::FlyCam( const FlyCam &rhs ) : mCamera( rhs.mCamera ), mInitialCam( *rhs.mCamera ), mWindowSize( rhs.mWindowSize ), mWindow( rhs.mWindow ), mEventOptions( rhs.mEventOptions ), mEnabled( rhs.mEnabled ), mMoveIncrement( rhs.mMoveIncrement ) { connect( mWindow, mEventOptions ); } FlyCam& FlyCam::operator=( const FlyCam &rhs ) { mCamera = rhs.mCamera; mInitialCam = *rhs.mCamera; mWindowSize = rhs.mWindowSize; mWindow = rhs.mWindow; mEventOptions = rhs.mEventOptions; mMoveIncrement = rhs.mMoveIncrement; mEnabled = rhs.mEnabled; connect( mWindow, mEventOptions ); return *this; } FlyCam::~FlyCam() { disconnect(); } //! Connects to mouseDown, mouseDrag, mouseWheel and resize signals of \a window, with optional priority \a signalPriority void FlyCam::connect( const app::WindowRef &window, const EventOptions &options ) { mEventConnections.clear(); mWindow = window; mEventOptions = options; if( window ) { if( options.mMouse ) { mEventConnections += window->getSignalMouseDown().connect( options.mPriority, [this]( app::MouseEvent &event ) { mouseDown( event ); } ); mEventConnections += window->getSignalMouseUp().connect( options.mPriority, [this]( app::MouseEvent &event ) { mouseUp( event ); } ); mEventConnections += window->getSignalMouseDrag().connect( options.mPriority, [this]( app::MouseEvent &event ) { mouseDrag( event ); } ); mEventConnections += window->getSignalMouseWheel().connect( options.mPriority, [this]( app::MouseEvent &event ) { mouseWheel( event ); } ); mEventConnections += window->getSignalKeyDown().connect( options.mPriority, [this]( app::KeyEvent &event ) { keyDown( event ); } ); } if( options.mKeyboard ) { mEventConnections += window->getSignalKeyUp().connect( options.mPriority, [this]( app::KeyEvent &event ) { keyUp( event ); } ); } if( options.mResize ) { mEventConnections += window->getSignalResize().connect( options.mPriority, [this]() { setWindowSize( mWindow->getSize() ); if( mCamera ) mCamera->setAspectRatio( mWindow->getAspectRatio() ); } ); } if( options.mUpdate && app::AppBase::get() ) { mEventConnections += app::AppBase::get()->getSignalUpdate().connect( options.mPriority, [this] { update(); } ); } } } //! Disconnects all signal handlers void FlyCam::disconnect() { mEventConnections.clear(); mWindow = nullptr; } bool FlyCam::isConnected() const { return mWindow != nullptr; } signals::Signal<void()>& FlyCam::getSignalCameraChange() { return mSignalCameraChange; } void FlyCam::mouseDown( app::MouseEvent &event ) { if( ! mEnabled ) return; mouseDown( event.getPos() ); event.setHandled(); } void FlyCam::mouseUp( app::MouseEvent &event ) { if( ! mEnabled ) return; mouseUp( event.getPos() ); event.setHandled(); } void FlyCam::mouseWheel( app::MouseEvent &event ) { if( ! mEnabled ) return; mouseWheel( event.getWheelIncrement() ); event.setHandled(); } void FlyCam::mouseDrag( app::MouseEvent &event ) { if( ! mEnabled ) return; bool isLeftDown = event.isLeftDown(); bool isMiddleDown = event.isMiddleDown() || event.isAltDown(); bool isRightDown = event.isRightDown() || event.isControlDown(); if( isMiddleDown ) isLeftDown = false; mouseDrag( event.getPos(), isLeftDown, isMiddleDown, isRightDown ); event.setHandled(); } void FlyCam::mouseDown( const vec2 &mousePos ) { if( ! mCamera || ! mEnabled ) return; mLookEnabled = true; mInitialMousePos = mousePos; mInitialCam = *mCamera; } void FlyCam::mouseUp( const vec2 &mousePos ) { mLookEnabled = false; mLookDelta = vec2( 0 ); mInitialCam = *mCamera; } void FlyCam::mouseDrag( const vec2 &mousePos, bool leftDown, bool middleDown, bool rightDown ) { if( ! mCamera || ! mEnabled ) return; mLookDelta = ( mousePos - mInitialMousePos ) / vec2( getWindowSize() ); mLookDelta *= 2.75f; mSignalCameraChange.emit(); } void FlyCam::mouseWheel( float increment ) { if( ! mCamera || ! mEnabled ) return; mMoveDirection.y = mMoveIncrement * increment * 0.1f; } // TODO: need a way to disable using up these keys void FlyCam::keyDown( ci::app::KeyEvent &event ) { // skip if any modifier key is being pressed, except shift which is used to decrease speed. if( event.isAltDown() || event.isControlDown() || event.isMetaDown() ) return; bool handled = true; float moveAmount = mMoveIncrement; if( event.isShiftDown() ) moveAmount *= 0.1f; const char c = tolower( event.getChar() ); if( c == 'a' ) { mMoveDirection.x = - moveAmount; } else if( event.getCode() == 'd' ) { mMoveDirection.x = moveAmount; } else if( c == 'w' ) { mMoveDirection.y = moveAmount; } else if( c == 's' ) { mMoveDirection.y = - moveAmount; } else if( c == 'e' ) { mMoveDirection.z = moveAmount; } else if( c == 'c' ) { mMoveDirection.z = - moveAmount; } else handled = false; event.setHandled( handled ); } void FlyCam::keyUp( ci::app::KeyEvent &event ) { bool handled = true; const char c = tolower( event.getChar() ); if( c == 'a' || c == 'd' ) { mMoveDirection.x = 0; mMoveAccel.x = 0; } else if( c == 'w' || c == 's' ) { mMoveDirection.y = 0; mMoveAccel.y = 0; } else if( c == 'e' || c == 'c' ) { mMoveDirection.z = 0; mMoveAccel.z = 0; } else handled = false; event.setHandled( handled ); } void FlyCam::update() { if( ! mCamera ) return; if( mLookEnabled ) { quat orientation = mInitialCam.getOrientation(); orientation = normalize( orientation * angleAxis( mLookDelta.x, vec3( 0, -1, 0 ) ) ); orientation = normalize( orientation * angleAxis( mLookDelta.y, vec3( -1, 0, 0 ) ) ); mCamera->setOrientation( orientation ); mCamera->setWorldUp( vec3( 0, 1, 0 ) ); } mMoveAccel += mMoveDirection; const float maxVelocity = mMoveIncrement * 5; vec3 targetVelocity = glm::clamp( mMoveAccel * 0.3f, vec3( -maxVelocity ), vec3( maxVelocity ) ); mMoveVelocity = lerp( mMoveVelocity, targetVelocity, 0.3f ); // if( glm::length( mMoveVelocity ) > 0.01 ) { // CI_LOG_I( "mMoveDirection: " << mMoveDirection << ", mMoveAccel: " << mMoveAccel << ", mMoveVelocity: " << mMoveVelocity ); // } vec3 forward, right, up; forward = mCamera->getViewDirection(); mCamera->getBillboardVectors( &right, &up ); vec3 eye = mCamera->getEyePoint(); eye += right * mMoveVelocity.x; eye += forward * mMoveVelocity.y; eye += up * mMoveVelocity.z; mCamera->setEyePoint( eye ); const float drag = 0.2f; mMoveAccel *= 1 - drag; } ivec2 FlyCam::getWindowSize() const { if( mWindow ) return mWindow->getSize(); else return mWindowSize; } }; // namespace mason
26.828571
127
0.692344
paulhoux
203660c9ee43bbb596adac1c7838e12c47a397ba
1,325
cpp
C++
5/src/plane.cpp
Galaxeaaa/MIT-courses
ec54d95ac3b8217ee107b90eb704118ec3eb94ac
[ "MIT" ]
1
2020-05-09T05:36:04.000Z
2020-05-09T05:36:04.000Z
5/src/plane.cpp
Galaxeaaa/MIT-courses
ec54d95ac3b8217ee107b90eb704118ec3eb94ac
[ "MIT" ]
null
null
null
5/src/plane.cpp
Galaxeaaa/MIT-courses
ec54d95ac3b8217ee107b90eb704118ec3eb94ac
[ "MIT" ]
null
null
null
#include "plane.h" Plane::Plane(Vec3f &n, float d, Material *m) : Object3D(m), normal(n), d(d) { normal.Normalize(); bbox = nullptr; } Plane::~Plane() {} bool Plane::intersect(const Ray &r, Hit &h, float tmin) { Vec3f Ro = r.getOrigin(); Vec3f Rd = r.getDirection(); if (normal.Dot3(Rd) == 0) return false; float t = (d - normal.Dot3(Ro)) / (normal.Dot3(Rd)); if (t >= tmin) { if (t < h.getT()) h.set(t, m->clone(), normal, r); return true; } else return false; } void Plane::paint() const { Vec3f b1, b2; Vec3f::Cross3(b1, normal, Vec3f(1, 0, 0)); if (b1.Length() == 0) { Vec3f::Cross3(b1, normal, Vec3f(0, 1, 0)); } Vec3f::Cross3(b2, normal, b1); b1.Normalize(); b2.Normalize(); glPushMatrix(); m->glSetMaterial(); glTranslatef(d * normal.x(), d * normal.y(), d * normal.z()); glBegin(GL_QUADS); glNormal3f(normal.x(), normal.y(), normal.z()); glVertex3f(BIG * (b1.x() + b2.x()), BIG * (b1.y() + b2.y()), BIG * (b1.z() + b2.z())); glVertex3f(BIG * (-b1.x() + b2.x()), BIG * (-b1.y() + b2.y()), BIG * (-b1.z() + b2.z())); glVertex3f(BIG * (-b1.x() - b2.x()), BIG * (-b1.y() - b2.y()), BIG * (-b1.z() - b2.z())); glVertex3f(BIG * (b1.x() - b2.x()), BIG * (b1.y() - b2.y()), BIG * (b1.z() - b2.z())); glEnd(); glPopMatrix(); } void Plane::insertIntoGrid(Grid *g, Matrix *m) { }
23.660714
90
0.553208
Galaxeaaa
2037b895edfd6068fa5ebf5876c1f349690d67ba
570
hpp
C++
src/feature_broker/include/inference/output_pipe.hpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
10
2020-03-17T00:35:54.000Z
2021-08-22T12:31:27.000Z
src/feature_broker/include/inference/output_pipe.hpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
3
2020-03-17T17:25:15.000Z
2020-03-17T21:10:41.000Z
src/feature_broker/include/inference/output_pipe.hpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
6
2020-03-13T15:39:03.000Z
2021-11-10T08:19:06.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <inference/handle.hpp> #include <rt/rt_expected.hpp> namespace inference { class IOutputPipe { public: virtual ~IOutputPipe() = default; virtual bool Changed() = 0; protected: IOutputPipe() = default; }; template <typename T> class OutputPipe : public IOutputPipe { public: virtual ~OutputPipe() = default; virtual rt::expected<bool> UpdateIfChanged(T& value) = 0; protected: OutputPipe() = default; }; } // namespace inference
18.387097
61
0.685965
TomFinley
2039079f0f6abe0db530193229f587c7838fdfed
3,086
cpp
C++
acm/cf/691C.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/cf/691C.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/cf/691C.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include<bits/stdc++.h> using namespace std; using namespace std; #define INF 0x3FFFFFFF #define PB(X) push_back(X) #define MP(X,Y) make_pair(X,Y) #define lson l,m,rt<<1 #define rson m+1,r,tr<<1|1 typedef pair<int,int>PII; typedef vector<PII>VII; const int MAXN = 100010; inline int input() { int x; scanf("%d", &x); return x;} inline void print(char s = NULL,int t = 0){printf("%s%d ",s,t);} int main(){ ios::sync_with_stdio(false); string s; while(cin>>s){ int len = s.length(); int has_p = -1; int start = -1,end = -1; int cnt = -1; for(int i = 0;i<len;i++){ if(s[i] == '.'){ has_p = i;break; } } for(int i = 0;i<len;i++){ if(s[i] == '.'); else if(s[i] == '0'); else{ start = i;break; } } for(int i = len-1;i>=0;i--){ if(s[i] == '.'); else if(s[i] == '0'); else{ end = i;break; } } // for(int i = start;i<=end;i++){ // cout<<s[i]; // } if(start == -1){cout<<"0"<<endl;continue;} if(has_p == -1)has_p = len; cnt = has_p - start; if(cnt>0)cnt-=1; if(cnt == 0){ if(end>start) for(int i = start;i<=end;i++){ if(i == start){cout<<s[i]<<".";} else if(s[i] == '.'); else cout<<s[i]; } else{ cout<<s[start]; } } else{ if(end>start) for(int i = start;i<=end;i++){ if(i == start){cout<<s[i]<<".";} else if(s[i] == '.'); else cout<<s[i]; }else{ cout<<s[start]; } cout<<"E"<<cnt; } cout<<endl; // int znum = 0; // int zs = 0; // int pnum = 0; // int zp = 0; // int ps = 0; // int pe = 0; // for(int i = 0;i<len;i++){ // if(s[i] == 0&&zs == 0){; // } // else{ // zs = 1; // if(s[i]!= '.'&&zp == 0){ // ps = i; // zp = 1; // } // if(s[i] == '.'){ // zp = i - ps; // } // } // // } // for(int i = len-1;i>0;i--){ // if(s[i] == 0&&pe == 0){; // } // else{ // pe = i; // break; // } // // } // if(zp == 1){ // for(int i = ps;i<=pe;i++){ // if(i == ps){cout<<s[i]<<".";} // if(s[i] == '.'); // else cout<<s[i]; // } // } // else{ // for(int i = ps;i<=pe;i++){ // if(i == ps){cout<<s[i]<<".";} // if(s[i] == '.'); // else cout<<s[i]; // } // cout<<"E"<<zp<<endl; // } // } } }
21.58042
64
0.306222
xiaohuihuigh
203c52a47435db492a8e00ecafdc73089bcb41aa
1,936
cpp
C++
third-party/Empirical/examples/web/RPS.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/examples/web/RPS.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/examples/web/RPS.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
// This file is part of Empirical, https://github.com/devosoft/Empirical // Copyright (C) Michigan State University, 2015-2018. // Released under the MIT Software license; see doc/LICENSE #include "emp/geometry/Surface.hpp" #include "emp/math/Random.hpp" #include "emp/web/Animate.hpp" #include "emp/web/canvas_utils.hpp" #include "emp/web/emfunctions.hpp" #include "emp/web/web.hpp" namespace UI = emp::web; struct Rock { size_t kills = 0; }; struct Paper { size_t kills = 0; }; struct Scissors { size_t kills = 0; }; UI::Document doc("emp_base"); double can_size = 400; emp::Surface<Rock, Paper, Scissors> surface(can_size, can_size); void CanvasAnim(double time) { auto mycanvas = doc.Canvas("can"); std::cerr << time << std::endl; // Update the line. mycanvas.Draw(surface); doc.Text("fps").Redraw(); }; int main() { // How big should each canvas be? const double w = can_size; const double h = can_size; emp::Random random; // Add objects size_t num_rocks = 10; size_t num_papers = 10; size_t num_scissors = 10; emp::vector<Rock> rocks(num_rocks); emp::vector<Paper> papers(num_papers); emp::vector<Scissors> scissors(num_scissors); for (size_t i = 0; i < num_rocks; i++) { surface.rocks[i] } // Draw a simple circle animation on a canvas auto mycanvas = doc.AddCanvas(w, h, "can"); mycanvas.Circle(cx, cy, cr, "green", "purple"); UI::Animate * anim = new UI::Animate(CanvasAnim, mycanvas); (void) anim; // Draw the new polygon. poly.AddPoint(0,0).AddPoint(60,25).AddPoint(50,50).AddPoint(-50,50).AddPoint(25,40); mycanvas.Draw(poly); doc << "<br>"; doc.AddButton([anim](){ anim->ToggleActive(); auto but = doc.Button("toggle"); if (anim->GetActive()) but.SetLabel("Pause"); else but.SetLabel("Start"); }, "Start", "toggle"); doc << UI::Text("fps") << "FPS = " << UI::Live( [anim](){return anim->GetStepTime();} ) ; }
25.142857
91
0.655992
koellingh
203f265a7f43ee66201b7c888c5d16bb7f4bb1cb
20,318
cpp
C++
src/AppLines/AppLines.cpp
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/AppLines/AppLines.cpp
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/AppLines/AppLines.cpp
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
1
2022-01-07T15:58:38.000Z
2022-01-07T15:58:38.000Z
/* ** ** $Filename: AppLines.cpp $ ** $Release: Dortmund 2001, 2002 $ ** $Revision$ ** $Date$ ** $Author$ ** $Developer: Steffen A. Mork $ ** ** Blizzard III - Lines application ** ** (C) Copyright 2001, 2002 Steffen A. Mork ** All Rights Reserved ** ** */ /************************************************************************* ** ** ** Lines III includes ** ** ** *************************************************************************/ #include "AppLinesInclude.h" #include "blz3/system/b3File.h" #include "blz3/system/b3FileDialog.h" #include "blz3/system/b3Plugin.h" #include "blz3/system/b3SelfTest.h" #include "blz3/system/b3SimplePreviewDialog.h" #include "blz3/system/b3Version.h" #include "blz3/base/b3FileMem.h" #include "DlgSearchPathList.h" #include "DlgProperties.h" #include "b3Splash.h" #include "b3StaticPluginInfoInit.h" #include "b3Profile.h" #include "b3ExceptionLogger.h" #include "b3SelectObject.h" #include "b3DocManager.h" #include "b3ImageMultiDocTemplate.h" /************************************************************************* ** ** ** CAppLinesApp implementation ** ** ** *************************************************************************/ BEGIN_MESSAGE_MAP(CAppLinesApp, CB3App) //{{AFX_MSG_MAP(CAppLinesApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) ON_COMMAND(ID_CHANGE_TEXTURE_PATH, OnChangeTexturePath) ON_COMMAND(ID_FILE_NEW, OnFileNew) ON_COMMAND(ID_PROPERTIES, OnProperties) ON_COMMAND(ID_FILE_OPEN, OnFileOpen) ON_COMMAND(ID_IMPORT_ARCON, OnImportArcon) //}}AFX_MSG_MAP END_MESSAGE_MAP() /************************************************************************* ** ** ** CAppLinesApp construction ** ** ** *************************************************************************/ CAppLinesApp::CAppLinesApp() : CB3App("Lines III") { // TODO: add construction code here, // Place all significant initialization in InitInstance m_ClipboardFormatForBlizzardObject = 0; } ///////////////////////////////////////////////////////////////////////////// // The one and only CAppLinesApp object CAppLinesApp theApp; IMPLEMENT_DYNAMIC(CB3DocManager,CDocManager) IMPLEMENT_DYNAMIC(CB3ImageMultiDocTemplate,CMultiDocTemplate) // This identifier was generated to be statistically unique for your app. // You may change it if you prefer to choose a specific identifier. // {F1E8F37D-3D18-4028-9E52-5A2D141EB769} const CLSID CAppLinesApp::m_SceneClsID = { 0xf1e8f37d, 0x3d18, 0x4028, { 0x9e, 0x52, 0x5a, 0x2d, 0x14, 0x1e, 0xb7, 0x69 } }; // {F346F6D2-0E7B-4b15-B887-D7A9B215EB62} const CLSID CAppLinesApp::m_ObjectClsID = { 0xf346f6d2, 0xe7b, 0x4b15, { 0xb8, 0x87, 0xd7, 0xa9, 0xb2, 0x15, 0xeb, 0x62 } }; /************************************************************************* ** ** ** CAppLinesApp initialization ** ** ** *************************************************************************/ const int CB3SimplePreviewDialog::m_AutoRefreshId = IDC_AUTO_REFRESH; const int CB3SimplePreviewDialog::m_RefreshId = IDC_REFRESH; const int CB3SimplePreviewDialog::m_PropertySheetId = IDC_PROPERTY; /************************************************************************* ** ** ** CAppLinesApp initialization ** ** ** *************************************************************************/ void CAppLinesApp::b3SetupSearchPath(b3SearchPath &search,CString &path) { CString sub; while(!path.IsEmpty()) { sub = path.SpanExcluding(";"); search.b3AddPath(sub); path = path.Right(path.GetLength() - sub.GetLength() - 1); } } void CAppLinesApp::b3SetupPluginPaths(b3SearchPath &search) { HKEY hSecKey = b3GetSectionKey("Plugins"); if (hSecKey) { TCHAR entry[MAX_PATH]; DWORD entry_len = sizeof(entry); TCHAR value[MAX_PATH]; DWORD value_len = sizeof(value); DWORD mode = 0; for (int i = 0;::RegEnumValue(hSecKey, i, entry, &entry_len, NULL, &mode, (unsigned char *)value, &value_len) == ERROR_SUCCESS;i++) { if (mode == REG_SZ) { search.b3AddPath(value); } entry_len = sizeof(entry); value_len = sizeof(value); } ::RegCloseKey (hSecKey); } } BOOL CAppLinesApp::InitInstance() { // Parse command line for standard shell commands, DDE, file open CB3Version version; CB3ExceptionLogger init_logging; CString path; b3Loader &plugins = b3Loader::b3GetLoader(); CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); #ifndef _DEBUG CSplashWnd::EnableSplashScreen(cmdInfo.m_bShowSplash); #endif // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T(BLIZZARD3_REG_COMPANY)); LoadStdProfileSettings(10); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. b3_log_level level; #ifndef _DEBUG level = (b3_log_level)b3ReadInt("Settings", "DebugLevel", B3LOG_NORMAL); #else level = B3LOG_FULL; #endif b3Log::b3SetLevel(level); b3PrintF(B3LOG_NORMAL,"%s %s\n%s\n\n", b3ClientName(), version.b3GetVersionString(), version.b3GetCopyrightString()); CB3Version::b3DumpOS(); #ifdef _DEBUG b3SelfTest::b3TestDataSize(); b3SelfTest::b3TestDate(); #endif // Default texture search path from HKEY_LOCAL_MACHINE // path = b3ReadString(b3ClientName(),"texture search path",""); // b3SetupSearchPath(b3Scene::m_TexturePool,path); // Default texture search path from HKEY_CURENT_USER path = GetProfileString(b3ClientName(),"texture search path",""); b3SetupSearchPath(b3Scene::m_TexturePool,path); // Add hard wired classes b3RaytracingItems::b3Register(); b3StaticPluginInfoInit::b3Init(); // FIXME: This should be local computer wide. path = GetProfileString(b3ClientName(),"plugin search path",""); b3SetupSearchPath(plugins,path); b3SetupPluginPaths(plugins); plugins.b3Load(); CDlgProperties::b3ReadConfig(); if (m_pDocManager == NULL) { // Add custom doc manager m_pDocManager = new CB3DocManager; } m_pSceneTemplate = new CMultiDocTemplate( IDR_BLZ3TYPE, RUNTIME_CLASS(CAppLinesDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CAppLinesView)); AddDocTemplate(m_pSceneTemplate); m_pImageTemplate = new CB3ImageMultiDocTemplate( IDR_DISPLAYTYPE, RUNTIME_CLASS(CAppRaytraceDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CAppRaytraceView)); AddDocTemplate(m_pImageTemplate); m_pObjectTemplate = new CMultiDocTemplate( IDR_OBJECT, RUNTIME_CLASS(CAppObjectDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CAppObjectView)); AddDocTemplate(m_pObjectTemplate); // Connect the COleTemplateServer to the document template. // The COleTemplateServer creates new documents on behalf // of requesting OLE containers by using information // specified in the document template. m_SceneServer.ConnectTemplate( m_SceneClsID, m_pSceneTemplate, FALSE); m_ObjectServer.ConnectTemplate(m_ObjectClsID, m_pObjectTemplate, FALSE); // Register all OLE server factories as running. This enables the // OLE libraries to create objects from other applications. COleTemplateServer::RegisterAll(); // Note: MDI applications register all server objects without regard // to the /Embedding or /Automation on the command line. // Init Blizzard values... b3InitInstance(); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) return FALSE; m_pMainWnd = pMainFrame; // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); // Enable DDE Execute open EnableShellOpen(); RegisterShellFileTypes(TRUE); m_ClipboardFormatForBlizzardObject = ::RegisterClipboardFormat("Blizzard Object"); // Check to see if launched as OLE server if (cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated) { // Application was run with /Embedding or /Automation. Don't show the // main window in this case. return TRUE; } // When a server application is launched stand-alone, it is a good idea // to update the system registry in case it has been damaged. m_SceneServer.UpdateRegistry(OAT_DISPATCH_OBJECT); m_ObjectServer.UpdateRegistry(OAT_DISPATCH_OBJECT); COleObjectFactory::UpdateRegistryAll(); // Dispatch commands specified on the command line if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew) { cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing; } if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it. pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); b3Profile *profile; B3_FOR_BASE(&b3Profile::m_LinesProfileBase,profile) { if (!profile->b3Create()) { b3PrintF(B3LOG_NORMAL,"Cannot create curve profile %s!\n",profile->b3GetTitle()); b3PrintF(B3LOG_NORMAL,"Exiting now!\n"); return false; } } return CB3App::InitInstance(); } int CAppLinesApp::ExitInstance() { // TODO: Add your specialized code here and/or call the base class b3Loader::b3GetLoader().b3Unload(); return CB3App::ExitInstance(); } ///////////////////////////////////////////////////////////////////////////// // CAppLinesApp message handlers CAppRaytraceDoc *CAppLinesApp::b3CreateRaytraceDoc() { return (CAppRaytraceDoc *)m_pImageTemplate->OpenDocumentFile(NULL); } void CAppLinesApp::b3UpdateAllViews() { CDocument *pDoc; POSITION pos; pos = m_pSceneTemplate->GetFirstDocPosition(); while(pos != NULL) { pDoc = (CAppObjectDoc *)m_pObjectTemplate->GetNextDoc(pos); pDoc->UpdateAllViews(NULL,B3_UPDATE_VIEW); } pos = m_pObjectTemplate->GetFirstDocPosition(); while(pos != NULL) { pDoc = (CAppObjectDoc *)m_pObjectTemplate->GetNextDoc(pos); pDoc->UpdateAllViews(NULL,B3_UPDATE_VIEW); } } CAppObjectDoc *CAppLinesApp::b3CreateObjectDoc( CAppLinesDoc *LinesDoc, b3BBox *bbox) { CAppObjectDoc *pDoc; CWaitCursor waiting_for_Isabella; POSITION pos; // Look if there is any open object edit -> use it. pos = m_pObjectTemplate->GetFirstDocPosition(); while(pos != NULL) { pDoc = (CAppObjectDoc *)m_pObjectTemplate->GetNextDoc(pos); if (pDoc->b3IsObjectAlreadyOpen(LinesDoc,bbox)) { pos = pDoc->GetFirstViewPosition(); pDoc->GetNextView(pos)->GetParentFrame()->BringWindowToTop(); return pDoc; } } // We didn't found the appropriate document -> create new one. pDoc = (CAppObjectDoc *)m_pObjectTemplate->OpenDocumentFile(NULL); if (pDoc != null) { pDoc->b3EditBBox(LinesDoc,bbox); } return pDoc; } void CAppLinesApp::b3CloseObjectDoc(CAppLinesDoc *LinesDoc) { POSITION pos; CAppObjectDoc *pDoc; pos = m_pObjectTemplate->GetFirstDocPosition(); while(pos != NULL) { pDoc = (CAppObjectDoc *)m_pObjectTemplate->GetNextDoc(pos); if (pDoc->b3IsLinesDoc(LinesDoc)) { if (pDoc->IsModified()) { LinesDoc->SetModifiedFlag(); } pDoc->OnCloseDocument(); } } } void CAppLinesApp::OnChangeTexturePath() { // TODO: Add your command handler code here CDlgSearchPathList dlg; CString path = ""; b3PathEntry *entry; b3_count count = 0; dlg.m_SearchPath = &b3Scene::m_TexturePool; dlg.DoModal(); B3_FOR_BASE(&b3Scene::m_TexturePool.m_SearchPath,entry) { if (count++ > 0) { path += ";"; } path += ((const char *)*entry); } WriteProfileString(b3ClientName(),"texture search path",path); } void CAppLinesApp::OnFileNew() { // TODO: Add your command handler code here // Force creating new geometry! m_pSceneTemplate->OpenDocumentFile(NULL); } void CAppLinesApp::OnImportArcon() { // TODO: Add your command handler code here CAppLinesDoc *pDoc; CMainFrame *main = CB3GetMainFrame(); CWaitCursor wait; CFrameWnd *frame; b3Path result = ""; if (CB3SelectLoadArcon::b3Select(result)) { pDoc = (CAppLinesDoc *)m_pSceneTemplate->CreateNewDocument(); if (pDoc->OnImportArcon(result)) { frame = m_pSceneTemplate->CreateNewFrame(pDoc,NULL); m_pSceneTemplate->InitialUpdateFrame(frame,pDoc); } } } void CAppLinesApp::OnProperties() { // TODO: Add your command handler code here CDlgProperties dlg; if (dlg.DoModal() == IDOK) { } } void CAppLinesApp::OnFileOpen() { // TODO: Add your command handler code here CB3App *app = CB3GetApp(); CString filename; CString filter_bwd,bwdFilterName,bwdFilterExt; CString filter_bod,bodFilterName,bodFilterExt; CString filter_img; // Build scene filter m_pSceneTemplate->GetDocString(bwdFilterName,CDocTemplate::filterName); m_pSceneTemplate->GetDocString(bwdFilterExt,CDocTemplate::filterExt); filter_bwd = bwdFilterName + "|*" + bwdFilterExt + "|"; // Build object filter m_pObjectTemplate->GetDocString(bodFilterName,CDocTemplate::filterName); m_pObjectTemplate->GetDocString(bodFilterExt,CDocTemplate::filterExt); filter_bod = bodFilterName + "|*" + bodFilterExt + "|"; // Build image filter filter_img.LoadString(IDS_TEXTURE_FILTER); // Select filename filename = app->GetProfileString(CB3ClientString(),"file load.document",null); CB3FileDialog dlg(TRUE,"",filename,OFN_HIDEREADONLY,filter_bwd + filter_bod + filter_img,m_pMainWnd); if (dlg.DoModal() == IDOK) { // and load document filename = dlg.GetPathName(); app->WriteProfileString(CB3ClientString(),"file load.document",filename); OpenDocumentFile(filename); } } /************************************************************************* ** ** ** CAppLinesApp clipboard operations ** ** ** *************************************************************************/ b3_bool CAppLinesApp::b3PutClipboard(b3BBox *bbox) { CMainFrame *main = CB3GetMainFrame(); b3_bool success = false; b3_size size; void *ptr; HANDLE handle; if (main->OpenClipboard()) { try { b3FileMem file(B_WRITE); if (b3WriteBBox(bbox,&file)) { size = file.b3Size(); handle = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,size); if (handle != 0) { ptr = ::GlobalLock(handle); if (ptr != null) { file.b3Seek(0,B3_SEEK_START); if (file.b3Read(ptr,size) == size) { ::GlobalUnlock(handle); ::EmptyClipboard(); ::SetClipboardData(m_ClipboardFormatForBlizzardObject,handle); success = true; } } } } } catch(b3FileException &f) { b3PrintF(B3LOG_NORMAL,"I/O ERROR: writing object %s to clipboard (code: %d)\n", bbox->b3GetName(),f.b3GetError()); B3_MSG_ERROR(f); } catch(b3WorldException &w) { b3PrintF(B3LOG_NORMAL,"ERROR: writing object %s to clipboard (code: %d)\n", bbox->b3GetName(),w.b3GetError()); B3_MSG_ERROR(w); } catch(...) { b3PrintF(B3LOG_NORMAL,"UNKNOWN ERROR: writing object %s to clipboard %s\n", bbox->b3GetName()); } ::CloseClipboard(); } return success; } b3BBox *CAppLinesApp::b3PasteClipboard(b3World *world) { CMainFrame *main = CB3GetMainFrame(); CWaitCursor wait; void *ptr; b3_size size; HANDLE handle; b3BBox *bbox = null; if (main->OpenClipboard()) { handle = ::GetClipboardData(m_ClipboardFormatForBlizzardObject); if (handle != 0) { size = ::GlobalSize(handle); ptr = ::GlobalLock(handle); try { b3FileMem file(B_WRITE); file.b3Write(ptr,size); file.b3Seek(0,B3_SEEK_START); if(world->b3Read(&file) == B3_WORLD_OK) { bbox = (b3BBox *)world->b3GetFirst(); } } catch(b3FileException &f) { b3PrintF(B3LOG_NORMAL,"I/O ERROR: reading object from clipboard (code: %d)\n", f.b3GetError()); B3_MSG_ERROR(f); } catch(b3WorldException &w) { b3PrintF(B3LOG_NORMAL,"ERROR: reading object from clipboard (code: %d)\n", w.b3GetError()); B3_MSG_ERROR(w); } ::GlobalUnlock(handle); } ::CloseClipboard(); } return bbox; } b3_bool CAppLinesApp::b3WriteBBox(b3BBox *bbox,const char *filename) { b3File file(filename,B_WRITE); return b3WriteBBox(bbox,&file); } b3_bool CAppLinesApp::b3WriteBBox(b3BBox *bbox,b3FileAbstract *file) { b3World world; world.m_AutoDelete = false; world.b3SetFirst(bbox); b3BBox::b3Recount(world.b3GetHead(),bbox->b3GetType()); return world.b3Write(file) == B3_WORLD_OK; } /************************************************************************* ** ** ** CAppLinesApp about box ** ** ** *************************************************************************/ class CAboutDlg : public CDialog { static const char m_AppLinesVersionString[]; static const char m_AppLinesNameString[]; public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; CStatic m_CtrlCopyright; CStatic m_CtrlVersion; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; const char CAboutDlg::m_AppLinesVersionString[] = "$Revision$"; const char CAboutDlg::m_AppLinesNameString[] = "$Id$"; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) DDX_Control(pDX, IDC_COPYRIGHT, m_CtrlCopyright); DDX_Control(pDX, IDC_VERSION, m_CtrlVersion); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CAboutDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here CB3Version version; m_CtrlVersion.SetWindowText(version.b3GetVersionString()); m_CtrlCopyright.SetWindowText(version.b3GetCopyrightString()); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } #ifdef _DEBUG #define DLG_TEST #endif #ifdef DLG_TEST #include "DlgItemMaintain.h" #include "blz3/raytrace/b3Material.h" #endif // App command to run the dialog void CAppLinesApp::OnAppAbout() { #ifdef DLG_TEST b3Base<b3Item> head; b3Item *item = b3World::b3AllocNode(WOOD); b3_scene_preparation prep_info; prep_info.m_Scene = null; prep_info.m_t = 0; head.b3InitBase(item->b3GetClass()); head.b3Append(item); if (item->b3Prepare(&prep_info)) { CDlgItemMaintain dlg(null,&head); dlg.DoModal(); } else { b3Runtime::b3MessageBox("Preparation failed!",B3_MSGBOX_ERROR); } head.b3Free(); #else CAboutDlg aboutDlg; aboutDlg.DoModal(); #endif }
27.681199
102
0.62639
stmork
204b7d2600d2e198028970f289b19c03f3aad014
11,068
cpp
C++
DNP3/APDUProxyImpl.cpp
rajive/dnp3
f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
DNP3/APDUProxyImpl.cpp
rajive/dnp3
f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
DNP3/APDUProxyImpl.cpp
rajive/dnp3
f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa
[ "ECL-2.0", "Apache-2.0" ]
2
2019-03-31T15:27:05.000Z
2019-09-17T16:12:53.000Z
/* Copyright 2014 Real-Time Innovations, Inc. 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. */ /* * APDUProxyImpl.cpp * * Created on: Jul 26, 2012 * Author: asorbini */ #include <iostream> #include <stdio.h> #include "APDUProxy.h" #include "APDUProxyImpl.h" /* #include <boost/thread/condition.hpp> #include <boost/thread/shared_mutex.hpp> */ namespace apl { namespace dnp { using namespace boost; bool APDUProxyImpl::AddAPDUListener( APDUListener* listener) { string& listName = listener->getName(); LOG_BLOCK(LEV_INTERPRET, "Adding new listener " << listName); this->listeners.push_back(listener); return true; } bool APDUProxyImpl::RemoveAPDUListener( APDUListener* listener) { string& listName = listener->getName(); LOG_BLOCK(LEV_WARNING, "Removal of listeners not implemented yet. Cannot remove : " << listName); return false; } CommandStatus APDUProxyImpl::SendRequestAPDU( APDU& apdu) { LOG_BLOCK(LEV_INTERPRET, "SendRequestAPDU " << apdu.ToString()); unique_lock<recursive_timed_mutex> lock(this->globalMutex); while (this->currentOp != PO_NONE) { LOG_BLOCK(LEV_INTERPRET, "SendRequestAPDU - waiting for current operation to end : "<<this->currentOp); this->sendCondition.wait(lock); } this->currentOp = PO_SEND_REQUEST; CommandStatus result = CS_HARDWARE_ERROR; try { LOG_BLOCK(LEV_INTERPRET, "SendRequestAPDU - Sending APDU..."); this->appLayer->SendRequest(apdu); } catch (apl::Exception& ex) { LOG_BLOCK(LEV_ERROR, "Exception sending request: " << ex.what()); this->currentOp = PO_NONE; return CS_HARDWARE_ERROR; } while (!this->hasResult) { LOG_BLOCK(LEV_INTERPRET, "SendRequestAPDU - Waiting for send outcome..."); this->sendOutcomeCondition.wait(lock); } this->hasResult = false; result = this->sendResults.front(); this->sendResults.pop_front(); LOG_BLOCK(LEV_INTERPRET, "SendRequestAPDU - Result : "<< result); this->currentOp = PO_NONE; this->sendCondition.notify_all(); return result; } CommandStatus APDUProxyImpl::SendResponseAPDU( APDU& apdu) { LOG_BLOCK(LEV_INTERPRET, "SendResponseAPDU " << apdu.ToString()); unique_lock<recursive_timed_mutex> lock(this->globalMutex); while (this->currentOp != PO_NONE) { LOG_BLOCK(LEV_INTERPRET, "SendResponseAPDU - waiting for current operation to end : "<<this->currentOp); this->sendCondition.wait(lock); } this->currentOp = PO_SEND_RESPONSE; CommandStatus result = CS_HARDWARE_ERROR; try { LOG_BLOCK(LEV_INTERPRET, "SendResponseAPDU - sending APDU..."); this->appLayer->SendResponse(apdu); } catch (apl::Exception& ex) { LOG_BLOCK(LEV_ERROR, "Exception sending RESPONSE: " << ex.what()); this->currentOp = PO_NONE; return CS_HARDWARE_ERROR; } // this->sendResultsSemaphore.wait(); while (!this->hasResult) { LOG_BLOCK(LEV_INTERPRET, "SendResponseAPDU - Waiting for send outcome..."); this->sendOutcomeCondition.wait(lock); } this->hasResult = false; result = this->sendResults.front(); this->sendResults.pop_front(); LOG_BLOCK(LEV_INTERPRET, "SendResponseAPDU - Result : "<< result); this->currentOp = PO_NONE; this->sendCondition.notify_all(); return result; } CommandStatus APDUProxyImpl::SendUnsolResponseAPDU( APDU& apdu) { LOG_BLOCK(LEV_INTERPRET, "SendUnsolResponseAPDU " << apdu.ToString()); unique_lock<recursive_timed_mutex> lock(this->globalMutex); while (this->currentOp != PO_NONE) { LOG_BLOCK(LEV_INTERPRET, "SendUnsolResponseAPDU - waiting for current operation to end : "<<this->currentOp); this->sendCondition.wait(lock); } this->currentOp = PO_SEND_UNSOL; CommandStatus result = CS_HARDWARE_ERROR; try { LOG_BLOCK(LEV_INTERPRET, "SendUnsolResponseAPDU - Sending APDU..."); this->appLayer->SendUnsolicited(apdu); } catch (apl::Exception& ex) { LOG_BLOCK(LEV_ERROR, "Exception sending UNSOL: " << ex.what()); this->currentOp = PO_NONE; return CS_HARDWARE_ERROR; } // this->sendResultsSemaphore.wait(); while (!this->hasResult) { LOG_BLOCK(LEV_INTERPRET, "SendUnsolResponseAPDU - Waiting for send outcome..."); this->sendOutcomeCondition.wait(lock); } this->hasResult = false; result = this->sendResults.front(); this->sendResults.pop_front(); LOG_BLOCK(LEV_INTERPRET, "SendUnsolResponseAPDU - Result : "<< result); this->currentOp = PO_NONE; this->sendCondition.notify_all(); return result; } void APDUProxyImpl::OnLowerLayerUp() { LOG_BLOCK(LEV_INTERPRET, "OnLowerLayerUp"); /*this->lowerLayerUp = true;*/ } void APDUProxyImpl::OnLowerLayerDown() { LOG_BLOCK(LEV_INTERPRET, "OnLowerLayerDown"); /*this->lowerLayerUp = false;*/ } void APDUProxyImpl::OnUnsolSendSuccess() { LOG_BLOCK(LEV_INTERPRET, "OnUnsolSendSuccess"); unique_lock<recursive_timed_mutex> lock(this->globalMutex); this->sendResults.push_back(CS_SUCCESS); this->hasResult = true; this->sendOutcomeCondition.notify_all(); LOG_BLOCK(LEV_INTERPRET, "OnUnsolSendSuccess - notified"); } void APDUProxyImpl::OnUnsolFailure() { LOG_BLOCK(LEV_INTERPRET, "OnUnsolFailure"); unique_lock<recursive_timed_mutex> lock(this->globalMutex); this->sendResults.push_back(CS_HARDWARE_ERROR); this->hasResult = true; this->sendOutcomeCondition.notify_all(); LOG_BLOCK(LEV_INTERPRET, "OnUnsolFailure - notified"); } void APDUProxyImpl::OnSolSendSuccess() { LOG_BLOCK(LEV_INTERPRET, "OnSolSendSuccess"); unique_lock<recursive_timed_mutex> lock(this->globalMutex); this->sendResults.push_back(CS_SUCCESS); this->hasResult = true; this->sendOutcomeCondition.notify_all(); LOG_BLOCK(LEV_INTERPRET, "OnSolSendSuccess - notified"); } void APDUProxyImpl::OnSolFailure() { LOG_BLOCK(LEV_INTERPRET, "OnSolFailure"); unique_lock<recursive_timed_mutex> lock(this->globalMutex); this->sendResults.push_back(CS_HARDWARE_ERROR); this->hasResult = true; this->sendOutcomeCondition.notify_all(); LOG_BLOCK(LEV_INTERPRET, "OnSolFailure - notified"); } bool APDUProxyImpl::IsMaster() { return this->config.isMaster; } void APDUProxyImpl::OnPartialResponse( const APDU& apdu) { LOG_BLOCK(LEV_INTERPRET, "OnPartialResponse : "<< apdu.ToString()); { unique_lock<recursive_timed_mutex> lock(this->globalMutex); APDU * received = new APDU(apdu); this->responseAPDUs.push_back(received); this->sendResults.push_back(CS_SUCCESS); this->hasResult = true; this->sendOutcomeCondition.notify_all(); lock.unlock(); } { unique_lock<recursive_timed_mutex> lock(this->notificationMutex); this->hasMessages = true; this->notifyListenersCondition.notify_all(); lock.unlock(); } LOG_BLOCK(LEV_INTERPRET, "OnPartialResponse - notified"); } void APDUProxyImpl::OnFinalResponse( const APDU& apdu) { LOG_BLOCK(LEV_INTERPRET, "OnFinalResponse : "<< apdu.ToString()); { unique_lock<recursive_timed_mutex> lock(this->globalMutex); APDU * received = new APDU(apdu); this->responseAPDUs.push_back(received); this->sendResults.push_back(CS_SUCCESS); this->hasResult = true; this->sendOutcomeCondition.notify_all(); lock.unlock(); } { unique_lock<recursive_timed_mutex> lock(this->notificationMutex); this->hasMessages = true; this->notifyListenersCondition.notify_all(); lock.unlock(); } LOG_BLOCK(LEV_INTERPRET, "OnFinalResponse - notified"); } void APDUProxyImpl::OnUnsolResponse( const APDU& apdu) { LOG_BLOCK(LEV_INTERPRET, "OnUnsolResponse : "<< apdu.ToString()); { unique_lock<recursive_timed_mutex> lock(this->notificationMutex); APDU * received = new APDU(apdu); this->unsolResponseAPDUs.push_back(received); this->hasMessages = true; this->notifyListenersCondition.notify_all(); lock.unlock(); } LOG_BLOCK(LEV_INTERPRET, "OnUnsolResponse - notified"); } void APDUProxyImpl::OnRequest( const APDU& apdu, SequenceInfo info) { LOG_BLOCK(LEV_INTERPRET, "OnRequest: "<< apdu.ToString()); { unique_lock<recursive_timed_mutex> lock(this->globalMutex); APDU * received = new APDU(apdu); this->requestAPDUs.push_back(received); lock.unlock(); } LOG_BLOCK(LEV_INTERPRET, "OnRequest - notifying notifier..."); { unique_lock<recursive_timed_mutex> lock(this->notificationMutex); this->hasMessages = true; this->notifyListenersCondition.notify_all(); lock.unlock(); } LOG_BLOCK(LEV_INTERPRET, "OnRequest - notified"); } void APDUProxyImpl::OnUnknownObject() { LOG_BLOCK(LEV_INTERPRET, "OnUnknownObject"); } void APDUProxyImpl::_OnUnsolResponse() { while (!this->unsolResponseAPDUs.empty()) { APDU& apdu = this->unsolResponseAPDUs.front(); LOG_BLOCK(LEV_INTERPRET, "Notifying UNSOL APDU : " << apdu.ToString()); for (boost::ptr_vector<APDUListener>::size_type i = 0; i < this->listeners.size(); i++) { APDUListener& listener = this->listeners[i]; listener.newResponseAPDU((APDUProxy*) this, const_cast<APDU&>(apdu)); } this->unsolResponseAPDUs.pop_front(); } } void APDUProxyImpl::_OnResponse() { while (!this->responseAPDUs.empty()) { APDU& apdu = this->responseAPDUs.front(); LOG_BLOCK(LEV_INTERPRET, "Notifying RESPONSE APDU : " << apdu.ToString()); for (boost::ptr_vector<APDUListener>::size_type i = 0; i < this->listeners.size(); i++) { APDUListener& listener = this->listeners[i]; listener.newResponseAPDU((APDUProxy*) this, const_cast<APDU&>(apdu)); } this->responseAPDUs.pop_front(); } } void APDUProxyImpl::_OnRequest() { while (!this->requestAPDUs.empty()) { APDU& apdu = this->requestAPDUs.front(); LOG_BLOCK(LEV_INTERPRET, "Notifying REQUEST APDU : " << apdu.ToString()); for (boost::ptr_vector<APDUListener>::size_type i = 0; i < this->listeners.size(); i++) { APDUListener& listener = this->listeners[i]; listener.newRequestAPDU((APDUProxy*) this, const_cast<APDU&>(apdu)); } this->requestAPDUs.pop_front(); } } void APDUProxyImpl::Run( APDUProxyImpl* proxy) { while (proxy->active) { LOGGER_BLOCK(proxy->mpLogger, LEV_INTERPRET, "NotificationThread - begin iteration"); unique_lock<recursive_timed_mutex> lock(proxy->notificationMutex); while (!proxy->hasMessages) { LOGGER_BLOCK(proxy->mpLogger, LEV_INTERPRET, "NotificationThread - waiting for APDU to notify..."); proxy->notifyListenersCondition.wait(lock); } LOGGER_BLOCK(proxy->mpLogger, LEV_INTERPRET, "NotificationThread - notifying APDUs"); proxy->_OnRequest(); proxy->_OnResponse(); proxy->_OnUnsolResponse(); proxy->hasMessages = false; LOGGER_BLOCK(proxy->mpLogger, LEV_INTERPRET, "NotificationThread - end of iteration"); /*boost::this_thread::sleep(boost::posix_time::milliseconds(100));*/ } } } }
26.042353
88
0.730936
rajive
204ba85a4dddc502200ac91a9ec60d44e5356cd1
11,495
cpp
C++
linked_list/linked_list1.cpp
M1NH42/learn-dsa
70b5011a83dd5c29d39b754ed856cb9e023511f3
[ "MIT" ]
null
null
null
linked_list/linked_list1.cpp
M1NH42/learn-dsa
70b5011a83dd5c29d39b754ed856cb9e023511f3
[ "MIT" ]
null
null
null
linked_list/linked_list1.cpp
M1NH42/learn-dsa
70b5011a83dd5c29d39b754ed856cb9e023511f3
[ "MIT" ]
null
null
null
// Implementation of the linked list which comprises of the operations like // 1. defining a Node // 2. creating a Node // 3. traversing // 4. displaying node's data #include <bits/stdc++.h> using namespace std; // define Node struct Node { int data; struct Node * next; }*first = NULL; // create linked list void create(int A[],int n) { int i; // create node pointers struct Node *t,*last; // allocate memory in the heap section of the memory first=(struct Node *)malloc(sizeof(struct Node)); // assign first element of array to data of first node first->data=A[0]; // make point to NULL first->next=NULL; // make last and first point to the same node last=first; // loop thru and allocate nodes for(i=1;i<n;i++) { t=(struct Node*)malloc(sizeof(struct Node)); t->data=A[i]; t->next=NULL; last->next=t; last=t; } } // counting number of nodes in the linked list // 1 iterative approach int count_nodes(struct Node *p) { int count = 0; // condition while(p != NULL) { count++; p = p->next; } // return result return count; } // 2. Recurssive approach to count number of nodes // 1 iterative method // displays the data of the nodes void display(struct Node *p) { // traverse through the linked list // as long as we reach the last node while (p != NULL) { printf("%d \n", p->data); p = p -> next; } } // 2 recurssive method // display function // this displays the data in excessing order // because display_rec fxn is called after the // print statement void dispay_rec(struct Node * p) { // base condition for cont.. if(p != NULL) { // if we call the recurssive fxn first then the print // statement will be executed in the returning acces // prints the node data in reverse order dispay_rec(p->next); cout<< p->data << endl; // dispay_rec(p->next); } } // sum of nodes int sum_of_nodes(struct Node *p) { int sum=0; // traverse and add while(p) // equivalent to p!=NULL { sum += p->data; p = p->next; } // return results return sum; } // to find max value in a linked list int max_node(struct Node *p) { // init first as max int max = p->data; // till p becomes NULL while(p) { // if next data is greater than the max value if (p->data > max) { // simply update the max vaue with the greater value max = p->data; } // move p to next of p p = p->next; } // return max value return max; } // to find minimum element in the linked list we must follow the same // method but changing variables // search element in linked list // 1. Iterative // returns addres of that node where the key is present Node * search_node(struct Node *p, int key) { // while(p != NULL) while (p) { // if key is the first data of p if(key == p->data) { // return p return p; } // move p to next p = p->next; } // elese return NULL return NULL; } // function to insert at the begining of the linked list /* void insert_at_beg(struct Node *p, int data) { // create new_node struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); // insert data into the new_node new_node->data = data; // make newnode point to first new_node->next = first; // make the newnode as first node first = new_node; } */ // combine function to insert at any given position including // before the first node void insert_at_pos(struct Node *p, int index, int data) { //struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); // index validation if (index<0 || index > count_nodes(p)) { return; } // create new node struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); // store data to new_node's data section new_node->data = data; if (index == 0) { // points to frist node new_node->next = first; // make it first node first = new_node; } else { // move p to the node just before the position for (int i=0; i<index-1; i++) { // move p to next p =p->next; } // make new node point to p new_node->next = p->next; p->next = new_node; } } // insert_at_last() /* void insert_at_last(int data) { struct Node * new_node = (struct Node *)malloc(sizeof(struct Node)); new_node->data = data; if(first == NULL) { first = last = } } */ // insert in the sorted linked list void insert_in_sorted(struct Node * p, int data) { // init two pointer Node *t, *q = NULL; // create node to be inserted t = new Node; // store data in new node's data t->data = data; // new_node's next to null t->next = NULL; // if linked list is empty if (first == NULL) { // make new node as first first = t; } else { // check if p is not null while (p && p->data < data) { // q points to p q=p; // move p forward p=p->next; } if(p == first) { // if p is the head node // new_node points to head_node t->next = first; // make new_node as first first = t; } else { // new_node's next points to present node's next t->next=p->next; // q points to new_node which is added q->next=t; } } } // Function to delete a node at a given position int delete_at_pos(int pos) { // take two pointers struct Node * p, *q; // init the value to be deleted int del_val = -1; // check if the position is first or not if (pos == 1) { // if true // ppoints to first node p = first; // move first pointer point to next first = first->next; // store delete value in del_val del_val = first->data; // delete p because it's been allocated in // the heap memory delete p; } else { p=first; q=NULL; // p points to the node whose data to be deleted // q points to the previous node which helps to // delete node p for(int i=0; i<pos-1 && p; i++) { q=p; p=p->next; } if(p) // if p is not null { q->next=p->next; del_val=p->data; delete p; } } return del_val; } // if linked list is sorted or not int is_sorted(struct Node* p) { // smallest number possible // change according to your convinience int x = -1; while (p) { /* code */ if(p->data < x) { return 0; } x = p->data; p=p->next; } return 1; } /* This function removes the duplicate value from a sorted linked list by using two extra pointer to trace the duplicate element in the linked list */ void remove_duplicate() { // point p to first node struct Node *p = first; // point q to point next of the first node struct Node *q = first -> next; // do not stop until while (q != NULL) { // check if prev data is equals to next data if (p->data != q->data) { // if not : slide bothe the pointer p=q; q=q->next; } else { // if yes // delete node q p->next = q->next; delete q; q = p->next; } } } // reversing a linked list // in this we'll be using an auxillary array to reverse a linked list void reverse_linked_list_a(){ Node *p = first; // pointer to an array int *A; // dynamicaly allocate memory to an array A = (int *)malloc(sizeof(int)*count_nodes(p)); int i =0; // until p becomes null while(p){ // copy linked list data to the array A[i] = p->data; p=p->next; i++; } // again start from first p=first; // point to end of the array i--; while(p){ // copy array data to linked list // in the reverse order p->data=A[i]; // move p p=p->next; // move i backwards i--; } } // reverse linked list by reversing the links between nodes using three pointers void reverse_lisnked_list_b(){ // we will use the concept of sliding pointers using three different // pointers tail to each other struct Node *p, *q, *r; // initialize three pointers // points to first p=first; // null pointer before p q=NULL; // null but following q (assumption) r=NULL; // while p is not null while(p){ // r follows q r=q; // q foloows p q=p; // and p moves forward by one step each p=p->next; // and q points to r in reverse direction q->next=r; } // q becomes first node of the linked list first=q; } int is_loop(Node *f) { Node* p, *q; p=q=f; do { /* code */ p = p->next; q = q->next; q = q != NULL ? q->next:NULL; } while (p && q && p!=q); return p==q?1:0; } int main() { //struct Node *first = NULL; // add node // allocate memory in heap // first = (struct Node *) malloc(sizeof(struct Node)); // store data //first -> data = 10; // next does not point to any node //first -> next = NULL; // create space for temp //struct Node *temp; int A[]={3, 5, 7, 10, 99}; int size_array = sizeof(A) / sizeof(A[0]); create(A, size_array); // display(first); // called cout << "*************** break *******************\n"; // for loop in linked list struct Node *t1, *t2; t1 = first->next->next; t2 = first->next->next->next->next; // from loop t2->next=t1; // dispay_rec(first); /* if(first->next == NULL) { cout << "last node\n"; } */ // call insert at begining function // insert_at_beg(first, 121); // insert at any position // insert_at_pos(first, 4, 221); // display(first); // insert_in_sorted(first, 45); // called delete_at_pos() with pos // delete_at_pos(4); // cout<<"##################################"<<endl; display(first); // call count_nodes() cout << "Number of nodes: " << count_nodes(first)<<endl; // call sum_of_nodes() cout << "Sum of nodes: "<< sum_of_nodes(first)<<endl; // return max element in a linked list cout << "Max element : " << max_node(first)<< endl; // searching in a linked list // cout << "Element present at: " << search_node(first, 2)<<endl; cout<<"Linked list sorted: "<<is_sorted(first)<<endl; // remove_duplicate(); // display(first); reverse_lisnked_list_b(); display(first); /* if(is_loop(first)) { cout<<"loop is present\n"; } else { cout<<"linear linked list\n"; } */ return 0; }
20.131349
80
0.532057
M1NH42
204e6154a8b9b0078f0c3be6fa10de0029294c9e
1,691
cpp
C++
2017/1021_ARC083/C.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2017/1021_ARC083/C.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2017/1021_ARC083/C.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int main () { int A, B, C, D, E, F; cin >> A >> B >> C >> D >> E >> F; double nodo = 0; int sitsuryo = -1; int anssato = -1; for (auto i = 0; i <= 30; ++i) { for (auto j = 0; j <= 30; ++j) { int mizu = A * 100 * i + B * 100 * j; if (mizu > F) continue; int sato = F - mizu; sato = min(sato, mizu / 100 * E); for (auto k = 0; k * C <= sato; ++k) { int nokori = sato - k * C; int realsato = k * C + (nokori/D) * D; double nownodo = ((double)realsato) / (realsato + mizu); if (nodo <= nownodo) { nodo = nownodo; sitsuryo = realsato + mizu; anssato = realsato; } } } } cout << sitsuryo << " " << anssato << endl; }
28.183333
69
0.528681
kazunetakahashi
204f4f97a070799104c1666885d2adf221769829
75
cc
C++
ugine/external_src/stb_image/stb_image.cc
AdrianOrcik/ugine
4f5a9a5641c834834d9e18fc5b85b55140544568
[ "Apache-2.0" ]
null
null
null
ugine/external_src/stb_image/stb_image.cc
AdrianOrcik/ugine
4f5a9a5641c834834d9e18fc5b85b55140544568
[ "Apache-2.0" ]
null
null
null
ugine/external_src/stb_image/stb_image.cc
AdrianOrcik/ugine
4f5a9a5641c834834d9e18fc5b85b55140544568
[ "Apache-2.0" ]
null
null
null
#include "uepch.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"
18.75
32
0.8
AdrianOrcik
2050282634f645c271824228ab336077f59398f4
781
cpp
C++
WeatherStation/record.cpp
robotrobotrobotrobotrobot/CST276SRS01
f827b856bf5772232d65e0ddb3a73e34e3a42a50
[ "MIT" ]
null
null
null
WeatherStation/record.cpp
robotrobotrobotrobotrobot/CST276SRS01
f827b856bf5772232d65e0ddb3a73e34e3a42a50
[ "MIT" ]
null
null
null
WeatherStation/record.cpp
robotrobotrobotrobotrobot/CST276SRS01
f827b856bf5772232d65e0ddb3a73e34e3a42a50
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <chrono> #include "record.h" #include <chrono> #include "temperature.h" #include "humidity.h" #include "pressure.h" namespace WeatherStation { Record::Record ( Temperature const temperature, Humidity const humidity, Pressure const pressure ): temperature_{ temperature }, humidity_{ humidity }, pressure_{ pressure } { } std::chrono::system_clock::time_point Record::getTimepoint() const { return timepoint_; } Temperature Record::getTemperature() const { return temperature_; } Humidity Record::getHumidity() const { return humidity_; } Pressure Record::getPressure() const { return pressure_; } }
18.162791
70
0.614597
robotrobotrobotrobotrobot
205353b71da75cfb8db0e1902a7b88b220fba4e8
3,016
cpp
C++
MonomialTest.cpp
pichtj/groebner
38e8fb8df9977ffa120ca21a35cac0b0ee3d5afe
[ "MIT" ]
2
2019-09-05T15:32:33.000Z
2021-07-25T08:32:00.000Z
MonomialTest.cpp
pichtj/groebner
38e8fb8df9977ffa120ca21a35cac0b0ee3d5afe
[ "MIT" ]
null
null
null
MonomialTest.cpp
pichtj/groebner
38e8fb8df9977ffa120ca21a35cac0b0ee3d5afe
[ "MIT" ]
1
2018-02-20T16:34:55.000Z
2018-02-20T16:34:55.000Z
#include <sstream> #include <gtest/gtest.h> #include "Monomial.h" using namespace std; TEST(MonomialTest, lex) { Monomial<> e; Monomial<> f; Monomial<> g; g[1] = 1; Monomial<> h; h[1] = 12; EXPECT_FALSE(e < f); EXPECT_FALSE(f < e); EXPECT_TRUE(e < g); EXPECT_TRUE(e < h); EXPECT_TRUE(h > e); EXPECT_TRUE(g < h); EXPECT_FALSE(h < g); } TEST(MonomialTest, degrevlex) { use_abc_var_names in_this_scope; Monomial<> a = Monomial<>::x(0); Monomial<> b = Monomial<>::x(1); Monomial<> c = Monomial<>::x(2); EXPECT_FALSE(a < b); EXPECT_FALSE(b < c); EXPECT_TRUE(b < a); EXPECT_TRUE(c < b); EXPECT_TRUE(a*b*b > b*b*c); EXPECT_TRUE(a*b*c < a*a*c); EXPECT_TRUE(a*b*c < pow(a, 5)); } TEST(MonomialTest, Equal) { Monomial<> e; Monomial<> f; e[1] = 12; EXPECT_NE(e, f); f[1] = 12; EXPECT_EQ(e, f); } TEST(MonomialTest, x_i) { Monomial<> e = Monomial<>::x(0); EXPECT_EQ(e.degree(), 1); } TEST(MonomialTest, hash) { Monomial<> e = Monomial<>::x(1); Monomial<> f; std::hash<Monomial<> > h; EXPECT_NE(h(e), h(f)); } TEST(MonomialTest, ostreamOperator) { Monomial<> e = Monomial<>::x(1); EXPECT_EQ("x1", to_string(e)); EXPECT_EQ("1", to_string(Monomial<>())); } TEST(MonomialTest, divides) { Monomial<> x = Monomial<>::x(0); Monomial<> y = Monomial<>::x(1); Monomial<> a = x*x*x*y*y; Monomial<> b = x*x*y*y*y; Monomial<> c = x*y*y; EXPECT_FALSE(a.divides(b)); EXPECT_FALSE(b.divides(a)); EXPECT_FALSE(a.divides(c)); EXPECT_TRUE(c.divides(a)); EXPECT_FALSE(b.divides(c)); EXPECT_TRUE(c.divides(b)); } TEST(MonomialTest, lcm) { Monomial<> x = Monomial<>::x(0); Monomial<> y = Monomial<>::x(1); Monomial<> a = x*x*x*y*y; Monomial<> b = x*x*y*y*y; EXPECT_EQ(pow(x, 3)*pow(y, 3), lcm(a, b)); } TEST(MonomialTest, Multiplication) { Monomial<> x = Monomial<>::x(0); Monomial<> y = Monomial<>::x(1); Monomial<> a = x*x*x*y*y; Monomial<> b = x*x*y*y*y; Monomial<> p = a; p *= b; EXPECT_EQ(pow(x, 5)*pow(y, 5), a * b); EXPECT_EQ(pow(x, 5)*pow(y, 5), b * a); EXPECT_EQ(pow(x, 5)*pow(y, 5), p); EXPECT_EQ(pow(x, 5)*pow(y, 5), a * b * Monomial<>()); EXPECT_EQ(pow(x, 5)*pow(y, 5), b * a * Monomial<>()); } TEST(MonomialTest, Division) { Monomial<> x = Monomial<>::x(0); Monomial<> y = Monomial<>::x(1); Monomial<> a = x*x*x*y*y; Monomial<> b = x*x*y*y*y; Monomial<> p = a; p /= x; EXPECT_EQ(pow(x, 2)*pow(y, 2), a / x); EXPECT_EQ(pow(x, 2)*pow(y, 2), b / y); EXPECT_EQ(pow(x, 2)*pow(y, 2), p); } TEST(MonomialTest, Input) { typedef Monomial<> M; use_abc_var_names in_this_scope; EXPECT_EQ(M::x(0), from_string<M>("a")); EXPECT_EQ(M::x(1), from_string<M>("b")); EXPECT_EQ(pow(M::x(0), 3), from_string<M>("a^3")); EXPECT_EQ(pow(M::x(1), 4), from_string<M>("b^4")); EXPECT_EQ(pow(M::x(0), 1) * pow(M::x(1), 4), from_string<M>("a*b^4")); EXPECT_EQ(pow(M::x(0), 3) * pow(M::x(1), 4), from_string<M>("a^3*b^4")); } // vim:ruler:cindent:shiftwidth=2:expandtab:
21.542857
74
0.581565
pichtj
20590a44325bc1c79454e12ce96788170aabc74b
15,061
cpp
C++
src/L1k++.cpp
BioDepot/L1kpp
a08b568fff9879a3ee56cdc339890dfb8a32a54c
[ "BSD-2-Clause", "MIT" ]
null
null
null
src/L1k++.cpp
BioDepot/L1kpp
a08b568fff9879a3ee56cdc339890dfb8a32a54c
[ "BSD-2-Clause", "MIT" ]
null
null
null
src/L1k++.cpp
BioDepot/L1kpp
a08b568fff9879a3ee56cdc339890dfb8a32a54c
[ "BSD-2-Clause", "MIT" ]
null
null
null
#include<fstream> #include<stdio.h> #include<string> #include<FCSIO.hpp> #include<tclap/CmdLine.h> #include<common.hpp> #include<gmm.hpp> #include<qNorm.hpp> #include<omp.h> void show_help (); void process_lxb_file(std::string inputFile,vector<float> *values,int nBins,bool logTransform); void process_binary_file(std::string inputFile,vector<float> *values,int nBins,bool logTransform); int main (int argc, char *argv[]){ using namespace std; string inputFile,outputFile,inputDir,list,refList,inqRefTextFile,inqRefBinFile,outDensityFile,outqRefBinFile,outqRefTextFile,outputDir; bool outBinary=0,inBinary=0,logTransform=0,convert=0,outqRef=0,qNorm=0,deCon=0,pruneFlag=0,ensemble=0,outputRawData=0; int minBeads=MINBEADS,nThreads=1,metaData=0,nGroups=1,nFold=1; float minLogValue,maxLogValue,smoothHalfWindowSize,peakGridSize,densityHalfWindowSize; try{ using namespace TCLAP; CmdLine cmd("lxbdecon flags", ' ', "0.1"); ValueArg<string> inputDirArg ("d","dir","input lxb directory",false,"","string"); ValueArg<string> outputDirArg ("o","outputDir","output directory",false,"","string"); ValueArg<string> inputFileArg ("i","inFile","input lxb file",false,"","string"); ValueArg<string> outDensityFileArg ("","outDensityFile","output density file",false,"","string"); ValueArg<string> outqRefBinFileArg ("","outqRefBinFile","make binary quantile reference density file from list of binary level 1.5 data",false,"","string"); ValueArg<string> outqRefTextFileArg ("","outqRefTextFile","make text quantile reference density file from list of binary level 1.5 data",false,"","string"); ValueArg<string> listArg ("","list","list of files to be processed",false,"","string"); ValueArg<string> refListArg ("","refList","list of files to be used as a reference for qNormalization",false,"","string"); ValueArg<string> inqRefTextFileArg ("","inqRefText","defines reference distribution for quantile normalization file in text format",false,"","string"); ValueArg<string> inqRefBinFileArg ("","inqRefBin","defines reference distribution for quantile normalization filmat",false,"","string"); ValueArg<int> metaDataArg ("m","metaData","indicates the amount of metadata to be output with deconvolution ",false,0,"int"); ValueArg<int> nThreadsArg ("n","nThreads","number of threads ",false,1,"int"); ValueArg<float> minLogValueArg ("","minLogValue","minimum expression value in log2 scale ",false,3.0,"float"); ValueArg<float> maxLogValueArg ("","maxLogValue","maximum expression value in log2 scale ",false,14.5,"float"); ValueArg<float> smoothHalfWindowSizeArg ("","smoothHalfWindowSize","windowing size for smoothing data ",false,0.2,"float"); ValueArg<float> densityHalfWindowSizeArg ("","densityHalfWindowSize","windowing size for smoothing density ",false,0.1,"float"); ValueArg<float> peakGridSizeArg ("","peakGridSize","maximum expression value in log2 scale ",false,0.2,"float"); ValueArg<int>nGroupsArg("","nGroups","number of groups to group together - for testing purposes",false,1,"int"); ValueArg<int> nBootStrapsArg ("","nBootStraps","number of bootstrap runs ",false,0,"int"); ValueArg<int> nFoldArg ("","nFold","number of repetitions for calculating median values (1/nFold samples are excluded from each run)",false,1,"int"); ValueArg<float> bootstrapSizeArg ("","bootstrapSize","proportion of set to sample per bootstrap",false,0.8,"float"); SwitchArg convertArg ("c","convert","indicates that the input file will be converted to another format - default is lxb to binary",cmd,false); SwitchArg outBinaryArg ("","outBinary","indicates that the output file will be in binary - default is text",cmd,false); SwitchArg inBinaryArg ("","inBinary","indicates that the input file is a binary file - default is lxb",cmd,false); SwitchArg logTransformArg ("l","logTransform","indicates that input file is to be logTransformed",cmd,false); SwitchArg qNormArg ("q","qNorm","indicates that input file or list is to be quantile normalized",cmd,false); SwitchArg ensembleArg ("e","ensemble","indicates that input file or list of files will be treated as one large experiment",cmd,false); SwitchArg deConArg ("","deCon","deConvolute spectra",cmd,false); SwitchArg outputRawDataArg ("","outputRawData","the raw expression numbers are outputted for each experiment",cmd,false); cmd.add(inputFileArg); cmd.add(inputDirArg); cmd.add(outputDirArg); cmd.add(metaDataArg); cmd.add(nThreadsArg); cmd.add(nGroupsArg); cmd.add(listArg); cmd.add(refListArg); cmd.add(inqRefTextFileArg); cmd.add(inqRefBinFileArg); cmd.add(outqRefTextFileArg); cmd.add(outqRefBinFileArg); cmd.add(outDensityFileArg); cmd.add(minLogValueArg); cmd.add(maxLogValueArg); cmd.add(smoothHalfWindowSizeArg); cmd.add(densityHalfWindowSizeArg); cmd.add(nFoldArg); cmd.parse( argc, argv ); outBinary=outBinaryArg.getValue(); inBinary=inBinaryArg.getValue(); logTransform=logTransformArg.getValue(); convert=convertArg.getValue(); inputFile= inputFileArg.getValue(); inputDir=inputDirArg.getValue(); outputDir=outputDirArg.getValue(); metaData=metaDataArg.getValue(); nThreads=nThreadsArg.getValue(); outDensityFile=outDensityFileArg.getValue(); inqRefTextFile=inqRefTextFileArg.getValue(); inqRefBinFile=inqRefBinFileArg.getValue(); outqRefTextFile=outqRefTextFileArg.getValue(); outqRefBinFile=outqRefBinFileArg.getValue(); list=listArg.getValue(); refList=refListArg.getValue(); qNorm=qNormArg.getValue(); deCon=deConArg.getValue(); ensemble=ensembleArg.getValue(); minLogValue=minLogValueArg.getValue(); maxLogValue=maxLogValueArg.getValue(); peakGridSize=peakGridSizeArg.getValue(); smoothHalfWindowSize=smoothHalfWindowSizeArg.getValue(); densityHalfWindowSize=densityHalfWindowSizeArg.getValue(); nGroups=nGroupsArg.getValue(); outputRawData=outputRawDataArg.getValue(); nFold=nFoldArg.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { cerr << "error: " << e.error() << " for arg " << e.argId() << endl; } cerr << list <<endl; //conversion routines //these routines were used to convert lxb files to level1.5 binary files //should move these into a separate toolbox for file conversions if(convert){ //convert a list of lxb files to a binary file size_t counts[NCOLORS1OFF]; //0 analyte is present - indicates error? memset(counts,0,(NCOLORS1OFF)*sizeof(size_t)); if(inputDir != ""){ namespace fs = boost::filesystem; if ( fs::exists(inputDir) && fs::is_directory(inputDir)){ cerr << "working on directory " << inputDir << endl; fs::directory_iterator end_itr; fs::path p(inputDir); fs::create_directory(inputDir+"_b"); //gather all the filenames - this is necessary for OpenMP parallelization vector <string> files; for (fs::directory_iterator itr(p); itr != end_itr; ++itr){ if (is_regular_file(itr->path())) { if(inBinary){ files.push_back(itr->path().stem().string()+itr->path().extension().string()); } else if(itr->path().extension().string() == ".lxb"){ files.push_back(itr->path().stem().string()+itr->path().extension().string()); } else{ continue; } } } #pragma omp parallel for num_threads(nThreads) for (int f=0;f<files.size();f++){ //read in each lxb file into values vector vector<float> values[NCOLORS1OFF]; string file = files[f]; cerr << "checking file " << inputDir+"/"+file <<" of type binary" <<endl; if(file.substr(file.length()-4,4) == ".lxb"){ process_lxb_file(inputDir+"/"+file,values,NCOLORS1OFF,logTransform); } string outputFile=inputDir+"_b/"+file+".bin"; cerr << "converting file to outputFile " << outputFile <<endl; FILE *outfp=fopen(outputFile.c_str(),"w"); for (int i=1; i<NCOLORS1OFF; ++i){ if(values[i].size()){ int16_t buffer[2]; buffer[0]=i; buffer[1]=(int16_t)values[i].size(); fwrite (buffer ,sizeof(int16_t),2,outfp); for(int k=0;k<values[i].size();k++){ int16_t v =(int16_t) (values[i][k]+.5); fwrite (&(v),sizeof(int16_t),1,outfp); } } } fclose(outfp); } } } else if(inputFile!=""){ cerr << "checking file " << inputFile <<endl; vector<float> values[NCOLORS1OFF]; if(inputFile.substr(inputFile.length()-4) == ".lxb"){ process_lxb_file(inputFile,values,NCOLORS1OFF,logTransform); } string outputFile=inputFile.substr(0,inputFile.length()-4) +".bin"; cerr << "converting file to outputFile " << outputFile <<endl; FILE *outfp=fopen(outputFile.c_str(),"w"); for (int i=1; i<NCOLORS1OFF; ++i){ if(values[i].size()){ int16_t buffer[2]; buffer[0]=i; buffer[1]=(int16_t)values[i].size(); fwrite (buffer ,sizeof(int16_t),2,outfp); for(int k=0;k<values[i].size();k++){ int16_t v =(int16_t) values[i][k]+.5; fwrite (&(v),sizeof(int16_t),1,outfp); } } } fclose(outfp); } } //routines to make qNormed baseline files if(outqRefBinFile != "" && refList == "" && list != ""){ //make qNorm files from list of files and save fprintf (stderr,"refList not given - using list %s to generate quantile normalization reference file\n",list.c_str()); wellRecord <int16_t,int> wells(list,minLogValue,maxLogValue,smoothHalfWindowSize,peakGridSize); density ref(wells); ref.write_refFile(outqRefBinFile.c_str()); return(1); } else if(outqRefBinFile != "" && refList != ""){ //make qNorm files from list of files and save wellRecord <int16_t,int> wells(refList,minLogValue,maxLogValue,smoothHalfWindowSize,peakGridSize); density ref(wells); ref.write_refFile(outqRefBinFile.c_str()); return(1); } else if(outqRefTextFile !="" && refList != ""){ wellRecord <int16_t,int> wells(list,minLogValue,maxLogValue,smoothHalfWindowSize,peakGridSize); density ref(wells); ref.write_textRefFile(outqRefTextFile.c_str()); return(1); } else if(outqRefTextFile !="" && refList == "" && list != ""){ fprintf (stderr,"refList not given - using list %s to generate quantile normalization reference file\n",list.c_str()); wellRecord <int16_t,int> wells(list,minLogValue,maxLogValue,smoothHalfWindowSize,peakGridSize); density ref(wells); ref.write_textRefFile(outqRefTextFile.c_str()); return(1); } //if we are not doing a conversion or making baseline files - we are deconvoluting //read the list of files in binary format wellRecord <int16_t,int> wells(list,minLogValue,maxLogValue,smoothHalfWindowSize,peakGridSize); for(int i=0;i<wells.groupNames.size();i++){ fprintf(stderr,"%d %d name %s offset %d\n",i,wells.nTotalWells,wells.groupNames[i].c_str(),wells.groupOffsets[i]); } density ref; //are we doing quantile normalization? if(qNorm){ //where are we getting the reference distribution from? if(inqRefTextFile !=""){ ref=density(inqRefTextFile,1); } else if (inqRefBinFile != ""){ ref=density(inqRefBinFile,2); } else if(refList !=""){ wellRecord <int16_t,int> qwells(refList,minLogValue,maxLogValue,smoothHalfWindowSize,peakGridSize); ref=density(qwells); } else{ ref=density(wells); } ref.qNorm(wells); } //do we deconvolute? if(deCon){ if(outBinary){ //check if we are outputing binary files metaData=-1; } //decon individual wells if(outputDir == "" ){ char buffer [L_tmpnam]; tmpnam (buffer); string bufferStr=buffer; outputDir=="output_"+bufferStr; } //deconvolute individual groups //make sure that there are no remainders int nIterations=(wells.groupNames.size()/nGroups)*nGroups; #pragma omp parallel num_threads(nThreads) { vector <DeconRecord <float>> deconRecords(nFold); vector <MedianRecord<float>> medianRecords(501); for(int i=0;i<nIterations;i+=nGroups){ int t=0; if(nThreads >1){ t=omp_get_thread_num(); } //initialize the deconRecord to nans and zeros for(int f=0;f<nFold;f++){ deconRecords[f].blank(); } for(int k=0;k<501;k++){ medianRecords[k].blank(); } string groupName=wells.groupNames[i]; FILE *fpRaw=0; if(outputRawData){ string rawOutputFile=outputDir+"/"+groupName+".raw"; fpRaw=fopen(rawOutputFile.c_str(),"w"); } string peaksFile=outputDir+"/"+groupName+".peaks"; string medianFile=outputDir+"/"+groupName+".medians"; if(wells.deconvolute(nFold,i,nGroups,deconRecords,medianRecords,fpRaw)){ FILE *fpPeaks=fopen(peaksFile.c_str(),"w"); for(int f=0;f<nFold;f++){ deconRecords[f].print_text(fpPeaks,metaData); } fclose(fpPeaks); FILE *fpMedian=fopen(medianFile.c_str(),"w"); for (int k=0;k<501;k++){ medianRecords[k].calculate_medians(); fprintf(fpMedian,"%d %f ",k,medianRecords[k].median0); for(int f=0;f<medianRecords[k].means0.size();f++){ fprintf(fpMedian,"%f:",medianRecords[k].means0[f]); } fprintf(fpMedian," %f ",medianRecords[k].median1); for(int f=0;f<medianRecords[k].means0.size();f++){ fprintf(fpMedian,"%f:",medianRecords[k].means1[f]); } fprintf(fpMedian,"\n"); } fclose(fpMedian); } if(fpRaw) fclose(fpRaw); } } } //are we dumping out a density file if(outDensityFile != ""){ wells.dumpDensity(outDensityFile,densityHalfWindowSize); } return(1); } void process_binary_file(std::string inputFile,vector<float> *values,int nBins,bool logTransform){ int16_t header[2]; FILE *fp=fopen(inputFile.c_str(),"r"); while(fread(&header,2*sizeof(int16_t),1,fp)){ values[header[0]].resize(0); values[header[0]].reserve(header[1]); for(int k=0;k<values[header[0]].size();k++){ int16_t v; int nRead=fread(&v,sizeof(int16_t),1,fp); if(nRead){ if(!logTransform)values[header[0]][k]=(float)v; else if(v<=1)values[header[0]][k]=0; else values[header[0]][k]=log((float)v)*INVLOG2; } } } fclose(fp); } void process_lxb_file(std::string inputFile,vector<float> *values,int nBins,bool logTransform){ using namespace FCSTools; std::fstream file (inputFile, std::ios::binary|std::ios::in); FCS<std::size_t> fcs= Reader<std::size_t> (file, 1); int nRecords=fcs.Data.size (); int colRID,colRP1; //find the RID and RP1 records for (int i=0; i<fcs.Head.Parameter.size();++i){ if(fcs.Head.Parameter[i].Name == "RID"){ colRID=i; } else if(fcs.Head.Parameter[i].Name == "RP1"){ colRP1=i; } } if(logTransform){ for (int i=0; i<fcs.Data.size(); ++i){ if(fcs.Data[i][colRID] && fcs.Data[i][colRID]<nBins){ if(fcs.Data[i][colRP1] <= 2) values[fcs.Data[i][colRID]].push_back(1); else values[fcs.Data[i][colRID]].push_back(log(fcs.Data[i][colRP1])*INVLOG2); } } } else{ for (int i=0; i<fcs.Data.size(); ++i){ if(fcs.Data[i][colRID] && fcs.Data[i][colRID]<nBins){ values[fcs.Data[i][colRID]].push_back(fcs.Data[i][colRP1]); } } } }
41.150273
158
0.685612
BioDepot
205a5a4f7e92f7fcd1fa2543b2d75a5bc1a1214b
12,532
cpp
C++
Blizzlike/ArcEmu/C++/InstanceScripts/Raid_TheObsidianSanctum.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/InstanceScripts/Raid_TheObsidianSanctum.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/InstanceScripts/Raid_TheObsidianSanctum.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" enum ENCOUNTER_CREATURES { CN_SARTHARION = 28860, CN_FLAME_TSUNAMI = 30616, CN_LAVA_BLAZE = 30643, CN_CYCLON = 30648, CN_DRAKE_TENEBRON = 30452, CN_DRAKE_VESPERON = 30449, CN_DRAKE_SHADRON = 30451, }; enum SARTHARION_DATA { DRAKE_TENEBRON, DRAKE_VESPERON, DRAKE_SHADRON, BOSS_SARTHARION, OS_DATA_END = 4 }; #define SARTHARION_FLAME_BREATH HeroicInt( 56908, 58956 ) #define SARTHARION_TAIL_LASH HeroicInt( 56910, 58957 ) enum ENCOUNTER_SPELLS { // Sartharion SARTHARION_CLEAVE = 56909, SARTHARION_ENRAGE = 61632, SARTHARION_AURA = 61254, // Tsunami spells TSUNAMI = 57492, TSUNAMI_VISUAL = 57494, // Cyclon spells CYCLON_AURA = 57562, CYCLON_SPELL = 57560, // TODO: add drake spells SHADRON_AURA = 58105, TENEBRON_AURA = 61248, VESPERON_AURA = 61251, }; static Location TSUNAMI_SPAWN[] = { // Right { 3283.215820f, 511.234100f, 59.288776f, 3.148659f }, { 3286.661133f, 533.317261f, 59.366989f, 3.156505f }, { 3283.311035f, 556.839611f, 59.397129f, 3.105450f }, // Left { 3211.564697f, 505.982727f, 59.556610f, 0.000000f }, { 3214.280029f, 531.491089f, 59.168331f, 0.000000f }, { 3211.609131f, 560.359375f, 59.420803f, 0.000000f }, }; static Location TSUNAMI_MOVE[] = { // Left if right { 3211.564697f, 505.982727f, 59.556610f, 3.148659f }, { 3214.280029f, 531.491089f, 59.168331f, 3.156505f }, { 3211.609131f, 560.359375f, 59.420803f, 3.105450f }, // Right 1 if left 1 { 3283.215820f, 511.234100f, 59.288776f, 3.148659f }, { 3286.661133f, 533.317261f, 59.366989f, 3.156505f }, { 3283.311035f, 556.839611f, 59.397129f, 3.105450f } }; #define MAP_OS 615 class ObsidianSanctumScript : public MoonInstanceScript { public: uint32 m_creatureGuid[OS_DATA_END]; MOONSCRIPT_INSTANCE_FACTORY_FUNCTION(ObsidianSanctumScript, MoonInstanceScript); ObsidianSanctumScript(MapMgr* pMapMgr) : MoonInstanceScript(pMapMgr) { memset(m_creatureGuid, 0, sizeof(m_creatureGuid)); }; void OnCreaturePushToWorld(Creature* pCreature) { switch(pCreature->GetEntry()) { case CN_DRAKE_TENEBRON: m_creatureGuid[DRAKE_TENEBRON] = pCreature->GetLowGUID(); break; case CN_DRAKE_VESPERON: m_creatureGuid[DRAKE_VESPERON] = pCreature->GetLowGUID(); break; case CN_DRAKE_SHADRON: m_creatureGuid[DRAKE_SHADRON] = pCreature->GetLowGUID(); break; case CN_SARTHARION: m_creatureGuid[BOSS_SARTHARION] = pCreature->GetLowGUID(); break; default: break; }; }; void OnCreatureDeath(Creature* pVictim, Unit* pKiller) { switch(pVictim->GetEntry()) { case CN_SARTHARION: m_creatureGuid[BOSS_SARTHARION] = 0; break; default: break; }; }; void DoDrakeAura(uint8 pData) { uint32 pSpellEntry = 0; switch(pData) { case DRAKE_TENEBRON: pSpellEntry = TENEBRON_AURA; break; case DRAKE_SHADRON: pSpellEntry = SHADRON_AURA; break; case DRAKE_VESPERON: pSpellEntry = VESPERON_AURA; break; default: break; }; Creature* pSartharion = GetCreature(BOSS_SARTHARION); if(pSartharion == NULL) return; pSartharion->CastSpell(pSartharion, pSpellEntry, true); pSartharion->RemoveAura(pSpellEntry); // unproper hackfix }; Creature* GetCreature(uint8 pData) { if(pData >= OS_DATA_END) // impossible tho return NULL; return GetCreatureByGuid(m_creatureGuid[pData]); }; }; void SpellFunc_FlameTsunami(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { if(pCreatureAI != NULL) { pCreatureAI->GetUnit()->SendChatMessage(CHAT_MSG_RAID_BOSS_EMOTE, LANG_UNIVERSAL, "The lava surrounding Sartharion churns!"); uint32 RandomSpeach = rand() % 4; switch(RandomSpeach) { case 0: pCreatureAI->Emote("Such flammable little insects....", Text_Yell, 14100); break; case 1: pCreatureAI->Emote("Your charred bones will litter the floor!", Text_Yell, 14101); break; case 2: pCreatureAI->Emote("How much heat can you take?", Text_Yell, 14102); break; case 3: pCreatureAI->Emote("All will be reduced to ash!", Text_Yell, 14103); break; }; uint32 RndSide = rand() % 2; Creature* Tsunami = NULL; for(int i = 0; i < 3; ++i) { switch(RndSide) { case 0: Tsunami = pCreatureAI->GetUnit()->GetMapMgr()->GetInterface()->SpawnCreature(CN_FLAME_TSUNAMI, TSUNAMI_SPAWN[i].x, TSUNAMI_SPAWN[i].y, TSUNAMI_SPAWN[i].z, TSUNAMI_SPAWN[i].o, true, true, 0, 0); if(Tsunami != NULL) Tsunami->GetAIInterface()->MoveTo(TSUNAMI_MOVE[i].x, TSUNAMI_MOVE[i].y, TSUNAMI_MOVE[i].z, TSUNAMI_MOVE[i].o); break; case 1: Tsunami = pCreatureAI->GetUnit()->GetMapMgr()->GetInterface()->SpawnCreature(CN_FLAME_TSUNAMI, TSUNAMI_SPAWN[i + 3].x, TSUNAMI_SPAWN[i + 3].y, TSUNAMI_SPAWN[i + 3].z, TSUNAMI_SPAWN[i + 3].o, true, true, 0, 0); if(Tsunami != NULL) Tsunami->GetAIInterface()->MoveTo(TSUNAMI_MOVE[i + 3].x, TSUNAMI_MOVE[i + 3].y, TSUNAMI_MOVE[i + 3].z, TSUNAMI_MOVE[i + 3].o); }; Tsunami = NULL; }; }; }; void SpellFunc_LavaSpawn(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { if(pCreatureAI == NULL) return; for(int i = 0; i < 2; ++i) { uint32 j = rand() % 6; pCreatureAI->SpawnCreature(CN_LAVA_BLAZE, pTarget->GetPositionX() + j, pTarget->GetPositionY() + j, pTarget->GetPositionZ(), pTarget->GetOrientation(), true); }; }; class SartharionAI : public MoonScriptBossAI { MOONSCRIPT_FACTORY_FUNCTION(SartharionAI, MoonScriptBossAI); SartharionAI(Creature* pCreature) : MoonScriptBossAI(pCreature) { mInstance = dynamic_cast<ObsidianSanctumScript*>(GetInstanceScript()); AddSpell(SARTHARION_CLEAVE, Target_Current, 24, 0, 8); SpellDesc* mFlame = AddSpell(SARTHARION_FLAME_BREATH, Target_Self, 18, 2, 16); mFlame->AddEmote("Burn, you miserable wretches!", Text_Yell, 14098); AddSpell(SARTHARION_TAIL_LASH, Target_Self, 40, 0, 12); mFlameTsunami = AddSpellFunc(&SpellFunc_FlameTsunami, Target_Self, 99, 0, 25); mSummonLava = AddSpellFunc(&SpellFunc_LavaSpawn, Target_RandomUnitNotCurrent, 25, 0, 8); AddEmote(Event_OnTargetDied, "You will make a fine meal for the hatchlings.", Text_Yell, 14094); AddEmote(Event_OnTargetDied, "You are at a grave disadvantage!", Text_Yell, 14096); AddEmote(Event_OnTargetDied, "This is why we call you lesser beings.", Text_Yell, 14097); AddEmote(Event_OnCombatStart, "It is my charge to watch over these eggs. I will see you burn before any harm comes to them!", Text_Yell, 14093); for(int i = 0; i < OS_DATA_END - 1; i++) { m_bDrakes[i] = false; m_cDrakes[i] = NULL; } mDrakeTimer = 0; m_bEnraged = false; m_iDrakeCount = 0; }; void OnCombatStart(Unit* pTarget) { m_bEnraged = false; mFlameTsunami->TriggerCooldown(); CheckDrakes(); if(m_iDrakeCount >= 1) //HardMode! { mDrakeTimer = AddTimer(30000); ApplyAura(SARTHARION_AURA); RemoveAuraOnPlayers(SARTHARION_AURA); // unproper hackfix Regenerate();// Lets heal him as aura increase his hp for 25% }; ParentClass::OnCombatStart(pTarget); }; void AIUpdate() { if(m_iDrakeCount >= 1) { if(IsTimerFinished(mDrakeTimer)) { if(m_bDrakes[DRAKE_TENEBRON] == true) CallTenebron(); else if(m_bDrakes[DRAKE_SHADRON] == true) CallShadron(); else if(m_bDrakes[DRAKE_VESPERON] == true) CallVesperon(); ResetTimer(mDrakeTimer, 45000); }; }; if(GetHealthPercent() <= 10 && m_bEnraged == false) // enrage phase { for(uint32 i = 0; i < 3; ++i) CastSpellNowNoScheduling(mSummonLava); m_bEnraged = true; }; ParentClass::AIUpdate(); }; void CheckDrakes() { if(mInstance == NULL) return; m_iDrakeCount = 0; for(uint8 i = 0; i < (OS_DATA_END - 1); ++i) { m_cDrakes[i] = mInstance->GetCreature(i); if(m_cDrakes[i] != NULL && m_cDrakes[i]->isAlive()) { m_bDrakes[i] = true; m_iDrakeCount++; mInstance->DoDrakeAura(i); }; }; }; void CallTenebron() { if(m_cDrakes[DRAKE_TENEBRON] != NULL && m_cDrakes[DRAKE_TENEBRON]->isAlive()) { Emote("Tenebron! The eggs are yours to protect as well!", Text_Yell, 14106); m_cDrakes[DRAKE_TENEBRON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_TENEBRON] = false; }; void CallShadron() { if(m_cDrakes[DRAKE_SHADRON] != NULL && m_cDrakes[DRAKE_SHADRON]->isAlive()) { Emote("Shadron! The clutch is in danger! Assist me!", Text_Yell, 14104); m_cDrakes[DRAKE_SHADRON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_SHADRON] = false; }; void CallVesperon() { if(m_cDrakes[DRAKE_VESPERON] != NULL && m_cDrakes[DRAKE_VESPERON]->isAlive()) { Emote("Vesperon! Come to me, all is at risk!", Text_Yell, 14105); m_cDrakes[DRAKE_VESPERON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_VESPERON] = false; }; void OnDied(Unit* pKiller) { Emote("Such is the price... of failure...", Text_Yell, 14107); RemoveAIUpdateEvent(); ParentClass::OnDied(pKiller); }; private: bool m_bDrakes[OS_DATA_END - 1]; int32 mDrakeTimer; bool m_bEnraged; int m_iDrakeCount; ObsidianSanctumScript* mInstance; Creature* m_cDrakes[OS_DATA_END - 1]; // exclude boss SpellDesc* mFlameTsunami, *mSummonLava; }; class TsunamiAI : public MoonScriptBossAI { MOONSCRIPT_FACTORY_FUNCTION(TsunamiAI, MoonScriptBossAI); TsunamiAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { RegisterAIUpdateEvent(1000); SetFlyMode(true); SetCanEnterCombat(false); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); Despawn(11500, 0); ParentClass::OnLoad(); }; void AIUpdate() { ApplyAura(TSUNAMI); ApplyAura(TSUNAMI_VISUAL); RegisterAIUpdateEvent(11000); ParentClass::OnLoad(); }; }; class CyclonAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(CyclonAI, MoonScriptBossAI); CyclonAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { SetCanMove(false); SetCanEnterCombat(false); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); ApplyAura(CYCLON_SPELL); ApplyAura(CYCLON_AURA); ParentClass::OnLoad(); }; }; class LavaBlazeAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(LavaBlazeAI, MoonScriptBossAI); LavaBlazeAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { AggroNearestPlayer(1); ParentClass::OnLoad(); }; void OnCombatStop(Unit* pTarget) { Despawn(1000, 0); }; void OnDied(Unit* pKiller) { Despawn(1000, 0); }; }; void SetupTheObsidianSanctum(ScriptMgr* mgr) { ////////////////////////////////////////////////////////////////////////////////////////// ///////// Mobs ////////////////////////////////////////////////////////////////////////////////////////// ///////// Bosses mgr->register_creature_script(CN_SARTHARION, &SartharionAI::Create); mgr->register_creature_script(CN_FLAME_TSUNAMI, &TsunamiAI::Create); mgr->register_creature_script(CN_CYCLON, &CyclonAI::Create); mgr->register_creature_script(CN_LAVA_BLAZE, &LavaBlazeAI::Create); ////////////////////////////////////////////////////////////////////////////////////////// ///////// Instance mgr->register_instance_script(MAP_OS, &ObsidianSanctumScript::Create); };
27.125541
214
0.671162
499453466
2063333dde42e7d2c921cb9b8d0887833a9c138a
18,297
cc
C++
src/paths/long/LoadCorrectCore.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
48
2016-04-26T16:52:59.000Z
2022-01-15T09:18:17.000Z
src/paths/long/LoadCorrectCore.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
45
2016-04-27T08:20:56.000Z
2022-02-14T07:47:11.000Z
src/paths/long/LoadCorrectCore.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
15
2016-05-11T14:35:25.000Z
2022-01-15T09:18:45.000Z
/////////////////////////////////////////////////////////////////////////////// // SOFTWARE COPYRIGHT NOTICE AGREEMENT // // This software and its documentation are copyright (2014) by the // // Broad Institute. All rights are reserved. This software is supplied // // without any warranty or guaranteed support whatsoever. The Broad // // Institute is not responsible for its use, misuse, or functionality. // /////////////////////////////////////////////////////////////////////////////// // MakeDepend: library OMP // MakeDepend: cflags OMP_FLAGS #include "Basevector.h" #include "CoreTools.h" #include "PairsManager.h" #include "ParseSet.h" #include "Qualvector.h" #include "paths/FindErrorsCore.h" #include "paths/HyperKmerPath.h" #include "kmers/naif_kmer/KernelKmerStorer.h" #include "lookup/LibInfo.h" //#include "lookup/SAM2CRD.h" #include "paths/long/Correct1Pre.h" #include "paths/long/CorrectPairs1.h" //#include "paths/long/DataSpec.h" #include "paths/long/FillPairs.h" #include "paths/long/Heuristics.h" #include "paths/long/LoadCorrectCore.h" #include "paths/long/Logging.h" #include "paths/long/LongProtoTools.h" #include "paths/long/LongReadsToPaths.h" #include "paths/long/PreCorrectAlt1.h" #include "paths/long/PreCorrectOldNew.h" #include "paths/long/DiscovarTools.h" #include <numeric> #include <type_traits> #include "util/w2rap_timers.h" #include "ReadStack.h" void PopulateSpecials( const vecbasevector& creads, const PairsManager& pairs, const vecbasevector& creads_done, const vec<Bool>& done, const VecEFasta& corrected, const int NUM_THREADS, vec<Bool>& special//, /*const long_logging& logc*/ ) { //if (logc.STATUS_LOGGING) std::cout << Date( ) << ": computing kmers_plus" << std::endl; const int M = 40; const int min_strong = 5; // only implmemented for K<=60 right now; need a wider Kmer below for higher K. ForceAssertLe(M, 60); typedef Kmer60 Kmer_t; typedef KmerKmerFreq<Kmer_t> KmerRec_t; // Kmer + frequency vec<KmerRec_t> kmer_vec; // calculate the kmer frequency db, thresholding at min_freq Validator valid( min_strong, 0 ); KernelKmerStorer<KmerRec_t> storer( creads, M, &kmer_vec, &valid ); naif_kmerize( &storer, NUM_THREADS, false ); // this is a kludge, but for now we're just going to convert the // kmers to the style expected by the code below. vec< kmer<M> > kmers; for ( size_t i = 0; i < kmer_vec.size(); ++i ) { basevector bv(M); for ( int j = 0; j < M; ++j ) bv.Set(j, kmer_vec[i][j] ); kmer<M> x(bv); kmers.push_back(x); x.ReverseComplement(); kmers.push_back(x); } vec<KmerRec_t>().swap( kmer_vec ); // return memory for kmer_vec. std::sort( kmers.begin(), kmers.end() ); // sort for later lookup, serial to avoid Parallel sort memory penalty //if (logc.STATUS_LOGGING) // std::cout << Date( ) << ": computing right extensions" << std::endl; const int min_ext = 200; vec<Bool> right_ext( kmers.size( ), False ); //#pragma omp parallel for for ( size_t id = 0; id < corrected.size( ); id++ ) // calculating right_ext[i] for kmers[i] { vec<basevector> v; corrected[id].ExpandTo(v); if ( done[id] ) v.push_back( creads_done[id] ); for ( int j = 0; j < v.isize( ); j++ ) { kmer<M> x; for ( int s = 0; s <= v[j].isize( ) - M; s++ ) { int ext = v[j].isize( ) - s; x.SetToSubOf( v[j], s ); int64_t p; if ( ext >= min_ext ) { p = BinPosition( kmers, x ); if ( p >= 0 && !right_ext[p] ) right_ext[p] = True; } ext = s + M; if ( ext >= min_ext ) { x.ReverseComplement( ); p = BinPosition( kmers, x ); if ( p >= 0 && !right_ext[p] ) right_ext[p] = True; } } } } //if (logc.STATUS_LOGGING) std::cout << Date( ) << ": finding specials" << std::endl; special.resize( creads.size(), False ); vec< kmer<M> > fails; for ( int64_t i = 0; i < kmers.jsize( ); i++ ) if ( !right_ext[i] ) fails.push_back( kmers[i] ); // fails is list of kmers for which !right_ext[] //#pragma omp parallel for for ( int64_t id = 0; id < (int64_t) creads.size( ); id++ ) { const int64_t idp = pairs.getPartnerID(id); kmer<M> x; for ( int s = 0; s <= creads[id].isize( ) - M; s++ ) { x.SetToSubOf( creads[id], s ); // kmerize read and populate "special" if ( BinMember( fails, x ) ) { special[id] = True; special[idp] = True; } if ( s + M >= min_ext ) { x.ReverseComplement( ); if ( BinMember( fails, x ) ) { special[id] = True; special[idp] = True; } } } } } // to switch between VirtualMasterVec<bvec> and vecbasevector. The former cannot be const& template<typename T> struct ZeroCorrectedQuals_impl{ static void do_it(T oreads, vecbvec const& creads, vecqvec* pQuals){ vecqvec& cquals = *pQuals; ForceAssertEq(oreads.size(),creads.size()); ForceAssertEq(oreads.size(),cquals.size()); auto iOBV = oreads.begin(); auto iCBV = creads.begin(); auto iEnd = cquals.end(); for ( auto iQV = cquals.begin(); iQV != iEnd; ++iOBV,++iCBV,++iQV ) { bvec const& bvOrig = *iOBV; bvec const& bvCorr = *iCBV; qvec& qv = *iQV; ForceAssertEq(bvOrig.size(), bvCorr.size()); ForceAssertEq(bvOrig.size(), qv.size()); auto iO = bvOrig.cbegin(); auto iC = bvCorr.cbegin(); for ( auto iQ = qv.begin(), iE = qv.end(); iQ != iE; ++iQ,++iO,++iC ) if ( *iO != *iC ) *iQ = 0; } } }; // zero all quality scores associated with corrections (for reads already in memory) void ZeroCorrectedQuals( vecbasevector const& oreads, vecbvec const& creads, vecqvec* pQuals ) { ZeroCorrectedQuals_impl<decltype(oreads)>::do_it(oreads,creads,pQuals); } void CapQualityScores( vecqualvector& cquals, const vec<Bool>& done ) { const int cap_radius = 4; for ( int64_t id = 0; id < (int64_t) cquals.size( ); id++ ) { if ( done[id] ) continue; vec<int> q( cquals[id].size( ), 1000000 ); for ( int j = 0; j < (int) cquals[id].size( ); j++ ) { int start = Max( 0, j - cap_radius ); int stop = Min( (int) cquals[id].size( ) - 1, j + cap_radius ); for ( int l = start; l <= stop; l++ ) q[j] = Min( q[j], (int) cquals[id][l] ); } for ( int j = 0; j < (int) cquals[id].size( ); j++ ) cquals[id][j] = q[j]; } } void CorrectionSuite(vecbasevector &gbases, vecqualvector &gquals, PairsManager &gpairs, const long_heuristics &heur, vecbasevector &creads, VecEFasta &corrected, vec<int> &cid, vec<pairing_info> &cpartner, const uint NUM_THREADS, const String &EXIT, bool useOldLRPMethod/*, LongProtoTmpDirManager &tmp_mgr*/) { // Run Correct1. vec<int> trace_ids, precorrect_seq; //A really complicated way to hardcode this to {24,40} ParseIntSet("{" + heur.PRECORRECT_SEQ + "}", precorrect_seq, false); const int max_freq = heur.FF_MAX_FREQ; const String sFragReadsOrig = "frag_reads_orig"; vecqualvector cquals; creads = gbases; cquals = gquals; size_t nReads = creads.size(); ForceAssertEq(nReads, cquals.size()); size_t nBases = 0, qualSum = 0; for (qvec const &qv : cquals) { nBases += qv.size(); qualSum = std::accumulate(qv.begin(), qv.end(), qualSum); } ForceAssertEq(nBases, creads.SizeSum()); if (heur.PRECORRECT_ALT1) //This is always false precorrectAlt1(&creads); else if (heur.PRECORRECT_OLD_NEW) //This is always false too PreCorrectOldNew(&creads, cquals, trace_ids); else { PC_Params pcp; const int K_PC = 25; KmerSpectrum kspec(K_PC); pre_correct_parallel(pcp, K_PC, &creads, &cquals, &kspec, -1, NUM_THREADS); } ZeroCorrectedQuals(gbases, creads, &cquals); PairsManager const &pairs = gpairs; pairs.makeCache(); // Carry out initial pair filling. vecbasevector creads_done; vec<Bool> to_edit(nReads, True); vec<Bool> done(nReads, False); creads_done = creads; vecbasevector filled; const int MIN_FREQ = 5; FillPairs(creads, pairs, MIN_FREQ, filled, heur.FILL_PAIRS_ALT); int64_t fill_count = 0; for (int64_t id = 0; id < (int64_t) filled.size(); id++) { if (filled[id].size() == 0) continue; fill_count++; int n = creads[id].size(); creads_done[id] = filled[id]; cquals[id].resize(0); cquals[id].resize(filled[id].size(), 40); creads[id] = creads_done[id]; if (n < creads[id].isize()) { cquals[id].resize(n); if (pairs.getPartnerID(id) >= id) creads[id].resize(n); else { creads[id].SetToSubOf(creads[id], creads[id].isize() - n, n); } } done[id] = True; if (pairs.getPartnerID(id) < id) { creads_done[id].resize(0); } to_edit[id] = False; } // New precorrection. vec<int> trim_to; CapQualityScores(cquals, done); // Do precorrection. for (int j = 0; j < precorrect_seq.isize(); j++) { Correct1Pre(precorrect_seq[j], creads, cquals, pairs, to_edit, trim_to, trace_ids, /*logc,*/ heur); } // Path the precorrected reads. unsigned const COVERAGE = 50u; const int K2 = 80; // SHOULD NOT BE HARDCODED! vecbasevector correctedv(creads); for (int64_t id = 0; id < (int64_t) creads.size(); id++) correctedv[id].resize(trim_to[id]); HyperBasevector hb; HyperKmerPath h; vecKmerPath paths, paths_rc; LongReadsToPaths(correctedv, K2, COVERAGE, &hb, &h, &paths, &paths_rc); vecKmerPath hpaths; vec<tagged_rpint> hpathsdb; for (int e = 0; e < h.EdgeObjectCount(); e++) hpaths.push_back_reserve(h.EdgeObject(e)); CreateDatabase(hpaths, hpathsdb); // Close pairs that we're done with. Code copied with minor // changes from LongHyper.cc. Should be completely rewritten. //#pragma omp parallel for for (int64_t id1 = 0; id1 < (int64_t) creads.size(); id1++) { if (done[id1]) continue; const int id2 = pairs.getPartnerID(id1); if (id2 < id1) continue; vec<vec<int> > u(2); vec<int> left(2); for (int pass = 0; pass < 2; pass++) { const KmerPath &p = (pass == 0 ? paths[id1] : paths_rc[id2]); vec<triple<ho_interval, int, ho_interval> > M, M2; int rpos = 0; for (int j = 0; j < p.NSegments(); j++) { const KmerPathInterval &I = p.Segment(j); vec<longlong> locs; Contains(hpathsdb, I, locs); for (int l = 0; l < locs.isize(); l++) { const tagged_rpint &t = hpathsdb[locs[l]]; int hid = t.PathId(); if (hid < 0) continue; longlong hpos = I.Start() - t.Start(); longlong start = Max(I.Start(), t.Start()); longlong stop = Min(I.Stop(), t.Stop()); longlong hstart = start - t.Start(); for (int r = 0; r < t.PathPos(); r++) hstart += hpaths[hid].Segment(r).Length(); longlong hstop = hstart + stop - start; longlong rstart = rpos + start - I.Start(); longlong rstop = rstart + stop - start; M.push(ho_interval(rstart, rstop), hid, ho_interval(hstart, hstop)); } rpos += I.Length(); } Bool bad = False; for (int i = 0; i < M.isize(); i++) { int j; for (j = i + 1; j < M.isize(); j++) { if (M[j].first.Start() != M[j - 1].first.Stop() + 1) { break; } if (M[j].second != M[j - 1].second) break; if (M[j].third.Start() != M[j - 1].third.Stop() + 1) { break; } } u[pass].push_back(M[i].second); Bool incomplete = False; if (i > 0 && M[i].third.Start() > 0) incomplete = True; if (j < M.isize() && M[j - 1].third.Stop() != hpaths[M[i].second].KmerCount() - 1) { incomplete = True; bad = True; } if (i == 0 && j == M.isize() && !incomplete) { i = j - 1; continue; } int last = (i == 0 ? -1 : M2.back().first.Stop()); if (M[i].first.Start() > last + 1) bad = True; M2.push(ho_interval(M[i].first.Start(), M[j - 1].first.Stop()), M[i].second, ho_interval(M[i].third.Start(), M[j - 1].third.Stop())); if (j == M.isize() && M[j - 1].first.Stop() < p.KmerCount() - 1) { bad = True; } i = j - 1; } if (bad) u[pass].clear(); if (u[pass].nonempty()) { left[pass] = M.front().third.Start(); } } if (u[0].solo() && u[1].solo() && u[0][0] == u[1][0]) { int b1siz = correctedv[id1].isize(); int b2siz = correctedv[id2].isize(); int offset = left[1] - left[0]; if (b1siz == creads[id1].isize() && b2siz == creads[id2].isize() && offset >= 0) { auto beg = hb.EdgeObject(u[0][0]).begin() + left[0]; auto end = beg + (left[1] - left[0] + b2siz); creads_done[id1].assign(beg, end); creads_done[id2] = creads_done[id1]; creads_done[id2].ReverseComplement(); creads[id1] = creads_done[id1]; creads[id1].resize(b1siz); creads[id2] = creads_done[id2]; creads[id2].SetToSubOf(creads[id2], creads[id2].isize() - b2siz, b2siz); cquals[id1].resize(0); cquals[id1].resize(creads[id1].size(), 40); cquals[id2].resize(0); cquals[id2].resize(creads[id2].size(), 40); done[id1] = done[id2] = True; creads_done[id2].resize(0); to_edit[id1] = False; to_edit[id2] = False; } } } corrected.clear().resize(creads.size()); CorrectPairs1( 40, max_freq, creads, cquals, pairs, to_edit, trace_ids, heur, /*log_control, logc,*/ corrected); for (size_t id = 0; id < corrected.size(); id++) { if (corrected[id].size() > 0) { to_edit[id] = False; const int64_t idp = pairs.getPartnerID(id); to_edit[idp] = False; } } if (heur.CP2) { vec<Bool> special; PopulateSpecials(creads, pairs, creads_done, done, corrected, NUM_THREADS, special/*, logc*/ ); for (size_t id = 0; id < corrected.size(); id++) if (!special[id]) to_edit[id] = False; long_heuristics heur2(heur); // heur2.CP_MIN_GLUE = 5; heur2.CP_MIN_GLUE = 15; heur2.CP_MINQ_FLOOR = 0; heur2.CP_RAISE_ZERO = True; heur2.CP_MAX_QDIFF = 25.0; CorrectPairs1( 40, max_freq, creads, cquals, pairs, to_edit, trace_ids, heur2, /*log_control, logc,*/ corrected); } // end of heur.CP2 for (int64_t id = 0; id < done.jsize(); id++) { if (done[id]) corrected[id] = creads_done[id]; } int count = 0; for ( int l = 0; l < (int) corrected.size( ); l++ ) if ( corrected[l].size( ) > 0 ) count++; if ( count > 0 ) { vec<Bool> to_delete( corrected.size( ), False ); DefinePairingInfo( gpairs, creads, to_delete, cid, corrected, cpartner/*, logc*/ ); } } // Define pairing info. Note that for now we set all the library ids to 0. void DefinePairingInfo( const PairsManager & gpairs, const vecbasevector& creads, const vec<Bool>& to_delete, vec<int>& cid, VecEFasta& corrected, vec<pairing_info>& cpartner/*, const long_logging& logc*/ ) { for ( int64_t id = 0; id < (int64_t) creads.size( ); id++ ) if ( !to_delete[id] ) cid.push_back(id); corrected.EraseIf(to_delete); cpartner.resize( creads.size( ) ); for ( int64_t xid1 = 0; xid1 < (int64_t) corrected.size( ); xid1++ ) { int id1 = cid[xid1]; int64_t pid = gpairs.getPairID(id1); if ( gpairs.isUnpaired(id1) ) cpartner[xid1] = pairing_info(0,-1,-1); else { int id2 = gpairs.getPartnerID(id1); int xid2 = BinPosition( cid, id2 ); if ( xid2 < 0 ) cpartner[xid1] = pairing_info(0,-1,-1); else { if ( gpairs.ID1(pid) == id1 ) cpartner[xid1] = pairing_info(1,xid2,0); else cpartner[xid1] = pairing_info(2,xid2,0); } } } /*REPORT_TIME( clock, "used in load tail" );*/ }
39.348387
126
0.512652
Amjadhpc
206530f6c1c71226c4213d8c7355d2dacb73e829
1,250
cpp
C++
test/module/shared_model/backend_proto/shared_proto_util_test.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
1
2017-01-15T08:47:16.000Z
2017-01-15T08:47:16.000Z
test/module/shared_model/backend_proto/shared_proto_util_test.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
2
2020-07-07T19:31:15.000Z
2021-06-01T22:29:48.000Z
test/module/shared_model/backend_proto/shared_proto_util_test.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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 "backend/protobuf/util.hpp" #include "block.pb.h" #include <gtest/gtest.h> using namespace iroha; using namespace shared_model::proto; using shared_model::crypto::toBinaryString; /** * @given some protobuf object * @when making a blob from it * @then make sure that the deserialized from string is the same */ TEST(UtilTest, StringFromMakeBlob) { protocol::Header base, deserialized; base.set_created_time(100); auto blob = makeBlob(base); ASSERT_TRUE(deserialized.ParseFromString(toBinaryString(blob))); ASSERT_EQ(deserialized.created_time(), base.created_time()); }
31.25
75
0.7424
laSinteZ
20679dcbb4a32f90de6dafe09f911450d101c2b3
2,830
cpp
C++
ogsr_engine/Layers/xrRender/RenderTargetPhaseSSLR.cpp
LVutner/OGSR-Engine
fea725c29e1a1b3e72295e1419c124097ed98dfd
[ "Apache-2.0" ]
247
2018-11-02T18:50:55.000Z
2022-03-15T09:11:43.000Z
ogsr_engine/Layers/xrRender/RenderTargetPhaseSSLR.cpp
LVutner/OGSR-Engine
fea725c29e1a1b3e72295e1419c124097ed98dfd
[ "Apache-2.0" ]
193
2018-11-02T20:12:44.000Z
2022-03-07T13:35:17.000Z
ogsr_engine/Layers/xrRender/RenderTargetPhaseSSLR.cpp
LVutner/OGSR-Engine
fea725c29e1a1b3e72295e1419c124097ed98dfd
[ "Apache-2.0" ]
106
2018-10-26T11:33:01.000Z
2022-03-19T12:34:20.000Z
#include "stdafx.h" void CRenderTarget::phase_SSLR() { u32 Offset = 0; constexpr float d_Z = EPS_S; constexpr float d_W = 1.0f; constexpr u32 C = color_rgba(0, 0, 0, 255); // Half-pixel offset (DX9 only) #if defined(USE_DX10) || defined(USE_DX11) constexpr Fvector2 p0{ 0.0f, 0.0f }, p1{ 1.0f, 1.0f }; #else Fvector2 p0, p1; p0.set(0.5f / w, 0.5f / h); p1.set((w + 0.5f) / w, (h + 0.5f) / h); #endif const u32 w = Device.dwWidth, h = Device.dwHeight; ///////////////////////////////////////////////////////////////////////////////////// // phase SSLR u_setrt(rt_SSLR_0, nullptr, nullptr, HW.pBaseZB); RCache.set_CullMode(CULL_NONE); RCache.set_Stencil(FALSE); FVF::TL* pv = (FVF::TL*)RCache.Vertex.Lock(4, g_combine->vb_stride, Offset); pv->set(0, float(h), d_Z, d_W, C, p0.x, p1.y); pv++; pv->set(0, 0, d_Z, d_W, C, p0.x, p0.y); pv++; pv->set(float(w), float(h), d_Z, d_W, C, p1.x, p1.y); pv++; pv->set(float(w), 0, d_Z, d_W, C, p1.x, p0.y); pv++; RCache.Vertex.Unlock(4, g_combine->vb_stride); RCache.set_Element(s_SSLR->E[0]); Fmatrix m_inv_v; m_inv_v.invert(Device.mView); RCache.set_c("m_inv_v", m_inv_v); RCache.set_c("SSLR_params", ps_ext_SSLR_L, 1.f, 1.f, 1.f); RCache.set_Geometry(g_combine); RCache.Render(D3DPT_TRIANGLELIST, Offset, 0, 4, 0, 2); if (fis_zero(ps_ext_SSLR_blur)) return; ///////////////////////////////////////////////////////////////////////////////////// // hblur u_setrt(rt_SSLR_1, nullptr, nullptr, HW.pBaseZB); RCache.set_CullMode(CULL_NONE); RCache.set_Stencil(FALSE); pv = (FVF::TL*)RCache.Vertex.Lock(4, g_combine->vb_stride, Offset); pv->set(0, float(h), d_Z, d_W, C, p0.x, p1.y); pv++; pv->set(0, 0, d_Z, d_W, C, p0.x, p0.y); pv++; pv->set(float(w), float(h), d_Z, d_W, C, p1.x, p1.y); pv++; pv->set(float(w), 0, d_Z, d_W, C, p1.x, p0.y); pv++; RCache.Vertex.Unlock(4, g_combine->vb_stride); RCache.set_Element(s_SSLR->E[1]); RCache.set_c("blur_params", ps_ext_SSLR_blur, 0.f, float(w), float(h)); RCache.set_Geometry(g_combine); RCache.Render(D3DPT_TRIANGLELIST, Offset, 0, 4, 0, 2); ///////////////////////////////////////////////////////////////////////////////////// // vblur u_setrt(rt_SSLR_0, nullptr, nullptr, HW.pBaseZB); RCache.set_CullMode(CULL_NONE); RCache.set_Stencil(FALSE); pv = (FVF::TL*)RCache.Vertex.Lock(4, g_combine->vb_stride, Offset); pv->set(0, float(h), d_Z, d_W, C, p0.x, p1.y); pv++; pv->set(0, 0, d_Z, d_W, C, p0.x, p0.y); pv++; pv->set(float(w), float(h), d_Z, d_W, C, p1.x, p1.y); pv++; pv->set(float(w), 0, d_Z, d_W, C, p1.x, p0.y); pv++; RCache.Vertex.Unlock(4, g_combine->vb_stride); RCache.set_Element(s_SSLR->E[2]); RCache.set_c("blur_params", 0.f, ps_ext_SSLR_blur, float(w), float(h)); RCache.set_Geometry(g_combine); RCache.Render(D3DPT_TRIANGLELIST, Offset, 0, 4, 0, 2); }
31.444444
86
0.592933
LVutner
2067cca4d5f628054ceda8673b9246025e3e53e4
23,993
cxx
C++
src/mod/pub/lib/mws/mws.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
1
2017-12-26T14:29:37.000Z
2017-12-26T14:29:37.000Z
src/mod/pub/lib/mws/mws.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
src/mod/pub/lib/mws/mws.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
#include "stdafx.hxx" #include "appplex-conf.hxx" #include "mws.hxx" #include "mws-com.hxx" #include "mws-camera.hxx" #include "fonts/mws-font.hxx" #include "fonts/mws-text-vxo.hxx" #include "gfx.hxx" #include "gfx-tex.hxx" #include "gfx-vxo.hxx" #include "mws-mod.hxx" #include "input/transitions.hxx" #include "mws-vkb/mws-vkb.hxx" #include "mod-list.hxx" #include <algorithm> #ifdef MWS_USES_EXCEPTIONS #include <exception> #endif // mws_model mws_sp<mws_model> mws_model::get_instance() { return shared_from_this(); } void mws_model::receive(mws_sp<mws_dp> i_dp) { } void mws_model::set_view(mws_sp<mws_obj> iview) { view = iview; notify_update(); } void mws_model::notify_update() { if (get_view()) { send(get_view(), mws_dp::nwi(mws_evt_model_update)); } } mws_sp<mws_obj> mws_model::get_view() { return view.lock(); } mws_sp<mws_sender> mws_model::sender_inst() { return get_instance(); } // mws_obj mws_obj::mws_obj(mws_sp<gfx> i_gi) : gfx_node(i_gi) // for rootless / parentless mws inst { visible = true; } mws_sp<mws_obj> mws_obj::nwi() { nwi_sws_obj(mws_obj); } mws_sp<mws_obj> mws_obj::get_instance() { return std::static_pointer_cast<mws_obj>(get_inst()); } gfx_obj::e_gfx_obj_type mws_obj::get_type()const { return gfx_obj::e_mws; } void mws_obj::add_to_draw_list(const std::string& i_camera_id, std::vector<mws_sp<gfx_vxo>>& i_opaque, std::vector<mws_sp<gfx_vxo>>& i_translucent) { if (visible) { auto cam = mws_cam.lock(); if (cam->camera_id() == i_camera_id) { for (auto it = children.begin(); it != children.end(); ++it) { if ((*it)->visible) { (*it)->add_to_draw_list(i_camera_id, i_opaque, i_translucent); } } } } } void mws_obj::attach(mws_sp<gfx_node> i_node, uint32_t i_position) { if (i_node->get_type() == gfx_obj::e_mws) { auto mws_ref = mws_dynamic_pointer_cast<mws_obj>(i_node); if (mws_ref) { mws_ref->mws_root_v = mws_root_v; mws_ref->mws_cam = mws_root_v.lock()->get_mod()->mws_cam; } } i_node->position = i_node->position + glm::vec3(0.f, 0.f, 0.0001f); gfx_node::attach(i_node, i_position); } void mws_obj::set_enabled(bool i_is_enabled) { enabled = i_is_enabled; } bool mws_obj::is_enabled() const { return enabled; } void mws_obj::set_visible(bool i_is_visible) { visible = i_is_visible; } bool mws_obj::is_visible()const { return visible; } void mws_obj::set_id(std::string i_id) { id = i_id; } const std::string& mws_obj::get_id() { return id; } mws_sp<mws_obj> mws_obj::find_by_id(const std::string& i_id) { return mws_root_v.lock()->contains_id(i_id); } mws_sp<mws_obj> mws_obj::contains_id(const std::string& i_id) { if (i_id == id) { return get_instance(); } else { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w->id == i_id) { return w; } auto w2 = w->contains_id(i_id); if (w2) { return w2; } } } return nullptr; } } bool mws_obj::contains_mws(const mws_sp<mws_obj> i_mws) { if (i_mws == get_instance()) { return true; } else { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w == i_mws || w->contains_mws(i_mws)) { return true; } } } return false; } } mws_sp<mws_obj> mws_obj::get_mws_parent() const { return mws_dynamic_pointer_cast<mws_obj>(get_parent()); } mws_sp<mws_page_tab> mws_obj::get_mws_root() const { return mws_root_v.lock(); } mws_sp<mws_mod> mws_obj::get_mod() const { return std::static_pointer_cast<mws_mod>(mws_root_v.lock()->get_mod()); } void mws_obj::process(mws_sp<mws_dp> i_dp) { i_dp->process(get_instance()); } void mws_obj::receive(mws_sp<mws_dp> i_dp) { if (receive_handler) { receive_handler(i_dp); } if (!i_dp->is_processed()) { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w && w->visible) { send(w, i_dp); if (i_dp->is_processed()) { break; } } } } } } void mws_obj::update_state() { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w && w->visible) { w->update_state(); } } } } void mws_obj::update_view(mws_sp<mws_camera> i_g) { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w && w->visible) { w->update_view(i_g); } } } } const mws_size& mws_obj::get_best_size() const { return best_size; } void mws_obj::set_best_size(const mws_size& i_size) { best_size = i_size; } mws_rect mws_obj::get_pos() { return mws_r; } float mws_obj::get_z() { return position().z; } void mws_obj::set_z(float i_z_position) { position = glm::vec3(position().x, position().y, i_z_position); } mws_sp<mws_sender> mws_obj::sender_inst() { return get_instance(); } // mws_page_tab mws_page_tab::mws_page_tab(mws_sp<mws_mod> i_mod) { if (!i_mod) { mws_throw mws_exception("mod cannot be null"); } mod = i_mod; mws_r.set(0, 0, (float)i_mod->get_width(), (float)i_mod->get_height()); } mws_sp<mws_page_tab> mws_page_tab::nwi(mws_sp<mws_mod> i_mod) { mws_sp<mws_page_tab> pt(new mws_page_tab(i_mod)); pt->new_instance_helper(); return pt; } void mws_page_tab::add_to_draw_list(const std::string& i_camera_id, std::vector<mws_sp<gfx_vxo>>& i_opaque, std::vector<mws_sp<gfx_vxo>>& i_translucent) { mws_obj::add_to_draw_list(i_camera_id, i_opaque, i_translucent); } void mws_page_tab::init() { mws_root_v = get_mws_page_tab_instance(); mws_cam = mws_root_v.lock()->get_mod()->mws_cam; } void mws_page_tab::init_pages() { for (auto& p : page_tab_v) { if (!p->is_init_v) { p->init(); p->is_init_v = true; } } } void mws_page_tab::init_page_nav() { if (page_nav) { if (page_nav->page_stack_size() > 0) { page_nav->set_current(page_nav->top_page()); } else if (!page_nav->get_main_page_id().empty()) { page_nav->reset_pages(); } else if (!page_tab_v.empty()) { page_tab_v[0]->visible = true; } } else if (!page_tab_v.empty()) { page_tab_v[0]->visible = true; } } void mws_page_tab::on_destroy() { for (auto& p : page_tab_v) { p->on_destroy(); } } mws_sp<mws_obj> mws_page_tab::contains_id(const std::string& i_id) { if (i_id.length() > 0) { if (i_id == get_id()) { return get_instance(); } for (auto& p : page_tab_v) { mws_sp<mws_obj> o = p->contains_id(i_id); if (o) { return o; } } } return nullptr; } bool mws_page_tab::contains_mws(const mws_sp<mws_obj> i_mws) { for (auto& p : page_tab_v) { if (i_mws == p || p->contains_mws(i_mws)) { return true; } } return false; } mws_sp<mws_page_tab> mws_page_tab::get_mws_page_tab_instance() { return static_pointer_cast<mws_page_tab>(get_instance()); } mws_sp<mws_mod> mws_page_tab::get_mod() { return static_pointer_cast<mws_mod>(mod.lock()); } bool mws_page_tab::empty() { return page_tab_v.empty(); } mws_sp<mws_text_vxo> mws_page_tab::get_text_vxo() const { return tab_text_vxo; } void mws_page_tab::receive(mws_sp<mws_dp> i_dp) { if (vkb && vkb->visible) { vkb->receive(i_dp); } if (!i_dp->is_processed()) { if (receive_handler) { receive_handler(i_dp); } else { if (i_dp->is_processed()) { return; } if (!empty()) { send(page_tab_v.back(), i_dp); } } } } void mws_page_tab::update_state() { if (vkb && vkb->visible) { vkb->update_state(); } if (tab_text_vxo) { tab_text_vxo->clear_text(); } for (mws_sp<mws_page> p : page_tab_v) { if (p->visible) { p->update_state(); } } } void mws_page_tab::update_view(mws_sp<mws_camera> i_g) { if (vkb && vkb->visible) { vkb->update_view(i_g); } for (mws_sp<mws_page> p : page_tab_v) { if (p->visible) { p->update_view(i_g); } } } void mws_page_tab::on_resize() { mws_r.w = static_cast<float>(mod.lock()->get_width()); mws_r.h = static_cast<float>(mod.lock()->get_height()); if (tab_text_vxo) { tab_text_vxo->clear_text(); } for (mws_sp<mws_page> p : page_tab_v) { if (p->visible) { p->on_resize(); } } if (vkb) { vkb->on_resize(); } } void mws_page_tab::add_page(mws_sp<mws_page> i_page) { attach(i_page); add(i_page); } void mws_page_tab::add(mws_sp<mws_page> p) { if (contains_mws(p)) { mws_throw mws_exception();//trs("page with id [%1%] already exists") % p->get_id()); } page_tab_v.push_back(p); if (!p->is_init_v) { p->init(); p->is_init_v = true; } } int mws_page_tab::get_page_index(mws_sp<mws_page> ipage) { int k = 0; for (auto& p : page_tab_v) { if (ipage == p) { return k; } k++; } return -1; } void mws_page_tab::new_instance_helper() { mws_sp<mws_page_tab> mws_root = get_mws_page_tab_instance(); mws_root_v = mws_root; mws_cam = mws_root_v.lock()->get_mod()->mws_cam; page_nav = mws_stack_page_nav::nwi(mws_root); #if defined MOD_VECTOR_FONTS { auto tab_text_vxo_ref = mws_text_vxo::nwi(); mws_root->tab_text_vxo = tab_text_vxo_ref; mws_root->attach(tab_text_vxo_ref); tab_text_vxo_ref->camera_id_list.clear(); tab_text_vxo_ref->camera_id_list.push_back("mws_cam"); } #endif } bool mws_page_tab::handle_back_evt() { if (vkb && vkb->visible) { vkb->visible = false; vkb->set_target(nullptr); return true; } return false; } mws_sp<mws_virtual_keyboard> mws_page_tab::get_keyboard() { if (mod_mws_vkb_on) { if (!vkb) { vkb = mws_vkb::gi(); vkb->set_file_store(get_file_store()); attach(vkb); vkb->visible = false; } return vkb; } return nullptr; } void mws_page_tab::show_keyboard(mws_sp<mws_text_area> i_tbx) { if (mod_mws_vkb_on) { auto kb = get_keyboard(); kb->visible = true; kb->set_target(i_tbx); } } mws_sp<mws_vkb_file_store> mws_page_tab::get_file_store() { #if MOD_MWS_VKB if (!vkb_store) { set_file_store(std::make_shared<mws_vkb_file_store_impl>(get_mod())); } #endif return vkb_store; } // mws_page_item void mws_page_item::set_rect(const mws_rect& i_rect) { set_position(glm::vec2(i_rect.x, i_rect.y)); set_size(glm::vec2(i_rect.w, i_rect.h)); } void mws_page_item::set_position(const glm::vec2& i_position) { mws_r.x = i_position.x; mws_r.y = i_position.y; } void mws_page_item::set_size(const glm::vec2& i_size) { mws_r.w = i_size.x; mws_r.h = i_size.y; } mws_sp<mws_page> mws_page_item::get_page() { mws_sp<gfx_node> parent_ref = get_parent(); while (parent_ref) { if (parent_ref->get_type() == gfx_obj::e_mws) { mws_sp<mws_page> page = mws_dynamic_pointer_cast<mws_page>(parent_ref); if (page) { return page; } } parent_ref = parent_ref->get_parent(); } return nullptr; } bool mws_page_item::has_focus() { mws_sp<mws_page> parent_ref = get_page(); return parent_ref->is_selected(get_instance()); } void mws_page_item::set_focus(bool i_set_focus) { get_page()->set_focus(get_instance(), i_set_focus); } mws_page_item::mws_page_item() {} void mws_page_item::setup() { mws_obj::setup(); } // mws_page mws_page::mws_page() { visible = false; } mws_sp<mws_page> mws_page::nwi(mws_sp<mws_page_tab> i_parent) { mws_sp<mws_page> u(new mws_page()); i_parent->attach(u); i_parent->add(u); return u; } void mws_page::init() { is_init_v = true; } void mws_page::on_destroy() { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); w->on_destroy(); } } } mws_sp<mws_obj> mws_page::contains_id(const std::string& i_id) { if (i_id.length() > 0) { if (i_id == get_id()) { return get_instance(); } for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); mws_sp<mws_obj> u = w->contains_id(i_id); if (u) { return u; } } } } return nullptr; } bool mws_page::contains_mws(const mws_sp<mws_obj> i_mws) { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w == i_mws || w->contains_mws(i_mws)) { return true; } } } return false; } mws_sp<mws_page> mws_page::get_mws_page_instance() { return static_pointer_cast<mws_page>(get_instance()); } mws_sp<mws_page_tab> mws_page::get_mws_page_parent() const { return static_pointer_cast<mws_page_tab>(get_mws_parent()); } mws_layout_info mws_page::find_closest_layout_match(const mws_layout_info& i_lyt_info) { if (layouts.empty()) { return mws_layout_info(); } float screen_aspect_ratio = (i_lyt_info.aspect_ratio == 0.f) ? static_cast<float>(i_lyt_info.width) / i_lyt_info.height : i_lyt_info.aspect_ratio; // sort the layouts by aspect ratio auto cmp_aspect_ratio = [](const mws_layout_info& i_a, const mws_layout_info& i_b) { return i_a.aspect_ratio < i_b.aspect_ratio; }; std::sort(layouts.begin(), layouts.end(), cmp_aspect_ratio); // find the layout with the closest match to the screen's aspect ratio auto closest_val = [&cmp_aspect_ratio](const std::vector<mws_layout_info>& i_vect, float i_value) -> const mws_layout_info& { mws_layout_info lyt; lyt.aspect_ratio = i_value; auto const it = std::lower_bound(i_vect.begin(), i_vect.end(), lyt, cmp_aspect_ratio); // if we have an exact match, return 'it' if (it == i_vect.end()) { return i_vect.back(); } // we don't have an exact match. return the closest value float upper_diff = it->aspect_ratio - i_value; // first check if i_value is less than last aspect ration and that we have a lower aspect ratio if (upper_diff > 0.f && it > i_vect.begin()) { auto const it_lower = it - 1; float lower_diff = i_value - it_lower->aspect_ratio; // if i_value is closer to the lower aspect ratio, return 'it_lower' if (lower_diff < upper_diff) { return *it_lower; } // i_value is closer to the upper/last aspect ratio, so return 'it' else { return *it; } } // if we don't, then 'it' is already the closest available aspect ratio. return 'it' else { return *it; } }; // found it const mws_layout_info& lyt = closest_val(layouts, screen_aspect_ratio); return lyt; } void mws_page::add_layout(mws_layout_info& i_lyt_info) { mws_assert(i_lyt_info.layout != nullptr); i_lyt_info.aspect_ratio = static_cast<float>(i_lyt_info.width) / i_lyt_info.height; layouts.push_back(i_lyt_info); } void mws_page::on_visibility_changed_handler(bool i_is_visible) { mws_obj::on_visibility_changed_handler(i_is_visible); if (i_is_visible) { mws_sp<mws_page_tab> parent_ref = get_mws_page_parent(); if (mws_r.w != parent_ref->mws_r.w || mws_r.h != parent_ref->mws_r.h) { on_resize(); } } } void mws_page::on_show_transition(const mws_sp<linear_transition> i_transition) {} void mws_page::on_hide_transition(const mws_sp<linear_transition> i_transition) {} void mws_page::receive(mws_sp<mws_dp> i_dp) { if (receive_handler) { receive_handler(i_dp); } else { update_input_sub_mws(i_dp); //update_input_std_behaviour(i_dp); } } void mws_page::update_input_sub_mws(mws_sp<mws_dp> i_dp) { if (i_dp->is_processed()) { return; } if (i_dp->is_type(mws_ptr_evt::ptr_evt_type)) { mws_sp<mws_obj> new_selected_item; mws_sp<mws_ptr_evt> ts = mws_ptr_evt::as_pointer_evt(i_dp); bool touch_select = ts->type == mws_ptr_evt_base::touch_began;// || ts->type == mws_ptr_evt_base::touch_ended; auto z_sort = [](mws_sp<gfx_node> a, mws_sp<gfx_node> b) { auto& pos_0 = gfx_util::get_pos_from_tf_mx(a->get_global_tf_mx()); auto& pos_1 = gfx_util::get_pos_from_tf_mx(b->get_global_tf_mx()); return (pos_0.z > pos_1.z); }; std::sort(children.begin(), children.end(), z_sort); for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { mws_sp<mws_obj> w = mws_dynamic_pointer_cast<mws_obj>(c); if (w && w->visible) { send(w, i_dp); if (touch_select && i_dp->is_processed()) { new_selected_item = mws_dynamic_pointer_cast<mws_obj>(i_dp->destination()); break; } } } } if (touch_select && selected_item != new_selected_item) { if (selected_item) { selected_item->on_focus_changed(false); } selected_item = new_selected_item; if (selected_item) { selected_item->on_focus_changed(true); } } } else if (i_dp->is_type(mws_key_evt::key_evt_type)) { if (selected_item) { selected_item->receive(i_dp); } } } void mws_page::update_input_std_behaviour(mws_sp<mws_dp> i_dp) { if (i_dp->is_processed()) { return; } if (i_dp->is_type(mws_ptr_evt::ptr_evt_type)) { mws_sp<mws_ptr_evt> ts = mws_ptr_evt::as_pointer_evt(i_dp); //switch (ts->get_type()) //{ //case touch_sym_evt::TS_PRESSED: //{ // float x = ts->pressed.te->points[0].x; // float y = ts->pressed.te->points[0].y; // if (ts->tap_count == 1) // { // ks.grab(x, y); // ts->process(); // } // break; //} //case touch_sym_evt::TS_PRESS_AND_DRAG: //{ // float x = ts->points[0].x; // float y = ts->points[0].y; // switch (ts->tap_count) // { // case 1: // { // if (ts->is_finished) // { // ks.start_slowdown(); // } // else // { // ks.begin(ts->points[0].x, ts->points[0].y); // } // mws_r.x += ts->points[0].x - ts->prev_state.te->points[0].x; // mws_r.y += ts->points[0].y - ts->prev_state.te->points[0].y; // if (mws_r.x > 0) // { // mws_r.x = 0; // } // else if (mws_r.x < -mws_r.w + mws::screen::get_width()) // { // mws_r.x = -mws_r.w + mws::screen::get_width(); // } // if (mws_r.y > 0) // { // mws_r.y = 0; // } // else if (mws_r.y < -mws_r.h + mws::screen::get_height()) // { // mws_r.y = -mws_r.h + mws::screen::get_height(); // } // ts->process(); // } // } // break; //} //case touch_sym_evt::TS_MOUSE_WHEEL: //{ // mws_sp<mouse_wheel_evt> mw = static_pointer_cast<mouse_wheel_evt>(ts); // mws_r.y += float(mw->wheel_delta) * 50.f; // if (mws_r.y > 0) // { // mws_r.y = 0; // } // else if (mws_r.y < -mws_r.h + mws::screen::get_height()) // { // mws_r.y = -mws_r.h + mws::screen::get_height(); // } // ts->process(); // break; //} //} } } void mws_page::update_state() { //glm::vec2 p = ks.update(); //mws_r.x += p.x; //mws_r.y += p.y; //for (auto& b : mlist) //{ // mws_r.w = std::max(mws_r.w, b->get_pos().w); // mws_r.h = std::max(mws_r.h, b->get_pos().h); //} //if (mws_r.x > 0) //{ // mws_r.x = 0; //} //else if (mws_r.x < -mws_r.w + mws::screen::get_width()) //{ // mws_r.x = -mws_r.w + mws::screen::get_width(); //} //if (mws_r.y > 0) //{ // mws_r.y = 0; //} //else if (mws_r.y < -mws_r.h + mws::screen::get_height()) //{ // mws_r.y = -mws_r.h + mws::screen::get_height(); //} for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w && w->visible) { w->update_state(); } } } } void mws_page::update_view(mws_sp<mws_camera> i_g) { for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); if (w && w->visible) { w->update_view(i_g); } } } } glm::vec2 mws_page::get_dim() const { return glm::vec2(mws_r.w - mws_r.x, mws_r.h - mws_r.y); } mws_sp<mws_obj> mws_page::get_mws_at(uint32_t i_idx) { uint32_t k = 0; for (auto& c : children) { if (c->get_type() == gfx_obj::e_mws) { if (k == i_idx) { auto w = mws_dynamic_pointer_cast<mws_obj>(c); return w; } k++; } } return nullptr; } bool mws_page::is_selected(mws_sp<mws_obj> i_item) { return i_item == selected_item; } void mws_page::set_focus(mws_sp<mws_obj> i_item, bool i_set_focus) { if (contains_mws(i_item)) { if (i_set_focus && (i_item != selected_item)) { if (selected_item) { selected_item->on_focus_changed(false); } selected_item = i_item; selected_item->on_focus_changed(true); } else { if (i_item == selected_item) { selected_item->on_focus_changed(false); selected_item = nullptr; } else { mws_println("mws_page::set_focus[ i_item was not focused ]"); } } } else { mws_println("mws_page::set_focus[ i_item is not in mws_page ]"); } } void mws_page::on_resize() { mws_sp<mws_mod> mod = get_mod(); mws_sp<mws_page_tab> parent_ref = get_mws_page_parent(); mws_layout_info lyt_ex{ mod->get_width(), mod->get_height(), nullptr, 0 }; mws_layout_info lyt = find_closest_layout_match(lyt_ex); mws_r.x = 0; mws_r.y = 0; mws_r.w = parent_ref->mws_r.w; mws_r.h = parent_ref->mws_r.h; if (lyt.layout && lyt.layout != crt_layout.layout) { if (crt_layout.layout) { crt_layout.layout->detach(); } crt_layout = lyt; attach(crt_layout.layout); } }
20.179142
152
0.567791
indigoabstract
206ddee92c7f1d16a532f0920761e22ef2a3121c
566
cpp
C++
LeetCode/Shortest Word Distance/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
LeetCode/Shortest Word Distance/main.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
null
null
null
LeetCode/Shortest Word Distance/main.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
null
null
null
class Solution { public: int shortestDistance(vector<string>& words, string word1, string word2) { vector<int> X, Y; int index = 0, ans = INT_MAX; for (const auto& ele : words) { if (ele == word1) { X.push_back(index); } else if (ele == word2) { Y.push_back(index); } index++; } for (const auto& x : X) { for (const auto& y : Y) { ans = min(ans, abs(x - y)); } } return ans; } };
26.952381
77
0.418728
Code-With-Aagam
206f5064800ece0fc96baffe7a7d31a6553694fd
1,683
cc
C++
tests/universal-coding-test.cc
pixie-grasper/research-library
26745bb0810a2fbe0292c7591ce01a2d6ee31acb
[ "MIT" ]
2
2016-03-06T08:03:18.000Z
2016-03-06T11:07:20.000Z
tests/universal-coding-test.cc
pixie-grasper/research-library
26745bb0810a2fbe0292c7591ce01a2d6ee31acb
[ "MIT" ]
1
2016-03-07T06:26:09.000Z
2016-03-07T06:26:09.000Z
tests/universal-coding-test.cc
pixie-grasper/research-library
26745bb0810a2fbe0292c7591ce01a2d6ee31acb
[ "MIT" ]
2
2016-03-06T08:19:49.000Z
2021-09-08T10:17:05.000Z
// Copyright 2015 pixie.grasper #include <cstdlib> #include <vector> #include "../includes/universal-coding.h" int main() { std::vector<int> buffer(10000); unsigned int seed = 10; for (size_t i = 0; i < buffer.size(); i++) { buffer[i] = rand_r(&seed) % 100 + 1; } auto&& uc = ResearchLibrary::UniversalCoding::UnaryCodingEncode(buffer); auto&& iuc = ResearchLibrary::UniversalCoding::UnaryCodingDecode(uc); for (size_t i = 0; i < buffer.size(); i++) { if (iuc[i] != buffer[i]) { return 1; } } auto&& gamma = ResearchLibrary::UniversalCoding::GammaCodingEncode(buffer); auto&& igamma = ResearchLibrary::UniversalCoding::GammaCodingDecode(gamma); for (size_t i = 0; i < buffer.size(); i++) { if (igamma[i] != buffer[i]) { return 1; } } auto&& delta = ResearchLibrary::UniversalCoding::DeltaCodingEncode(buffer); auto&& idelta = ResearchLibrary::UniversalCoding::DeltaCodingDecode(delta); for (size_t i = 0; i < buffer.size(); i++) { if (idelta[i] != buffer[i]) { return 1; } } auto&& omega = ResearchLibrary::UniversalCoding::OmegaCodingEncode(buffer); auto&& iomega = ResearchLibrary::UniversalCoding::OmegaCodingDecode(omega); for (size_t i = 0; i < buffer.size(); i++) { if (iomega[i] != buffer[i]) { return 1; } } auto&& golomb = ResearchLibrary::UniversalCoding ::GolombCodingEncode(buffer, 6); auto&& igolomb = ResearchLibrary::UniversalCoding ::GolombCodingDecode(golomb, 6); for (size_t i = 0; i < buffer.size(); i++) { if (igolomb[i] != buffer[i]) { return 1; } } return 0; }
28.525424
77
0.61022
pixie-grasper
207177c2749926a919f82cf5492b78ad96807655
762
hpp
C++
libs/options/include/fcppt/options/option_name_set.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/options/include/fcppt/options/option_name_set.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/options/include/fcppt/options/option_name_set.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_OPTIONS_OPTION_NAME_SET_HPP_INCLUDED #define FCPPT_OPTIONS_OPTION_NAME_SET_HPP_INCLUDED #include <fcppt/options/option_name.hpp> #include <fcppt/options/option_name_comparison.hpp> #include <fcppt/config/external_begin.hpp> #include <set> #include <fcppt/config/external_end.hpp> namespace fcppt::options { /** \brief The set of option names. \ingroup fcpptoptions Each string in this set is expected to be followed by a value, e.g. "--foo bar". */ using option_name_set = std::set<fcppt::options::option_name>; } #endif
25.4
62
0.754593
freundlich
20728eaa4512239fc1f9fe6d20af1359716e9977
510
cpp
C++
Sources/special_file.cpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
1
2022-02-15T02:58:58.000Z
2022-02-15T02:58:58.000Z
Sources/special_file.cpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
null
null
null
Sources/special_file.cpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
1
2021-12-19T13:25:43.000Z
2021-12-19T13:25:43.000Z
/// \file /// \brief Source file that contains implementation of the SpecialFile class. /// \author Lyberta /// \copyright BSLv1. #include <Internal/special_file.h> namespace std::io { SpecialFile::SpecialFile(native_handle_type handle) : BasicFile{handle} { } streamsize SpecialFile::read_some(span<byte> buffer) { return Platform::ReadSome(this->native_handle(), buffer); } streamsize SpecialFile::write_some(span<const byte> buffer) { return Platform::WriteSome(this->native_handle(), buffer); } }
18.888889
77
0.747059
YarikTH
2072c207a6726d480c41b0290e7def79a65c97ef
15,701
cpp
C++
Source/Graphics.cpp
maxattack/Trinket
b989bc88800ac858f0a150858e1c9670b88d4aad
[ "Unlicense" ]
1
2020-06-11T21:31:25.000Z
2020-06-11T21:31:25.000Z
Source/Graphics.cpp
maxattack/Trinket
b989bc88800ac858f0a150858e1c9670b88d4aad
[ "Unlicense" ]
null
null
null
Source/Graphics.cpp
maxattack/Trinket
b989bc88800ac858f0a150858e1c9670b88d4aad
[ "Unlicense" ]
null
null
null
// Trinket Game Engine // (C) 2020 Max Kaufmann <max.kaufmann@gmail.com> #include "Graphics.h" #include "DiligentCore/Graphics/GraphicsTools/interface/MapHelper.hpp" #include "DiligentCore/Graphics/GraphicsTools/interface/GraphicsUtilities.h" #include <glm/gtx/color_space.hpp> #include <glm/gtx/quaternion.hpp> #include "Math.h" #include "World.h" Graphics::Graphics(Display* aDisplay, World* aWorld) : pDisplay(aDisplay) , pWorld(aWorld) , pov{ RPose(ForceInit::Default), 60.f, 0.01f, 100000.f } , lightDirection(0, -1, 0) { pWorld->db.AddListener(this); pWorld->scene.AddListener(this); pWorld->skel.AddListener(this); let pDevice = pDisplay->GetDevice(); let pSwapChain = pDisplay->GetSwapChain(); let pContext = pDisplay->GetContext(); let pEngineFactory = pDisplay->GetEngineFactory(); // create the "shader source" (just use surface filesystem hook for now) pEngineFactory->CreateDefaultShaderSourceStreamFactory("Assets", &pShaderSourceFactory); // create shadow map texture { TextureDesc SMDesc; SMDesc.Name = "Shadow Map"; SMDesc.Type = RESOURCE_DIM_TEX_2D; SMDesc.Width = 2048; SMDesc.Height = 2048; SMDesc.Format = TEX_FORMAT_SHADOW_MAP; SMDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_DEPTH_STENCIL; pDevice->CreateTexture(SMDesc, nullptr, &pShadowMap); pShadowMapSRV = pShadowMap->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); pShadowMapDSV = pShadowMap->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL); } // create render constants { BufferDesc BD; BD.Name = "CB_Surface"; BD.uiSizeInBytes = sizeof(RenderConstants); BD.Usage = USAGE_DYNAMIC; BD.BindFlags = BIND_UNIFORM_BUFFER; BD.CPUAccessFlags = CPU_ACCESS_WRITE; pDevice->CreateBuffer(BD, nullptr, &pRenderConstants); } // create shadow map pipeline state { PipelineStateCreateInfo PCI; PipelineStateDesc& PSODesc = PCI.PSODesc; PSODesc.Name = "PS_Shadow"; PSODesc.IsComputePipeline = false; PSODesc.GraphicsPipeline.NumRenderTargets = 0; PSODesc.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_UNKNOWN; PSODesc.GraphicsPipeline.DSVFormat = TEX_FORMAT_SHADOW_MAP; PSODesc.GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; PSODesc.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_BACK; PSODesc.GraphicsPipeline.DepthStencilDesc.DepthEnable = True; RefCntAutoPtr<IShader> pVS; { ShaderCreateInfo SCI; SCI.pShaderSourceStreamFactory = pShaderSourceFactory; SCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; SCI.UseCombinedTextureSamplers = true; SCI.Desc.ShaderType = SHADER_TYPE_VERTEX; SCI.EntryPoint = "main"; SCI.Desc.Name = "VS_shadow"; SCI.FilePath = "shadow.vsh"; pDevice->CreateShader(SCI, &pVS); } PSODesc.GraphicsPipeline.pVS = pVS; PSODesc.GraphicsPipeline.pPS = nullptr; // depth/vertex-shader only PSODesc.GraphicsPipeline.InputLayout.LayoutElements = MeshVertexLayoutElems; PSODesc.GraphicsPipeline.InputLayout.NumElements = _countof(MeshVertexLayoutElems); PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; PSODesc.GraphicsPipeline.RasterizerDesc.DepthClipEnable = false; PSODesc.GraphicsPipeline.RasterizerDesc.DepthBias = 60; PSODesc.GraphicsPipeline.RasterizerDesc.SlopeScaledDepthBias = 3.33f; pDevice->CreatePipelineState(PCI, &pShadowPipelineState); pShadowPipelineState->GetStaticVariableByName(SHADER_TYPE_VERTEX, "Constants")->Set(pRenderConstants); pShadowPipelineState->CreateShaderResourceBinding(&pShadowResourceBinding, true); } #if SHADOW_MAP_DEBUG // shadowmap viz pso { PipelineStateCreateInfo PSOCreateInfo; PipelineStateDesc& PSODesc = PSOCreateInfo.PSODesc; PSODesc.Name = "PSO_ShadowMapDebug"; PSODesc.IsComputePipeline = false; PSODesc.GraphicsPipeline.NumRenderTargets = 1; PSODesc.GraphicsPipeline.RTVFormats[0] = pSwapChain->GetDesc().ColorBufferFormat; PSODesc.GraphicsPipeline.DSVFormat = pSwapChain->GetDesc().DepthBufferFormat; PSODesc.GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; PSODesc.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; PSODesc.GraphicsPipeline.DepthStencilDesc.DepthEnable = False; ShaderCreateInfo ShaderCI; ShaderCI.pShaderSourceStreamFactory = pShaderSourceFactory; ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; ShaderCI.UseCombinedTextureSamplers = true; RefCntAutoPtr<IShader> pShadowMapDebugVS; { ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX; ShaderCI.EntryPoint = "main"; ShaderCI.Desc.Name = "Shadow Map Vis VS"; ShaderCI.FilePath = "shadow_debug.vsh"; pDevice->CreateShader(ShaderCI, &pShadowMapDebugVS); } RefCntAutoPtr<IShader> pShadowMapDebugPS; { ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL; ShaderCI.EntryPoint = "main"; ShaderCI.Desc.Name = "Shadow Map Vis PS"; ShaderCI.FilePath = "shadow_debug.psh"; pDevice->CreateShader(ShaderCI, &pShadowMapDebugPS); } PSODesc.GraphicsPipeline.pVS = pShadowMapDebugVS; PSODesc.GraphicsPipeline.pPS = pShadowMapDebugPS; PSODesc.GraphicsPipeline.SmplDesc.Count = pDisplay->GetMultisampleCount(); PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE; SamplerDesc SamLinearClampDesc{ FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP }; StaticSamplerDesc StaticSamplers[]{ {SHADER_TYPE_PIXEL, "g_ShadowMap", SamLinearClampDesc} }; PSODesc.ResourceLayout.StaticSamplers = StaticSamplers; PSODesc.ResourceLayout.NumStaticSamplers = _countof(StaticSamplers); pDevice->CreatePipelineState(PSOCreateInfo, &pShadowMapDebugPSO); pShadowMapDebugPSO->CreateShaderResourceBinding(&pShadowMapDebugSRB, true); pShadowMapDebugSRB->GetVariableByName(SHADER_TYPE_PIXEL, "g_ShadowMap")->Set(pShadowMapSRV); } #endif #if TRINKET_TEST // debug wireframe { // Wireframe PSO PipelineStateCreateInfo Args; PipelineStateDesc& PSODesc = Args.PSODesc; PSODesc.Name = "PSO_DebugWireframe"; PSODesc.IsComputePipeline = false; PSODesc.GraphicsPipeline.NumRenderTargets = 1; PSODesc.GraphicsPipeline.RTVFormats[0] = pSwapChain->GetDesc().ColorBufferFormat; PSODesc.GraphicsPipeline.DSVFormat = pSwapChain->GetDesc().DepthBufferFormat; PSODesc.GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_LINE_LIST; PSODesc.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; PSODesc.GraphicsPipeline.DepthStencilDesc.DepthEnable = false; PSODesc.GraphicsPipeline.SmplDesc.Count = pDisplay->GetMultisampleCount(); ShaderCreateInfo SCI; SCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; SCI.UseCombinedTextureSamplers = true; // For GL Compat SCI.pShaderSourceStreamFactory = GetShaderSourceStream(); RefCntAutoPtr<IShader> pVS; { SCI.Desc.ShaderType = SHADER_TYPE_VERTEX; SCI.EntryPoint = "main"; SCI.Desc.Name = "VS_DebugWireframe"; SCI.FilePath = "wireframe.vsh"; pDevice->CreateShader(SCI, &pVS); CHECK_ASSERT(pVS); } RefCntAutoPtr<IShader> pPS; { SCI.Desc.ShaderType = SHADER_TYPE_PIXEL; SCI.EntryPoint = "main"; SCI.Desc.Name = "PS_DebugWireframe"; SCI.FilePath = "wireframe.psh"; pDevice->CreateShader(SCI, &pPS); CHECK_ASSERT(pPS); } const LayoutElement WireframeLayoutElems[2]{ LayoutElement{ 0, 0, 3, VT_FLOAT32, false }, LayoutElement{ 1, 0, 4, VT_FLOAT32, false }, }; PSODesc.GraphicsPipeline.InputLayout.LayoutElements = WireframeLayoutElems; PSODesc.GraphicsPipeline.InputLayout.NumElements = _countof(WireframeLayoutElems); PSODesc.GraphicsPipeline.pVS = pVS; PSODesc.GraphicsPipeline.pPS = pPS; PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; PSODesc.ResourceLayout.NumVariables = 0; PSODesc.ResourceLayout.NumStaticSamplers = 0; pDevice->CreatePipelineState(Args, &pDebugWireframePSO); CHECK_ASSERT(pDebugWireframePSO); pDebugWireframePSO->GetStaticVariableByName(SHADER_TYPE_VERTEX, "Constants")->Set(GetRenderConstants()); pDebugWireframePSO->CreateShaderResourceBinding(&pDebugWireframeSRB, true); // Wireframe Vertex Buffer BufferDesc VBD; VBD.Name = "VB_DebugWireframe"; VBD.Usage = USAGE_DEFAULT; //USAGE_DYNAMIC; VBD.BindFlags = BIND_VERTEX_BUFFER; VBD.uiSizeInBytes = sizeof(lineBuf); pDevice->CreateBuffer(VBD, nullptr, &pDebugWireframeBuf); CHECK_ASSERT(pDebugWireframeBuf); } #endif } Graphics::~Graphics() { pWorld->db.RemoveListener(this); pWorld->scene.RemoveListener(this); pWorld->skel.RemoveListener(this); } void Graphics::Database_WillReleaseAsset(AssetDatabase* caller, ObjectID id) { // TODO } void Graphics::Scene_WillReleaseObject(Scene* caller, ObjectID id) { // TODO } void Graphics::Skeleton_WillReleaseSkeleton(class SkelRegistry* Caller, ObjectID id) { // TODO } void Graphics::Skeleton_WillReleaseSkelAsset(class SkelRegistry* Caller, ObjectID id) { // TODO } void Graphics::AddRenderPasses(Material* pMaterial) { for (int it = 0; it < pMaterial->NumPasses(); ++it) passes.push_back(RenderPass{ pMaterial, it, 0 }); } bool Graphics::AddMeshRenderer(ObjectID id, const RenderMeshData& data) { // check refs if (!pWorld->scene.IsValid(id)) return false; if (data.pMesh == nullptr) return false; if (data.pMaterial == nullptr) return false; if (!meshRenderers.TryAppendObject(id, data)) return false; // add render items, update render passes int itemIdx = 0; for (auto pit = passes.begin(); pit != passes.end(); ++pit) { if (pit->pMaterial == data.pMaterial) { for (uint16 submeshIdx = 0; submeshIdx < data.pMesh->GetSubmeshCount(); ++submeshIdx) { items.insert(items.begin() + itemIdx, RenderItem { data.pMesh, id, submeshIdx, data.castsShadow }); } pit->itemCount += data.pMesh->GetSubmeshCount(); } itemIdx += pit->itemCount; } return true; } void Graphics::DrawDebugLine(const vec4& color, const vec3& start, const vec3& end) { #if TRINKET_TEST if (lineCount >= DEBUG_LINE_CAPACITY) return; let idx = lineCount << 1; lineBuf[idx].position = start; lineBuf[idx].color = color; lineBuf[idx+1].position = end; lineBuf[idx+1].color = color; ++lineCount; #endif } void Graphics::Draw() { let pDevice = pDisplay->GetDevice(); let pSwapChain = pDisplay->GetSwapChain(); let pContext = pDisplay->GetContext(); const auto& DevCaps = pDevice->GetDeviceCaps(); const auto& NDCAttribs = DevCaps.GetNDCAttribs(); const bool IsGL = DevCaps.IsGLDevice(); // get transforms, bounding boxes if (matrices.size() < items.size()) { matrices.resize(items.size()); boundingBoxes.resize(items.size()); } for(uint it=0; it<items.size(); ++it) { let& item = items[it]; let pHierarchy = pWorld->scene.GetSublevelHierarchyFor(item.id); let pPose = pHierarchy->GetScenePose(item.id); matrices[it] = pPose->ToMatrix(); boundingBoxes[it] = item.pMesh->GetBoundingBox().GetTransformed(matrices[it]); } // draw shadow map let lightz = lightDirection; const vec3 referenceVec = lightz.y * lightz.y < lightz.z * lightz.z ? vec3(0, 1, 0) : vec3(0, 0, 1); let lightx = glm::normalize(glm::cross(referenceVec, lightz)); let lighty = glm::cross(lightz, lightx); // TODO: actually calculate view bounds float r = 5.f; const vec3 viewCenter (0.f, 0.f, 0.f); let viewMin = viewCenter - vec3(r, r, r); let viewMax = viewCenter + vec3(r, r, r); let viewExtent = viewMax - viewMin; // Apply bias to shift the extent to // [-1,1]x[-1,1]x[0,1] for DX or to // [-1,1]x[-1,1]x[-1,1] for GL // Find bias such that sceneMin -> // (-1,-1,0) for DX or // (-1,-1,-1) for GL const vec3 lightSpaceScale ( 2.f / viewExtent.x, 2.f / viewExtent.y, (IsGL ? 2.f : 1.f) / viewExtent.z ); const vec3 lightSpaceScaledBias ( -viewMin.x * lightSpaceScale.x - 1.f, -viewMin.y * lightSpaceScale.y - 1.f, -viewMin.z * lightSpaceScale.z + (IsGL ? -1.f : 0.f) ); let worldToLightProjSpace = glm::translate(lightSpaceScaledBias) * // offset to scene center glm::scale(lightSpaceScale) * // scale to scene extents mat4(glm::transpose(mat3(lightx, lighty, lightz))); // view matrix of directional light let worldToShadowMapUVDepth = glm::translate(vec3(0.5f, 0.5f, NDCAttribs.GetZtoDepthBias())) * // to UV bias glm::scale(vec3(0.5f, NDCAttribs.YtoVScale, NDCAttribs.ZtoDepthScale)) * // to UV scale worldToLightProjSpace; { pContext->SetRenderTargets(0, nullptr, pShadowMapDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->ClearDepthStencil(pShadowMapDSV, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->SetPipelineState(pShadowPipelineState); pContext->CommitShaderResources(pShadowResourceBinding, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); for(auto it=0u; it<items.size(); ++it) { let& item = items[it]; if (item.shadows) { { MapHelper<RenderConstants> CBConstants(pContext, pRenderConstants, MAP_WRITE, MAP_FLAG_DISCARD); CBConstants->ModelViewProjectionTransform = worldToLightProjSpace * matrices[it]; } item.pMesh->GetSubmesh(item.submeshIdx)->DoDraw(pContext); } } } // draw material passes let view = pov.pose.Inverse().ToMatrix(); let aspect = pDisplay->GetAspect(); let viewProjection = glm::perspective(glm::radians(pov.fovy), aspect, pov.zNear, pov.zFar) * view; pDisplay->SetMultisamplingTargetAndClear(); int itemIdx=0; for(auto& pass : passes) { let bSkip = pass.itemCount == 0 || !pass.pMaterial->GetPass(pass.materialPassIdx).Bind(this); if (bSkip) continue; for(int it=0; it<pass.itemCount; ++it) { let& item = items[itemIdx + it]; let& pose = matrices[itemIdx + it]; let normalXf = glm::inverseTranspose(mat3(pose)); let mvp = viewProjection * pose; let mv = view * pose; { MapHelper<RenderConstants> CBConstants(pContext, pRenderConstants, MAP_WRITE, MAP_FLAG_DISCARD); CBConstants->ModelViewProjectionTransform = mvp; CBConstants->ModelViewTransform = mv; CBConstants->ModelTransform = pose; CBConstants->NormalTransform = normalXf; CBConstants->SceneToShadowMapUVDepth = worldToShadowMapUVDepth; CBConstants->LightDirection = vec4(lightz, 0); } item.pMesh->GetSubmesh(item.submeshIdx)->DoDraw(pContext); } itemIdx += pass.itemCount; } #if TRINKET_TEST if (lineCount > 0) { pContext->UpdateBuffer(pDebugWireframeBuf, 0, sizeof(WireframeVertex)* (lineCount + lineCount), lineBuf, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->SetPipelineState(pDebugWireframePSO); pContext->CommitShaderResources(pDebugWireframeSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); uint32 offset = 0; IBuffer* pBuffers[]{ pDebugWireframeBuf }; pContext->SetVertexBuffers(0, 1, pBuffers, &offset, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET); { MapHelper<RenderConstants> CBConstants(pContext, pRenderConstants, MAP_WRITE, MAP_FLAG_DISCARD); CBConstants->ModelViewProjectionTransform = viewProjection; CBConstants->ModelViewTransform = view; CBConstants->ModelTransform = glm::identity<mat4>(); CBConstants->NormalTransform = glm::identity<mat3>(); //CBConstants->SceneToShadowMapUVDepth = worldToShadowMapUVDepth; //CBConstants->LightDirection = vec4(lightz, 0); } DrawAttribs draw; draw.NumVertices = lineCount << 1; pContext->Draw(draw); lineCount = 0; } #endif #if SHADOW_MAP_DEBUG // draw shadow debug { pContext->SetPipelineState(pShadowMapDebugPSO); pContext->CommitShaderResources(pShadowMapDebugSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); DrawAttribs DrawAttrs(4, DRAW_FLAG_VERIFY_ALL); pContext->Draw(DrawAttrs); } #endif }
35.283146
150
0.751736
maxattack
20744a94bdfc7f6af5f77ffce76d0daae362fd30
3,310
cpp
C++
src/ogl/renderer/oglbuffer.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/ogl/renderer/oglbuffer.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/ogl/renderer/oglbuffer.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
/* Copyright 2009-2021 Nicolas Colombe Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ogl/renderer/oglbuffer.hpp> #include <ogl/oglutils.hpp> #include <ogl/renderer/oglinclude.hpp> #include <ogl/renderer/ogltypesconv.hpp> namespace eXl { IMPLEMENT_RefC(OGLBuffer); #ifdef __ANDROID__ static void* s_TempBuffer = NULL; static size_t s_TempBufferSize = 0; #endif OGLBuffer* OGLBuffer::CreateBuffer(OGLBufferUsage iUsage, size_t iSize, void* iData) { #ifdef EXL_WITH_OGL GLenum glUsage = GetGLUsage(iUsage); GLuint newBufferId; glGenBuffers(1,&newBufferId); if(newBufferId != 0) { glBindBuffer(glUsage,newBufferId); while(GL_NO_ERROR != glGetError()){} glBufferData(glUsage,iSize,iData,GL_STATIC_DRAW); GLenum error = glGetError(); if(error == GL_NO_ERROR) { OGLBuffer* newBuffer = eXl_NEW OGLBuffer; newBuffer->m_Id = newBufferId; newBuffer->m_Size = iSize; newBuffer->m_Usage = iUsage; return newBuffer; } } #endif return nullptr; } void OGLBuffer::SetData(size_t iOffset, size_t iSize, void* iData) { #ifdef EXL_WITH_OGL GLenum glUsage = GetGLUsage(m_Usage); glBindBuffer(glUsage,m_Id); glBufferSubData(glUsage,iOffset,iSize,iData); #endif } void* OGLBuffer::MapBuffer(OGLBufferAccess iAccess) { #ifdef EXL_WITH_OGL GLenum glUsage = GetGLUsage(m_Usage); GLenum glAccess = GetGLAccess(iAccess); #ifndef __ANDROID__ glBindBuffer(glUsage,GetBufferId()); return glMapBuffer(glUsage,glAccess); #else //return glMapBufferOES(GL_ARRAY_BUFFER,GL_WRITE_ONLY_OES); if(GetBufferSize() > s_TempBufferSize) { s_TempBuffer = realloc(s_TempBuffer,GetBufferSize()); } return s_TempBuffer; #endif #else return nullptr; #endif } void OGLBuffer::UnmapBuffer() { #ifdef EXL_WITH_OGL GLenum glUsage = GetGLUsage(m_Usage); #ifndef __ANDROID__ glBindBuffer(glUsage,m_Id); glUnmapBuffer(glUsage); #else //glUnmapBufferOES(GL_ARRAY_BUFFER); glBindBuffer(glUsage,GetBufferId()); glBufferSubData(glUsage,0,GetBufferSize(),s_TempBuffer); #endif CHECKOGL(); #endif } OGLBuffer::~OGLBuffer() { #ifdef EXL_WITH_OGL glDeleteBuffers(1,&m_Id); #endif } OGLBuffer::OGLBuffer():m_Id(0) { } }
29.81982
460
0.729607
eXl-Nic
207913cf191753a50182523406eb60b79a3009a3
544
cpp
C++
hackerrankrunningtimealgo.cpp
ap9891/hackerrank
05fa0bc3a20ad736cd357775923b528254ec28ab
[ "MIT" ]
1
2020-07-09T19:52:30.000Z
2020-07-09T19:52:30.000Z
hackerrankrunningtimealgo.cpp
ap9891/hackerrank
05fa0bc3a20ad736cd357775923b528254ec28ab
[ "MIT" ]
null
null
null
hackerrankrunningtimealgo.cpp
ap9891/hackerrank
05fa0bc3a20ad736cd357775923b528254ec28ab
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; void insertsort(int *arr, int n) { int count =0 ; for (int i = 0; i < n; i++) { int min = arr[i]; int j = i-1; while(j >=0 && arr[j] > min) { arr[j+1]= arr[j]; j=j-1; count++; } arr[j+1] = min; } cout<<count; } int main() { int n,arr[10000]; cin>>n; for (int i = 0; i < n; i++) { cin>>arr[i]; } insertsort(arr,n); return 0; }
17.548387
37
0.371324
ap9891
207ba5b32ab0acd46ca7023558f0ac8e86e22a09
915
cpp
C++
Source/AutonomousAgents/Behavior/Decorators/LeaderCheckDecorator.cpp
AnupamSahu/AutonomousAgents
f521faccc4187217e97c137c527bac1952a5b92a
[ "MIT" ]
null
null
null
Source/AutonomousAgents/Behavior/Decorators/LeaderCheckDecorator.cpp
AnupamSahu/AutonomousAgents
f521faccc4187217e97c137c527bac1952a5b92a
[ "MIT" ]
null
null
null
Source/AutonomousAgents/Behavior/Decorators/LeaderCheckDecorator.cpp
AnupamSahu/AutonomousAgents
f521faccc4187217e97c137c527bac1952a5b92a
[ "MIT" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. #include "LeaderCheckDecorator.h" #include "AIController.h" #include "../Types/SensedActorsWrapper.h" #include "BehaviorTree/BlackboardComponent.h" void ULeaderCheckDecorator::OnGameplayTaskActivated(UGameplayTask& Task) { Super::OnGameplayTaskActivated(Task); } void ULeaderCheckDecorator::OnGameplayTaskDeactivated(UGameplayTask& Task) { Super::OnGameplayTaskDeactivated(Task); } bool ULeaderCheckDecorator::CalculateRawConditionValue(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) const { USensedActorsWrapper* NeighborsWrapper = Cast<USensedActorsWrapper>(OwnerComp.GetBlackboardComponent()->GetValueAsObject("Neighbors")); if(NeighborsWrapper != nullptr) { NeighborsWrapper->SenseNeighbors(OwnerComp.GetAIOwner()->GetAIPerceptionComponent(), SightRadius, LoseSightRadius, HalfFOV); return NeighborsWrapper->Num()==0; } return false; }
30.5
136
0.809836
AnupamSahu
2083fb91d7225663e497b8224f88724059736b33
1,985
cpp
C++
Striver Sheet/Day-14/Rotting Oranges.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
Striver Sheet/Day-14/Rotting Oranges.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
Striver Sheet/Day-14/Rotting Oranges.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2022-01-23T22:00:48.000Z
2022-01-23T22:00:48.000Z
/* Rotting Oranges =============== You are given an m x n grid where each cell can have one of three values: 0 representing an empty cell, 1 representing a fresh orange, or 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1. Example 1: Input: grid = [[2,1,1],[1,1,0],[0,1,1]] Output: 4 Example 2: Input: grid = [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. Example 3: Input: grid = [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 10 grid[i][j] is 0, 1, or 2. */ class Solution { public: int dirs[4][4] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int orangesRotting(vector<vector<int>> &grid) { queue<vector<int>> q; int ans = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j] == 2) { q.push({i, j, 0}); } } } while (q.size()) { auto curr = q.front(); q.pop(); int i = curr[0], j = curr[1], time = curr[2]; ans = max(ans, time); for (auto &d : dirs) { int nextI = i + d[0], nextJ = j + d[1]; if (nextI >= 0 && nextJ >= 0 && nextI < grid.size() && nextJ < grid[0].size()) { if (grid[nextI][nextJ] == 1) { grid[nextI][nextJ] = 2; q.push({nextI, nextJ, time + 1}); } } } } for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j] == 1) return -1; } } return ans; } };
22.816092
130
0.524433
Akshad7829
208409bf72c2611ec8740edbf4bff96b2adb9208
1,652
cpp
C++
src/condor_lease_manager/lease_manager_lease.cpp
zhangzhehust/htcondor
e07510d62161f38fa2483b299196ef9a7b9f7941
[ "Apache-2.0" ]
2
2018-06-18T23:11:20.000Z
2021-01-11T06:30:00.000Z
src/condor_lease_manager/lease_manager_lease.cpp
AmesianX/htcondor
10aea32f1717637972af90459034d1543004cb83
[ "Apache-2.0" ]
1
2021-04-06T04:19:40.000Z
2021-04-06T04:19:40.000Z
src/condor_lease_manager/lease_manager_lease.cpp
AmesianX/htcondor
10aea32f1717637972af90459034d1543004cb83
[ "Apache-2.0" ]
2
2016-05-24T17:12:13.000Z
2017-02-13T01:25:35.000Z
/*************************************************************** * * Copyright (C) 1990-2008, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 <list> #include <string> #include "lease_manager_lease.h" using namespace std; LeaseManagerLease::LeaseManagerLease( const string &lease_id, int lease_duration, bool release_when_done ) { setLeaseId( lease_id ); setLeaseDuration( lease_duration ); m_release_when_done = release_when_done ; } LeaseManagerLease::~LeaseManagerLease( void ) { } void LeaseManagerLease::setLeaseId( const string &lease_id ) { m_id = lease_id; } void LeaseManagerLease::setLeaseDuration( int duration ) { m_duration = duration; } void LeaseManagerLease::setReleaseWhenDone( bool rel ) { m_release_when_done = rel; } void LeaseManagerLease_FreeList( list<LeaseManagerLease *> &lease_list ) { for( list<LeaseManagerLease *>::iterator iter = lease_list.begin(); iter != lease_list.end(); iter++ ) { delete *iter; } }
24.294118
75
0.677966
zhangzhehust
208697c061c7fe4612c673b1df693cd8b062f84d
2,192
cc
C++
tests&old_stuff/old tests/learning by doing/unordered_test.cc
reiss-josh/RESTful_memcache
40a21020cd3830c9e11b075039cb7a3b760ac0ad
[ "MIT" ]
1
2019-05-02T21:47:15.000Z
2019-05-02T21:47:15.000Z
tests&old_stuff/old tests/learning by doing/unordered_test.cc
reiss-josh/RESTful_memcache
40a21020cd3830c9e11b075039cb7a3b760ac0ad
[ "MIT" ]
null
null
null
tests&old_stuff/old tests/learning by doing/unordered_test.cc
reiss-josh/RESTful_memcache
40a21020cd3830c9e11b075039cb7a3b760ac0ad
[ "MIT" ]
1
2018-10-08T06:04:44.000Z
2018-10-08T06:04:44.000Z
#include <cache.hh> #include <iostream> #include <unordered_map> #include <string> using key_type = const std::string; using val_type = const void*; using hash_func = std::function<uint32_t(key_type)>; std::unordered_map<std::string, void*> data_; void assign(key_type key, val_type val) { void* val_p = &val; data_[key] = val_p; } int main() { using namespace std; key_type k = "help"; val_type v = "apple"; assign(k, v); cout << data_[k] << endl; cout << endl; int myvar = 25; void* val = &myvar; int* val_ptr = (int*)val; int apple = *val_ptr; cout << myvar << endl; cout << val << endl; cout << apple << endl; } //boop /* unordered_map<std::string, void*, hash_func> my_table(0, hasher_; hash_func hasher; hash_vale = hasher(); std::hash<std::string> h; h(); struct Cache::Impl { unordered_map<std::string, void*, hash_func> data_; ... Impl(maxmem, hasher, evictor) : data_(0, hasher) } */ /* Cache::index_type my_hash_func(Cache::key_type key) { return key[0]; } struct MyHasher { int data_; MyHasher() : data_(0) {} Cache::index_type operator()(Cache::key_type key) { return key[0]; } }; MyHasher hs; hs("yohoo!"); Cache test_cache(100, [](){return 0;}, my_hash_func); Cache test_cache(100, [](){return 0;}, hs); char data[10] = "abcdefghi"; test_cache.set("my_key", static_cast<Cache::val_type>(data), 10); int size; p = test_cache.get("my_key", size) */ /* char* val_ptr = (char*)val; //cast val as real ptr std::cout<<val_ptr<<std::endl; char outt[size]; for(int i = 0; i < size; i++) //char outt = *val_ptr; { outt[i] = *(val_ptr + i); }*/ //void* val_ptr; //std::memcpy(val_ptr, val, size); //std::cout<< val_ptr <<std::endl; //std::cout<<outt<<std::endl; //check successful copy //void* outt_ptr = static_cast<void*>(outt); //save as void* //char* extractedboyo = (char*)val_ptr; //std::cout<< extractedboyo << std::endl; /* unordered_map<std::string, void*, hash_func> my_table(0, hasher_); hash_func hasher; hash_vale = hasher(); std::hash<std::string> h; h(); struct Cache::Impl { unordered_map<std::string, void*, hash_func> data_; ... Impl(maxmem, hasher, evictor) : data_(0, hasher) } */
19.06087
66
0.643704
reiss-josh
208737b87f789e12188ecfe6e4dc0d6ed953d6a6
25,160
cpp
C++
talpa/iomesh.cpp
q349wang/eltopo
a63a43d2a890c53f8e0c51034c46ce01ead86564
[ "BSD-2-Clause" ]
null
null
null
talpa/iomesh.cpp
q349wang/eltopo
a63a43d2a890c53f8e0c51034c46ce01ead86564
[ "BSD-2-Clause" ]
null
null
null
talpa/iomesh.cpp
q349wang/eltopo
a63a43d2a890c53f8e0c51034c46ce01ead86564
[ "BSD-2-Clause" ]
null
null
null
// --------------------------------------------------------- // // iomesh.cpp // // Non-member functions for reading and writing various mesh file formats. // // --------------------------------------------------------- #include <iomesh.h> #include <bfstream.h> #include <cstdarg> #include <cstdlib> #include <cmath> #include <fstream> #include <nondestructivetrimesh.h> #ifndef NO_GUI #include <gluvi.h> #endif #define LINESIZE 1024 // maximum line size when reading .OBJ files // --------------------------------------------------------- /// /// Write mesh in binary format /// // --------------------------------------------------------- bool write_binary_file( const NonDestructiveTriMesh &mesh, const std::vector<Vec3d> &x, const std::vector<double> &masses, double curr_t, const char *filename_format, ...) { va_list ap; va_start(ap, filename_format); bofstream outfile( filename_format, ap ); va_end(ap); outfile.write_endianity(); outfile << curr_t; unsigned int nverts = static_cast<unsigned int>( x.size() ); outfile << nverts; for ( unsigned int i = 0; i < x.size(); ++i ) { outfile << x[i][0]; outfile << x[i][1]; outfile << x[i][2]; } assert( x.size() == masses.size() ); for ( unsigned int i = 0; i < masses.size(); ++i ) { outfile << masses[i]; } unsigned int ntris = static_cast<unsigned int>( mesh.num_triangles() ); outfile << ntris; for ( unsigned int t = 0; t < mesh.num_triangles(); ++t ) { const Vec3ui& tri = Vec3ui( mesh.get_triangle(t) ); outfile << tri[0]; outfile << tri[1]; outfile << tri[2]; } outfile.close(); return outfile.good(); } // --------------------------------------------------------- /// /// Write mesh in binary format, with per-vertex velocities /// // --------------------------------------------------------- bool write_binary_file_with_velocities( const NonDestructiveTriMesh &mesh, const std::vector<Vec3d> &x, const std::vector<double> &masses, const std::vector<Vec3d> &v, double curr_t, const char *filename_format, ...) { va_list ap; va_start(ap, filename_format); bofstream outfile( filename_format, ap ); va_end(ap); outfile.write_endianity(); outfile << curr_t; unsigned int nverts = static_cast<unsigned int>( x.size() ); outfile << nverts; for ( unsigned int i = 0; i < x.size(); ++i ) { outfile << x[i][0]; outfile << x[i][1]; outfile << x[i][2]; } assert( x.size() == masses.size() ); for ( unsigned int i = 0; i < masses.size(); ++i ) { outfile << masses[i]; } for ( unsigned int i = 0; i < v.size(); ++i ) { outfile << v[i][0]; outfile << v[i][1]; outfile << v[i][2]; } unsigned int ntris = static_cast<unsigned int>( mesh.num_triangles() ); outfile << ntris; for ( unsigned int t = 0; t < mesh.num_triangles(); ++t ) { const Vec3ui& tri = Vec3ui( mesh.get_triangle(t) ); outfile << tri[0]; outfile << tri[1]; outfile << tri[2]; } outfile.close(); return outfile.good(); } // --------------------------------------------------------- bool write_surface_ids( const std::vector<size_t> &ids, const char *filename_format, ... ) { va_list ap; va_start(ap, filename_format); bofstream outfile( filename_format, ap ); va_end(ap); outfile.write_endianity(); size_t nids = ids.size(); outfile << nids; for ( unsigned int i = 0; i < ids.size(); ++i ) { unsigned int curr_id = static_cast<unsigned int>(ids[i]); outfile << curr_id; } outfile.close(); return outfile.good(); } // --------------------------------------------------------- /// /// Read mesh in binary format /// // --------------------------------------------------------- bool read_binary_file( NonDestructiveTriMesh &mesh, std::vector<Vec3d> &x, std::vector<double> &masses, double& curr_t, const char *filename_format, ...) { va_list ap; va_start(ap, filename_format); bifstream infile( filename_format, ap ); va_end(ap); assert( infile.good() ); infile.read_endianity(); infile >> curr_t; unsigned int nverts; infile >> nverts; x.resize( nverts ); for ( unsigned int i = 0; i < nverts; ++i ) { infile >> x[i][0]; infile >> x[i][1]; infile >> x[i][2]; mesh.add_vertex(); } masses.resize( nverts ); for ( unsigned int i = 0; i < nverts; ++i ) { infile >> masses[i]; } unsigned int ntris; infile >> ntris; for ( unsigned int t = 0; t < ntris; ++t ) { Vec3ui tri; infile >> tri[0]; infile >> tri[1]; infile >> tri[2]; mesh.add_triangle( Vec3st(tri) ); } infile.close(); return infile.good(); } // --------------------------------------------------------- /// /// Read mesh in binary format, with per-vertex velocities /// // --------------------------------------------------------- bool read_binary_file_with_velocities( NonDestructiveTriMesh &mesh, std::vector<Vec3d> &x, std::vector<double> &masses, std::vector<Vec3d> &v, double& curr_t, const char *filename_format, ...) { va_list ap; va_start(ap, filename_format); bifstream infile( filename_format, ap ); va_end(ap); infile.read_endianity(); infile >> curr_t; unsigned int nverts; infile >> nverts; mesh.set_num_vertices(nverts); x.resize( nverts ); for ( unsigned int i = 0; i < nverts; ++i ) { infile >> x[i][0]; infile >> x[i][1]; infile >> x[i][2]; } masses.resize( nverts ); for ( unsigned int i = 0; i < masses.size(); ++i ) { infile >> masses[i]; } v.resize( nverts ); for ( unsigned int i = 0; i < nverts; ++i ) { infile >> v[i][0]; infile >> v[i][1]; infile >> v[i][2]; } unsigned int ntris; infile >> ntris; for ( unsigned int t = 0; t < ntris; ++t ) { Vec3st tri; infile >> tri[0]; infile >> tri[1]; infile >> tri[2]; mesh.add_triangle(tri); } infile.close(); return infile.good(); } // --------------------------------------------------------- bool read_surface_ids( std::vector<unsigned int>& ids, const char *filename_format, ... ) { va_list ap; va_start(ap, filename_format); bifstream infile( filename_format, ap ); va_end(ap); infile.read_endianity(); unsigned int n; infile >> n; ids.resize(n); for ( unsigned int i = 0; i < ids.size(); ++i ) { infile >> ids[i]; } infile.close(); return infile.good(); } // --------------------------------------------------------- /// /// Write mesh in Wavefront OBJ format /// // --------------------------------------------------------- bool write_objfile(const NonDestructiveTriMesh &mesh, const std::vector<Vec3d> &x, const char *filename_format, ...) { #ifdef _MSC_VER va_list ap; va_start(ap, filename_format); int len=_vscprintf(filename_format, ap) // _vscprintf doesn't count +1; // terminating '\0' char *filename=new char[len]; vsprintf(filename, filename_format, ap); std::ofstream output(filename, std::ofstream::binary); delete[] filename; va_end(ap); #else va_list ap; va_start(ap, filename_format); char *filename; vasprintf(&filename, filename_format, ap); std::ofstream output(filename, std::ofstream::binary); std::free(filename); va_end(ap); #endif if(!output.good()) return false; output<<"# generated by editmesh"<<std::endl; for(unsigned int i=0; i<x.size(); ++i) output<<"v "<<x[i]<<std::endl; for(unsigned int t=0; t<mesh.num_triangles(); ++t) output<<"f "<<mesh.get_triangle(t)[0]+1<<' '<<mesh.get_triangle(t)[1]+1<<' '<<mesh.get_triangle(t)[2]+1<<std::endl; // correct for 1-based indexing in OBJ files return output.good(); } namespace { // --------------------------------------------------------- /// /// Helper for reading OBJ file /// // --------------------------------------------------------- bool read_int(const char *s, int &value, bool &leading_slash, int &position) { leading_slash=false; for(position=0; s[position]!=0; ++position){ switch(s[position]){ case '/': leading_slash=true; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto found_int; } } return false; found_int: value=0; for(;; ++position){ switch(s[position]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value=10*value+s[position]-'0'; break; default: return true; } } return true; // should never get here, but keeps compiler happy } // --------------------------------------------------------- /// /// Helper for reading OBJ file /// // --------------------------------------------------------- void read_face_list(const char *s, std::vector<int> &vertex_list) { vertex_list.clear(); int v, skip; bool leading_slash; for(int i=0;;){ if(read_int(s+i, v, leading_slash, skip)){ if(!leading_slash) vertex_list.push_back(v-1); // correct for 1-based index i+=skip; }else break; } } } // unnamed namespace // --------------------------------------------------------- /// /// Read mesh in Wavefront OBJ format /// // --------------------------------------------------------- bool read_objfile(NonDestructiveTriMesh &mesh, std::vector<Vec3d> &x, const char *filename_format, ...) { #ifdef _MSC_VER va_list ap; va_start(ap, filename_format); int len=_vscprintf(filename_format, ap) // _vscprintf doesn't count +1; // terminating '\0' char *filename=new char[len]; vsprintf(filename, filename_format, ap); std::ifstream input(filename, std::ifstream::binary); delete[] filename; va_end(ap); #else va_list ap; va_start(ap, filename_format); char *filename; vasprintf(&filename, filename_format, ap); std::ifstream input(filename, std::ifstream::binary); std::free(filename); va_end(ap); #endif if(!input.good()) return false; x.clear(); mesh.clear(); char line[LINESIZE]; std::vector<int> vertex_list; while(input.good()){ input.getline(line, LINESIZE); switch(line[0]){ case 'v': // vertex data if(line[1]==' '){ Vec3d new_vertex; std::sscanf(line+2, "%lf %lf %lf", &new_vertex[0], &new_vertex[1], &new_vertex[2]); x.push_back(new_vertex); } break; case 'f': // face data if(line[1]==' '){ read_face_list(line+2, vertex_list); for(int j=0; j<(int)vertex_list.size()-2; ++j) mesh.add_triangle( Vec3st(vertex_list[0], vertex_list[j+1], vertex_list[j+2]) ); } break; } } return true; } // --------------------------------------------------------- /// /// Write mesh in Renderman RIB format. /// // --------------------------------------------------------- bool write_ribfile(const NonDestructiveTriMesh &mesh, const std::vector<float> &x, const char *filename_format, ...) { #ifdef _MSC_VER va_list ap; va_start(ap, filename_format); int len=_vscprintf(filename_format, ap) // _vscprintf doesn't count +1; // terminating '\0' char *filename=new char[len]; vsprintf(filename, filename_format, ap); std::ofstream output(filename, std::ofstream::binary); delete[] filename; va_end(ap); #else va_list ap; va_start(ap, filename_format); char *filename; vasprintf(&filename, filename_format, ap); std::ofstream output(filename, std::ofstream::binary); std::free(filename); va_end(ap); #endif if(!output.good()) return false; return write_ribfile(mesh, x, output); } // --------------------------------------------------------- /// /// Write mesh in Renderman RIB format. /// // --------------------------------------------------------- bool write_ribfile(const NonDestructiveTriMesh &mesh, const std::vector<float> &x, std::ostream &output) { output<<"# generated by editmesh"<<std::endl; output<<"PointsPolygons"<<std::endl; output<<" [ "; const std::vector<Vec3st>& tris = mesh.get_triangles(); for(unsigned int i=0; i<tris.size(); ++i){ output<<"3 "; if(i%38==37 && i!=tris.size()-1) output<<std::endl; } output<<"]"<<std::endl; output<<" [ "; for(unsigned int i=0; i<tris.size(); ++i){ output<<tris[i]<<" "; if(i%6==5 && i!=tris.size()-1) output<<std::endl; } output<<"]"<<std::endl; output<<" \"P\" ["; for(unsigned int i=0; i<x.size(); ++i){ output<<x[i]<<" "; if(i%4==3 && i!=x.size()-1) output<<std::endl; } output<<"]"<<std::endl; return output.good(); } // --------------------------------------------------------- /// /// Write mesh in Renderman RIB format. /// // --------------------------------------------------------- bool write_ribfile(const NonDestructiveTriMesh &mesh, const std::vector<float> &x, FILE *output) { fprintf( output, "# generated by editmesh\n" ); fprintf( output, "PointsPolygons\n" ); fprintf( output, " [ " ); const std::vector<Vec3st>& tris = mesh.get_triangles(); for(unsigned int i=0; i<tris.size(); ++i){ fprintf( output, "3 " ); if(i%38==37 && i!=tris.size()-1) fprintf( output, "\n" ); } fprintf( output, "]\n" ); fprintf( output, " [ " ); for(unsigned int i=0; i<tris.size(); ++i){ Vec3ui new_tri; fprintf( output, " %d %d %d ", (int)tris[i][0], (int)tris[i][1], (int)tris[i][2] ); if(i%6==5 && i!=tris.size()-1) fprintf( output, "\n" ); } fprintf( output, "]\n" ); fprintf( output, " \"P\" [" ); for(unsigned int i=0; i<x.size(); ++i){ fprintf( output, " %f ", x[i] ); if(i%4==3 && i!=x.size()-1) fprintf( output, "\n" ); } fprintf( output, "]\n" ); return true; } #ifndef NO_GUI // --------------------------------------------------------- /// /// Write an RIB file for the shadow map for the given light /// // --------------------------------------------------------- bool output_shadow_rib( Gluvi::Target3D& light, const std::vector<Vec3d>& positions, const NonDestructiveTriMesh& mesh, const char *filename_format, ...) { #ifdef _MSC_VER va_list ap; va_start(ap, filename_format); int len=_vscprintf(filename_format, ap) // _vscprintf doesn't count +1; // terminating '\0' char *filename=new char[len]; vsprintf(filename, filename_format, ap); std::ofstream out; out.open( filename ); delete[] filename; if( out == NULL ) { return false; } len=_vscprintf("track%04d_shadow.tiff", ap) // _vscprintf doesn't count +1; // terminating '\0' filename=new char[len]; vsprintf( filename, "track%04d_shadow.tiff", ap ); va_end(ap); #else va_list ap; va_start(ap, filename_format); char *filename; vasprintf(&filename, filename_format, ap); std::ofstream out; out.open( filename ); delete[] filename; if( !out ) { return false; } vasprintf( &filename, "track%04d_shadow.tiff", ap ); va_end(ap); #endif // flatten std::vector<float> xs; for ( unsigned int i = 0; i < positions.size(); ++i ) { xs.push_back( (float) positions[i][0] ); xs.push_back( (float) positions[i][1] ); xs.push_back( (float) positions[i][2] ); } out << "Display \"" << filename << "\" \"file\" \"z\"" << std::endl; delete[] filename; // next line: image format (width and height in pixels, pixel aspect ratio) out << "Format " << "1024 1024 1" << std::endl; out << "PixelFilter \"box\" 1 1 " << std::endl; // then write out the camera specification light.export_rib(out); // start the scene out << "WorldBegin\n"; out << "AttributeBegin\n"; out << " Color [0.6 0.6 0.2]\n"; out << " Opacity [1 1 1]\n"; out << " Surface \"matte\" \"Kd\" 1\n"; const float plane_limit = 50.0f; char buf[256]; sprintf( buf, " Polygon \"P\" [-%f -%f -%f %f -%f -%f %f %f -%f -%f %f -%f]\n", plane_limit, plane_limit, plane_limit, plane_limit, plane_limit, plane_limit, plane_limit, plane_limit, plane_limit, plane_limit, plane_limit, plane_limit ); out << buf; out << "AttributeEnd\n"; out << "Color [0.7 0.7 0.9]\n"; out << "Surface \"matte\" \n"; write_ribfile( mesh, xs, out); // finish the scene out << "WorldEnd\n"; out.flush(); out.close(); return true; } // --------------------------------------------------------- /// /// Write a render-ready RIB file. /// // --------------------------------------------------------- bool output_rib( const std::vector<Vec3d>& positions, const NonDestructiveTriMesh& mesh, const char *filename_format, ...) { #ifdef _MSC_VER va_list ap; va_start(ap, filename_format); int len=_vscprintf(filename_format, ap) // _vscprintf doesn't count +1; // terminating '\0' char *filename=new char[len]; vsprintf(filename, filename_format, ap); std::ofstream out; out.open( filename ); delete[] filename; if( out == NULL ) { return false; } // first line: what image file this RIB file should produce len=_vscprintf("track%04d.tiff", ap) // _vscprintf doesn't count +1; // terminating '\0' filename=new char[len]; vsprintf( filename, "track%04d.tiff", ap ); len=_vscprintf("track%04d_shadow.shad", ap) // _vscprintf doesn't count +1; // terminating '\0' char *shadow_filename=new char[len]; vsprintf( shadow_filename, "track%04d_shadow.shad", ap ); va_end(ap); #else va_list ap; va_start(ap, filename_format); char *filename; vasprintf(&filename, filename_format, ap); std::ofstream out; out.open( filename ); delete[] filename; if( !out ) { return false; } // first line: what image file this RIB file should produce vasprintf( &filename, "track%04d.tiff", ap ); char *shadow_filename; vasprintf( &shadow_filename, "track%04d_shadow.shad", ap ); va_end(ap); #endif // flatten std::vector<float> xs; for ( unsigned int i = 0; i < positions.size(); ++i ) { xs.push_back( (float) positions[i][0] ); xs.push_back( (float) positions[i][1] ); xs.push_back( (float) positions[i][2] ); } std::vector<Vec3f> normals; for ( unsigned int i = 0; i < positions.size(); ++i ) { Vec3f n(0,0,0); for ( unsigned int j = 0; j < mesh.m_vertex_to_triangle_map[i].size(); ++j ) { const Vec3st& tri = mesh.get_triangle( mesh.m_vertex_to_triangle_map[i][j] ); Vec3d u = positions[ tri[1] ] - positions[ tri[0] ]; Vec3d v = positions[ tri[2] ] - positions[ tri[0] ]; Vec3d tn = normalized(cross(u, v)); n += Vec3f( (float)tn[0], (float)tn[1], (float)tn[2] ); } normals.push_back( n / (float) mesh.m_vertex_to_triangle_map[i].size() ); } out << "Display \"" << filename << "\" \"file\" \"rgb\"" << std::endl; delete[] filename; // next line: image format (width and height in pixels, pixel aspect ratio) out << "Format " << Gluvi::winwidth << " " << Gluvi::winheight << " 1" << std::endl; out << "PixelSamples 2 2" << std::endl; out << "Exposure 1.0 2.2" << std::endl; // then write out the camera specification Gluvi::camera->export_rib(out); // start the scene out << "WorldBegin\n"; out << "LightSource \"ambientlight\" 1 \"intensity\" .3 \"lightcolor\" [1 1 1]\n"; /* for ( unsigned int i = 0; i < lights.size(); ++i ) { // compute location of light Vec3f light_pos( 0, 0, lights[i].dist ); rotate( light_pos, lights[i].pitch, Vec3f(1,0,0) ); rotate( light_pos, lights[i].heading, Vec3f(0,1,0) ); light_pos += Vec3f( lights[i].target[0], lights[i].target[1], lights[i].target[2] ); out << "LightSource \"singleshadowpoint\" 2 \"intensity\" 30 \"from\" [" << light_pos << "] \"shadowmap\" \"" << shadow_filename << "\"\n"; } */ //out << "LightSource \"distantlight\" 3 \"intensity\" 0.3 \"from\" [-5 -10 20] \"to\" [0 0 0]\n"; out << "AttributeBegin\n"; out << " Color [0.6 0.6 0.2]\n"; out << " Opacity [1 1 1]\n"; out << " Surface \"matte\" \"Kd\" 1\n"; const float plane_limit = 50.0f; const float plane_distance = 10.0f; char buf[256]; sprintf( buf, " Polygon \"P\" [-%f -%f -%f %f -%f -%f %f %f -%f -%f %f -%f]\n", plane_limit, plane_limit, plane_distance, plane_limit, plane_limit, plane_distance, plane_limit, plane_limit, plane_distance, plane_limit, plane_limit, plane_distance ); out << buf; out << "AttributeEnd\n"; out << "Color [0.3 0.3 0.9]\n"; out << "Surface \"matte\" \n"; write_ribfile( mesh, xs, out); out << " \"N\" ["; for(unsigned int i=0; i<normals.size(); ++i) { out << normals[i] << " "; } out << "]" << std::endl; // finish the scene out << "WorldEnd\n"; out.flush(); out.close(); return true; } #endif // --------------------------------------------------------- // // Write mesh in PBRT format // // --------------------------------------------------------- bool write_pbrtfile(const NonDestructiveTriMesh &mesh, const std::vector<float> &x, const char *filename_format, ...) { #ifdef _MSC_VER va_list ap; va_start(ap, filename_format); int len=_vscprintf(filename_format, ap) // _vscprintf doesn't count +1; // terminating '\0' char *filename=new char[len]; vsprintf(filename, filename_format, ap); std::ofstream output(filename, std::ofstream::binary); delete[] filename; va_end(ap); #else va_list ap; va_start(ap, filename_format); char *filename; vasprintf(&filename, filename_format, ap); std::ofstream output(filename, std::ofstream::binary); std::free(filename); va_end(ap); #endif if(!output.good()) return false; return write_ribfile(mesh, x, output); } // --------------------------------------------------------- // // Write mesh in PBRT format // // --------------------------------------------------------- bool write_pbrtfile(const NonDestructiveTriMesh &mesh, const std::vector<float> &x, std::ostream &output) { output<<"# generated by editmesh"<<std::endl; //output<<"\"integer nlevels\" [3]"<<std::endl; output<<"\"point P\" ["<<std::endl; for(unsigned int i=0; i<x.size(); ++i){ output<<x[i]<<" "; if(i%4==3 && i!=x.size()-1) output<<std::endl; } output<<"]"<<std::endl; output<<" \"integer indices\" ["<<std::endl; const std::vector<Vec3st>& tris = mesh.get_triangles(); for(unsigned int i=0; i<tris.size(); ++i){ output<<tris[i]<<" "; if(i%6==5 && i!=tris.size()-1) output<<std::endl; } output<<"]"<<std::endl; return output.good(); }
27.739802
169
0.492965
q349wang
208beb25cb46baf46f48d288100066e82922dd40
414
cpp
C++
problems/009.cpp
hsw0905/Algorithm_study
ab0670f89ae6252393984ffeab9c50d4300b7f16
[ "MIT" ]
null
null
null
problems/009.cpp
hsw0905/Algorithm_study
ab0670f89ae6252393984ffeab9c50d4300b7f16
[ "MIT" ]
null
null
null
problems/009.cpp
hsw0905/Algorithm_study
ab0670f89ae6252393984ffeab9c50d4300b7f16
[ "MIT" ]
null
null
null
// 모두의 약수(제한시간 1초) // 시간복잡도 줄이기 : j = j + i (약수 n을 갖는다 == n의 배수는 모두 해당) #include <stdio.h> #define MAX_LENGTH (50001) int main() { freopen("input_009.txt", "rt", stdin); int num, i, j, cnt[MAX_LENGTH]; scanf("%d", &num); for (i = 1; i <= num; i++) { // i를 약수로 갖는 숫자를 찾는 작업 for (j = i; j <= num; j = j + i) { cnt[j]++; } } for (i = 1; i <= num; i++) { printf("%d ", cnt[i]); } return 0; }
15.333333
52
0.490338
hsw0905
208eb5a8c672bd40b5ec87d741bd901cc6dd9ca4
804
cpp
C++
leetcode2/lettercombinationsofaphonenumber.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
leetcode2/lettercombinationsofaphonenumber.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
leetcode2/lettercombinationsofaphonenumber.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<string> letterCombinations(string digits) { vector<string> res; if(digits.size()==0){ return res; } vector<string> books={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; string path; helper(path, books, res,0,digits); return res; } void helper(string &path, vector<string> &books, vector<string> &res, int start, string digits){ if(path.size()==digits.size()){ res.push_back(path); return; } for(int i=0; i<books[digits[start]-'2'].size(); i++){ path+=books[digits[start]-'2'][i]; helper(path, books, res, start+1, digits); path.erase(path.end()-1); } } };
28.714286
100
0.496269
WIZARD-CXY
209ef491137cc4c976730c1f645b35aeec81fd47
1,623
cpp
C++
src/analyzers/filters/filter_factory.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
615
2015-01-31T17:14:03.000Z
2022-03-27T03:03:02.000Z
src/analyzers/filters/filter_factory.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
167
2015-01-20T17:48:16.000Z
2021-12-20T00:15:29.000Z
src/analyzers/filters/filter_factory.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
264
2015-01-30T00:08:01.000Z
2022-03-02T17:19:11.000Z
/** * @file filter_factory.cpp * @author Chase Geigle */ #include "meta/analyzers/filter_factory.h" #include "meta/analyzers/tokenizers/character_tokenizer.h" #include "meta/analyzers/tokenizers/whitespace_tokenizer.h" #include "meta/analyzers/tokenizers/icu_tokenizer.h" #include "meta/analyzers/filters/all.h" namespace meta { namespace analyzers { template <class Tokenizer> void filter_factory::register_tokenizer() { add(Tokenizer::id, [](std::unique_ptr<token_stream> source, const cpptoml::table& config) { if (source) throw token_stream_exception{ "tokenizers must be the first filter"}; return tokenizers::make_tokenizer<Tokenizer>(config); }); } template <class Filter> void filter_factory::register_filter() { add(Filter::id, filters::make_filter<Filter>); } filter_factory::filter_factory() { // built-in tokenizers register_tokenizer<tokenizers::character_tokenizer>(); register_tokenizer<tokenizers::whitespace_tokenizer>(); register_tokenizer<tokenizers::icu_tokenizer>(); // built-in filters register_filter<filters::alpha_filter>(); register_filter<filters::empty_sentence_filter>(); register_filter<filters::english_normalizer>(); register_filter<filters::icu_filter>(); register_filter<filters::length_filter>(); register_filter<filters::list_filter>(); register_filter<filters::lowercase_filter>(); register_filter<filters::porter2_filter>(); register_filter<filters::ptb_normalizer>(); register_filter<filters::sentence_boundary>(); } } }
27.508475
78
0.71719
Lolik111
20a740f1a3c0afc62b7f68b98e8b99fa6dd6e511
613
cpp
C++
atcoder/abc097/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
atcoder/abc097/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
atcoder/abc097/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; // o(NK * log(NK) * K) string solve(string const& S, int K) { const int N = S.size(); vector<string> M; for (int l = 0; l < N; ++l) { for (int c = 1; c <= K && l + c <= N; ++c) { string ss = S.substr(l, c); M.push_back(ss); } } sort(M.begin(), M.end()); M.erase(unique(M.begin(), M.end()), M.end()); return M[K-1]; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string S; int K; cin >> S >> K; cout << solve(S, K) << endl; return 0; }
19.774194
52
0.468189
xirc
20a8fda06a2a5c2f8d1d586db8f78869f26ca729
1,549
hpp
C++
src/elona/lua_env/lua_class/lua_class_ability.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/lua_env/lua_class/lua_class_ability.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/lua_env/lua_class/lua_class_ability.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
1
2020-02-24T18:52:19.000Z
2020-02-24T18:52:19.000Z
#pragma once #include "../handle_manager.hpp" #include "../lua_api/lua_api_common.hpp" namespace elona { namespace lua { /** * Userdata object used to validate the handle reference it was created from. * For example, when a skill reference is retrieved from a character, it can be * tested for validity by comparing the UUID of the reference to that of the * handle corresponding to the index on the reference. If they don't match, then * the handle is out of date and any method calls on the reference can be safely * ignored. */ struct LuaRef { LuaRef() : index(-1) , type("") , uuid("") { } LuaRef(int index, std::string type, std::string uuid) : index(index) , type(type) , uuid(uuid) { } bool is_valid() { if (index == -1) { return false; } auto handle = lua::lua->get_handle_manager().get_handle(index, type); if (handle == sol::lua_nil) { return false; } std::string handle_uuid = handle["__uuid"]; return handle_uuid == uuid; } int index; std::string type; std::string uuid; }; /** * @luadoc * * A reference to a skill on a LuaCharacter. */ struct LuaAbility : LuaRef { LuaAbility(int skill_id_, int index, std::string type, std::string uuid) : LuaRef(index, type, uuid) { skill_id = skill_id_; } static void bind(sol::state& lua); int skill_id; }; } // namespace lua } // namespace elona
19.858974
80
0.59264
XrosFade
20b12d09a36904ae0f619da353d14a646edaaf65
1,148
cpp
C++
Source/TsuRuntime/Private/TsuStringConv.cpp
mihe/tsu
5656ace9cb631b1ec60346b833e9233ded78e2c1
[ "Apache-2.0" ]
72
2019-03-25T18:01:55.000Z
2022-01-24T05:22:51.000Z
Source/TsuRuntime/Private/TsuStringConv.cpp
shakirullah7892/tsu
5656ace9cb631b1ec60346b833e9233ded78e2c1
[ "Apache-2.0" ]
39
2019-03-25T19:03:13.000Z
2019-05-12T10:17:41.000Z
Source/TsuRuntime/Private/TsuStringConv.cpp
shakirullah7892/tsu
5656ace9cb631b1ec60346b833e9233ded78e2c1
[ "Apache-2.0" ]
9
2019-04-30T03:08:32.000Z
2022-03-13T03:13:36.000Z
#include "TsuStringConv.h" #include "TsuIsolate.h" v8::Local<v8::String> FTsuStringConv::To(const FString& String) { return To(*String, String.Len()); } v8::Local<v8::String> FTsuStringConv::To(const TCHAR* String, int32 Length) { static_assert(sizeof(TCHAR) == sizeof(uint16_t), "Character size mismatch"); return v8::String::NewFromTwoByte( FTsuIsolate::Get(), reinterpret_cast<const uint16_t*>(String), v8::NewStringType::kNormal, Length ).ToLocalChecked(); } FString FTsuStringConv::From(v8::Local<v8::String> String) { static_assert(sizeof(uint16_t) == sizeof(TCHAR), "Character size mismatch"); v8::Isolate* Isolate = FTsuIsolate::Get(); v8::String::Value StringValue{Isolate, String}; auto Length = (int32)StringValue.length(); auto Ptr = reinterpret_cast<const TCHAR*>(*StringValue); return FString(Length, Ptr); } v8::Local<v8::String> operator""_v8(const char16_t* StringPtr, size_t StringLen) { return v8::String::NewFromTwoByte( FTsuIsolate::Get(), reinterpret_cast<const uint16_t*>(StringPtr), v8::NewStringType::kNormal, (int)StringLen ).ToLocalChecked(); }
27.333333
81
0.703833
mihe
20b965c2043d66777ca93e6a534fbce6b42eb1ef
1,552
cpp
C++
Recursion and Backtracking/palindromicPemutations.cpp
Ankitlenka26/IP2021
99322c9c84a8a9c9178a505afbffdcebd312b059
[ "MIT" ]
null
null
null
Recursion and Backtracking/palindromicPemutations.cpp
Ankitlenka26/IP2021
99322c9c84a8a9c9178a505afbffdcebd312b059
[ "MIT" ]
null
null
null
Recursion and Backtracking/palindromicPemutations.cpp
Ankitlenka26/IP2021
99322c9c84a8a9c9178a505afbffdcebd312b059
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <map> using namespace std; void palindromicPerm(int i, int n, map<char, int> &freqm, char oddc, string asf) { // base case if (i > n) { string res = asf; if (oddc != '0') { res += oddc; } reverse(asf.begin(), asf.end()); res += asf; cout << res << endl; return; } // we will go to those elements whose freq is more than one for (auto it : freqm) { char currch = it.first; int freq = it.second; if (freq > 0) { freqm[currch]--; palindromicPerm(i + 1, n, freqm, oddc, asf + currch); freqm[currch]++; } } return; } int main() { string s; cin >> s; map<char, int> freqm; for (int i = 0; i < s.size(); i++) { freqm[s[i]]++; } char oddc = '0'; // odd char that is present; int odds = 0; // no of char with odd freq; int len = 0; // length of the half string for (auto it : freqm) { if (it.second % 2 == 1) { // odd char oddc = it.first; odds++; } freqm[it.first] = (it.second) / 2; len += freqm[it.first]; } // for(auto it : freqm){ // cout << it.first << " " << it.second; // } if (odds > 1) { cout << -1 << endl; } else { palindromicPerm(1, len, freqm, oddc, ""); } return 0; }
20.155844
80
0.449742
Ankitlenka26