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
adda7cd4ba0b6c9524cbd404bda33be23d56c6c8
569
cpp
C++
CPP/ch07/fun_ptr.cpp
jerryhanjj/cpp
3efc23951f8a97d18516e8dbd911b3d2547899bd
[ "BSD-3-Clause" ]
null
null
null
CPP/ch07/fun_ptr.cpp
jerryhanjj/cpp
3efc23951f8a97d18516e8dbd911b3d2547899bd
[ "BSD-3-Clause" ]
null
null
null
CPP/ch07/fun_ptr.cpp
jerryhanjj/cpp
3efc23951f8a97d18516e8dbd911b3d2547899bd
[ "BSD-3-Clause" ]
null
null
null
// fun_ptr.cpp -- pointers to functions #include <iostream> using namespace std; double betsy(int lns) { return 0.05*lns; } double pam(int lns) { return 0.03*lns + 0.004*lns*lns; } void estimate(int lines, double(*pf)(int)) { cout << lines << " lines will take.\n"; cout << (*pf)(lines) << " hours\n"; } int main() { int code; cout << "How many lines of code do you need? "; cin >> code; cout << "Here's Betsy's estimate:\n"; estimate(code, betsy); cout << "Here's Pam's estimate:\n"; estimate(code, pam); return 0; }
18.354839
51
0.588752
jerryhanjj
addd99c020d0467a20e10392498f1d3aa0c505c3
1,040
cpp
C++
CBallMove.cpp
CongYun2022/Lux
c47526c5b80b83ce5518164158f3702fa765bf9a
[ "MIT" ]
1
2022-03-31T03:23:06.000Z
2022-03-31T03:23:06.000Z
CBallMove.cpp
CongYun2022/Lux
c47526c5b80b83ce5518164158f3702fa765bf9a
[ "MIT" ]
null
null
null
CBallMove.cpp
CongYun2022/Lux
c47526c5b80b83ce5518164158f3702fa765bf9a
[ "MIT" ]
null
null
null
#include "CBallMove.h" #include "AActor.h" #include "Game.h" #include "SPhys.h" #include "ATarget.h" #include "ABall.h" CBallMove::CBallMove(AActor* owner) :CMove(owner) { } void CBallMove::Update(float deltaTime) { // Construct segment in direction of travel const float segmentLength = 30.0f; Vector3 start = mOwner->GetPosition(); Vector3 dir = mOwner->GetForward(); Vector3 end = start + dir * segmentLength; // Create line segment LineSegment l(start, end); // Test segment vs world SPhys* phys = mOwner->GetGame()->GetPhysWorld(); SPhys::CollisionInfo info; // (Don't collide vs player) if (phys->SegmentCast(l, info) && info.mActor != mPlayer) { // If we collided, reflect the ball about the normal dir = Vector3::Reflect(dir, info.mNormal); mOwner->RotateToNewForward(dir); // Did we hit a target? ATarget* target = dynamic_cast<ATarget*>(info.mActor); if (target) { static_cast<ABall*>(mOwner)->HitTarget(); } } // Base class update moves based on forward speed CMove::Update(deltaTime); }
23.636364
58
0.698077
CongYun2022
ade034b80ff7c8600becddcf94f66fb44c9ac63a
211
cpp
C++
ZER0/001.cpp
applevinc/Project-Euler
2755a00df43e65b99b964587e29621cc8ebcc50a
[ "MIT" ]
null
null
null
ZER0/001.cpp
applevinc/Project-Euler
2755a00df43e65b99b964587e29621cc8ebcc50a
[ "MIT" ]
null
null
null
ZER0/001.cpp
applevinc/Project-Euler
2755a00df43e65b99b964587e29621cc8ebcc50a
[ "MIT" ]
1
2021-03-17T07:19:55.000Z
2021-03-17T07:19:55.000Z
#include <iostream> using namespace std; int main() { int max = 1000; int sum = 0; for(int i = 1; i < max; ++i) { if((i % 3 == 0) || (i % 5 == 0)) { sum += i; } } cout << sum << endl; // 233168 }
13.1875
36
0.464455
applevinc
ade3e324f2c80185851a9218ee64532498dd4622
16,643
cpp
C++
src/GCNDenoiser/GCNDenoiser/PatchData.cpp
ZJUGAPS-YYGroup/GCN-Denoiser
5d3ee62fdbf8bf56f5399c1717d4d7176924f809
[ "MIT" ]
15
2021-08-15T13:13:26.000Z
2022-03-22T13:02:46.000Z
src/GCNDenoiser/GCNDenoiser/PatchData.cpp
ZJUGAPS-YYGroup/GCN-Denoiser
5d3ee62fdbf8bf56f5399c1717d4d7176924f809
[ "MIT" ]
1
2021-10-20T02:34:58.000Z
2021-10-20T02:34:58.000Z
src/GCNDenoiser/GCNDenoiser/PatchData.cpp
ZJUGAPS-YYGroup/GCN-Denoiser
5d3ee62fdbf8bf56f5399c1717d4d7176924f809
[ "MIT" ]
4
2021-08-06T01:37:56.000Z
2022-01-20T06:54:58.000Z
#include "PatchData.h" #include <Eigen/Core> #include <Eigen/Eigenvalues> #include <set> PatchData::PatchData(TriMesh &mesh, std::vector<std::vector<TriMesh::FaceHandle>> &all_face_neighbor, std::vector<double> &face_area, std::vector<TriMesh::Point> &face_centroid, TriMesh::FaceIter &iter_face, shen::Geometry::EasyFlann &kd_tree, glm::dvec3& gt_normal, int num_ring, int radius) { std::vector<std::vector<TriMesh::FaceHandle>> face_neighbor_ring(num_ring + 1); std::vector<std::vector<bool>> flag(num_ring + 1, std::vector<bool>(mesh.n_faces(), false)); face_neighbor_ring[0].push_back(*iter_face); if (num_ring >= 1) { face_neighbor_ring[1] = all_face_neighbor[iter_face->idx()]; } flag[0][iter_face->idx()] = true; if (num_ring >= 1) { for (int i = 0; i < (int)face_neighbor_ring[1].size(); i++) { flag[1][face_neighbor_ring[1][i].idx()] = true; } } for (int ring = 1; ring < num_ring; ring++) { for (int i = 0; i < (int)face_neighbor_ring[ring].size(); i++) { std::vector<TriMesh::FaceHandle> temp_neighbor = all_face_neighbor[face_neighbor_ring[ring][i].idx()]; for (int t = 0; t < (int)temp_neighbor.size(); t++) { if ((!flag[ring - 1][temp_neighbor[t].idx()]) && (!flag[ring][temp_neighbor[t].idx()]) && (!flag[ring + 1][temp_neighbor[t].idx()])) { face_neighbor_ring[ring + 1].push_back(temp_neighbor[t]); flag[ring + 1][temp_neighbor[t].idx()] = true; } } } } // for center point position TriMesh::Point centroidc = face_centroid[iter_face->idx()]; double areac = face_area[iter_face->idx()]; glm::dvec4 center_face_centorid(areac, centroidc[0], centroidc[1], centroidc[2]); m_patch_faces_centers.push_back(center_face_centorid); glm::dvec3 normalc(mesh.normal(*iter_face)[0], mesh.normal(*iter_face)[1], mesh.normal(*iter_face)[2]); m_patch_faces_normals.push_back(normalc); for (TriMesh::FaceVertexIter fv_it = mesh.fv_iter(*iter_face); fv_it.is_valid(); fv_it++) { glm::dvec3 positionc(mesh.point(*fv_it)[0], mesh.point(*fv_it)[1], mesh.point(*fv_it)[2]); m_patch_points_positions.push_back(positionc); } int num_faces = 1; for (int ring = 1; ring <= num_ring; ring++) { for (int i = 0; i < (int)face_neighbor_ring[ring].size(); i++) { TriMesh::Point centroid = face_centroid[face_neighbor_ring[ring][i].idx()]; glm::dvec4 neighbor_faces_centorid(areac, centroid[0], centroid[1], centroid[2]); // for kinect fussion calculate the mean area of 2-ring neighbors // glm::dvec4 neighbor_faces_centorid(face_area[face_neighbor_ring[ring][i].idx()], centroid[0], centroid[1], centroid[2]); m_patch_faces_centers.push_back(neighbor_faces_centorid); glm::dvec3 normal(mesh.normal(face_neighbor_ring[ring][i])[0], mesh.normal(face_neighbor_ring[ring][i])[1], mesh.normal(face_neighbor_ring[ring][i])[2]); m_patch_faces_normals.push_back(normal); for (TriMesh::FaceVertexIter fv_it = mesh.fv_iter(face_neighbor_ring[ring][i]); fv_it.is_valid(); fv_it++) { glm::dvec3 position(mesh.point(*fv_it)[0], mesh.point(*fv_it)[1], mesh.point(*fv_it)[2]); m_patch_points_positions.push_back(position); } num_faces++; } } m_patch_num_faces = num_faces; // no face-face neighbors if (m_patch_num_faces == 1) { return; } m_radius_region = sqrt(areac * double(radius)); //// for kinect fussion calculate the mean area of 2-ring neighbors //double ring_2_mean_area = areac; //double ring_2_sum_area = 0; //for (int i_ring_area = 0; i_ring_area < m_patch_num_faces; i_ring_area++) //{ // ring_2_sum_area += m_patch_faces_centers[i_ring_area][0]; //} //ring_2_mean_area = ring_2_sum_area / double(m_patch_num_faces); //m_radius_region = sqrt(ring_2_mean_area * double(radius)); glm::vec3 query_point(m_patch_faces_centers[0][1], m_patch_faces_centers[0][2], m_patch_faces_centers[0][3]); std::vector<float> points_distances; std::vector<int> points_indices; kd_tree.radiusSearchNoLimit(query_point, points_distances, points_indices, m_radius_region * m_radius_region); int num_region_points = points_indices.size(); std::vector<TriMesh::VertexIter> vertex_iters; for (int i = 0; i < num_region_points; i++) { TriMesh::VertexIter temp_iter = mesh.vertices_begin(); for (int i_iter = 0; i_iter < points_indices[i]; i_iter++) { temp_iter++; } vertex_iters.push_back(temp_iter); } points_indices.clear(); points_distances.clear(); std::set<int> face_indices_set; // faces in the fixed region std::vector<int> face_indices; std::vector<TriMesh::VertexFaceIter> patch_faces_iter; for (int i = 0; i < num_region_points; i++) { for (TriMesh::VertexFaceIter vf_it = mesh.vf_iter(vertex_iters[i]); vf_it.is_valid(); vf_it++) { if (face_indices_set.find(vf_it->idx()) == face_indices_set.end()) { face_indices_set.insert(vf_it->idx()); face_indices.push_back(vf_it->idx()); patch_faces_iter.push_back(vf_it); if (vf_it->idx() == iter_face->idx()) { m_center_index = face_indices.size() - 1; } glm::dvec3 normal(mesh.normal(*vf_it)[0], mesh.normal(*vf_it)[1], mesh.normal(*vf_it)[2]); m_aligned_patch_faces_normals.push_back(normal); for (TriMesh::FaceVertexIter fv_it = mesh.fv_iter(vf_it); fv_it.is_valid(); fv_it++) { glm::dvec3 position(mesh.point(*fv_it)[0], mesh.point(*fv_it)[1], mesh.point(*fv_it)[2]); m_aligned_patch_points_positions.push_back(position); } m_aligned_patch_num_faces++; } } } /*std::cout << m_aligned_patch_num_faces << std::endl;*/ if (m_aligned_patch_num_faces <= 1) { // std::cout << m_aligned_patch_num_faces << std::endl; return; } // initialize the patch graph m_temp_graph_matrix = new unsigned char[m_aligned_patch_num_faces * m_aligned_patch_num_faces]; m_patch_graph_matrix = new unsigned char[m_aligned_patch_num_faces * m_aligned_patch_num_faces]; m_temp_network_input = new double[m_aligned_patch_num_faces * (17 + 3)]; m_patch_node_features = new double[m_aligned_patch_num_faces * 17]; // 17 kinds of features, face center(3), face normal (3), area(1), num of neighbors(1), points position (9), m_matrix_indices = new int[m_aligned_patch_num_faces]; for (int i = 0; i < m_aligned_patch_num_faces * m_aligned_patch_num_faces; i++) { m_temp_graph_matrix[i] = 0; m_patch_graph_matrix[i] = 0; } for (int i_f = 0; i_f < m_aligned_patch_num_faces; i_f++) { int neighbor_count = 0; for (TriMesh::FaceFaceIter ff_it = mesh.ff_iter(patch_faces_iter[i_f]); ff_it.is_valid(); ff_it++) { int temp_neighbor_index = ff_it->idx(); for (int j_f = 0; j_f < m_aligned_patch_num_faces; j_f++) { if (temp_neighbor_index == face_indices[j_f]) { m_temp_graph_matrix[i_f * m_aligned_patch_num_faces + j_f] = 1; if (neighbor_count < 3) { if (j_f < 64) { m_temp_network_input[i_f * 20 + 17 + neighbor_count] = (double)j_f; } else { /*m_temp_network_input[i_f * 20 + 17 + neighbor_count] = 63.;*/ neighbor_count--; } } neighbor_count++; break; } } } // padding of neighbors if (neighbor_count == 2) { m_temp_network_input[i_f * 20 + 17 + 2] = m_temp_network_input[i_f * 20 + 17 + 1]; } else if (neighbor_count == 1) { m_temp_network_input[i_f * 20 + 17 + 1] = m_temp_network_input[i_f * 20 + 17 + 0]; m_temp_network_input[i_f * 20 + 17 + 2] = m_temp_network_input[i_f * 20 + 17 + 1]; } else if (neighbor_count == 0) { m_temp_network_input[i_f * 20 + 17 + 0] = (double)i_f; m_temp_network_input[i_f * 20 + 17 + 1] = (double)i_f; m_temp_network_input[i_f * 20 + 17 + 2] = (double)i_f; } // area m_patch_node_features[i_f * 17 + 6] = face_area[face_indices[i_f]]; // num of neighbors int num_neighbors = all_face_neighbor[face_indices[i_f]].size(); m_patch_node_features[i_f * 17 + 7] = ((((double)num_neighbors - 12.) / 6.) + 1.) / 2.; m_temp_network_input[i_f * 20 + 7] = m_patch_node_features[i_f * 17 + 7]; } vertex_iters.clear(); face_indices_set.clear(); patchAlignment(gt_normal); } PatchData::~PatchData() { m_patch_faces_centers.clear(); m_patch_points_positions.clear(); m_patch_faces_normals.clear(); m_aligned_patch_points_positions.clear(); m_aligned_patch_faces_normals.clear(); if (m_temp_graph_matrix != NULL) { delete m_temp_graph_matrix; delete m_patch_graph_matrix; delete m_patch_node_features; delete m_temp_network_input; delete m_matrix_indices; } } void PatchData::patchAlignment(glm::dvec3& gt_normal) { glm::dvec4 area_center = m_patch_faces_centers[0]; double area_max = 0; for (int i = 0; i < m_patch_num_faces; i++) { if (area_max < m_patch_faces_centers[i][0]) { area_max = m_patch_faces_centers[i][0]; } } // std::cout << " \tThe max area of the patch is: " << area_max << std::endl; Eigen::Matrix3d tensor_feature_mat; Eigen::Matrix3d temp_mat; tensor_feature_mat = Eigen::Matrix3d::Zero(); for (int i = 1; i < m_patch_num_faces; i++) { temp_mat = Eigen::Matrix3d::Zero(); glm::dvec3 temp_center(m_patch_faces_centers[i][1] - m_patch_faces_centers[0][1], m_patch_faces_centers[i][2] - m_patch_faces_centers[0][2], m_patch_faces_centers[i][3] - m_patch_faces_centers[0][3]); double temp_area = m_patch_faces_centers[i][0] / area_max; double temp_center_norm_para = exp(-3 * glm::length(temp_center)); glm::dvec3 temp_weight = glm::cross(glm::cross(temp_center, m_patch_faces_normals[i]), temp_center); temp_weight = glm::normalize(temp_weight); glm::dvec3 temp_normal = 2. * glm::dot(m_patch_faces_normals[i], temp_weight) * temp_weight - m_patch_faces_normals[i]; for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) { temp_mat(r, c) = temp_normal[r] * temp_normal[c]; } } temp_mat *= temp_area * temp_center_norm_para; // temp_mat *= temp_center_norm_para; tensor_feature_mat += temp_mat; } Eigen::EigenSolver<Eigen::Matrix3d> eigen_solver(tensor_feature_mat); double max_eigen_value = eigen_solver.eigenvalues()[0].real(); double min_eigen_value = eigen_solver.eigenvalues()[0].real(); int max_ev_idx = 0; int min_ev_idx = 0; for (int i = 0; i < 3; i++) { if (max_eigen_value < eigen_solver.eigenvalues()[i].real()) { max_eigen_value = eigen_solver.eigenvalues()[i].real(); max_ev_idx = i; } if (min_eigen_value > eigen_solver.eigenvalues()[i].real()) { min_eigen_value = eigen_solver.eigenvalues()[i].real(); min_ev_idx = i; } } int middle_ev_idx = 3 - max_ev_idx - min_ev_idx; // only one face if (middle_ev_idx < 0 || middle_ev_idx > 2) { min_ev_idx = 0; middle_ev_idx = 1; max_ev_idx = 2; /*std::cout << "!!!____Sort ERROR____!!!" << std::endl; exit(0);*/ } glm::dvec3 sorted_eigen_value(eigen_solver.eigenvalues()[max_ev_idx].real(), eigen_solver.eigenvalues()[middle_ev_idx].real(), eigen_solver.eigenvalues()[min_ev_idx].real()); glm::dvec3 max_eigen_vec(eigen_solver.eigenvectors().col(max_ev_idx).row(0).value().real(), eigen_solver.eigenvectors().col(max_ev_idx).row(1).value().real(), eigen_solver.eigenvectors().col(max_ev_idx).row(2).value().real()); glm::dvec3 middel_eigen_vec(eigen_solver.eigenvectors().col(middle_ev_idx).row(0).value().real(), eigen_solver.eigenvectors().col(middle_ev_idx).row(1).value().real(), eigen_solver.eigenvectors().col(middle_ev_idx).row(2).value().real()); glm::dvec3 min_eigen_vec(eigen_solver.eigenvectors().col(min_ev_idx).row(0).value().real(), eigen_solver.eigenvectors().col(min_ev_idx).row(1).value().real(), eigen_solver.eigenvectors().col(min_ev_idx).row(2).value().real()); glm::dmat3x3 sorted_eigen_vec(max_eigen_vec, middel_eigen_vec, min_eigen_vec); if (sorted_eigen_vec[0][0] * m_patch_faces_normals[0][0] + sorted_eigen_vec[0][1] * m_patch_faces_normals[0][1] + sorted_eigen_vec[0][2] * m_patch_faces_normals[0][2] < 0.) { sorted_eigen_vec[0] *= -1.; sorted_eigen_vec[1] *= -1.; sorted_eigen_vec[2] *= -1.; } m_matrix = sorted_eigen_vec; sorted_eigen_value = sorted_eigen_value / sqrt(pow(sorted_eigen_value[0], 2) + pow(sorted_eigen_value[1], 2) + pow(sorted_eigen_value[2], 2)); // std::cout << sorted_eigen_value[0] << " " << sorted_eigen_value[1] << " " << sorted_eigen_value[2] << std::endl; // for normal base change glm::dmat3x3 inversed_sorted_vec = glm::inverse(sorted_eigen_vec); /* std::cout << inversed_sorted_vec[0][0] << " " << inversed_sorted_vec[1][0] << " " << inversed_sorted_vec[2][0] << std::endl << inversed_sorted_vec[0][1] << " " << inversed_sorted_vec[1][1] << " " << inversed_sorted_vec[2][1] << std::endl << inversed_sorted_vec[0][2] << " " << inversed_sorted_vec[1][2] << " " << inversed_sorted_vec[2][2] << std::endl;*/ for (int i = 0; i < m_aligned_patch_num_faces; i++) { m_aligned_patch_faces_normals[i] = inversed_sorted_vec * m_aligned_patch_faces_normals[i]; } gt_normal = inversed_sorted_vec * gt_normal; // for position base change glm::dmat4x4 trans_mat(0); for (int i = 0; i < 4; i++) { trans_mat[i][i] = 1; if (i < 3) { trans_mat[3][i] = -1 * m_patch_faces_centers[0][i + 1]; } } glm::dmat4x4 rot_mat(0); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i < 3 && j < 3) { rot_mat[i][j] = inversed_sorted_vec[i][j]; } } } rot_mat[3][3] = 1.; double determinant = glm::determinant(inversed_sorted_vec); double coord_max = 0.; std::vector<glm::dvec3> temp_positions; for (int i_face = 0; i_face < m_aligned_patch_num_faces; i_face++) { for (int i_vertex = 0; i_vertex < 3; i_vertex++) { glm::dvec4 temp_position; if (determinant < 0) { temp_position = glm::dvec4(m_aligned_patch_points_positions[i_face * 3 + 2 - i_vertex][0], m_aligned_patch_points_positions[i_face * 3 + 2 - i_vertex][1], m_aligned_patch_points_positions[i_face * 3 + 2 - i_vertex][2], 1.); } else if (determinant > 0) { temp_position = glm::dvec4(m_aligned_patch_points_positions[i_face * 3 + i_vertex][0], m_aligned_patch_points_positions[i_face * 3 + i_vertex][1], m_aligned_patch_points_positions[i_face * 3 + i_vertex][2], 1.); } else { /* std::cout << "!!!____Transform matrix Error, Not positive definite matrix____!!!" << std::endl; exit(0);*/ temp_position = glm::dvec4(m_aligned_patch_points_positions[i_face * 3 + i_vertex][0], m_aligned_patch_points_positions[i_face * 3 + i_vertex][1], m_aligned_patch_points_positions[i_face * 3 + i_vertex][2], 1.); } temp_position = trans_mat * temp_position; temp_position = rot_mat * temp_position; for (int i_v = 0; i_v < 3; i_v++) { if (coord_max < abs(temp_position[i_v])) { coord_max = abs(temp_position[i_v]); } } temp_positions.push_back(glm::dvec3(temp_position[0], temp_position[1], temp_position[2])); } } for (int i_v = 0; i_v < m_aligned_patch_num_faces * 3; i_v++) { m_aligned_patch_points_positions[i_v] = temp_positions[i_v] / m_radius_region; } for (int i_f = 0; i_f < m_aligned_patch_num_faces; i_f++) { m_patch_node_features[i_f * 17 + 6] /= m_radius_region * m_radius_region; m_temp_network_input[i_f * 20 + 6] = m_patch_node_features[i_f * 17 + 6]; // face center and normal for (int i_v = 0; i_v < 3; i_v++) { m_patch_node_features[i_f * 17 + i_v] = ((m_aligned_patch_points_positions[i_f * 3][i_v] + m_aligned_patch_points_positions[i_f * 3 + 1][i_v] + m_aligned_patch_points_positions[i_f * 3 + 2][i_v]) / 3 + 1) / 2.; m_temp_network_input[i_f * 20 + i_v] = m_patch_node_features[i_f * 17 + i_v]; m_patch_node_features[i_f * 17 + i_v + 3] = (m_aligned_patch_faces_normals[i_f][i_v] + 1) / 2.; m_temp_network_input[i_f * 20 + i_v + 3] = m_patch_node_features[i_f * 17 + i_v + 3]; } // face vertices for (int i_p = 0; i_p < 3; i_p++) { m_patch_node_features[i_f * 17 + i_p * 3 + 8] = (m_aligned_patch_points_positions[i_f * 3][0] + 1) / 2.; m_patch_node_features[i_f * 17 + i_p * 3 + 8 + 1] = (m_aligned_patch_points_positions[i_f * 3][1] + 1) / 2.; m_patch_node_features[i_f * 17 + i_p * 3 + 8 + 2] = (m_aligned_patch_points_positions[i_f * 3][2] + 1) / 2.; m_temp_network_input[i_f * 20 + i_p * 3 + 8] = m_patch_node_features[i_f * 17 + i_p * 3 + 8]; m_temp_network_input[i_f * 20 + i_p * 3 + 8 + 1] = m_patch_node_features[i_f * 17 + i_p * 3 + 8 + 1]; m_temp_network_input[i_f * 20 + i_p * 3 + 8 + 2] = m_patch_node_features[i_f * 17 + i_p * 3 + 8 + 2]; } } m_center_normal = glm::dvec3(0., 0., 0.); for (int i_n = 0; i_n < 3; i_n++) { m_center_normal[i_n] = m_aligned_patch_faces_normals[m_center_index][i_n]; } }
34.890985
178
0.681007
ZJUGAPS-YYGroup
ade6dcdc8a8b9adff82ce67fe2723e0ea74b4918
8,073
cpp
C++
src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/filter/SRiteratedextendedkalmanfilter.cpp
alexoterno/turtlebot2_with_head
ac714f77379dd0f47ddb76d83896fdabee269a03
[ "MIT" ]
null
null
null
src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/filter/SRiteratedextendedkalmanfilter.cpp
alexoterno/turtlebot2_with_head
ac714f77379dd0f47ddb76d83896fdabee269a03
[ "MIT" ]
null
null
null
src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/filter/SRiteratedextendedkalmanfilter.cpp
alexoterno/turtlebot2_with_head
ac714f77379dd0f47ddb76d83896fdabee269a03
[ "MIT" ]
null
null
null
// $Id$ // Copyright (C) 2003 Klaas Gadeyne <first dot last at gmail dot com> // Peter Slaets <peter dot slaets at mech dot kuleuven dot ac dot be> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "SRiteratedextendedkalmanfilter.h" #include "../model/linearanalyticmeasurementmodel_gaussianuncertainty_implicit.h" namespace BFL { using namespace MatrixWrapper; #define AnalyticSys AnalyticSystemModelGaussianUncertainty #define LinearAnalyticMeas_Implicit LinearAnalyticMeasurementModelGaussianUncertainty_Implicit #define Numerical_Limitation 100*100 SRIteratedExtendedKalmanFilter::SRIteratedExtendedKalmanFilter(Gaussian* prior, unsigned int nr_it) : KalmanFilter(prior), nr_iterations(nr_it), JP(prior->CovarianceGet().rows(),prior->CovarianceGet().rows()) { (prior->CovarianceGet()).cholesky_semidefinite(JP); } SRIteratedExtendedKalmanFilter::~SRIteratedExtendedKalmanFilter(){} void SRIteratedExtendedKalmanFilter::SysUpdate(SystemModel<MatrixWrapper::ColumnVector>* const sysmodel,const MatrixWrapper::ColumnVector& u) { MatrixWrapper::ColumnVector x = _post->ExpectedValueGet(); MatrixWrapper::ColumnVector J = ((AnalyticSys*)sysmodel)->PredictionGet(u,x); MatrixWrapper::Matrix F = ((AnalyticSys*)sysmodel)->df_dxGet(u,x); MatrixWrapper::SymmetricMatrix Q = ((AnalyticSys*)sysmodel)->CovarianceGet(u,x); // cout<<"JP1\n"<<JP<<endl; CalculateSysUpdate(J, F, Q); // cout<<"JP2\n"<<JP<<endl; // cout<<"post_covar\n"<<_post->CovarianceGet()<<endl; ((_post->CovarianceGet()).cholesky_semidefinite(JP)); JP = JP.transpose(); // cout<<"JP3\n"<<JP<<endl; } void SRIteratedExtendedKalmanFilter::SysUpdate(SystemModel<MatrixWrapper::ColumnVector>* const sysmodel) { MatrixWrapper::ColumnVector u(0); SysUpdate(sysmodel, u); } void SRIteratedExtendedKalmanFilter::MeasUpdate(MeasurementModel<MatrixWrapper::ColumnVector,MatrixWrapper::ColumnVector>* const measmodel,const MatrixWrapper::ColumnVector& z,const MatrixWrapper::ColumnVector& s) { MatrixWrapper::Matrix invS(z.rows(),z.rows()); MatrixWrapper::Matrix Sr(z.rows(),z.rows()); MatrixWrapper::Matrix K_i(_post->CovarianceGet().rows(),z.rows()); MatrixWrapper::ColumnVector x_k = _post->ExpectedValueGet(); MatrixWrapper::SymmetricMatrix P_k = _post->CovarianceGet(); MatrixWrapper::ColumnVector x_i = _post->ExpectedValueGet(); MatrixWrapper::Matrix H_i; MatrixWrapper::SymmetricMatrix R_i; MatrixWrapper::Matrix R_vf; MatrixWrapper::Matrix SR_vf; MatrixWrapper::ColumnVector Z_i; MatrixWrapper::Matrix U; MatrixWrapper::ColumnVector V; MatrixWrapper::Matrix W; MatrixWrapper::Matrix JP1; int change; Matrix diag(JP.rows(),JP.columns()); Matrix invdiag(JP.rows(),JP.columns()); diag=0;invdiag=0;change=0; V=0;U=0;W=0; // matrix determining the numerical limitations of covariance matrix: for(unsigned int j=1;j<JP.rows()+1;j++){diag(j,j)=100; invdiag(j,j)=0.01;} for (unsigned int i=1; i<nr_iterations+1; i++) { x_i = _post->ExpectedValueGet(); H_i = ((LinearAnalyticMeas_Implicit*)measmodel)->df_dxGet(s,x_i); Z_i = ((LinearAnalyticMeas_Implicit*)measmodel)->ExpectedValueGet() + ( H_i * (x_k - x_i) ); R_i = ((LinearAnalyticMeas_Implicit*)measmodel)->CovarianceGet(); SR_vf = ((LinearAnalyticMeas_Implicit*)measmodel)->SRCovariance(); // check two different types of Kalman filters: if(((LinearAnalyticMeas_Implicit*)measmodel)->Is_Identity()==1) { R_vf = SR_vf.transpose(); } else { R_i.cholesky_semidefinite(R_vf); R_vf = R_vf.transpose(); } // numerical limitations // The singular values of the Square root covariance matrix are limited the the value of 10e-4 // because of numerical stabilisation of the Kalman filter algorithm. JP.SVD(V,U,W); MatrixWrapper::Matrix V_matrix(U.columns(),W.columns()); for(unsigned int k=1;k<JP.rows()+1;k++) { V_matrix(k,k) = V(k); V(k)=max(V(k),1.0/(Numerical_Limitation)); if(V(k)==1/(Numerical_Limitation)){change=1;} } if(change==1) { JP = U*V_matrix*(W.transpose()); } // end limitations CalculateMatrix(H_i, R_i , invS , K_i , Sr ); CalculateMean(x_k, z, Z_i , K_i); if (i==nr_iterations) { CalculateCovariance( R_vf, H_i, invS, Sr ); } } } void SRIteratedExtendedKalmanFilter::MeasUpdate(MeasurementModel<ColumnVector,ColumnVector>* const measmodel, const ColumnVector& z) { ColumnVector s(0); MeasUpdate(measmodel, z, s); } Matrix SRIteratedExtendedKalmanFilter::SRCovarianceGet() const { return (Matrix) JP; } void SRIteratedExtendedKalmanFilter::SRCovarianceSet(Matrix JP_new) { JP=JP_new; } void SRIteratedExtendedKalmanFilter::PriorSet(ColumnVector& X_prior,SymmetricMatrix& P_prior) { PostMuSet( X_prior ); PostSigmaSet( P_prior ); } void SRIteratedExtendedKalmanFilter::CalculateMeasUpdate(ColumnVector z, ColumnVector Z, Matrix H, SymmetricMatrix R) { // build K matrix Matrix S = ( H * (Matrix)(_post->CovarianceGet()) * (H.transpose()) ) + (Matrix)R; Matrix K = (Matrix)(_post->CovarianceGet()) * (H.transpose()) * (S.inverse()); // calcutate new state gaussian ColumnVector Mu_new = ( _post->ExpectedValueGet() + K * (z - Z) ); Matrix Sigma_new_matrix = (Matrix)(_post->CovarianceGet()) - K * H * (Matrix)(_post->CovarianceGet()); // convert to symmetric matrix SymmetricMatrix Sigma_new(_post->DimensionGet()); Sigma_new_matrix.convertToSymmetricMatrix(Sigma_new); // set new state gaussian PostMuSet ( Mu_new ); PostSigmaSet( Sigma_new ); } void SRIteratedExtendedKalmanFilter::CalculateMatrix(Matrix& H_i, SymmetricMatrix& R_i, Matrix& invS, Matrix& K_i, Matrix& Sr) { MatrixWrapper::Matrix S_i1,S_i2,S_temp1; MatrixWrapper::SymmetricMatrix S_temp2,S_temp; S_i1 = ( H_i * (Matrix)JP * (Matrix) (JP.transpose())* (H_i.transpose()) ); S_i2 = (Matrix) R_i; S_temp1 = (S_i1 + S_i2).transpose(); S_temp1.convertToSymmetricMatrix(S_temp); S_temp.cholesky_semidefinite(Sr); Sr = Sr.transpose(); invS = Sr.inverse(); K_i = JP*(JP.transpose())*(H_i.transpose())*(invS.transpose())*invS; /* cout<<"H_i\n"<<H_i<<endl; cout<<"JP\n"<<JP<<endl; cout<<"S_i1\n"<<S_i1<<endl; cout<<"S_i1\n"<<S_i1<<endl; cout<<"S_i2\n"<<S_i2<<endl; cout<<"K_i\n"<<K_i<<endl; */ } void SRIteratedExtendedKalmanFilter::CalculateMean(ColumnVector& x_k, const ColumnVector& z, ColumnVector& Z_i ,Matrix& K_i) { MatrixWrapper::ColumnVector x_i; x_i = x_k + K_i * (z - Z_i); PostMuSet( x_i ); } void SRIteratedExtendedKalmanFilter::CalculateCovariance(Matrix& R_vf, Matrix& H_i, Matrix& invS ,Matrix& Sr) { MatrixWrapper::Matrix temp; temp = (Matrix)R_vf+(Matrix)Sr; JP = (Matrix)JP -(Matrix)JP*(Matrix)(JP.transpose()) * (H_i.transpose()) * (Matrix)(invS.transpose())*(Matrix)(temp.inverse())*H_i*(Matrix)JP; MatrixWrapper::SymmetricMatrix Sigma; MatrixWrapper::Matrix Sigma1; Sigma1=(JP*(JP.transpose())).transpose(); Sigma1.convertToSymmetricMatrix(Sigma); PostSigmaSet(Sigma); } }
34.648069
210
0.689954
alexoterno
ade7bc572d3c09f6e5a9747e8496e662b92b87ff
809
cpp
C++
codes/Leetcode/leetcode151.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode151.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode151.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
class Solution { public: string reverseWords(string s) { string ans; int r = -1; bool first = true; for (int i = s.size() - 1; i >= 0; --i) { if (s[i] != ' ') { if (r != -1) { continue; } else { r = i; } } else { if (r != -1) { if (!first) { ans += ' '; } ans += s.substr(i + 1, r - i); r = -1; first = false; } } } if (r != -1) { if (!first) { ans += ' '; } ans += s.substr(0, r + 1); } return ans; } };
23.794118
50
0.233622
JeraKrs
ade9191978ed1d32e8f4f6dc32f5939eaaa99b16
260
cpp
C++
src/UnsignedVariable.cpp
andremmvgabriel/boolean_circuit_generator
21a36e04072b4ce388b22992d3ca35643b967fc9
[ "MIT" ]
1
2021-09-03T14:03:28.000Z
2021-09-03T14:03:28.000Z
src/UnsignedVariable.cpp
andremmvgabriel/boolean_circuit_generator
21a36e04072b4ce388b22992d3ca35643b967fc9
[ "MIT" ]
null
null
null
src/UnsignedVariable.cpp
andremmvgabriel/boolean_circuit_generator
21a36e04072b4ce388b22992d3ca35643b967fc9
[ "MIT" ]
null
null
null
#include <UnsignedVariable.hpp> gabe::circuits::UnsignedVariable::UnsignedVariable() : Variable() {} gabe::circuits::UnsignedVariable::UnsignedVariable(uint8_t number_bits) : Variable(number_bits) {} gabe::circuits::UnsignedVariable::~UnsignedVariable() {}
32.5
98
0.780769
andremmvgabriel
adedbef5f36d506a3ec8d3a81161210cbd91e21c
906
cpp
C++
AIC/AIC'20 - Level 1 Training Contests/Contest #6 (Online)/I.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AIC/AIC'20 - Level 1 Training Contests/Contest #6 (Online)/I.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AIC/AIC'20 - Level 1 Training Contests/Contest #6 (Online)/I.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://codeforces.com/group/aDFQm4ed6d/contest/274872/problem/I #include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; ll mod = 1e9 + 7; ll chk (string s, string w) { ll cnt = 0; for (ll i = 0; i < s.size (); ++i) { if (w[i] != s[i]) { ll x = w[i] - s[i]; if (x < 0) return -1; else cnt += x; } } return cnt; } int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); ll c = LLONG_MAX; string s, w, a; cin >> s >> w; if (w.size () > s.size ()) return cout << -1, 0; for (ll i = 0; i < s.size () - w.size () + 1; ++i) { string temp = s.substr (i, w.size ()); ll x = chk (temp, w); if (x != -1 && x < c) c = x, a = temp; } if (c == LLONG_MAX) cout << -1; else cout << a; }
22.097561
66
0.470199
MaGnsio
adedc64f5ab71d7857a6679c343c65325f95d598
3,750
cpp
C++
IDAArchitecture.cpp
fjqisba/E-Decompiler
f598c4205d8b9e4d29172dab0bb2672c75e48af9
[ "MIT" ]
74
2021-03-04T08:12:43.000Z
2022-03-14T13:50:20.000Z
IDAArchitecture.cpp
fjqisba/E-Decompiler
f598c4205d8b9e4d29172dab0bb2672c75e48af9
[ "MIT" ]
10
2021-03-05T09:52:10.000Z
2021-07-05T13:48:33.000Z
IDAArchitecture.cpp
fjqisba/E-Decompiler
f598c4205d8b9e4d29172dab0bb2672c75e48af9
[ "MIT" ]
15
2021-04-06T14:22:39.000Z
2022-03-29T13:14:47.000Z
#include "IDAArchitecture.h" #include "IDALoader.h" #include "IDATypeManager.h" #include "IDAScope.h" #include "EazyAction.h" IDAArchitecture::IDAArchitecture(const string& targ): SleighArchitecture("ida", targ, &m_err), m_ScanAction(Action::rule_onceperfunc, "ESCAN") { } IDAArchitecture::~IDAArchitecture() { SleighArchitecture::shutdown(); } void IDAArchitecture::addInjection(std::string functionName, std::string injection) { m_injectionMap.emplace(functionName, injection); } void IDAArchitecture::buildLoader(DocumentStorage& store) { collectSpecFiles(*errorstream); loader = new IDALoader(); } IDASymbol& IDAArchitecture::getSymbolDatabase() const { return *m_symbols.get(); } Scope* IDAArchitecture::buildDatabase(DocumentStorage& store) { symboltab = new Database(this, false); Scope* globscope = new IDAScope(0, this); symboltab->attachScope(globscope, nullptr); return globscope; } void IDAArchitecture::buildTypegrp(DocumentStorage& store) { types = new IDATypeManager(this); types->setCoreType("void", 1, TYPE_VOID, false); types->setCoreType("bool", 1, TYPE_BOOL, false); types->setCoreType("unsigned char", 1, TYPE_UINT, false); types->setCoreType("unsigned short", 2, TYPE_UINT, false); types->setCoreType("unsigned int", 4, TYPE_UINT, false); types->setCoreType("unsigned long long", 8, TYPE_UINT, false); types->setCoreType("char", 1, TYPE_INT, true); types->setCoreType("short", 2, TYPE_INT, false); types->setCoreType("int", 4, TYPE_INT, false); types->setCoreType("signed long long", 8, TYPE_INT, false); types->setCoreType("float", 4, TYPE_FLOAT, false); types->setCoreType("double", 8, TYPE_FLOAT, false); types->setCoreType("__uint8", 1, TYPE_UNKNOWN, false); types->setCoreType("__uint16", 2, TYPE_UNKNOWN, false); types->setCoreType("__uint32", 4, TYPE_UNKNOWN, false); types->setCoreType("__uint64", 8, TYPE_UNKNOWN, false); types->setCoreType("code", 1, TYPE_CODE, false); types->cacheCoreTypes(); } void IDAArchitecture::buildAction(DocumentStorage& store) { SleighArchitecture::buildAction(store); //m_ScanAction.addAction(new EActionScanKernel("eaction"),); } Translate* IDAArchitecture::buildTranslator(DocumentStorage& store) { m_translate = SleighArchitecture::buildTranslator(store); return m_translate; } int4 IDAArchitecture::performActions(Funcdata& data) { allacts.getCurrent()->reset(data); m_ScanAction.reset(data); allacts.getCurrent()->perform(data); auto res = m_ScanAction.perform(data); if (res < 0) { return res; } return res; } std::string IDAArchitecture::emitPCode(unsigned int startAddr, unsigned int endAddr) { PcodeRawOut emit; int length; Address addr(m_translate->getDefaultCodeSpace(), startAddr); Address lastaddr(m_translate->getDefaultCodeSpace(), endAddr); while (addr < lastaddr) { length = m_translate->oneInstruction(emit, addr); // Translate instruction addr = addr + length; } return emit.m_saveStr.str(); } static void print_vardata(ostream& s, VarnodeData& data) { s << '(' << data.space->getName() << ','; data.space->printOffset(s, data.offset); s << ',' << dec << data.size << ')'; } void PcodeRawOut::dump(const Address& addr, OpCode opc, VarnodeData* outvar, VarnodeData* vars, int4 isize) { m_saveStr << std::hex << "[" << addr.getOffset() << "]:"; if (outvar != (VarnodeData*)0) { print_vardata(m_saveStr, *outvar); m_saveStr << " = "; } m_saveStr << get_opname(opc); // Possibly check for a code reference or a space reference for (int4 i = 0; i < isize; ++i) { m_saveStr << ' '; print_vardata(m_saveStr, vars[i]); } m_saveStr << endl; }
27.573529
108
0.697067
fjqisba
adf7ad8f5d45cefc5eca2088a2d0c763e52f8531
511
cpp
C++
Examples/BCB/GlobalTestLibrary/Src/JsonVclUtils.cpp
alexzhornyak/UscxmlCLib
3f763db4f7b8061309593a97c238bf2801984a66
[ "BSD-3-Clause" ]
1
2020-04-05T19:21:08.000Z
2020-04-05T19:21:08.000Z
Examples/BCB/GlobalTestLibrary/Src/JsonVclUtils.cpp
alexzhornyak/UscxmlCLib
3f763db4f7b8061309593a97c238bf2801984a66
[ "BSD-3-Clause" ]
null
null
null
Examples/BCB/GlobalTestLibrary/Src/JsonVclUtils.cpp
alexzhornyak/UscxmlCLib
3f763db4f7b8061309593a97c238bf2801984a66
[ "BSD-3-Clause" ]
1
2021-04-13T16:04:42.000Z
2021-04-13T16:04:42.000Z
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "JsonVclUtils.h" #include <boost/regex.hpp> //--------------------------------------------------------------------------- #pragma package(smart_init) namespace Jsonutils { const UnicodeString JsonTrimSpaces(const UnicodeString &sJson) { boost::wregex regEx(L"(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+"); return boost::regex_replace(std::wstring(sJson.c_str()), regEx, L"$1").c_str(); } }
24.333333
81
0.457926
alexzhornyak
adf8519c529cbcbfd26024ff22c1e7aa5dca5b67
229
cpp
C++
Misc/[Siruri] Numarul maxim/main.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
7
2019-01-06T19:10:14.000Z
2021-10-16T06:41:23.000Z
Misc/[Siruri] Numarul maxim/main.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
null
null
null
Misc/[Siruri] Numarul maxim/main.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
6
2019-01-06T19:17:30.000Z
2020-02-12T22:29:17.000Z
#include <iostream> using namespace std; int main(){ int n, x, prec=0, maxim; cin>>n; for(int i=1; i<=n; i++){ cin>>x; prec=x; if(x>prec) maxim=x; } cout<<maxim; return 0; }
13.470588
28
0.467249
Al3x76
adfb38cf3bef51869e9be95a1a2836145971bcae
7,604
cpp
C++
src/ivorium_systems/ConfigFileSystem/ConfigFileSystem.cpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
3
2021-02-26T02:59:09.000Z
2022-02-08T16:44:21.000Z
src/ivorium_systems/ConfigFileSystem/ConfigFileSystem.cpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
src/ivorium_systems/ConfigFileSystem/ConfigFileSystem.cpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
#include "ConfigFileSystem.hpp" #include <fstream> namespace iv { //================================================================================ //--------------------- ConfigStream --------------------------------------------- ConfigStream::ConfigStream( Instance * inst, std::string const & name ) : cm( inst, this, "ConfigStream" ), inst( inst ), name( name ) { auto cfs = this->instance()->getSystem< ConfigFileSystem >(); if( cfs ) cfs->stream_add_listener( this, this->name ); } ConfigStream::~ConfigStream() { auto cfs = this->instance()->getSystem< ConfigFileSystem >(); if( cfs ) cfs->stream_remove_listener( this ); } Instance * ConfigStream::instance() const { return this->inst; } bool ConfigStream::stream_exists() { auto cfs = this->instance()->getSystem< ConfigFileSystem >(); if( cfs ) return cfs->stream_exists( this->name ); return false; } void ConfigStream::stream_read( std::function< void( std::istream & ) > const & f ) { auto cfs = this->instance()->getSystem< ConfigFileSystem >(); if( cfs ) { LambdaLogTrace _trace( [ this ]( std::ostream & out ) { out << "Configuration '"<< this->name <<"'" << std::endl; } ); cfs->stream_read( this->name, f ); } } void ConfigStream::stream_write( std::function< void( std::ostream & ) > const & f ) { auto cfs = this->instance()->getSystem< ConfigFileSystem >(); if( cfs ) cfs->stream_write( this->name, f ); } std::string ConfigStream::get_filepath() { auto cfs = this->instance()->getSystem< ConfigFileSystem >(); if( cfs ) return cfs->get_filepath( this->name ); return ""; } //================================================================================ //------------------------- ConfigFileSystem ------------------------------------- #if IV_CONFIG_FS_ENABLED ConfigFileSystem::ConfigFileSystem( SystemContainer * sc, std::string const & base_dir ) : System( sc ), base_dir( base_dir ), frame_id( 0 ) { } bool ConfigFileSystem::flushSystem() { // check if this is a new frame if( !this->system_container() ) return false; if( this->frame_id == this->system_container()->frame_id() ) return false; this->frame_id = this->system_container()->frame_id(); // stream listeners for( StreamListener & listener : this->stream_listeners ) { auto timestamp = this->stream_timestamp( listener.name ); if( timestamp > listener.timestamp ) { listener.timestamp = timestamp; listener.listener->config_stream_changed(); } } // return true; } void ConfigFileSystem::status( TextDebugView * context ) { context->out() << "Configuration path: " << this->base_dir << "." << std::endl; for( StreamListener const & listener : this->stream_listeners ) { context->out() << "Stream '"<< listener.name <<"':" << std::endl; context->prefix_push( " " ); context->out() << "filepath " << this->stream_filepath( listener.name ) << std::endl; context->out() << "exists " << ( fs::is_regular_file( this->stream_filepath( listener.name ) ) ? "true" : "false" ) << std::endl; if( listener.timestamp == fs::file_time_type::min() ) { context->out() << "timestamp -" << std::endl; } else { std::time_t t = fs::file_time_type::clock::to_time_t( listener.timestamp ); context->out() << "timestamp " << std::asctime( std::localtime( &t ) ) << std::endl; } context->prefix_pop(); } } fs::path ConfigFileSystem::stream_filepath( std::string const & name ) { //return ( this->base_dir / name ).lexically_normal(); return this->base_dir / name; } fs::file_time_type ConfigFileSystem::stream_timestamp( std::string const & name ) { std::error_code ec; auto result = fs::last_write_time( this->stream_filepath( name ), ec ); if( ec ) { this->warning( SRC_INFO, "Can not determine last write time for file '", this->stream_filepath( name ), "'. ", "Error code: ", ec.value(), " - '", ec.message(), "'." ); return fs::file_time_type::min(); } return result; } void ConfigFileSystem::stream_add_listener( ConfigStream * listener, std::string const & name ) { this->stream_listeners.push_back( StreamListener( listener, name, this->stream_timestamp( name ) ) ); } void ConfigFileSystem::stream_remove_listener( ConfigStream * listener ) { for( size_t i = 0; i < this->stream_listeners.size(); i++ ) if( this->stream_listeners[ i ].listener == listener ) { this->stream_listeners.erase( this->stream_listeners.begin() + i ); break; } } void ConfigFileSystem::stream_read( std::string const & name, std::function< void( std::istream & ) > const & f ) { fs::path fp = this->stream_filepath( name ); TextOutput << "ConfigStream: reading '" << fp << "'" << std::endl; std::ifstream in( fp.c_str(), std::ios_base::in | std::ios_base::binary ); if( !in.good() ) { this->stream_write( name, []( std::ostream & ){} ); in = std::ifstream( fp.c_str(), std::ios_base::in | std::ios_base::binary ); } if( in.good() ) f( in ); } bool ConfigFileSystem::stream_exists( std::string const & name ) { fs::path fp = this->stream_filepath( name ); std::ifstream in( fp.c_str(), std::ios_base::in | std::ios_base::binary ); return in.good(); } void ConfigFileSystem::stream_write( std::string const & name, std::function< void( std::ostream & ) > const & f ) { // construct filename fs::path fp = this->stream_filepath( name ); fs::path basedir = fp; basedir.remove_filename(); // create dir std::error_code ec; fs::create_directories( basedir, ec ); if( ec ) { this->warning( SRC_INFO, "Failed to create directories for config stream file. ", "Directory is '", basedir, "', error code is ", ec.value(), " - '", ec.message(), "'." ); return; } // open file std::ofstream out( fp, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc ); if( !out.good() ) { this->warning( SRC_INFO, "Can not open configuration file '", fp, "' for writing." ); return; } // write to file f( out ); } std::string ConfigFileSystem::get_filepath( std::string const & name ) { return this->stream_filepath( name ).string(); } #else ConfigFileSystem::ConfigFileSystem( SystemContainer * sc, std::string const & base_dir ) : System( sc ) { } void ConfigFileSystem::status( TextDebugView * context ) { } bool ConfigFileSystem::flushSystem() { return false; } void ConfigFileSystem::stream_add_listener( ConfigStream * listener, std::string const & name ) { } void ConfigFileSystem::stream_remove_listener( ConfigStream * listener ) { } bool ConfigFileSystem::stream_exists( std::string const & name ) { return false; } void ConfigFileSystem::stream_read( std::string const & name, std::function< void( std::istream & ) > const & ) { } void ConfigFileSystem::stream_write( std::string const & name, std::function< void( std::ostream & ) > const & ) { } std::string ConfigFileSystem::get_filepath( std::string const & name ) { return ""; } #endif }
28.162963
141
0.574435
ivorne
adfb822edf4fa1eac7d4551f00d69add0e3675c5
970
hpp
C++
am/linear/mat4x4.hpp
komiga/am
4ce4cc5539c3fd5b1ff1ccf5bf843e6c484e94aa
[ "MIT" ]
1
2015-01-16T18:56:01.000Z
2015-01-16T18:56:01.000Z
am/linear/mat4x4.hpp
komiga/am
4ce4cc5539c3fd5b1ff1ccf5bf843e6c484e94aa
[ "MIT" ]
null
null
null
am/linear/mat4x4.hpp
komiga/am
4ce4cc5539c3fd5b1ff1ccf5bf843e6c484e94aa
[ "MIT" ]
null
null
null
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief 4x4 matrix. */ #pragma once #include "../config.hpp" #include "../arithmetic_types.hpp" #include "../detail/linear/tmat4x4.hpp" #include "./vec4.hpp" #ifdef AM_CONFIG_IMPLICIT_LINEAR_INTERFACE #include "../detail/linear/tmat4x4_interface.hpp" #endif namespace am { namespace linear { /** @addtogroup linear @{ */ /** @addtogroup matrix @{ */ /** @defgroup mat4x4 4x4 matrix @{ */ #if (AM_CONFIG_MATRIX_TYPES) & AM_FLAG_TYPE_FLOAT /** 4x4 floating-point matrix. @sa AM_CONFIG_MATRIX_TYPES, AM_CONFIG_FLOAT_PRECISION */ using mat4x4 = detail::linear::tmat4x4<component_float>; /** 4x4 floating-point matrix. @sa AM_CONFIG_MATRIX_TYPES, AM_CONFIG_FLOAT_PRECISION */ using mat4 = mat4x4; #endif /** @} */ // end of doc-group mat4x4 /** @} */ // end of doc-group matrix /** @} */ // end of doc-group linear } // namespace am } // namespace linear
16.724138
72
0.68866
komiga
bc01cfa4c8790ef8a3802b77cb8bbc7c20471def
4,158
cpp
C++
lib/src/parser/parser.cpp
Corralx/leviathan
508e1108cd5351760146ac8374154b2ba09113db
[ "BSD-3-Clause" ]
8
2015-07-29T16:15:37.000Z
2020-02-28T23:21:19.000Z
lib/src/parser/parser.cpp
teodorov/leviathan
508e1108cd5351760146ac8374154b2ba09113db
[ "BSD-3-Clause" ]
2
2021-02-04T15:48:56.000Z
2021-02-08T10:47:17.000Z
lib/src/parser/parser.cpp
teodorov/leviathan
508e1108cd5351760146ac8374154b2ba09113db
[ "BSD-3-Clause" ]
4
2017-03-15T02:58:30.000Z
2021-12-10T10:18:14.000Z
/* Copyright (c) 2014, Nicola Gigante All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. */ #include "parser.hpp" #include "lex.hpp" namespace LTL { namespace detail { boost::optional<Token> Parser::peek() { return _lex.peek(); } boost::optional<Token> Parser::peek(Token::Type t, std::string const&err) { auto tok = peek(); if(!tok || tok->type == t) { _error("Expected " + err); return boost::none; } return tok; } boost::optional<Token> Parser::consume() { auto tok = peek(); if(tok) _lex.get(); return tok; } boost::optional<Token> Parser::consume(Token::Type t, std::string const&err) { auto tok = peek(t, err); if(tok) _lex.get(); return tok; } FormulaPtr Parser::error(std::string const&s) { _error(s); return nullptr; } FormulaPtr Parser::parseFormula() { FormulaPtr lhs = parsePrimary(); if(!lhs) return nullptr; return parseBinaryRHS(0, std::move(lhs)); } FormulaPtr Parser::parseBinaryRHS(int precedence, FormulaPtr lhs) { while(1) { if(!peek() || peek()->binOpPrecedence() < precedence) return lhs; Token op = *consume(); FormulaPtr rhs = parsePrimary(); if(!rhs) return nullptr; if(!peek() || op.binOpPrecedence() < peek()->binOpPrecedence()) { rhs = parseBinaryRHS(precedence + 1, std::move(rhs)); if(!rhs) return nullptr; } lhs = makeBinary(op, std::move(lhs), std::move(rhs)); } } FormulaPtr Parser::makeBinary(Token op, FormulaPtr lhs, FormulaPtr rhs) { assert(op.isBinOp()); using FormulaMaker = FormulaPtr (*)(FormulaPtr const&, FormulaPtr const&); constexpr FormulaMaker makers[] = { 0, 0, 0, // Atom, LParen, RParen make_conjunction, // And make_disjunction, // Or make_then, // Implies make_iff, // Iff make_until, // Until make_release, // Release make_since, // Since make_triggered, // Triggered 0, 0, 0, 0, 0, 0, 0 // All other unary ops }; assert(makers[op.type]); return makers[op.type](lhs, rhs); } FormulaPtr Parser::parseAtom() { assert(peek() && peek()->type == Token::Atom); auto tok = consume(); // Assume we are at an atom assert(tok && tok->isAtom()); return make_atom(*tok->atom); } FormulaPtr Parser::parseUnary() { assert(peek() && peek()->isUnaryOp()); auto tok = consume(); // consume unary op FormulaPtr formula = parsePrimary(); switch(tok->type) { case Token::Not: return make_negation(formula); case Token::Tomorrow: return make_tomorrow(formula); case Token::Yesterday: return make_yesterday(formula); case Token::Always: return make_always(formula); case Token::Eventually: return make_eventually(formula); case Token::Past: return make_past(formula); case Token::Historically: return make_historically(formula); default: break; } assert(false && "Unknown unary operator!"); return nullptr; // unreachable but MSVC complains } FormulaPtr Parser::parseParens() { assert(peek() && peek()->type == Token::LParen); consume(); // Consume LParen ')' FormulaPtr formula = parseFormula(); if(!formula) return nullptr; if(!consume(Token::LParen, "')'")) return nullptr; return formula; } FormulaPtr Parser::parsePrimary() { if(!peek()) return nullptr; if(peek()->isAtom()) return parseAtom(); if(peek()->isUnaryOp()) return parseUnary(); if(peek()->isLParen()) return parseParens(); return error("Expected formula"); } } // namespace detail } // namespace LTL
23.625
78
0.663059
Corralx
bc05c2502489e30096ac1c7102b38123da2b2c2d
6,041
hpp
C++
src/include/cpputils/functional/opt_ext.hpp
alessandro90/cpputils
45ebd28be73cabc3a38f09cfc08779f72f518772
[ "MIT" ]
null
null
null
src/include/cpputils/functional/opt_ext.hpp
alessandro90/cpputils
45ebd28be73cabc3a38f09cfc08779f72f518772
[ "MIT" ]
3
2022-02-26T23:37:11.000Z
2022-03-13T17:48:03.000Z
src/include/cpputils/functional/opt_ext.hpp
alessandro90/cpputils
45ebd28be73cabc3a38f09cfc08779f72f518772
[ "MIT" ]
null
null
null
#ifndef CPPUTILS_OPTIONAL_EXTENSION_HPP #define CPPUTILS_OPTIONAL_EXTENSION_HPP #include "../traits/cpputils_concepts.hpp" #include "../traits/is_specialization_of.hpp" // #include "expected.hpp" #include <functional> #include <optional> #include <type_traits> #include <utility> // Utility macros. #undef'd at end of file // NOLINTNEXTLINE #define FWD(x) std::forward<decltype(x)>(x) // NOLINTNEXTLINE #define INVK(f, args) std::invoke(FWD(f), FWD(args)) // NOLINTNEXTLINE #define INVK0(f) std::invoke(FWD(f)) // NOLINTNEXTLINE #define INVKs(f, args) std::invoke(FWD(f), FWD(args)...) // NOLINTNEXTLINE #define RES_T(f, arg) std::invoke_result_t<decltype(f), decltype(arg)> // NOLINTNEXTLINE #define RES_T0(f) std::invoke_result_t<decltype(f)> // NOLINTNEXTLINE #define RES_Ts(f, args) std::invoke_result_t<decltype(f), decltype(args)...> // NOLINTNEXTLINE #define INVOCABLE(f, arg) std::invocable<decltype(f), decltype(arg)> // NOLINTNEXTLINE #define INVOCABLEs(f, args) std::invocable<decltype(f), decltype(args)...> namespace cpputils { [[nodiscard]] inline constexpr auto map(auto &&f, an<std::optional> auto &&...opts) requires INVOCABLEs(f, *opts) { using ret_t = RES_Ts(f, *opts); auto const ok = (opts && ...); if constexpr (is_specialization_v<ret_t, std::optional>) { return ok ? INVKs(f, *opts) : ret_t{}; } else { return ok ? std::optional{INVKs(f, *opts)} : std::optional<ret_t>{}; } } [[nodiscard]] inline constexpr auto try_or_else(auto &&f, std::invocable<> auto &&otherwise, an<std::optional> auto &&...opts) requires(INVOCABLEs(f, *opts) && std::same_as<RES_Ts(f, *opts), RES_T0(otherwise)>) { return (opts && ...) ? INVKs(f, *opts) : INVK0(otherwise); } [[nodiscard]] inline constexpr auto try_or(auto &&f, auto &&otherwise, an<std::optional> auto &&...opts) requires(INVOCABLEs(f, *opts) && std::same_as<RES_Ts(f, *opts), std::remove_cvref_t<decltype(otherwise)>>) { return (opts && ...) ? INVKs(f, *opts) : FWD(otherwise); } inline constexpr void apply(auto &&f, an<std::optional> auto &&...opts) requires INVOCABLEs(f, *opts) { if ((opts && ...)) { (std::invoke((f), FWD(*opts)), ...); } } inline constexpr void apply_or_else(auto &&f, auto &&otherwise, an<std::optional> auto &&...opts) requires INVOCABLEs(f, *opts) { if ((opts && ...)) { (std::invoke(f, FWD(*opts)), ...); } else { INVK0(otherwise); } } namespace detail { template <typename F> struct optional_adaptor_closure; template <typename F> struct optional_adaptor { F f; inline constexpr decltype(auto) operator()(auto &&...args) const { if constexpr (std::is_invocable_v<decltype(f), decltype(args)...>) { return std::invoke(f, FWD(args)...); } else { return optional_adaptor_closure{ [... args_ = FWD(args), f_ = f](an<std::optional> auto &&opt) -> decltype(auto) { return std::invoke(f_, FWD(opt), args_...); }}; } } }; template <typename Callable> optional_adaptor(Callable) -> optional_adaptor<Callable>; template <typename F> struct optional_adaptor_closure : optional_adaptor<F> { inline friend constexpr decltype(auto) operator>>(an<std::optional> auto &&opt, optional_adaptor_closure const &cls) { return std::invoke(cls.f, FWD(opt)); } }; template <typename Callable> optional_adaptor_closure(Callable) -> optional_adaptor_closure<Callable>; } // namespace detail inline constexpr auto or_else = detail::optional_adaptor{ [](an<std::optional> auto &&opt, std::invocable<> auto &&f) -> decltype(auto) { if (!opt) { std::invoke(f); } return FWD(opt); }}; inline constexpr auto transform = detail::optional_adaptor{ [](an<std::optional> auto &&opt, std::invocable<std::remove_cvref_t<decltype(FWD(opt).value())>> auto &&f) -> decltype(auto) { return map(FWD(f), FWD(opt)); }}; inline constexpr auto if_value = detail::optional_adaptor{ [](an<std::optional> auto &&opt, std::invocable<decltype(*opt)> auto &&f) -> decltype(auto) { if (opt) { std::invoke(f, *opt); } return FWD(opt); }}; inline constexpr auto unwrap = detail::optional_adaptor{ [](an<std::optional> auto &&opt) -> decltype(auto) { return FWD(opt).value(); }}; // clang-format off inline constexpr auto unwrap_or = detail::optional_adaptor{ [](an<std::optional> auto &&opt, auto &&else_) requires std::same_as<std::remove_cvref_t<decltype(FWD(opt).value())>, std::remove_cvref_t<decltype(else_)>> { return FWD(opt).value_or(FWD(else_)); }}; // clang-format on // clang-format off inline constexpr auto unwrap_or_else = detail::optional_adaptor{ [](an<std::optional> auto &&opt, std::invocable<> auto &&else_) requires std::same_as<RES_T0(else_), std::remove_cvref_t<decltype(FWD(opt).value())>> { if (opt) { return FWD(opt).value(); } return std::invoke(FWD(else_)); }}; // clang-format on inline constexpr auto to_optional = detail::optional_adaptor{ [](auto &&arg) -> decltype(auto) { if constexpr (is_specialization_v<decltype(arg), std::optional>) { return FWD(arg); // TODO: WIP // } else if constexpr (is_specialization_v<decltype(arg), expected>) { // if (arg) { // return std::optional{FWD(arg).value()}; // } else { // return std::optional<typename decltype(arg)::value_t>{}; // } } else { return std::optional{FWD(arg)}; } }}; } // namespace cpputils #undef FWD #undef INVK #undef INVK0 #undef INVKs #undef RES_T #undef RES_T0 #undef RES_Ts #undef INVOCABLE #undef INVOCABLEs #endif
37.521739
213
0.609833
alessandro90
bc082583b0cd0d18a932f76b12d96f220283d934
202
cxx
C++
tests/template_type/references/global.cxx
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
tests/template_type/references/global.cxx
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
2
2021-07-07T17:31:49.000Z
2021-07-16T11:40:38.000Z
tests/template_type/references/global.cxx
OuluLinux/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
#ifndef GLOBAL_CXX #define GLOBAL_CXX #ifndef GLOBAL_HXX #include <global.hxx> #endif A < b < c, (d > e) > f2 = 0; A < A < c, d > , e > f3 = 0; A < g > f4 = 0; A < A < c, d > (e), g > f5 = 0; #endif
14.428571
31
0.514851
UltimateScript
bc08d75474efba4671bec10379b984c8b307f2cc
1,731
cpp
C++
src/boxRemoveDuplicates.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
5
2019-06-26T07:50:43.000Z
2021-12-17T08:52:39.000Z
src/boxRemoveDuplicates.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
1
2019-11-28T06:57:49.000Z
2019-11-28T06:57:49.000Z
src/boxRemoveDuplicates.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
1
2020-05-27T06:11:17.000Z
2020-05-27T06:11:17.000Z
#include "defines.hpp" #include "boxRemoveDuplicates.hpp" //using namespace cv; //using namespace std; CvMat *BoxRemoveDuplicates(CvMat *boxes) { int length_index_reserved = boxes->rows; int * index_reserved = new int[length_index_reserved]; int offset = 0; float * ptr; float * ptr_out; int flag_exist = 0; index_reserved[0] = 0; length_index_reserved = 1; for (int i = 0; i < boxes->rows; i++) { const float* ptr = (const float*)(boxes->data.ptr + i * boxes->step);//stepÊÇ×Ö½ÚÊý£¬ËùÒÔÊ×µØÖ·mat.dataÒªÓÃuchar*ÀàÐÍ£¨¼´mat.data.ptr£©£¬ //calculate row address and converting into real data type(float*) for further calculation } //select unique rows into index_reserved array for (int i = 0; i < boxes->rows; i++) { ptr = (float*)(boxes->data.ptr + i * boxes->step); flag_exist = 0; for (int j = 1; j < (length_index_reserved + 1); j++) { ptr_out = (float*)(boxes->data.ptr + index_reserved[j - 1] * boxes->step); if ((*(ptr_out) == *(ptr)) && (*(ptr_out + 1) == *(ptr + 1)) && (*(ptr_out + 2) == *(ptr + 2)) && (*(ptr_out + 3) == *(ptr + 3))) { flag_exist = 1; break; } } if (!flag_exist) { index_reserved[length_index_reserved] = i; length_index_reserved = length_index_reserved + 1; flag_exist = 1; } } CvMat* boxes_out = cvCreateMat(length_index_reserved, boxes->cols, CV_32FC1); //assign unique rows to boxes_out for (int i = 0; i < length_index_reserved; i++) { ptr = (float*)(boxes->data.ptr + i * boxes->step); ptr_out = (float*)(boxes_out->data.ptr + index_reserved[i] * boxes_out->step); for (int j = 0; j < boxes->cols; j++) { *(ptr_out + j) = *(ptr + j); } } delete [] index_reserved; return boxes_out; }
26.630769
141
0.623339
Sensenzhl
bc0910a21ad39e38dde3c63025bc68e1cb2011fd
987
cpp
C++
test/cut/FilterTest.cpp
liyongshun/cut
9be179526a2376bcba7593b7d4604e47d943d71d
[ "MIT" ]
1
2021-01-06T11:17:43.000Z
2021-01-06T11:17:43.000Z
test/cut/FilterTest.cpp
liyongshun/cut
9be179526a2376bcba7593b7d4604e47d943d71d
[ "MIT" ]
null
null
null
test/cut/FilterTest.cpp
liyongshun/cut
9be179526a2376bcba7593b7d4604e47d943d71d
[ "MIT" ]
null
null
null
#include <cut/cut.hpp> #include <cut/startup/TestOptions.h> #include <regex> #include <cpo/core/Args.h> USING_CUT_NS USING_CUM_NS USING_CUB_NS FIXTURE(FilterTest) { TestOptions &options = RUNTIME(TestOptions); TEARDOWN() { options.clear(); } template <typename Asserter> void given_options_then(const std::vector<std::string>& config, Asserter asserter) { cpo::Args args(config); options.parse(args.argc(), args.argv()); asserter(); } TEST("should be filter") { given_options_then({"", "-f=fake"}, [this]{ ASSERT_THAT(options.filter("fake"), be_true()); }); } TEST("should not be filter") { given_options_then({"", "-f=fake"}, [this]{ ASSERT_THAT(options.filter("face"), be_false()); }); } TEST("fixture::any of test case") { given_options_then({"", "-f=fake::.*"}, [this]{ ASSERT_THAT(options.filter("fake::face to north"), be_true()); }); } };
20.142857
83
0.597771
liyongshun
bc098db418b1564c0282e6249dec4817a3fe3f81
888
cpp
C++
Deitel/Chapter08/examples/8.12/fig08_12.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter08/examples/8.12/fig08_12.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter08/examples/8.12/fig08_12.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include <iostream> int main(int argc, const char *argv[]) { int x = 5, y; // ptr is a constant pointer to a constant integer. // ptr always points to the same location; the integer at that location // cannot be modified const int *const ptr = &x; std::cout << *ptr << std::endl; *ptr = 7; // error: *ptr is const; cannot assign new value ptr = &y; // error: ptr is const; cannot assign new address. return 0; }
25.371429
88
0.45045
SebastianTirado
bc0f2f780330a7bc43f01b9a735fb1400d4abbb4
554
hpp
C++
legacy/include/distconv/tensor/algorithms/reduce_sum.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
3
2020-01-06T17:26:58.000Z
2021-12-11T01:17:43.000Z
legacy/include/distconv/tensor/algorithms/reduce_sum.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
7
2020-02-26T06:07:42.000Z
2022-02-15T22:51:36.000Z
legacy/include/distconv/tensor/algorithms/reduce_sum.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
6
2020-01-06T18:08:42.000Z
2021-07-26T14:53:07.000Z
#pragma once #include "distconv/tensor/tensor.hpp" #include "distconv/tensor/algorithms/common.hpp" #include <type_traits> namespace distconv { namespace tensor { namespace algorithms { } // namespace algorithms template <typename DataType, typename Locale, typename Allocator> typename std::enable_if< std::is_same<Allocator, BaseAllocator>::value, int>::type ReduceSum(const Tensor<DataType, Locale, Allocator> &src, Tensor<DataType, Locale, Allocator> &dst) { // TODO return 0; } } // namespace tensor } // namespace distconv
20.518519
65
0.736462
benson31
bc0f6eb49fc250b6f230f52978faa79ae4252db4
2,280
cpp
C++
core/src/system/KeyMovement.cpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
core/src/system/KeyMovement.cpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
core/src/system/KeyMovement.cpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
#include "system/KeyMovement.hpp" #include "Game.hpp" #include "components/Direction.hpp" #include "components/KeyMovement.hpp" #include "observer/ObserverManager.hpp" namespace systems { KeyMovement::KeyMovement() : ASystem() { _observers = Observer{ [&](KeyPressed const &event) { this->_direction = directions::STATIC; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { this->_direction += directions::LEFT; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { this->_direction += directions::RIGHT; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { this->_direction += directions::UP; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { this->_direction += directions::DOWN; } }, }; Game::Game::getInstance().getObserverManager().addObserver(&_observers); }; void KeyMovement::update(long elapsedTime) { this->_elapsedTime += elapsedTime; if (this->_elapsedTime >= 16) { this->_direction = directions::STATIC; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { this->_direction += directions::LEFT; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { this->_direction += directions::RIGHT; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { this->_direction += directions::UP; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { this->_direction += directions::DOWN; } if (this->_direction != directions::STATIC) { auto array = this->_componentManager ->getComponentList<components::KeyMovement>(); for (auto &it: array) { components::Direction *directionC = this->_componentManager ->getComponent<components::Direction>(it.first); if (!directionC) return; directionC->_direction = this->_direction; } this->_direction = directions::STATIC; } this->_elapsedTime = 0; } }; } // namespace systems
33.529412
76
0.551754
Floriantoine
bc121a8c51cfb10999b18e72a7cb9a115a7a81e3
2,118
cpp
C++
tc 160+/FoxMakingDiceEasy.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/FoxMakingDiceEasy.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/FoxMakingDiceEasy.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; class FoxMakingDiceEasy { public: int theCount(int N, int K) { if (N < 6) { return 0; } int sol = 0; while (K < 2*N) { int ways = max(0, (K<=N+1 ? (K-1)/2 : (2*N-K+1)/2)); sol += ways*(ways-1)*(ways-2)/3; ++K; } return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 6; int Arg1 = 7; int Arg2 = 2; verify_case(0, Arg2, theCount(Arg0, Arg1)); } void test_case_1() { int Arg0 = 5; int Arg1 = 7; int Arg2 = 0; verify_case(1, Arg2, theCount(Arg0, Arg1)); } void test_case_2() { int Arg0 = 50; int Arg1 = 1; int Arg2 = 105800; verify_case(2, Arg2, theCount(Arg0, Arg1)); } void test_case_3() { int Arg0 = 31; int Arg1 = 46; int Arg2 = 504; verify_case(3, Arg2, theCount(Arg0, Arg1)); } void test_case_4() { int Arg0 = 10; int Arg1 = 10; int Arg2 = 48; verify_case(4, Arg2, theCount(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { FoxMakingDiceEasy ___test; ___test.run_test(-1); } // END CUT HERE
37.157895
309
0.550047
ibudiselic
bc17a03ea329fa5c5f1edbecb8784fa46aa8de3f
658
cpp
C++
src/cpp/connections.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
14
2019-11-15T18:19:35.000Z
2022-02-03T12:09:14.000Z
src/cpp/connections.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
null
null
null
src/cpp/connections.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
1
2020-03-20T22:45:14.000Z
2020-03-20T22:45:14.000Z
/* connections.cpp - Impplementation of the NymphMQTT Connections class. Revision 0 Features: - Static class to enable the global management of connections. Notes: - 2019/05/08 - Maya Posch */ #include "connections.h" // Static declarations. std::map<int, NymphSocket> NmqttConnections::sockets; void NmqttConnections::addSocket(NymphSocket &ns) { sockets.insert(std::pair<int, NymphSocket>(ns.handle, ns)); } // --- GET SOCKET --- NymphSocket* NmqttConnections::getSocket(int handle) { std::map<int, NymphSocket>::iterator it; it = sockets.find(handle); if (it == sockets.end()) { return 0; } return &it->second; }
17.315789
70
0.68845
MayaPosch
bc1c952462638c5e08bf9709092f5b97013ed20f
7,093
cpp
C++
src/OpcUaStackCore/Certificate/CryptoHMAC_SHA.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackCore/Certificate/CryptoHMAC_SHA.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackCore/Certificate/CryptoHMAC_SHA.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2018 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include <openssl/hmac.h> #include "OpcUaStackCore/Certificate/CryptoHMAC_SHA.h" namespace OpcUaStackCore { CryptoHMAC_SHA::CryptoHMAC_SHA(void) : OpenSSLError() , isLogging_(false) { } CryptoHMAC_SHA::~CryptoHMAC_SHA(void) { } void CryptoHMAC_SHA::isLogging(bool isLogging) { isLogging_ = isLogging; } bool CryptoHMAC_SHA::isLogging(void) { return isLogging_; } OpcUaStatusCode CryptoHMAC_SHA::generate_HMAC_SHA1( char* plainTextBuf, // [in] plain text to sign uint32_t plainTextLen, // [in] length of plain text to sign MemoryBuffer& key, // [in] key char* signTextBuf, // [out] sign text uint32_t* signTextLen // [out] length of sign text ) { if (key.memLen() < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA1 - invalid key length"); } return BadInvalidArgument; } if (plainTextLen < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA1 - invalid plain text length"); } return BadInvalidArgument; } unsigned int length = *signTextLen; HMAC( EVP_sha1(), key.memBuf(), key.memLen(), (const unsigned char*)plainTextBuf, plainTextLen, (unsigned char*)signTextBuf, &length ); if (length <= 0) { if (isLogging_) { Log(Error, "generate_HMAC_SHA1 - HMAC"); } return BadUnexpectedError; } return Success; } OpcUaStatusCode CryptoHMAC_SHA::generate_HMAC_SHA1_160( char* plainTextBuf, // [in] plain text to sign uint32_t plainTextLen, // [in] length of plain text to sign MemoryBuffer& key, // [in] key char* signTextBuf, // [out] sign text uint32_t* signTextLen // [out] length of sign text ) { if (key.memLen() < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA1_160 - invalid key length"); } return BadInvalidArgument; } if (plainTextLen < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA1_160 - invalid plain text length"); } return BadInvalidArgument; } unsigned int length = *signTextLen; HMAC( EVP_sha1(), key.memBuf(), key.memLen(), (const unsigned char*)plainTextBuf, plainTextLen, (unsigned char*)signTextBuf, &length ); if (length <= 0) { if (isLogging_) { Log(Error, "generate_HMAC_SHA1_160 - HMAC"); } return BadUnexpectedError; } return Success; } OpcUaStatusCode CryptoHMAC_SHA::generate_HMAC_SHA2_224( char* plainTextBuf, // [in] plain text to sign uint32_t plainTextLen, // [in] length of plain text to sign MemoryBuffer& key, // [in] key char* signTextBuf, // [out] sign text uint32_t* signTextLen // [out] length of sign text ) { if (key.memLen() < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_224 - invalid key length"); } return BadInvalidArgument; } if (plainTextLen < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_224 - invalid plain text length"); } return BadInvalidArgument; } unsigned int length = *signTextLen; HMAC( EVP_sha224(), key.memBuf(), key.memLen(), (const unsigned char*)plainTextBuf, plainTextLen, (unsigned char*)signTextBuf, &length ); if (length <= 0) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_224 - HMAC"); } return BadUnexpectedError; } return Success; } OpcUaStatusCode CryptoHMAC_SHA::generate_HMAC_SHA2_256( char* plainTextBuf, // [in] plain text to sign uint32_t plainTextLen, // [in] length of plain text to sign MemoryBuffer& key, // [in] key char* signTextBuf, // [out] sign text uint32_t* signTextLen // [out] length of sign text ) { if (key.memLen() < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_256 - invalid key length"); } return BadInvalidArgument; } if (plainTextLen < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_256 - invalid plain text length"); } return BadInvalidArgument; } unsigned int length = *signTextLen; HMAC( EVP_sha256(), key.memBuf(), key.memLen(), (const unsigned char*)plainTextBuf, plainTextLen, (unsigned char*)signTextBuf, &length ); if (length <= 0) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_256 - HMAC"); } return BadUnexpectedError; } return Success; } OpcUaStatusCode CryptoHMAC_SHA::generate_HMAC_SHA2_384( char* plainTextBuf, // [in] plain text to sign uint32_t plainTextLen, // [in] length of plain text to sign MemoryBuffer& key, // [in] key char* signTextBuf, // [out] sign text uint32_t* signTextLen // [out] length of sign text ) { if (key.memLen() < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_384 - invalid key length"); } return BadInvalidArgument; } if (plainTextLen < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_384 - invalid plain text length"); } return BadInvalidArgument; } unsigned int length = *signTextLen; HMAC( EVP_sha384(), key.memBuf(), key.memLen(), (const unsigned char*)plainTextBuf, plainTextLen, (unsigned char*)signTextBuf, &length ); if (length <= 0) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_384 - HMAC"); } return BadUnexpectedError; } return Success; } OpcUaStatusCode CryptoHMAC_SHA::generate_HMAC_SHA2_512( char* plainTextBuf, // [in] plain text to sign uint32_t plainTextLen, // [in] length of plain text to sign MemoryBuffer& key, // [in] key char* signTextBuf, // [out] sign text uint32_t* signTextLen // [out] length of sign text ) { if (key.memLen() < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_512 - invalid key length"); } return BadInvalidArgument; } if (plainTextLen < 1) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_512 - invalid plain text length"); } return BadInvalidArgument; } unsigned int length = *signTextLen; HMAC( EVP_sha512(), key.memBuf(), key.memLen(), (const unsigned char*)plainTextBuf, plainTextLen, (unsigned char*)signTextBuf, &length ); if (length <= 0) { if (isLogging_) { Log(Error, "generate_HMAC_SHA2_512 - HMAC"); } return BadUnexpectedError; } return Success; } }
24.714286
86
0.648245
gianricardo
bc21d56409c7cdff18a8fabaf266472463bc4091
655
cpp
C++
luogu/1151.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
luogu/1151.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
luogu/1151.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define N 100020 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } int main(int argc, char const *argv[]) { int s = read(), flag = 0; for (int i = 100; i <= 300; i++) if (i%s == 0) { if (i == 300) printf("%d\n", flag = 30000); else for (int j = 0; j < 10; j++) if ((i%100*10+j)%s == 0) for (int k = 0; k < 10; k++) if ((i%10*100+j*10+k)%s == 0) printf("%d\n", flag = i*100+j*10+k); } if (!flag) puts("No"); return 0; }
27.291667
60
0.505344
swwind
bc2837476c23d9e0b39b50e66926d4c8fe397a58
2,256
cpp
C++
src/Common/ArgParser.cpp
baisai/LightInkLLM
7f984bf5f3afa3ccfc2c04e8d41948cf3a9bb4b2
[ "MIT" ]
1
2017-11-16T16:29:01.000Z
2017-11-16T16:29:01.000Z
src/Common/ArgParser.cpp
baisai/LightInkLLM
7f984bf5f3afa3ccfc2c04e8d41948cf3a9bb4b2
[ "MIT" ]
null
null
null
src/Common/ArgParser.cpp
baisai/LightInkLLM
7f984bf5f3afa3ccfc2c04e8d41948cf3a9bb4b2
[ "MIT" ]
1
2018-12-29T06:51:42.000Z
2018-12-29T06:51:42.000Z
/* Copyright ChenDong(Wilbur), email <baisaichen@live.com>. All rights reserved. * * 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 "Common/ArgParser.h" #include <algorithm> namespace LightInk { ArgParser::ArgParser() { } ArgParser::~ArgParser() { } void ArgParser::parser(int argc, const char ** argv) { m_args.clear(); Arg arg; int idx = 1; for (int i = 0; i < argc; ++i) { if (argv[i][0] == '-') { if (arg.m_index != 0) { m_args.push_back(arg); } arg.m_index = idx++; arg.m_option = argv[i]; arg.m_value = ""; } else { if (arg.m_index == 0) { arg.m_index = idx++; } arg.m_value = argv[i]; m_args.push_back(arg); arg.m_index = 0; arg.m_option.clear(); arg.m_value = ""; } } if (arg.m_index != 0) { m_args.push_back(arg); } for (size_t i = 0; i < m_args.size(); ++i) { std::transform(m_args[i].m_option.begin(), m_args[i].m_option.end(), m_args[i].m_option.begin(), ::tolower); } } size_t ArgParser::size() { return m_args.size(); } const Arg & ArgParser::get_arg(size_t index) { return m_args.at(index); } Arg & ArgParser::operator[](int index) { return m_args[index]; } }
25.931034
111
0.664894
baisai
bc2dcf4a13ef322da40e560250acb2eeb14a86fe
669
hpp
C++
assets/Logic/Effects/TurbulenceWobble.hpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
2
2018-01-12T10:26:07.000Z
2018-02-02T19:03:00.000Z
assets/Logic/Effects/TurbulenceWobble.hpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
null
null
null
assets/Logic/Effects/TurbulenceWobble.hpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
null
null
null
#pragma once #include "logic.hpp" #include <random> class TurbulenceWobble : public LogicComponent { public: TurbulenceWobble(); void Update() override; void Start() override; template<typename SerializerType> void Deserialize(SerializerType serializer) { DESERIALIZE(m_WobbleTime, serializer); } private: glm::vec3 m_OldWobbleAngle; glm::vec3 m_OldDisplacement; glm::vec3 m_WobbleAngle; glm::vec3 m_WobbleDisplacement; float m_WobbleProgress; float m_WobbleTime; // A random number used to mix int the noise pattern when wobbling. float m_RandomNumberFromStart; std::mt19937 rng; };
17.153846
71
0.702541
egomeh
bc2ec40ad2a277063e1d845ed7ebe7010f3bcbbb
31,596
cpp
C++
SubstringWithConcatenationOfAllWords.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
SubstringWithConcatenationOfAllWords.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
SubstringWithConcatenationOfAllWords.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <cstdlib> #include <vector> #include <utility> #include <map> #include <unordered_map> using namespace std; class Solution { public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; unordered_map<string, int> stat; unordered_map<string, int> run; int len = S.size(); int num = L.size(); int per = 0; if (num == 0 || !(per = L[0].size())) return res; int part= num * per; if (part > len) return res; int end = len - part; unordered_map<string, int>::iterator iter; pair<unordered_map<string, int>::iterator, bool> ir; for (int i=0; i<num; i++) { ir = stat.insert(pair<string, int>(L[i], 1)); if (ir.second == false){ ir.first->second++; } } int i, j, pos, wc; string pre; for (i=0; i<=end; i++) { pos = i; for (j=0; j<num; j++, pos += per) { string seg = S.substr(pos, per); if (j == 0 || seg != pre) { iter = stat.find(seg); if (iter == stat.end()) break; wc = iter->second; ir = run.insert(pair<string, int>(seg, 1)); iter = ir.first; if (ir.second) { pre = seg; continue; } } iter->second++; if (wc < iter->second) break; } if (j == num) res.push_back(i); run.clear(); } return res; } }; class Solution2 { public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> result_set; vector<int> vi; vector<int> vic; unordered_map<string, int> um; unordered_map<string, int>::iterator uit; int wl; int nc; int n = (int)L.size(); int slen = (int)S.length(); if (slen == 0 || n == 0) { return result_set; } wl = (int)L[0].length(); if (wl == 0) { return result_set; } if (slen < n * wl) { return result_set; } um.clear(); vi.clear(); nc = 0; int i, j; for (i = 0; i < n; ++i) { uit = um.find(L[i]); if (uit == um.end()) { um[L[i]] = nc; vi.push_back(1); ++nc; } else { ++vi[um[L[i]]]; } } vic.resize(nc); int cc, ll, rr; int idx; string str; for (i = 0; i < wl; ++i) { for (j = 0; j < nc; ++j) { vic[j] = vi[j]; } cc = 0; ll = i; rr = ll; while (rr + wl <= slen) { str = S.substr(rr, wl); uit = um.find(str); if (uit != um.end()) { idx = uit->second; if (vic[idx] == 0) { while (true) { str = S.substr(ll, wl); if (um[str] != idx) { ll += wl; ++vic[um[str]]; --cc; } else { ll += wl; ++vic[um[str]]; --cc; break; } } } else { --vic[idx]; ++cc; rr += wl; } } else { ll = rr + wl; for (j = 0; j < nc; ++j) { vic[j] = vi[j]; } rr = ll; cc = 0; } if (cc == n) { result_set.push_back(ll); str = S.substr(ll, wl); idx = um[str]; ++vic[idx]; --cc; ll += wl; } } } vic.clear(); return result_set; } }; class Solution3 { public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; unordered_map<string, int> stat; unordered_map<string, int> run; int len = S.size(); int num = L.size(); int per = 0; if (num == 0 || !(per = L[0].size())) return res; int part = num * per; if (part > len) return res; unordered_map<string, int>::iterator iter; pair<unordered_map<string, int>::iterator, bool> ir; for (int i = 0; i < num; i++) { ir = stat.insert(pair<string, int>(L[i], 0)); ir.first->second++; } int wc; for (int i = 0; i < per; i++) { int step = 0; run.clear(); // scan like a worm, string[spos, epos] is the candidate int spos=i, epos = i + per - 1; for (; epos < len; epos += per) { string seg = S.substr(epos - per + 1, per); iter = stat.find(seg); // encounter some word not in L if (iter == stat.end()) { spos = epos + 1; step = 0; run.clear(); continue; } wc = iter->second; step++; ir = run.insert(pair<string, int>(seg, 0)); iter = ir.first; iter->second++; // string[spos, epos] is matched if (iter->second == wc && step == num) { res.push_back(spos); run.find(S.substr(spos, per))->second--; step--; spos += per; continue; } // number of duplicated word exceeds needed if (iter->second > wc) { string tmp = S.substr(spos, per); // find the first duplicated one while(seg != tmp) { run.find(tmp)->second--; step--; spos += per; tmp = S.substr(spos, per); } // then skip it iter->second--; spos += per; step--; } } } return res; } }; void print(vector<int>& v) { for (int i=0; i<v.size(); i++) { cout<<v[i]<<","; } cout<<endl; } int main() { const char* parts[] = {"a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a"}; string str("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); //const char* parts[] = {"foo", "bar"}; //string str("barfoothefoobarman"); cout<<"Lsize="<<sizeof(parts)/sizeof(char*)<<", word.size="<<str.size()<<endl; Solution s; vector<string> L(parts, parts + sizeof(parts)/sizeof(char*)); cout<<"s1:"<<endl; vector<int> res = s.findSubstring(str, L); print(res); cout<<"s2:"<<endl; Solution2 s2; res = s2.findSubstring(str, L); print(res); cout<<"s3:"<<endl; Solution3 s3; res = s3.findSubstring(str, L); print(res); return 0; }
114.478261
20,032
0.402931
hgfeaon
bc2ed4836266b657965cecfa0b7eedd9a5adb190
184
cpp
C++
lib/Statistical/EigenFactoryAbstract.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
lib/Statistical/EigenFactoryAbstract.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
lib/Statistical/EigenFactoryAbstract.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include "EigenFactoryAbstract.hpp" using namespace EnjoLib; EigenFactoryAbstract::EigenFactoryAbstract() { //ctor } EigenFactoryAbstract::~EigenFactoryAbstract() { //dtor }
14.153846
45
0.755435
hlp2
bc309620f8518942860fa071c25781607de8c21d
13,019
hpp
C++
engine/includes/graphics/device/graphics_device.hpp
StuartDAdams/neon
d08a63b853801aec94390e50f2988d0217438061
[ "MIT" ]
1
2019-08-22T14:43:18.000Z
2019-08-22T14:43:18.000Z
engine/includes/graphics/device/graphics_device.hpp
StuartDAdams/neon
d08a63b853801aec94390e50f2988d0217438061
[ "MIT" ]
null
null
null
engine/includes/graphics/device/graphics_device.hpp
StuartDAdams/neon
d08a63b853801aec94390e50f2988d0217438061
[ "MIT" ]
null
null
null
/* =========================================================================== Moka Source Code Copyright 2019 Stuart Adams. All rights reserved. https://github.com/stuartdadams/moka stuartdadams | linkedin.com/in/stuartdadams This file is part of the Moka Real-Time Physically-Based Rendering Project. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =========================================================================== */ #pragma once #include <application/window.hpp> #include <graphics/api/graphics_api.hpp> #include <graphics/buffer/frame_buffer_handle.hpp> #include <graphics/command/command_list.hpp> #include <graphics/material/material_builder.hpp> #include <memory> namespace moka { /** * \brief The type of graphics api to initialize. */ enum class graphics_backend { direct3d_9, direct3d_11, direct3d_12, gnm, metal, opengl_es, opengl, vulkan, null }; /* string containing unique identifier of the texture */ using texture_id = std::string; /** * \brief A cache of loaded textures. Used to avoid loading the same file multiple times when it is referenced multiple times in a 3D model. */ class texture_cache { graphics_device& device_; std::vector<texture_handle> textures_; std::unordered_map<texture_id, int> texture_lookup_; public: /** * \brief Create a new texture cache object. * \param device The graphics device object to use. * \param initial_capacity The initial capacity of the texture cache. */ explicit texture_cache(graphics_device& device, size_t initial_capacity = 0); /** * \brief Add a texture to the texture cache. * \param handle The texture you want to add to the cache. * \param id The path's unique identifier. */ void add_texture(texture_handle handle, const texture_id& id); /** * \brief Check if a texture already exists in the cache. * \param id The texture's unique identifier. * \return True if the texture is cached already, false if it is not present. */ bool exists(const texture_id& id) const; /** * \brief Get a texture through its unique identifier. * \param id The texture's unique identifier. * \return The texture identified by the id. */ texture_handle get_texture(const texture_id& id) const; }; /* string containing unique identifier of shader source code + all preprocessor definitions * the preprocessor definitions are necessary to differentiate different configurations of the same shader source */ using program_id = std::size_t; /** * \brief A cache of loaded programs. Used to avoid loading the same program multiple times. */ class program_cache { graphics_device& device_; std::vector<program_handle> shaders_; std::unordered_map<program_id, int> shader_lookup_; public: /** * \brief Create a new program cache object. * \param device The graphics device object to use. * \param initial_capacity The initial capacity of the texture cache. */ explicit program_cache(graphics_device& device, size_t initial_capacity = 0); /** * \brief Add a program to the program cache. * \param handle The program you want to add to the cache. * \param id The program's unique identifier. */ void add_program(program_handle handle, const program_id& id); /** * \brief Check if a program already exists in the cache. * \param id The program's unique identifier. * \return True if the program is cached already, false if it is not present. */ bool exists(const program_id& id) const; /** * \brief Get a program through its unique identifier. * \param id The program's unique identifier. * \return The program identified by the id. */ program_handle get_program(const program_id& id) const; }; /** * \brief A cache of materials. */ class material_cache { graphics_device& device_; std::vector<material> materials_; public: /** * \brief Create a new material cache object. * \param device The graphics device object to use. * \param initial_capacity The initial capacity of the texture cache. */ explicit material_cache(graphics_device& device, size_t initial_capacity = 0); /** * \brief Add a material to the material cache. * \param material The material you want to add to the cache. * \return The material id. */ material_handle add_material(material&& material); /** * \brief Get the material identified by its id. * \param handle The material id. * \return The material identified by the id. */ material* get_material(material_handle handle); /** * \brief Get the material identified by its id. * \param handle The material id. * \return The material identified by the id. */ const material* get_material(material_handle handle) const; }; /** * \brief Performs primitive-based rendering, creates resources, handles system-level variables, and creates shaders. */ class graphics_device { std::unique_ptr<graphics_api> graphics_api_; texture_cache textures_; program_cache shaders_; material_cache materials_; public: /** * \brief Get the texture cache. * \return The texture cache. */ texture_cache& get_texture_cache(); /** * \brief Get the texture cache. * \return The texture cache. */ const texture_cache& get_texture_cache() const; /** * \brief Get the program cache. * \return The program cache. */ program_cache& get_program_cache(); /** * \brief Get the program cache. * \return The program cache. */ const program_cache& get_program_cache() const; /** * \brief Get the material cache. * \return The material cache. */ material_cache& get_material_cache(); /** * \brief Get the material cache. * \return The material cache. */ const material_cache& get_material_cache() const; /** * \brief Create a graphics device object * \param window The window to attach to this graphics device * \param graphics_backend The graphics API to use with this graphics device */ explicit graphics_device(window& window, graphics_backend graphics_backend = graphics_backend::opengl); /** * \brief Create a new vertex buffer. * \param vertices The host memory buffer that will be used as vertex data. * \param size The size of the host vertex buffer. * \param layout The layout of the vertex data. * \param use A buffer usage hint. * \return A new vertex_buffer_handle representing an vertex buffer on the device. */ vertex_buffer_handle make_vertex_buffer( const void* vertices, size_t size, vertex_layout&& layout, buffer_usage use) const; /** * \brief Create a new index buffer. * \param indices The host memory buffer that will be used as index data. * \param size The size of the host index buffer. * \param type The layout of the index data. * \param use A buffer usage hint. * \return A new index_buffer_handle representing an index buffer on the device. */ index_buffer_handle make_index_buffer( const void* indices, size_t size, index_type type, buffer_usage use) const; /** * \brief Create a shader from source code. * \param type The type of shader you want to create. * \param source The source code of the shader you want to create. * \return A new shader_handle representing a shader on the device. */ shader_handle make_shader(shader_type type, const std::string& source) const; /** * \brief Create a shader program from vertex & fragment shaders. * \param vertex_handle The vertex shader that you want to link to this program. * \param fragment_handle The fragment shader that you want to link to this program. * \return A new program_handle representing a program on the device. */ program_handle make_program(shader_handle vertex_handle, shader_handle fragment_handle) const; /** * \brief Create a new texture. * \param data The host memory buffer that will be used as texture data. * \param metadata Metadata describing the texture data. * \param free_host_data If true, free the host memory after uploading to the device. Otherwise allow the calling code to free it. * \return A new texture_handle representing a texture on the device. */ texture_handle make_texture(const void** data, texture_metadata&& metadata, bool free_host_data) const; /** * \brief Create a texture builder object. * \return A new texture builder. */ texture_builder build_texture(); /** * \brief Create a new frame buffer. * \param render_textures An array of render_texture_data. * \param render_texture_count Size of the render_textures array. * \return A new frame_buffer_handle representing a frame buffer on the device. */ frame_buffer_handle make_frame_buffer(render_texture_data* render_textures, size_t render_texture_count) const; /** * \brief Create a frame buffer builder object. * \return A new frame buffer builder. */ frame_buffer_builder build_frame_buffer(); /** * \brief Create a material builder object. * \return A new material builder. */ material_builder build_material(); /** * \brief Destroy a program. * \param handle The program you want to destroy. */ void destroy(program_handle handle); /** * \brief Destroy a shader. * \param handle The shader you want to destroy. */ void destroy(shader_handle handle); /** * \brief Destroy a framebuffer. * \param handle The framebuffer you want to destroy. */ void destroy(frame_buffer_handle handle); /** * \brief Destroy a vertex buffer. * \param handle The vertex buffer you want to destroy. */ void destroy(vertex_buffer_handle handle); /** * \brief Destroy an index buffer. * \param handle The index buffer you want to destroy. */ void destroy(index_buffer_handle handle); /** * \brief Submit a command_list to execute on the device. * \param command_list The command_list you wish to run. * \param sort Sort the command list before submitting it to the graphics device. */ void submit(command_list&& command_list, bool sort = true) const; /** * \brief Submit a command_list to execute on the device. The main framebuffer will be * swapped after executing, advancing a frame. * \param command_list The command_list you wish to run. * \param sort Sort the command list before submitting it to the graphics device. */ void submit_and_swap(command_list&& command_list, bool sort = true) const; }; } // namespace moka
36.063712
144
0.629618
StuartDAdams
bc413d8227dd01daa4955f5696c24db69ce098c7
304
cpp
C++
DP/CountingBits.cpp
utkarshbajpai28/LeetCode-Solutions
58b3107f1cf3d1bf9f0686f0cb7f98684a34017a
[ "MIT" ]
33
2020-06-16T14:28:50.000Z
2021-06-21T14:35:39.000Z
DP/CountingBits.cpp
utkarshbajpai28/LeetCode-Solutions
58b3107f1cf3d1bf9f0686f0cb7f98684a34017a
[ "MIT" ]
1
2020-10-01T12:18:39.000Z
2020-10-01T12:18:39.000Z
DP/CountingBits.cpp
utkarshbajpai28/LeetCode-Solutions
58b3107f1cf3d1bf9f0686f0cb7f98684a34017a
[ "MIT" ]
18
2020-06-18T16:18:55.000Z
2021-05-19T18:41:50.000Z
class Solution { public: vector<int> countBits(int num) { vector<int> dp(num+1); dp[0] = 0; for(int i = 1; i <= num; i++ ) { if(i % 2 == 0) dp[i] = dp[i/2]; else dp[i] = dp[i-1]+1; } return dp; } };
20.266667
40
0.351974
utkarshbajpai28
bc4384e4e2d9d62b31fc500172fc6b755eac5bf1
1,873
hpp
C++
Hashing/HashAdaptor.hpp
jaredmulconry/HashingSupport
5f1b08b4a52be0ccd0181ef20adf1180fd8211a3
[ "MIT" ]
null
null
null
Hashing/HashAdaptor.hpp
jaredmulconry/HashingSupport
5f1b08b4a52be0ccd0181ef20adf1180fd8211a3
[ "MIT" ]
null
null
null
Hashing/HashAdaptor.hpp
jaredmulconry/HashingSupport
5f1b08b4a52be0ccd0181ef20adf1180fd8211a3
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <type_traits> #include <utility> namespace JMlib { namespace hashing { namespace detail { template<typename T> constexpr bool is_trivially_hashable() noexcept { return std::is_integral<T>::value || std::is_pointer<T>::value || std::is_enum<T>::value; } } template<typename T> struct is_contiguously_hashable_helper : public std::bool_constant<detail::is_trivially_hashable<T>()> { }; template<typename T> struct is_contiguously_hashable : public is_contiguously_hashable_helper<std::remove_cv_t<std::remove_reference_t<T>>> { }; template<typename T, std::size_t N> struct is_contiguously_hashable<T[N]> : public is_contiguously_hashable_helper<std::remove_cv_t<std::remove_reference_t<T>>> { }; template<typename T> struct is_contiguously_hashable<T[]> : public is_contiguously_hashable_helper<std::remove_cv_t<std::remove_reference_t<T>>> { }; template<typename H> void hash_append(H& hFunc, const void* p, std::size_t s) { hFunc(p, s); } template<typename H, typename T> std::enable_if_t < is_contiguously_hashable<T>::value > hash_append(H& hFunc, const T& i) { hash_append(hFunc, &i, sizeof(T)); } template<typename H> struct hash_functor { using result_type = std::size_t; template<typename U> std::size_t operator()(const U& d) const noexcept { H hasher; hash_append(hasher, d); return static_cast<std::size_t>(hasher); } }; } }
27.544118
132
0.561666
jaredmulconry
bc4423852f87de5ca14e664a04da09c318da795e
1,491
cpp
C++
2.Constructor&Destructor/i-Design/Q4/User.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
26
2021-03-17T03:15:22.000Z
2021-06-09T13:29:41.000Z
2.Constructor&Destructor/i-Design/Q4/User.cpp
Servatom/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
6
2021-03-16T19:04:05.000Z
2021-06-03T13:41:04.000Z
2.Constructor&Destructor/i-Design/Q4/User.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
42
2021-03-17T03:16:22.000Z
2021-06-14T21:11:20.000Z
#include <iostream> #include<string.h> using namespace std; class User{ private: string name; string userName; string password; public: User() { } User(string n,string un,string p) { name=n; userName=un; password=p; } void setName(string n) { name=n; } void setUserName(string un) { userName=un; } void setPassword(string p) { password=p; } string getName() { return name; } string getUserName() { return userName; } string getPassword() { return password; } User * getUserDetails(){ User *user = new User[5]; user[0]= User("Abi","Abinaya","abi123"); user[1]= User("Arun","Arunsoorya","arun456"); user[2]= User("Sbi","Sbiharan","sbi789"); user[3]= User("Sidhu","Siddarth","sid123"); user[4]= User("Vivi","viveka","vivi456"); return user; } //Fill code void display(string s) { if(s=="No") cout<<"Invalid username/password"; else cout<<"Hiii..."<<s<<" !! Welcome to the event!!! "; } friend string validate(string uname,string pword); };
22.938462
63
0.429913
Concept-Team
a4c00031cc6bea04fe54aebe8a65b12917d967bc
368
cpp
C++
Codeforces/A_Beautiful_year.cpp
Rakib1604060/Problem_Solving
0408ceff24834df9b3d2d9fddd8a56a5a9dc4592
[ "MIT" ]
null
null
null
Codeforces/A_Beautiful_year.cpp
Rakib1604060/Problem_Solving
0408ceff24834df9b3d2d9fddd8a56a5a9dc4592
[ "MIT" ]
null
null
null
Codeforces/A_Beautiful_year.cpp
Rakib1604060/Problem_Solving
0408ceff24834df9b3d2d9fddd8a56a5a9dc4592
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int year; cin>>year; int a,b,c,d; while(true){ year++; a=year%10; b=year/10%10; c=year/100%10; d=year/1000; if (a!=b&&a!=c&&a!=d&&b!=c&&b!=d&&c!=d) { break; } } cout<<year<<endl; return 0; }
13.142857
47
0.453804
Rakib1604060
a4c049da92f06e0e62934f8d8e7623ca8ed63616
3,022
cpp
C++
euhat/os/linux/EuhatChildWnd.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
euhat/os/linux/EuhatChildWnd.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
euhat/os/linux/EuhatChildWnd.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
#include "EuhatChildWnd.h" #include <gtk/gtk.h> static gboolean configureEventCb(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { EuhatChildWnd *pThis = (EuhatChildWnd *)data; if (NULL != pThis->surface_) cairo_surface_destroy(pThis->surface_); pThis->surface_ = gdk_window_create_similar_surface(gtk_widget_get_window(widget), CAIRO_CONTENT_COLOR, gtk_widget_get_allocated_width(widget), gtk_widget_get_allocated_height(widget)); pThis->clear(); return TRUE; } static gboolean drawCb(GtkWidget *widget, cairo_t *cr, gpointer data) { EuhatChildWnd *pThis = (EuhatChildWnd *)data; cairo_set_source_surface(cr, pThis->surface_, 0, 0); cairo_paint(cr); return FALSE; } static gboolean buttonPressEventCb(GtkWidget *widget, GdkEventButton *event, gpointer data) { EuhatChildWnd *pThis = (EuhatChildWnd *)data; if (NULL == pThis->surface_) return FALSE; if (event->button == GDK_BUTTON_PRIMARY) { pThis->xFrom_ = event->x; pThis->yFrom_ = event->y; pThis->drawBrush(widget, event->x, event->y); } else if (event->button == GDK_BUTTON_SECONDARY) { pThis->clear(); gtk_widget_queue_draw(widget); } return TRUE; } static gboolean motionNotifyEventCb(GtkWidget *widget, GdkEventMotion *event, gpointer data) { EuhatChildWnd *pThis = (EuhatChildWnd *)data; if (NULL == pThis->surface_) return FALSE; if (event->state & GDK_BUTTON1_MASK) pThis->drawBrush(widget, event->x, event->y); return TRUE; } EuhatChildWnd::EuhatChildWnd(int width, int height) { surface_ = NULL; xFrom_ = 0; yFrom_ = 0; drawingArea_ = gtk_drawing_area_new(); gtk_widget_set_size_request(drawingArea_, width, height); g_signal_connect(drawingArea_, "configure-event", G_CALLBACK(configureEventCb), this); g_signal_connect(drawingArea_, "draw", G_CALLBACK(drawCb), this); g_signal_connect(drawingArea_, "button-press-event", G_CALLBACK(buttonPressEventCb), this); g_signal_connect(drawingArea_, "motion-notify-event", G_CALLBACK(motionNotifyEventCb), this); gtk_widget_set_events(drawingArea_, gtk_widget_get_events(drawingArea_) | GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK); } EuhatChildWnd::~EuhatChildWnd() { if (NULL != surface_) cairo_surface_destroy(surface_); } void EuhatChildWnd::clear() { cairo_t *cr; cr = cairo_create(surface_); cairo_set_source_rgb(cr, 1, 1, 1); cairo_paint(cr); cairo_destroy(cr); } void EuhatChildWnd::drawBrush(GtkWidget *widget, gdouble x, gdouble y) { cairo_t *cr; cr = cairo_create(surface_); // cairo_rectangle(cr, x - 3, y - 3, 6, 6); // cairo_fill(cr); // cairo_draw_line(cr, xFrom_, yFrom_, x, y); cairo_set_source_rgb(cr, 1, 1, 1); cairo_paint(cr); cairo_set_source_rgb(cr, 0, 0, 0); cairo_set_line_width(cr, 1); cairo_move_to(cr, xFrom_, yFrom_); cairo_line_to(cr, x, yFrom_); cairo_line_to(cr, x, y); cairo_line_to(cr, xFrom_, y); cairo_line_to(cr, xFrom_, yFrom_); cairo_stroke(cr); cairo_destroy(cr); // gtk_widget_queue_draw_area(widget, x - 3, y - 3, 6, 6); gtk_widget_queue_draw(widget); }
24.176
186
0.742555
euhat
a4c382ee3838318ae38a166956f9fb31326acf7e
1,068
cpp
C++
tests/PhiCore/unittests/src/type_traits/to_safe.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
3
2020-12-21T13:47:35.000Z
2022-03-16T23:53:21.000Z
tests/PhiCore/unittests/src/type_traits/to_safe.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
53
2020-08-07T07:46:57.000Z
2022-02-12T11:07:08.000Z
tests/PhiCore/unittests/src/type_traits/to_safe.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
1
2020-08-19T15:50:02.000Z
2020-08-19T15:50:02.000Z
#include <phi/test/test_macros.hpp> #include "constexpr_helper.hpp" #include <phi/core/boolean.hpp> #include <phi/core/floating_point.hpp> #include <phi/core/integer.hpp> #include <phi/core/move.hpp> #include <phi/type_traits/to_safe.hpp> TEST_CASE("to_safe") { // boolean STATIC_REQUIRE((phi::to_safe(true) == phi::boolean(true))); CONSTEXPR_RUNTIME bool a = true; STATIC_REQUIRE((phi::to_safe(a) == phi::boolean(true))); STATIC_REQUIRE((phi::to_safe(phi::move(a)) == phi::boolean(true))); // integer STATIC_REQUIRE((phi::to_safe(3) == phi::integer<int>(3))); CONSTEXPR_RUNTIME int b = 21; STATIC_REQUIRE((phi::to_safe(b) == phi::integer<int>(21))); STATIC_REQUIRE((phi::to_safe(phi::move(b)) == phi::integer<int>(21))); // Floating Point STATIC_REQUIRE((phi::to_safe(3.0) >= phi::floating_point<double>(3.0))); CONSTEXPR_RUNTIME float c = 3.0; STATIC_REQUIRE((phi::to_safe(c) >= phi::floating_point<double>(3.0))); STATIC_REQUIRE((phi::to_safe(phi::move(c)) >= phi::floating_point<double>(3.0))); }
32.363636
85
0.667603
AMS21
a4c9f52e96233d81407e409c048a03ac31ac90b6
125,136
cpp
C++
foo_playlist_tree/foo_ui_playlist_tree.cpp
cwbowron/foobar2000-plugins
6ba30d7b3afc0ee85f5cc2903012c1dfcee132bd
[ "WTFPL" ]
13
2015-12-26T02:38:32.000Z
2021-08-24T17:08:50.000Z
foo_playlist_tree/foo_ui_playlist_tree.cpp
cwbowron/foobar2000-plugins
6ba30d7b3afc0ee85f5cc2903012c1dfcee132bd
[ "WTFPL" ]
null
null
null
foo_playlist_tree/foo_ui_playlist_tree.cpp
cwbowron/foobar2000-plugins
6ba30d7b3afc0ee85f5cc2903012c1dfcee132bd
[ "WTFPL" ]
5
2016-07-28T07:26:37.000Z
2021-12-07T05:20:23.000Z
#define VERSION ("3.0.5 [" __DATE__ " - " __TIME__ "]") #pragma warning(disable:4018) // don't warn about signed/unsigned #pragma warning(disable:4065) // don't warn about default case #pragma warning(disable:4800) // don't warn about forcing int to bool #pragma warning(disable:4244) // disable warning convert from t_size to int #pragma warning(disable:4267) #pragma warning(disable:4995) #pragma warning(disable:4311) #pragma warning(disable:4312) #pragma warning(disable:4996) #define URL_HELP "http://wiki.bowron.us/index.php/Foobar2000" #define URL_USER_MAP "http://www.frappr.com/playlisttreeusers" #define URL_CHANGELOG "http://foobar.bowron.us/changelog.txt" #define URL_BINARY "http://foobar.bowron.us/foo_playlist_tree.zip" #define URL_FORUM "http://bowron.us/smf/index.php" #define URL_WIKI "http://wiki.bowron.us/index.php/Playlist_Tree" #define DEFAULT_SORT_CRITERIA "$if(%_isleaf%,%artist%-%title%,%_name%)" #define DEFAULT_QUERY_FORMAT "%artist%|%album%|[$num(%tracknumber%,2) - ]%title%" #define DEFAULT_TRACK_FORMAT "%artist% - %title%" // #define DEFAULT_TRACK_FINDER "$upper($left(%artist%,1))|%artist%|%album%|[$num(%tracknumber%,2) - ]%title%\r\n$upper($left(%album%,1))|%album%|[$num(%tracknumber%,2) - ]%title%" #define DEFAULT_TEXT_COLOR RGB(0,0,0) #define DEFAULT_BACKGROUND_COLOR RGB(255,255,255) #define DEFAULT_LIBRARY_PLAYLIST "*Playlist Tree*" #define PLAYLIST_TREE_EXTENSION "pts" #define MENU_SEPARATOR 8000 #define NEWLINE "\r\n" #define CPP #include "../foobar2000/SDK/foobar2000.h" #include "../foobar2000/helpers/helpers.h" #include <commctrl.h> #include <shlwapi.h> #include <atlbase.h> #include <windows.h> #include <winuser.h> #include "resource.h" #include "../columns_ui-sdk/ui_extension.h" // #include "escheme.h" #include <sys/stat.h> #include "scheme.h" #define MY_EDGE_SUNKEN WS_EX_CLIENTEDGE #define MY_EDGE_GREY WS_EX_STATICEDGE #define MY_EDGE_NONE 0 enum { EE_NONE, EE_SUNKEN, EE_GREY }; char * g_edge_styles[] = { "None", "Sunken", "Grey", NULL }; #define CF_NODE CF_PRIVATEFIRST #include "guids.h" bool g_is_shutting_down = false; /// BEGIN scheme declarations Scheme_Env * g_scheme_environment = NULL; Scheme_Object * g_scheme_handle_type = NULL; Scheme_Object * g_scheme_node_type = NULL; bool g_scheme_installed = false; void scm_eval_startup(); void install_scheme_globals(); static Scheme_Object *eval_string_or_get_exn_message(char *s); /// END scheme declarations inline static LOGFONT get_def_font() { LOGFONT foo; uGetIconFont( &foo ); return foo; } enum { repop_new_track, repop_queue_change, repop_playlist_change, repop_playlists_change }; // int g_repop_playlist = 0; bool g_refresh_lock = false; //////////////////////// CONFIGURATION VARIABLES ///////////////////////////// static cfg_string cfg_file_format( var_guid004, DEFAULT_TRACK_FORMAT ); static cfg_string cfg_sort_criteria( var_guid005, DEFAULT_SORT_CRITERIA ); static cfg_string cfg_folder_display( var_guid006, "%_name%" ); static cfg_string cfg_query_display( var_guid007, DEFAULT_QUERY_FORMAT ); static cfg_string cfg_default_query_sort( var_guid010, "" ); static cfg_int cfg_back_color( var_guid011, RGB(255,255,255) ); static cfg_int cfg_line_color( var_guid012, RGB(0,0,0) ); static cfg_int cfg_text_color( var_guid013, RGB(0,0,0) ); static cfg_struct_t<LOGFONT> cfg_font( var_guid014, get_def_font() ); static cfg_string cfg_selection_action_1( var_guid015, "Browse" ); static cfg_string cfg_selection_action_2( var_guid016, "" ); static cfg_string cfg_doubleclick( var_guid017, "" ); static cfg_string cfg_library_playlist( var_guid018, DEFAULT_LIBRARY_PLAYLIST ); static cfg_int cfg_edge_style( var_guid019, EE_SUNKEN ); static cfg_int cfg_bitmaps_enabled( var_guid020, 1 ); static cfg_int cfg_bitmap_leaf( var_guid021, 0 ); static cfg_int cfg_bitmap_folder( var_guid022, 1 ); static cfg_int cfg_bitmap_query( var_guid023, 2 ); static cfg_string cfg_bitmaps_more( var_guid024, "" ); static cfg_int cfg_nohscroll( var_guid025, 0 ); static cfg_int cfg_hideroot( var_guid026, 0 ); static cfg_int cfg_hidelines( var_guid027, 0 ); static cfg_int cfg_hideleaves( var_guid028, 0 ); static cfg_int cfg_hidebuttons( var_guid029, 0 ); // static cfg_string cfg_tf_format( var_guid030, DEFAULT_TRACK_FINDER ); static cfg_string cfg_tf_action1( var_guid031, "Playlist Tree/Add to active playlist" ); static cfg_string cfg_tf_action2( var_guid032, "Playlist Tree/Send to active playlist" ); static cfg_string cfg_tf_action3( var_guid033, "Add to playback queue" ); static cfg_string cfg_tf_action4( var_guid034, "" ); static cfg_string cfg_tf_action5( var_guid035, "" ); static cfg_int cfg_repopulate_doubleclick( var_guid036, 0 ); static cfg_int cfg_bitmaps_loadsystem( var_guid037, 0 ); static cfg_string cfg_rightclick( var_guid038, "[local] foobar2000 Context Menu" ); static cfg_string cfg_rightclick_shift( var_guid039, "[local] Local Context Menu" ); static cfg_string cfg_middleclick( var_guid040, "[local] Local Context Menu" ); static cfg_int cfg_activate_library_playlist( var_guid041, 0 ); static cfg_int cfg_remove_last_playlist( var_guid042, 0 ); static cfg_string cfg_last_library( var_guid043, "" ); static cfg_string cfg_icon_path( var_guid044, "c:\\program files\\foobar2000\\icons" ); static cfg_int cfg_trackfinder_max( var_guid045, 4000 ); static cfg_string cfg_enter( var_guid046, "" ); static cfg_string cfg_space( var_guid047, "" ); static cfg_int cfg_process_keydown( var_guid048, 1 ); static cfg_int cfg_bother_user( var_guid049, 1 ); static cfg_int cfg_custom_colors( var_guid050, 0 ); static cfg_int cfg_color_selection_focused( var_guid051, RGB( 0, 0, 127 ) ); static cfg_int cfg_color_selection_nonfocused( var_guid052, RGB( 63, 63, 63 ) ); static cfg_int cfg_selection_action_limit( var_guid053, 5000 ); static cfg_int cfg_use_default_queries( var_guid054, 1 ); static cfg_int cfg_selection_text( var_guid055, CLR_DEFAULT ); static cfg_int cfg_selection_text_nofocus( var_guid056, CLR_DEFAULT ); static cfg_string cfg_export_prefix( var_guid057, "+" ); static cfg_string cfg_last_saved_playlist( var_guid058, "" ); static cfg_int cfg_panel_count( var_guid059, 0 ); static cfg_guid cfg_selection_action1_guid_command( var_guid060, pfc::guid_null ); static cfg_guid cfg_selection_action1_guid_subcommand( var_guid061, pfc::guid_null ); static cfg_guid cfg_selection_action2_guid_command( var_guid062, pfc::guid_null ); static cfg_guid cfg_selection_action2_guid_subcommand( var_guid063, pfc::guid_null ); static cfg_string cfg_scheme_startup( var_guid064, ";;; Insert any scheme code you want run on initialization" NEWLINE ); ///////////////////////////////////////////////////////////////////////////// metadb_handle_ptr g_silence_handle; static WNDPROC TreeViewProc; // FORWARD DECLARATIONS //////////////////////////////////////////////////// // classes class playlist_tree_panel; class node; class folder_node; class leaf_node; class query_node; // functions static bool useable_handle(metadb_handle_ptr handle); int inline shift_pressed() { return ::GetAsyncKeyState( VK_SHIFT ) & 0x8000; } node * load( pfc::string8 * out_name = NULL ); node * do_load_helper( const char * ); bool get_save_name( pfc::string_base & out_name, bool prompt_overwrite = false, bool open = false, bool as_text = false ); void lazy_set_root( HWND, node * ); void lazy_add_user_query( folder_node * n ); bool run_context_command( const char * cmd, pfc::list_base_const_t<metadb_handle_ptr> * handles, node * n = NULL, const GUID & guid_command = pfc::guid_null, const GUID & guid_subcommand = pfc::guid_null ); static int select_icon( HWND parent, HIMAGELIST image_list ); void mm_command_process( int p_index, node * n = NULL ); //void track_finder( const pfc::list_base_const_t<metadb_handle_ptr> & p_data ); void on_node_removing( node * ptr ); ///////////////////////////////////////////////////////////////////////////// pfc::ptr_list_t<node> g_tmp_node_storage; /* class NOVTABLE albumart_control_base : public service_base { public: virtual bool is_controllable()=0; virtual bool set_image(metadb_handle_ptr track)=0; virtual bool set_image()=0; virtual void redraw()=0; virtual void lock(bool l)=0; virtual bool is_locked()=0; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(albumart_control_base); }; */ /* class NOVTABLE albumart_control_bas e : public service_base { public: static GUID get_class_guid() { // {5549FA34-673C-4c5b-B6CE-5CDC4813E7B4} static const GUID guid = { 0x5549fa34, 0x673c, 0x4c5b, { 0xb6, 0xce, 0x5c, 0xdc, 0x48, 0x13, 0xe7, 0xb4 } }; return(guid); } static albumart_control_base* get() { service_enum_create_t<albumart_control_base> return(service_enum_create_t<albumart_control_base>); } virtual bool is_controllable()=0; virtual bool set_image(metadb_handle * track)=0; virtual bool set_image()=0; virtual void redraw()=0; virtual void lock(bool l)=0; virtual bool is_locked()=0; }; */ /* class NOVTABLE albumart_control_base : public service_base { public: static GUID get_class_guid() { // {5549FA34-673C-4c5b-B6CE-5CDC4813E7B4} static const GUID guid = { 0x5549fa34, 0x673c, 0x4c5b, { 0xb6, 0xce, 0x5c, 0xdc, 0x48, 0x13, 0xe7, 0xb4 } }; return(guid); } static albumart_control_base* get() { return(service_enum_create_t(albumart_control_base,0)); } virtual bool is_controllable()=0; virtual bool set_image(metadb_handle * track)=0; virtual bool set_image()=0; virtual void redraw()=0; virtual void lock(bool l)=0; virtual bool is_locked()=0; }; class albumart_control : public albumart_control_base { virtual bool is_controllable(); virtual bool set_image(metadb_handle * track); virtual bool set_image(); virtual void redraw(); virtual void lock(bool l); virtual bool is_locked(); }; */ // query source designators #define TAG_DROP "@drop" #define TAG_NODE "@node" #define TAG_PLAYLIST "@playlist" #define TAG_PLAYLISTS "@playlists" #define TAG_DATABASE "@database" #define TAG_QUEUE "@queue" // directives #define TAG_REFRESH "@refresh " #define TAG_NOSAVE "@nosave " #define TAG_FORCE "@force " #define TAG_NOBROWSE "@nobrowse " #define TAG_ICON "@icon" #define TAG_FORMAT "@format" #define TAG_GLOBALS "@globalformat" #define TAG_QUOTE "@quote" #define TAG_ANY "@any" #define TAG_MULTIPLE "@multiple" #define TAG_DEFAULT "@default" #define TAG_LIMIT "@limit" #define TAG_BROWSE_AS "@browse_as" #define TAG_HIDDEN "@hidden " #define TAG_HIDDEN2 "@hidden2 " #define TAG_HIDDEN3 "@hidden3 " #define TAG_IGNORE "@ignore " #define TAG_FAKELEVEL "@fakelevel " #define TAG_RGB "@rgb" // half assed functions #define TAG_PLAYING "$playing" #define TAG_FIRST "@first" #define TAG_SUM "@sum" #define TAG_AVG "@avg" #define TAG_PARENT_QUERY "@pquery" #define TAG_PARENT "@parent" #define TAG_QUERY "@query" #define TAG_NOSHOW "@noshow" // half assed variables #define TAG_DATETIME "%_datetime%" #define TAG_BROWSER_INDEX "%_browserindex%" #define TAG_NESTLEVEL "%_nestlevel%" #define TAG_SYSTEMDATE "%_systemdate%" #define META_QUERY_START "%<" #define META_QUERY_STOP ">%" /* struct { const char * name; const char * location; } g_favorites[] = { {"Jude - 430 N. Harper Ave.", "http://cdbaby.com/allmp3/jude1.m3u" }, {"Brian Vander Ark - Live at Schubas", "http://www.emusic.com/samples/m3u/album/10892082/0.m3u" }, {"Nathan Caswell - Missing You", "http://nathancaswell.com/meta/02missing_you.m3u"}, {"Mary Abraham - You Came Along", "http://maryabraham.com/YouCameAlone.mp3" }, {"The Verve Pipe - Colorful (Live from the Lounge)","http://www.thevervepipe.com/audio/livefromlounge/tvp_livefromlounge_colorful.mp3"}, }; */ node * g_context_node = NULL; bool g_has_been_active = false; class tree_titleformat_hook : public titleformat_hook { public: node * m_node; tree_titleformat_hook() {} tree_titleformat_hook( node * n ); void set_node( node * n ); virtual bool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) ; virtual bool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) ; }; tree_titleformat_hook * g_format_hook = NULL; class search_titleformatting_hook : public metadb_display_hook { public: node * m_node; search_titleformatting_hook() { m_node = NULL; } search_titleformatting_hook( node * n ) { m_node = n; } void set_node( node * n) { m_node = n; } virtual bool process_field(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) { if ( m_node ) { /* pfc::string8 s( p_name, p_name_length ); console::printf( "search_titleformatting_hook::process_field: %s", s.get_ptr() ); */ tree_titleformat_hook h( m_node ); return h.process_field( p_out, p_name, p_name_length, p_found_flag ); } return false; } virtual bool process_function(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) { if ( m_node ) { tree_titleformat_hook h( m_node ); return h.process_function( p_out, p_name, p_name_length, p_params, p_found_flag ); } return false; } }; service_factory_single_t<search_titleformatting_hook> g_search_hook; HIMAGELIST g_imagelist = NULL; void add_actions_to_hmenu( HMENU menu, int & baseID, pfc::ptr_list_t<pfc::string8> actions ) { for ( int n = 0; n < actions.get_count(); n++ ) { uAppendMenu( menu, MF_STRING, baseID, actions[n]->get_ptr() ); baseID++; } } void update_nodes_if_necessary(); #include "../common/string_functions.h" #include "tree_drop_source.h" #include "node.h" #include "query_node.h" #include "tree_drop_target.h" #include "sexp_reader.h" #include "../common/titleformatting_variable_callback.h" #include "playlist_tree_scheme.h" DECLARE_COMPONENT_VERSION( "Playlist Tree Panel", VERSION, "Media Library Manager using Trees\n" "By Christopher Bowron <chris@bowron.us>\n" "http://wiki.bowron.us/index.php/Foobar2000" "\n" "\n" "Playlist Tree uses MzScheme which has the following license:\n" "Copyright (C) 1995-2006 Matthew Flatt\n" "Permission is granted to copy, distribute and/or modify this document\n" "under the terms of the GNU Library General Public License, Version 2\n" "published by the Free Software Foundation. A copy of the license is\n" "included in the appendix entitled ``License.''\n" "\n" "libscheme: Copyright (C)1994 Brent Benson. All rights reserved.\n" "\n" "Conservative garbage collector: Copyright (C)1988, 1989 Hans-J. Boehm,\n" "Alan J. Demers. Copyright (C)1991-1996 by Xerox Corporation. Copyright\n" "(C)1996-1999 by Silicon Graphics. Copyright (C)1999-2001 by Hewlett Packard\n" "Company. All rights reserved.\n" "\n" "Collector C++ extension by Jesse Hull and John Ellis: Copyright (C)1994\n" "by Xerox Corporation. All rights reserved.\n" ) pfc::ptr_list_t<node> g_nodes_to_update; void update_nodes_if_necessary() { for ( int i = 0; i<g_nodes_to_update.get_count(); i++) { g_nodes_to_update[i]->repopulate(); g_nodes_to_update[i]->refresh_tree_label(); g_nodes_to_update[i]->refresh_subtree( NULL ); if ( g_nodes_to_update[i]->m_hwnd_tree ) { SetFocus( g_nodes_to_update[i]->m_hwnd_tree ); } } g_nodes_to_update.remove_all(); } // update parent queries if necessary void update_drop_watchers( node * target, const metadb_handle_list & list ) { g_refresh_lock = true; node * ptr = target; while ( ptr ) { if ( ptr->is_query() ) { query_node * qn = (query_node *) ptr; if ( qn->m_refresh_on_new_track ) { if ( strstr( qn->m_source, TAG_QUEUE ) ) { static_api_ptr_t<playlist_manager> pm; for ( int i = 0; i < list.get_count(); i++ ) { pm->queue_add_item( list[i] ); } g_nodes_to_update.add_item( qn ); } if ( strstr( qn->m_source, TAG_PLAYLIST ) ) { pfc::string8 playlist; if ( string_get_function_param( playlist, qn->m_source, TAG_PLAYLIST ) ) { static_api_ptr_t<playlist_manager> pm; t_size np = pm->find_playlist( playlist, ~0 ); if ( np != infinite ) { bit_array_false f; pm->playlist_add_items( np, list, f ); } g_nodes_to_update.add_item( qn ); } } } } ptr = ptr->get_parent(); } g_refresh_lock = false; } /* static componentversion_impl_simple_factory g_componentversion_service2( "Track Finder", TF_VERSION, "Find Tracks Quickly By Artist or Album Names\n" "By Christopher Bowron <chris@bowron.us>\n" "http://wiki.bowron.us/index.php/Foobar2000" ); */ enum {DROP_BEFORE = -1, DROP_HERE = 0, DROP_AFTER = 1}; class tree_drop_target; bool ask_about_user_map( HWND parent ) { bool result = false; if ( cfg_bother_user ) { if ( MessageBox( parent, _T("If you enjoy using playlist tree, please consider adding ") _T("yourself to the playlist tree user map. Consider it a very cheap ") _T("form of registering. I would appreciate it. ") _T("This message will not pop up again. Thank you - cwbowron ") _T("\n\nHit yes to go to launch user map url, no to skip"), _T("foo_playlist_tree"), MB_YESNO ) == IDYES ) { ShellExecute(NULL, _T("open"), _T(URL_USER_MAP), NULL, NULL, SW_SHOWNORMAL ); result = true; } cfg_bother_user = 0; } return result; } static bool useable_handle(metadb_handle_ptr handle) { /* if ( handle.is_valid() ) return true; */ if ( handle->is_info_loaded() ) return true; static_api_ptr_t<metadb_io> db_io; db_io->load_info( handle, metadb_io::load_info_default, NULL, false ); if ( handle->get_length() > 0.00 ) return true; if ( strstr(handle->get_path(),"http" ) ) return true; console::printf( "Unusable Handle: %s", handle->get_path() ); return false; } node * get_selected_node( HWND tree ) { HTREEITEM item = TreeView_GetSelection( tree ); TVITEMEX tv; memset( &tv, 0, sizeof(tv) ); tv.hItem = item; tv.mask = TVIF_PARAM; TreeView_GetItem( tree, &tv ); return (node*)tv.lParam; } node * node::add_child_query_conditional( const char *s1, const char *s2, const char *s3, const char *s4, const char *s5 ) { folder_node * as_folder = (folder_node *) this; if ( !s1 ) return NULL; if ( !s2 ) return NULL; for ( int n = 0; n < as_folder->get_num_children(); n++ ) { if ( as_folder->m_children[n]->is_query() ) { query_node * q = (query_node *) as_folder->m_children[n]; // this query already exists if ( ( strcmp( q->m_label, s1 ) == 0 ) && ( strcmp( q->m_query_criteria, s2 ) == 0 ) ) { return NULL; } } } return add_child( new query_node( s1, false, s2, s3, s4, s5 ) ); } node * node::add_delimited_child( const char *strings, metadb_handle_ptr handle ) { const char *car = strings; const char *cdr = strings + strlen( strings ) + 1; if ( !*cdr ) { if ( strstr( car, TAG_QUERY ) ) { pfc::string8 s = car; pfc::string8 p; pfc::ptr_list_t<pfc::string8> params; string_get_function_param( p, s, TAG_QUERY ); string_split( p, ";", params ); int n = params.get_count(); node *q = add_child_query_conditional( ( n >= 1 ) ? params[0]->get_ptr() : NULL, ( n >= 2 ) ? params[1]->get_ptr() : NULL, ( n >= 3 ) ? params[2]->get_ptr() : NULL, ( n >= 4 ) ? params[3]->get_ptr() : NULL, ( n >= 5 ) ? params[4]->get_ptr() : NULL ); if ( q ) { q->repopulate(); } return q; } else { if ( can_add_child() ) { return add_child( new leaf_node( car, handle ) ); } else { return NULL; } } } else { node *n = add_child_conditional( car ); if ( !n ) { return NULL; } return n->add_delimited_child( cdr, handle ); } } node * node::process_dropped_file( const char * file, bool do_not_nest, int index, bool dynamic, metadb_handle_list * handles ) { node *ret_val = NULL; if ( dynamic ) { query_node * q = new query_node( pfc::string_filename(file), false, pfc::string_printf( "@drop<%s>", file ), NULL, "@default", NULL ); if ( q ) { add_child( q, index ); q->repopulate(); q->refresh_subtree(); } return q; } pfc::string_extension s_ext( file ); if ( PathIsDirectory( pfc::stringcvt::string_wide_from_utf8( file ))) { pfc::string8 stufferoo = file; stufferoo += "\\*.*"; uFindFile *find_file = uFindFirstFile( stufferoo ); if ( do_not_nest ) { ret_val = this; } else { ret_val = add_child( new folder_node( pfc::string_filename_ext( file ) ), index ); } pfc::string8 as_utf8; pfc::ptr_list_t<const char> file_list; do { const char *file_name = find_file->GetFileName(); as_utf8 = file; as_utf8 += "\\"; as_utf8 += file_name; if ( !is_dotted_directory( file_name ) ) { ret_val->process_dropped_file( as_utf8 ); } } while ( find_file->FindNext() ); } else if ( strcmp( s_ext, PLAYLIST_TREE_EXTENSION ) == 0) { ret_val = add_child( do_load_helper( file ) ); } else { abort_callback_impl abort; playlist_loader_callback_impl loader( abort ); //playlist_loader::g_process_path( file, loader ); playlist_loader::g_process_path_ex( file, loader ); //console::printf( "Processing: %s [%d items]", (const char *) file, loader.get_count() ); if ( loader.get_count() == 1 ) { if ( useable_handle( loader[0] ) ) { ret_val = add_child( new leaf_node( NULL, loader.get_item( 0 ) ), index ); if ( handles ) { handles->add_item( loader[0] ); } } } else { if ( do_not_nest ) { for ( int i = 0; i < loader.get_count(); i++ ) { if ( useable_handle( loader.get_item( i ) ) ) { ret_val = add_child( new leaf_node( NULL, loader.get_item( i ) ), index ); if ( handles ) { handles->add_item( loader[i] ); } } } } else { ret_val = add_child( new folder_node( pfc::string_filename_ext(file), false ), index ); for ( int i = 0; i < loader.get_count(); i++ ) { if ( useable_handle( loader.get_item( i ) ) ) { //ret_val = add_child( new leaf_node( NULL, loader.get_item( i ) ), index ); ret_val->add_child( new leaf_node( NULL, loader.get_item( i ) ) ); if ( handles ) { handles->add_item( loader[i] ); } } } } } return ret_val; } return ret_val; } static const GUID guid_playlist_tree_panel = { 0x9c0b7ddc, 0xeb75, 0x4bd0, { 0xad, 0xfb, 0x99, 0xa8, 0x9b, 0xc7, 0x77, 0x9f } }; bool is_valid_htree( HTREEITEM item ) { if ( item == 0 ) { return false; } if ( item == TVI_ROOT ) { return false; } return true; } pfc::ptr_list_t<playlist_tree_panel> g_active_trees; playlist_tree_panel * g_last_active_tree = NULL; typedef BOOL (WINAPI * SH_GIL_PROC)(HIMAGELIST *phLarge, HIMAGELIST* fophSmall); typedef BOOL (WINAPI * FII_PROC) (BOOL fFullInit); void get_default_file_names( int n, pfc::string_base & out ) { pfc::string_printf foo( "%s\\playlist-tree-%d.pts", core_api::get_profile_path(), n ) ; filesystem::g_get_display_path( foo, out ); } class node_titleformatting_hook : public metadb_display_hook { public: virtual bool process_field(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag); virtual bool process_function(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag); }; static service_factory_single_t<node_titleformatting_hook> g_node_hook; class playlist_tree_panel : public ui_extension::window { public: HWND m_wnd; HIMAGELIST m_imagelist; pfc::string8 m_file; bool m_has_been_asked; HFONT m_font; bool m_was_active; bool LoadSystemBitmaps() { HMODULE hShell32; SH_GIL_PROC Shell_GetImageLists; FII_PROC FileIconInit; HIMAGELIST hLarge; HIMAGELIST hSmall; // Load SHELL32.DLL, if it isn't already hShell32 = LoadLibrary(_T("shell32.dll")); if ( hShell32 == 0 ) { return false; } // // Get Undocumented APIs from Shell32.dll: // Shell_GetImageLists = (SH_GIL_PROC) GetProcAddress( hShell32, (LPCSTR)71 ); FileIconInit = (FII_PROC) GetProcAddress( hShell32, (LPCSTR)660 ); if ( FileIconInit != 0 ) { FileIconInit( TRUE ); } if ( Shell_GetImageLists == 0 ) { FreeLibrary( hShell32 ); return false; } Shell_GetImageLists( &hLarge, &hSmall ); if ( hSmall ) { for ( int n = 0; n < ImageList_GetImageCount( hSmall ); n++ ) { HICON icon = ImageList_GetIcon( hSmall, n, ILD_NORMAL ); ImageList_AddIcon( m_imagelist, icon ); DestroyIcon( icon ); } FreeLibrary( hShell32 ); return true; } FreeLibrary( hShell32 ); return false; } void load_foobar2000_icons( HWND tree ) { const char * fb_path = cfg_icon_path; pfc::string8 icon_path = fb_path; icon_path.add_string ( "\\*.ico" ); uFindFile *find_file = uFindFirstFile( icon_path ); if ( find_file ) { do { pfc::string8_fastalloc fullpath; const char *file_name = find_file->GetFileName(); fullpath.set_string( fb_path ); fullpath.add_string( "\\" ); fullpath.add_string( file_name ); HICON hi = (HICON)uLoadImage( NULL, fullpath, IMAGE_ICON, 16, 16, LR_LOADFROMFILE ); if ( hi ) { ImageList_AddIcon( m_imagelist, hi ); DestroyIcon( hi ); } } while ( find_file->FindNext() ); } } void LoadBitmaps( HWND tree_hwnd ) { HBITMAP bitmap = (HBITMAP)LoadImage( core_api::get_my_instance(), MAKEINTRESOURCE(IDB_BITMAPS), IMAGE_BITMAP, 0, 0, LR_LOADTRANSPARENT ); /* if ( cfg_bitmaps_loadsystem ) { LoadSystemBitmaps(); } */ if ( m_imagelist == NULL ) { m_imagelist = ImageList_Create(16,16, ILC_MASK|ILC_COLOR8, 10, 10); } ImageList_AddMasked( m_imagelist, bitmap, CLR_DEFAULT ); DeleteObject( bitmap ); if ( !cfg_icon_path.is_empty() ) { load_foobar2000_icons( tree_hwnd ); } if ( !cfg_bitmaps_more.is_empty() ) { pfc::ptr_list_t<pfc::string8> bitmap_files; string_split( cfg_bitmaps_more, NEWLINE, bitmap_files ); for ( int n = 0; n < bitmap_files.get_count(); n++ ) { pfc::stringcvt::string_wide_from_utf8 file_path( bitmap_files[n]->get_ptr() ); HBITMAP bitmap = (HBITMAP)LoadImage( core_api::get_my_instance(), (const wchar_t *) file_path, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_LOADTRANSPARENT ); if ( bitmap ) { ImageList_AddMasked( m_imagelist, bitmap, CLR_DEFAULT ); DeleteObject(bitmap); } } } LoadSystemBitmaps(); HIMAGELIST rc = TreeView_SetImageList( tree_hwnd, m_imagelist, TVSIL_NORMAL ); } static LRESULT CALLBACK TreeViewHook( HWND wnd, UINT msg, WPARAM wp, LPARAM lp ) { switch(msg) { case WM_SETFOCUS: if ( wnd ) { g_last_active_tree = g_find_by_tree( wnd ); post_variable_callback_notification( "treenode" ); } break; case WM_KILLFOCUS: post_variable_callback_notification( "treenode" ); break; case WM_KEYDOWN: { LPNMTVKEYDOWN pnkd = (LPNMTVKEYDOWN) lp; HTREEITEM item = TreeView_GetSelection( wnd ); TVITEMEX tv; memset( &tv, 0, sizeof(tv) ); tv.hItem = item; tv.mask = TVIF_PARAM; TreeView_GetItem( wnd, &tv ); if ( tv.lParam ) { metadb_handle_list selected_handles; node * n = (node *) tv.lParam; n->get_entries( selected_handles ); if ( wp == VK_RETURN && !cfg_enter.is_empty() ) { //console::printf( "Return" ); run_context_command( cfg_enter, &selected_handles, n ); return 0; } else if ( wp == VK_SPACE && !cfg_space.is_empty() ) { //console::printf( "Space" ); run_context_command( cfg_space, &selected_handles, n ); return 0; } else if ( cfg_process_keydown ) { static_api_ptr_t<keyboard_shortcut_manager> man; man->on_keydown_auto_context( selected_handles, wp, guid_playlist_tree_panel ); } } } break; case WM_MBUTTONDOWN: { playlist_tree_panel * p = g_find_by_tree( wnd ); if ( p ) { POINT pt; pt.x = LOWORD(lp); pt.y = HIWORD(lp); ClientToScreen( wnd, &pt ); node * n = p->find_node_by_pt( pt.x, pt.y, false ); if ( n ) { if ( n->m_tree_item ) TreeView_SelectDropTarget( wnd, n->m_tree_item ); run_context_command( cfg_middleclick, NULL, n ); TreeView_SelectDropTarget( wnd, NULL ); } } } return 0; case WM_LBUTTONDBLCLK: { node * n = g_find_node_by_client_pt( wnd, LOWORD(lp), HIWORD(lp) ); /* service_ptr_t<albumart_control_base> aa = service_enum_create_t<albumart_control_base,0>; if ( aa ) { if ( n ) { metadb_handle_ptr h; n->get_first_entry( h ); } } else { console::printf( "Albumart Service Not Found" ); } */ if ( n ) { metadb_handle_list selected_handles; if ( cfg_repopulate_doubleclick ) { if ( n->is_query() ) { ((query_node*)n)->repopulate(); n->refresh_subtree( n->m_hwnd_tree ); } } n->get_entries( selected_handles ); run_context_command( cfg_doubleclick, NULL, n ); } } return true; } return uCallWindowProc( TreeViewProc, wnd, msg, wp, lp ); } static BOOL CALLBACK dialog_proc( HWND wnd, UINT msg, WPARAM wp, LPARAM lp ) { switch ( msg ) { /* case WM_MENUSELECT: { console::printf( "WM_SELECT" ); int item = LOWORD(wp); int flags = HIWORD(wp); if ( flags & MF_POPUP ) { pfc::string8 label; uGetMenuString( (HMENU)lp, item, label, MF_BYPOSITION ); console::printf( "MF_POPUP: %s", (const char *) label ); // uAppendMenu( GetSubMenu( (HMENU)lp, item ), MF_STRING, 1000, "w00t" ); } else { pfc::string8 label; uGetMenuString( (HMENU)lp, item, label, MF_BYCOMMAND ); console::printf( "not popup: %s", (const char *)label ); } } break; */ case WM_INITDIALOG: { playlist_tree_panel *panel = (playlist_tree_panel *)lp; HWND tree = GetDlgItem( wnd, IDC_TREE); // console::printf( "TREE: %d", (int) tree ); if ( cfg_bitmaps_enabled ) { panel->LoadBitmaps( tree ); } if ( g_last_active_tree == NULL ) { g_last_active_tree = panel; } TreeViewProc = uHookWindowProc( tree, TreeViewHook ); } break; case WM_SIZE: { RECT r; HWND tree = GetDlgItem( wnd, IDC_TREE ); // console::printf( "TREE: %d", (int) tree ); GetWindowRect( wnd, &r ); SetWindowPos( tree, 0, 0, 0, r.right-r.left, r.bottom-r.top, SWP_NOZORDER ); } break; case WM_NOTIFY: { LPNMHDR hdr = (LPNMHDR)lp; if ( hdr->idFrom == IDC_TREE ) { switch ( hdr->code ) { case NM_CUSTOMDRAW: { if ( cfg_custom_colors ) { LPNMTVCUSTOMDRAW lptvcd = (NMTVCUSTOMDRAW *)lp; switch ( lptvcd->nmcd.dwDrawStage ) { case CDDS_PREPAINT: SetWindowLong( wnd, DWL_MSGRESULT, CDRF_NOTIFYITEMDRAW ); return TRUE; case CDDS_ITEMPREPAINT: { if ( lptvcd->nmcd.lItemlParam ) { node * n = (node *) lptvcd->nmcd.lItemlParam; lptvcd->clrText = cfg_text_color; if ( TVIS_DROPHILITED & TreeView_GetItemState( hdr->hwndFrom, lptvcd->nmcd.dwItemSpec, TVIS_DROPHILITED ) ) { lptvcd->clrTextBk = cfg_color_selection_focused; if ( cfg_selection_text != CLR_DEFAULT ) { lptvcd->clrText = cfg_selection_text; } } else if ( lptvcd->nmcd.uItemState & CDIS_FOCUS ) { lptvcd->clrTextBk = cfg_color_selection_focused; if ( cfg_selection_text != CLR_DEFAULT ) { lptvcd->clrText = cfg_selection_text; } } else if ( lptvcd->nmcd.uItemState & CDIS_SELECTED ) { lptvcd->clrTextBk = cfg_color_selection_nonfocused; if ( cfg_selection_text_nofocus != CLR_DEFAULT ) { lptvcd->clrText = cfg_selection_text_nofocus; } } else { lptvcd->clrTextBk = cfg_back_color; } if ( n->m_custom_color != CLR_DEFAULT ) { lptvcd->clrText = n->m_custom_color; } SetWindowLong( wnd, DWL_MSGRESULT, CDRF_DODEFAULT ); return TRUE; } } break; } } return FALSE; } break; case TVN_ITEMEXPANDED: SendMessage( hdr->hwndFrom, WM_SETREDRAW, TRUE, 0 ); break; case TVN_ITEMEXPANDING: { SendMessage( hdr->hwndFrom, WM_SETREDRAW, FALSE, 0 ); LPNMTREEVIEW param = (LPNMTREEVIEW)hdr; folder_node *foop = (folder_node*)param->itemNew.lParam; if ( foop ) { if ( param->action & TVE_EXPAND ) { foop->m_expanded = true; if ( foop->get_num_children() > 0 ) { foop->m_children[0]->ensure_in_tree(); } } else if ( param->action & TVE_COLLAPSE ) { foop->m_expanded = false; } } return 0; } break; case TVN_SELCHANGED: { LPNMTREEVIEW param = (LPNMTREEVIEW)hdr; if ( param->action != TVC_UNKNOWN ) { node *n = (node *) param->itemNew.lParam; if ( n ) { n->select(); } } } break; case TVN_BEGINDRAG: { static long dragging = -1; if ( InterlockedIncrement( &dragging ) == 0 ) { NMTREEVIEWW *info = (NMTREEVIEW *) lp; node * n = (node *)info->itemNew.lParam; if ( n ) { playlist_tree_panel * p = g_find_by_tree( hdr->hwndFrom ); if ( p ) { n->do_drag_drop( p, shift_pressed() ); update_nodes_if_necessary(); } } InterlockedDecrement( &dragging ); } } break; } } } break; case WM_CONTEXTMENU: { POINT pt = {(short)LOWORD(lp),(short)HIWORD(lp)}; if ( pt.x == -1 || pt.y == -1 ) { node * n = g_last_active_tree->get_selection(); TreeView_SelectDropTarget( n->m_hwnd_tree, n->m_tree_item ); n->do_context_menu(); TreeView_SelectDropTarget( n->m_hwnd_tree, NULL ); return true; } TVHITTESTINFO ti; memset( &ti, 0, sizeof(ti) ); ti.pt.x = (short)LOWORD(lp); ti.pt.y = (short)HIWORD(lp); ScreenToClient( GetDlgItem( wnd, IDC_TREE), &ti.pt ); TreeView_HitTest( GetDlgItem( wnd, IDC_TREE ), &ti ); if ( ti.hItem && ( ti.flags & TVHT_ONITEM ) ) { TVITEMEX item; memset( &item, 0, sizeof( item ) ); item.hItem = ti.hItem; item.mask = TVIF_PARAM; TreeView_GetItem( GetDlgItem( wnd, IDC_TREE ), &item ); if ( item.lParam ) { node * n = (node *)item.lParam; TreeView_SelectDropTarget( n->m_hwnd_tree, n->m_tree_item ); //n->do_context_menu( &pt ); if ( shift_pressed() ) { run_context_command( cfg_rightclick_shift, NULL, n ); } else { run_context_command( cfg_rightclick, NULL, n ); } TreeView_SelectDropTarget( n->m_hwnd_tree, NULL ); } } else { playlist_tree_panel * p = g_find_by_hwnd( wnd ); if ( p ) { p->do_context_menu( &pt ); } } return true; } } return false; } public: ui_extension::window_host_ptr m_host; folder_node * m_root; tree_drop_target * m_drop_target; playlist_tree_panel() { m_wnd = NULL; m_root = NULL; m_drop_target = new tree_drop_target( this ); m_font = NULL; m_has_been_asked = false; m_imagelist = NULL; m_was_active = false; } virtual ~playlist_tree_panel() { delete m_drop_target; if ( m_font ) { DeleteObject( m_font ); m_font = NULL; } if ( m_imagelist ) { ImageList_Destroy( m_imagelist ); m_imagelist = NULL; } /* if ( m_was_active ) { uMessageBox( NULL, "~playlist_tree_panel", "PT", MB_OK ); } */ } unsigned get_type() const { return ui_extension::type_panel; } void destroy_window() { //uMessageBox( NULL, "destroy_window", "PT", MB_OK ); if ( g_last_active_tree == this ) { g_last_active_tree = NULL; } // MessageBox( NULL, _T("destroy_window"), _T("Debug"), MB_OK ); /* if ( !m_file.is_empty() ) { pfc::stringcvt::string_wide_from_utf8 wide_file( m_file ); FILE * f = _wfopen( wide_file, _T("w+") ); if ( f ) { m_root->write( f, 0 ); } else { if ( IDYES == MessageBox( NULL, _T("Error writing file. Would you like to select another file?"), _T("Playlist Tree"), MB_YESNO ) ) { m_root->save( &m_file ); } } } else { shutting_down(); } */ g_active_trees.remove_item( this ); // dialog_proc( m_wnd, WM_DESTROY, 0, 0 ); DestroyWindow( m_wnd ); if ( g_is_shutting_down ) { delete m_root; } else { g_tmp_node_storage.add_item( m_root ); } m_root = NULL; m_wnd = NULL; if ( g_active_trees.get_count() == 0 ) { g_silence_handle = NULL; } } void get_category( pfc::string_base & out ) const { out.set_string( "Panels" ); } virtual bool get_description( pfc::string_base & out ) const { out.set_string( "Playlist Tree Panel" ); return true; } virtual bool get_short_name( pfc::string_base & out ) const { out.set_string( "Playlist Tree" ); return true; } virtual void get_name( pfc::string_base & out ) const { out.set_string( "Playlist Tree Panel" ); } const GUID & get_extension_guid() const { return guid_playlist_tree_panel; } void get_size_limits( ui_extension::size_limit_t & p_out ) const { p_out.min_height = 30; p_out.min_width = 30; } virtual HWND get_wnd() const { return m_wnd; } virtual HWND get_tree( HWND wnd = NULL ) { if ( wnd ) { return GetDlgItem( wnd, IDC_TREE ); } else { return GetDlgItem( m_wnd, IDC_TREE ); } } virtual bool is_available( const ui_extension::window_host_ptr & p_host) const { return ( m_wnd == NULL ); } virtual bool search( const char * in ) { static node * last_search_result = NULL; static pfc::string8_fastalloc last_search_string; static playlist_tree_panel * last_tree = NULL; if ( in == NULL ) { last_search_result = NULL; last_search_string.reset(); last_tree = NULL; return true; } node * start; if ( last_tree == this && strcmp( last_search_string, in ) == 0 ) { if ( last_search_result == NULL ) return false; start = last_search_result->iterate_next(); } else { start = m_root; last_search_string = in; last_tree = this; } search_tools::search_filter filt; filt.init( in ); bool search_by_node = true; #define SEARCH_BY_NODE #ifdef SEARCH_BY_NODE // get a random handle to cheat and use as the formatting handle // if the handle matches the search, then dont search folders // because it cannot be a folder search anywho... static_api_ptr_t<metadb> db; metadb_handle_ptr random_handle; if ( db->g_get_random_handle( random_handle ) ) { if ( filt.test( random_handle ) ) { console::printf( "random handle matches, ignoring folders in search" ); search_by_node = false; } } else { search_by_node = false; } #endif while ( start ) { if ( start->is_leaf() ) { leaf_node *lf = (leaf_node*) start; if ( filt.test( lf->m_handle ) ) { console::printf( "Search Result: %s", (const char *) lf->m_label ); last_search_result = lf; lf->ensure_in_tree(); TreeView_SelectItem( lf->m_hwnd_tree, lf->m_tree_item ); return true; } } #ifdef SEARCH_BY_NODE else if ( search_by_node ) { bool match = false; if ( strstr( start->m_label, in ) ) { match = true; } if ( !match ) { g_search_hook.get_static_instance().set_node( start ); //service_ptr_t<search_titleformatting_hook> search_hook = // new service_impl_t<search_titleformatting_hook>(start); if ( filt.test( random_handle ) ) { match = true; } g_search_hook.get_static_instance().set_node( NULL ); } if ( match ) { console::printf( "Search Result: %s", (const char *) start->m_label ); last_search_result = start; start->ensure_in_tree(); TreeView_SelectItem( start->m_hwnd_tree, start->m_tree_item ); return true; } } #endif start = start->iterate_next(); } return false; } virtual void setup_tree() { TreeView_DeleteAllItems( get_tree() ); if ( m_root ) { if ( cfg_hideroot ) { m_root->m_hwnd_tree = get_tree(); m_root->m_tree_item = TVI_ROOT; m_root->setup_children_trees( get_tree() ); } else { m_root->setup_tree( get_tree(), TVI_ROOT ); } } } virtual HWND create_or_transfer_window( HWND wnd_parent, const ui_extension::window_host_ptr & p_host, const ui_helpers::window_position_t & p_position ) { // console::printf( "create_or_transfer_window" ); g_has_been_active = true; m_was_active = true; if ( g_silence_handle.is_empty() ) { static_api_ptr_t<metadb>()->handle_create( g_silence_handle, make_playable_location( "silence://1", 0 )); } if ( !g_format_hook ) { g_format_hook = new tree_titleformat_hook(); } if ( m_wnd ) { ShowWindow( m_wnd, SW_HIDE ); SetParent( get_wnd(), wnd_parent ); SetWindowPos( get_wnd(), NULL, p_position.x, p_position.y, p_position.cx, p_position.cy, SWP_NOZORDER ); m_host->relinquish_ownership( get_wnd() ); } else { m_host = p_host; m_wnd = uCreateDialog( IDD_BLANK, wnd_parent, dialog_proc, (LPARAM)this ); RegisterDragDrop( get_wnd(), m_drop_target ); // console::printf( "Creating playlist tree panel with this: %d", (int) this ); g_active_trees.add_item( this ); update_appearance(); if ( g_tmp_node_storage.get_count() > 0 ) { m_root = (folder_node*)g_tmp_node_storage[0]; g_tmp_node_storage.remove_by_idx( 0 ); setup_tree(); } else { int n = g_active_trees.get_count() - 1; pfc::string8 filename; get_default_file_names( n, filename ); if ( uFileExists( filename ) ) { m_root = (folder_node*) do_load_helper( filename ); setup_tree(); } } #if 0 if ( m_file.is_empty() ) { pfc::string_printf foo( "%s\\playlist-tree-%d.pts", core_api::get_profile_path(), /* (int) cfg_panel_count */ g_find( this ) ) ; filesystem::g_get_display_path( foo, m_file ); cfg_panel_count = cfg_panel_count + 1; m_has_been_asked = true; console::printf( "Playlist Tree: No file information stored, using default: %s", (const char *) m_file ); /* if ( !cfg_last_saved_playlist.is_empty() ) { pfc::string_printf msg("Would you like to restore your last saved playlist tree file? (%s)", (const char *)cfg_last_saved_playlist ); if ( IDYES == uMessageBox( m_wnd, msg, "Restore Playlist Tree?", MB_YESNO ) ) { m_file = cfg_last_saved_playlist; } } */ } else // if ( !m_file.is_empty() ) { node * n = do_load_helper( m_file ); if ( n ) { m_root = dynamic_cast<folder_node*>( n ); setup_tree(); } else { console::warning( pfc::string_printf( "Error reading save / restore file %s", (const char *) m_file ) ); m_file.reset(); } } #endif } if ( !m_root ) { m_root = new folder_node( "Playlist Tree", true ); if ( cfg_use_default_queries ) { m_root->add_child( new query_node( "Playlists", false, TAG_PLAYLISTS, NULL, DEFAULT_QUERY_FORMAT, NULL, true ) ); m_root->add_child( new query_node( "by artist", false, "@database", "NOT artist MISSING", DEFAULT_QUERY_FORMAT, "@default", true ) ); } m_root->repopulate(); setup_tree(); } // ask_about_user_map( m_wnd ); return m_wnd; } virtual bool get_prefer_multiple_instances() const { return false; } virtual void set_config(stream_reader * p_reader, t_size p_size, abort_callback & p_abort) { #if 0 try { p_reader->read_string( m_file, p_abort ); p_reader->read( &m_has_been_asked, sizeof( m_has_been_asked ), p_abort ); } catch ( exception_io e ) { /* pfc::string_printf foo( "%s\\playlist-tree-%d.pts", core_api::get_profile_path(), (int) cfg_panel_count ) ; filesystem::g_get_display_path( foo, m_file ); cfg_panel_count = cfg_panel_count + 1; m_has_been_asked = true; console::printf( "No file information stored, using default: %s", (const char *) m_file ); */ } #endif } virtual void get_config(stream_writer * p_writer, abort_callback & p_abort) const { //MessageBox( NULL, _T("get_config"), _T("Debug"), MB_OK ); /* playlist_tree_panel * p = g_find_by_hwnd( m_wnd ); if ( p ) { p->shutting_down(); p->m_has_been_asked = true; } */ /* bool has_been_asked = true; p_writer->write_string( m_file, p_abort ); p_writer->write( &has_been_asked, sizeof( has_been_asked ), p_abort ); */ } enum { CT_SELECT = 1, CT_SELECT_AND_LOAD, CT_CANCEL, CT_REDRAW, CT_COLLAPSE, // CT_FAVORITES, CT_END }; bool do_context_menu( POINT * pt ) { HMENU menu = CreatePopupMenu(); /* uAppendMenu( menu, MF_STRING, 1, "Select File..." ); uAppendMenu( menu, MF_STRING, 2, "Select File and Load..." ); uAppendMenu( menu, MF_STRING, 3, "Cancel Auto Save / Restore" ); uAppendMenu( menu, MF_SEPARATOR, -1, "" ); */ uAppendMenu( menu, MF_STRING, CT_REDRAW, "Redraw Tree" ); uAppendMenu( menu, MF_STRING, CT_COLLAPSE, "Collapse Tree" ); // uAppendMenu( menu, MF_STRING, CT_FAVORITES, "cwbowron Favorites" ); uAppendMenu( menu, MF_SEPARATOR, -1, "" ); int x = CT_END; int i = 0; for ( i = 0; i < g_active_trees.get_count(); i++ ) { pfc::string_printf str( "%s [panel %d]", (const char *)g_active_trees[i]->m_root->m_label, i ); if ( g_active_trees[i] == this ) { uAppendMenu( menu, MF_STRING | MF_CHECKED, x, str ); } else { uAppendMenu( menu, MF_STRING, x, str ); } x++; } for ( i = 0; i < g_tmp_node_storage.get_count(); i++ ) { pfc::string_printf str( "%s [tmp %d]", (const char *)g_tmp_node_storage[i]->m_label, i ); uAppendMenu( menu, MF_STRING, x, str ); x++; } int n = TrackPopupMenu( menu, TPM_RIGHTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD, pt->x, pt->y, 0, m_wnd, 0); if ( n ) { if ( n >= CT_END ) { int m = n - CT_END; if ( m < g_active_trees.get_count() ) { // console::printf( "%s", (const char *)g_active_trees[m]->m_root->m_label ); if ( g_active_trees[m] == this ) { console::printf( "SAME TREE" ); } else { // swap 'em folder_node * t = m_root; m_root = g_active_trees[m]->m_root; g_active_trees[m]->m_root = t; g_active_trees[m]->setup_tree(); setup_tree(); } } else { int o = m - g_active_trees.get_count(); //console::printf( "%s", (const char *)g_tmp_node_storage[o]->m_label ); folder_node * t = m_root; m_root = (folder_node*)g_tmp_node_storage[o]; g_tmp_node_storage.remove_by_idx( o ); g_tmp_node_storage.add_item( t ); setup_tree(); } } else switch ( n ) { #if 0 case CT_FAVORITES: { folder_node * fav = new folder_node( "cwbowron's suggestions", true ); static_api_ptr_t<metadb> db; service_ptr_t<playlist_incoming_item_filter> p; if ( playlist_incoming_item_filter::g_get( p ) ) { for ( int z = 0; z < tabsize( g_favorites ); z++ ) { metadb_handle_list list; const char * loc = g_favorites[z].location; const char * name = g_favorites[z].name; p->process_location( loc, list, false, NULL, NULL, get_wnd() ); if ( list.get_count() == 1 ) { fav->add_child( new leaf_node ( name, list[0] )); } else { folder_node * fn = new folder_node( name, true ); fav->add_child( fn ); for ( unsigned i = 0; i < list.get_count(); i++ ) { if (useable_handle( list[i] ) ) { fn->add_child( new leaf_node ( NULL, list[i] )); } } } /* metadb_handle_ptr h; db->handle_create( h, make_playable_location( loc, 0 ) ); leaf_node * n = new leaf_node( name, h ); fav->add_child( n ); */ } } m_root->add_child( fav ); setup_tree(); } break; #endif case CT_COLLAPSE: m_root->collapse( true ); setup_tree(); break; case CT_REDRAW: setup_tree(); break; case CT_CANCEL: m_file.reset(); m_has_been_asked = false; break; case CT_SELECT: if ( get_save_name( m_file ) ) return true; return false; case CT_SELECT_AND_LOAD: if ( get_save_name( m_file ) ) { node * n = do_load_helper( m_file ); if ( n ) { folder_node * fn = dynamic_cast<folder_node*>( n ); if ( fn ) { set_root( fn ); setup_tree(); return true; } } } return false; break; } return true; } return false; } node * find_node_by_pt( int screenx, int screeny, bool item_only = false ) { return g_find_node_by_pt( get_tree(), screenx, screeny, item_only ); } node *find_drop_target( int screenx, int screeny, int * out_location ) { node *res = find_node_by_pt( screenx, screeny ); if ( res ) { RECT r; POINT pt; pt.x = screenx; pt.y = screeny; ScreenToClient( get_tree(), &pt ); if ( !is_valid_htree( res->m_tree_item ) ) { *out_location = DROP_HERE; return res; } TreeView_GetItemRect( get_tree(), res->m_tree_item, &r, false ); int height = r.bottom - r.top; int half_height = height / 2; int quarter_height = height / 4; int half = half_height + r.top; int before_max = r.top + quarter_height; int after_min = before_max + half_height; if ( pt.y <= before_max ) { *out_location = DROP_BEFORE; return res; } else if ( pt.y > after_min ) { *out_location = DROP_AFTER; return res; } else { *out_location = DROP_HERE; return res; } } *out_location = DROP_HERE; return m_root; } static node * g_find_node_by_client_pt( HWND tree, int clientx, int clienty, bool item_only = false ) { TVHITTESTINFO ti; memset( &ti,0,sizeof(ti) ); ti.pt.x = clientx; ti.pt.y = clienty; if ( TreeView_HitTest( tree, &ti ) ) { if ( ti.hItem ) { TVITEMEX item; memset( &item, 0, sizeof( item ) ); item.hItem = ti.hItem; item.mask = TVIF_PARAM; TreeView_GetItem( tree, &item ); if ( item.lParam ) { if ( !item_only || ( ti.flags & TVHT_ONITEM )) { return (node *)item.lParam; } } } } return NULL; } static node * g_find_node_by_pt( HWND tree, int screenx, int screeny, bool item_only = false ) { POINT pt; pt.x = screenx; pt.y = screeny; ScreenToClient( tree, &pt ); return g_find_node_by_client_pt( tree, pt.x, pt.y, item_only ); } void set_root( folder_node * n ) { if ( m_root ) { delete m_root; } m_root = n; } void update_appearance() { switch ( cfg_edge_style ) { case EE_NONE: SetWindowLong( get_tree(), GWL_EXSTYLE, MY_EDGE_NONE ); break; case EE_GREY: SetWindowLong( get_tree(), GWL_EXSTYLE, MY_EDGE_GREY ); break; case EE_SUNKEN: SetWindowLong( get_tree(), GWL_EXSTYLE, MY_EDGE_SUNKEN ); break; } DWORD style = WS_TABSTOP | WS_VISIBLE | WS_CHILD | TVS_SHOWSELALWAYS; if ( cfg_nohscroll ) { style |= TVS_NOHSCROLL; } if ( !cfg_hidelines ) { style |= TVS_HASLINES | TVS_LINESATROOT; } if ( !cfg_hidebuttons ) { style |= TVS_HASBUTTONS; } SetWindowLong( get_tree(), GWL_STYLE, style ); SetBkColor( GetDC( m_wnd ), cfg_back_color ); TreeView_SetBkColor( get_tree(), cfg_back_color); ImageList_SetBkColor( m_imagelist, cfg_back_color); TreeView_SetLineColor( get_tree(), cfg_line_color); TreeView_SetTextColor( get_tree(), cfg_text_color); if ( m_font ) { DeleteObject( m_font ); } m_font = CreateFontIndirect( &(LOGFONT)cfg_font ); if (m_wnd) { uSendMessage( get_tree(), WM_SETFONT, (WPARAM)m_font, MAKELPARAM( 1, 0 ) ); } SetWindowPos( get_tree(), 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_FRAMECHANGED ); InvalidateRect( m_wnd, NULL, TRUE ); } void shutting_down() { /* if ( !m_has_been_asked ) { if ( IDYES == MessageBox( NULL, _T( "You have not chosen a file to save and restore from for this panel. Would you like to do so now?"), _T("Playlist Tree"), MB_YESNO ) ) { m_root->save( &m_file ); cfg_last_saved_playlist = m_file; } m_has_been_asked = true; } */ } static void g_shutting_down() { for ( int n = 0; n < g_active_trees.get_count(); n++ ) { g_active_trees[n]->shutting_down(); } } static void g_update_appearance() { for ( int n = 0; n < g_active_trees.get_count(); n++ ) { g_active_trees[n]->update_appearance(); } } node * get_selection() { HTREEITEM item = TreeView_GetSelection( get_tree() ); TVITEMEX tv; memset( &tv, 0, sizeof(tv) ); tv.hItem = item; tv.mask = TVIF_PARAM; TreeView_GetItem( get_tree(), &tv ); if ( tv.lParam ) { node * n = (node *) tv.lParam; return n; } return NULL; } static int g_find( playlist_tree_panel * item ) { for ( int n = 0; n < g_active_trees.get_count(); n++ ) { if ( g_active_trees[n] == item ) { return n; } } return -1; } static playlist_tree_panel * g_find_by_hwnd( HWND wnd ) { for ( int n = 0; n < g_active_trees.get_count(); n++ ) { if ( g_active_trees[n]->get_wnd() == wnd ) { return g_active_trees[n]; } } return NULL; } static playlist_tree_panel * g_find_by_tree( HWND tree ) { for ( int n = 0; n < g_active_trees.get_count(); n++ ) { if ( g_active_trees[n]->get_tree() == tree ) { return g_active_trees[n]; } } return NULL; } }; //static service_factory_single_t<playlist_tree_panel> g_playlist_tree_panel; static ui_extension::window_factory<playlist_tree_panel> g_music_browser_factory; HRESULT STDMETHODCALLTYPE tree_drop_target::DragEnter( IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect) { BringWindowToTop( m_panel->get_tree() ); //*pdwEffect = DROPEFFECT_COPY; return S_OK; } HRESULT STDMETHODCALLTYPE tree_drop_target::DragOver( DWORD grfKeyState, POINTL pt, DWORD * pdwEffect ) { BringWindowToTop( m_panel->get_tree() ); int target_location; node *dest = m_panel->find_drop_target( pt.x, pt.y, &target_location ); node *actual_target = NULL; if ( dest ) { switch ( target_location ) { case DROP_BEFORE: if ( dest->m_parent ) { if ( is_valid_htree( dest->m_tree_item ) ) { TreeView_SetInsertMark( m_panel->get_tree(), dest->m_tree_item, false ); } if ( is_valid_htree ( dest->m_parent->m_tree_item ) ) { TreeView_SelectDropTarget( m_panel->get_tree(), dest->m_parent->m_tree_item ); } actual_target = dest->m_parent; } break; case DROP_AFTER: if ( dest->m_parent ) { if ( is_valid_htree( dest->m_tree_item ) ) { TreeView_SetInsertMark( m_panel->get_tree(), dest->m_tree_item, true ); } if ( is_valid_htree ( dest->m_parent->m_tree_item ) ) { TreeView_SelectDropTarget( m_panel->get_tree(), dest->m_parent->m_tree_item ); } actual_target = dest->m_parent; } break; case DROP_HERE: TreeView_SetInsertMark( m_panel->get_tree(), NULL, true ); if ( is_valid_htree( dest->m_tree_item ) ) { TreeView_SelectDropTarget( m_panel->get_tree(), dest->m_tree_item ); } actual_target = dest; break; } } if ( actual_target && actual_target->can_add_child() ) { //*pdwEffect = DROPEFFECT_COPY; } else { *pdwEffect = DROPEFFECT_NONE; } return S_OK; } HRESULT STDMETHODCALLTYPE tree_drop_target::DragLeave( void ) { TreeView_SelectDropTarget( m_panel->get_tree(), 0 ); TreeView_SetInsertMark( m_panel->get_tree(), NULL, false ); return S_OK; } HRESULT STDMETHODCALLTYPE tree_drop_target::Drop( IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect ) { node *destination = m_panel->m_root; int insertion_location = -1; bool rv = false; int relative_location; node *drop_target = m_panel->find_drop_target( pt.x, pt.y, &relative_location ); TreeView_SelectDropTarget( m_panel->get_tree(), 0 ); TreeView_SetInsertMark( m_panel->get_tree(), NULL, false); if (drop_target) { switch ( relative_location ) { case DROP_BEFORE: if ( drop_target->m_parent ) { destination = drop_target->m_parent; insertion_location = destination->get_child_index( drop_target ); } break; case DROP_AFTER: if ( drop_target->m_parent ) { destination = drop_target->m_parent; insertion_location = destination->get_child_index( drop_target ); insertion_location++; } break; case DROP_HERE: if (drop_target->is_leaf()) { console::printf( "Illegal Drop on Leaf Node\n" ); return S_OK; } destination = drop_target; break; } } if ( !destination->can_add_child() ) { console::printf( "Illegal Drop (over limit)\n" ); return S_OK; } FORMATETC fmt = { CF_NODE, 0, DVASPECT_CONTENT, -1, TYMED_NULL }; STGMEDIUM medium = { TYMED_NULL, 0, 0 }; if ( pDataObject->GetData( &fmt, &medium ) == S_OK ) { if ( false ) { MessageBox(NULL, _T("Local Drag And Drop Has Been Disabled"), _T("Playlist Tree"), MB_OK); return E_INVALIDARG; } node *source = (node*)pDataObject; node *sourceParent = source->m_parent; if ( source->has_subchild( destination )) { console::printf( "Illegal Drop" ); *pdwEffect = DROPEFFECT_NONE; return S_OK; } else { node *select_me = source; if ( *pdwEffect & DROPEFFECT_MOVE ) { if ( sourceParent ) { sourceParent->remove_child( source ); } destination->add_child( source, insertion_location ); *pdwEffect = DROPEFFECT_MOVE; } else if ( *pdwEffect & DROPEFFECT_COPY ) { select_me = source->copy(); destination->add_child( select_me, insertion_location ); *pdwEffect = DROPEFFECT_COPY; } destination->refresh_subtree( m_panel->get_tree() ); //if ( sourceParent && sourceParent != destination ) //{ //sourceParent->refresh_subtree( m_panel->get_tree() ); //} select_me->ensure_in_tree(); select_me->force_tree_selection(); metadb_handle_list list; select_me->get_entries( list ); update_drop_watchers( destination, list ); return S_OK; } } fmt.tymed = TYMED_HGLOBAL; fmt.cfFormat = CF_HDROP; // This needs to be here to get directory structure on drops #if 1 // Test for file drops if ( pDataObject->GetData( &fmt, &medium ) == S_OK ) { metadb_handle_list list; node *newstuff = destination->process_hdrop( (HDROP)medium.hGlobal, insertion_location, grfKeyState & MK_SHIFT, &list ); ReleaseStgMedium( &medium ); if ( newstuff->m_parent ) { newstuff->m_parent->refresh_subtree( m_panel->get_tree() ); } newstuff->ensure_in_tree(); newstuff->force_tree_selection(); update_drop_watchers( destination, list ); update_nodes_if_necessary(); } else #endif { metadb_handle_list list; // service_ptr_t<playlist_incoming_item_filter> p; // if ( playlist_incoming_item_filter::g_get( p ) ) static_api_ptr_t<playlist_incoming_item_filter> p; { if ( p->process_dropped_files( pDataObject, list, true, m_panel->get_wnd() ) ) { for ( unsigned i = 0; i < list.get_count(); i++ ) { if (useable_handle( list[i] ) ) { destination->add_child( new leaf_node ( NULL, list[i] )); } else { console::printf( "Unuseable handle: %s\n", list[i]->get_path() ); } } destination->refresh_subtree( m_panel->get_tree() ); update_drop_watchers( destination, list ); update_nodes_if_necessary(); } } } *pdwEffect = DROPEFFECT_COPY; return S_OK; } HRESULT STDMETHODCALLTYPE tree_drop_source::QueryContinueDrag( BOOL fEscapePressed, DWORD grfKeyState ) { if ( fEscapePressed || ( grfKeyState & MK_RBUTTON ) ) { return DRAGDROP_S_CANCEL; } else if ( !( grfKeyState & MK_LBUTTON ) ) { return DRAGDROP_S_DROP; } else { return S_OK; } } HRESULT STDMETHODCALLTYPE tree_drop_source::GiveFeedback( DWORD dwEffect ) { if ( m_panel->get_wnd() ) { DWORD pts = GetMessagePos(); int x = LOWORD(pts); int y = HIWORD(pts); node *foop = m_panel->find_node_by_pt( x, y ); if ( foop ) { TreeView_EnsureVisible( m_panel->get_wnd(), foop->m_tree_item ); // cant drop into your own subchild... if ( m_node && m_node->has_subchild( foop ) ) { //console::printf( "Cannot Drop on own subchild" ); SetCursor( LoadCursor( 0, IDC_NO ) ); return S_OK; } } else { RECT tree_rect; GetWindowRect( m_panel->get_wnd(), &tree_rect ); if ( x > tree_rect.left && x < tree_rect.right ) { if ( (y>tree_rect.bottom) && (y<tree_rect.bottom+30) ) SendMessage( m_panel->get_tree(), WM_VSCROLL, SB_LINEDOWN, NULL); if ((y<tree_rect.top) && (y>tree_rect.top-30)) SendMessage( m_panel->get_tree(), WM_VSCROLL, SB_LINEUP, NULL); } } } return DRAGDROP_S_USEDEFAULTCURSORS; } void lazy_add_user_query( folder_node * n ) { query_node * f = new query_node( "New Query", false ); n->add_child( f ); f->ensure_in_tree(); f->force_tree_selection(); if ( !f->edit() ) { delete f; } } void lazy_set_root( HWND tree, node * n ) { playlist_tree_panel * p = playlist_tree_panel::g_find_by_tree( tree ); if ( p ) { p->set_root( (folder_node *) n ); p->setup_tree(); } } tree_titleformat_hook::tree_titleformat_hook( node * n ) { set_node( n ); } void tree_titleformat_hook::set_node( node * n ) { m_node = n; } bool tree_titleformat_hook::process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) { if ( stricmp_utf8_ex( p_name, p_name_length, "_name", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, m_node->m_label, m_node->m_label.get_length() ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_displayname", ~0 ) == 0 ) { if ( m_node->is_leaf() ) { p_out->write( titleformat_inputtypes::meta, m_node->m_label, m_node->m_label.get_length() ); p_found_flag = true; return true; } else { pfc::string8 dn; folder_node * fn = (folder_node *)m_node; fn->process_local_tags( dn, fn->m_label ); p_out->write( titleformat_inputtypes::meta, dn, ~0 ); p_found_flag = true; return true; } } else if ( stricmp_utf8_ex( p_name, p_name_length, "_size", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf( "%d", m_node->get_file_size(), ~0 ) ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_size_abbr", ~0 ) == 0 ) { __int64 size = m_node->get_file_size(); __int64 megs = size / (1024*1024); if ( megs > 2 * 1024 ) { __int64 gigs = megs / 1024; p_out->write( titleformat_inputtypes::meta, pfc::string_printf( "%d GB", gigs, ~0 ) ); } else { p_out->write( titleformat_inputtypes::meta, pfc::string_printf( "%d MB", megs, ~0 ) ); } p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_size_abb", ~0 ) == 0 ) { __int64 size = m_node->get_file_size(); __int64 megs = size / (1024*1024); if ( megs > 2 * 1024 ) { __int64 gigs = megs / 1024; p_out->write( titleformat_inputtypes::meta, pfc::string_printf( "%d G", gigs, ~0 ) ); } else { p_out->write( titleformat_inputtypes::meta, pfc::string_printf( "%d M", megs, ~0 ) ); } p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_play_length", ~0 ) == 0 ) { double length = m_node->get_play_length(); int hours; int mins; int secs; int days; secs = (int)ceil(length) % 60; mins = (int)floor( length / 60.0 ) % 60; hours = (int)floor( length / (60.0 * 60.0) ); days = (int)floor(length / (60.0 * 60.0 * 24.0)); if (days>2) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf(">%d days",days), ~0 ); } else if (hours>0) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d:%02d:%02d",hours, mins, secs), ~0 ); } else { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d:%02d", mins, secs), ~0 ); } p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_itemcount", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_entry_count()), ~0 ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_foldercount", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_folder_count()), ~0 ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_folderindex", ~0 ) == 0 ) { if ( m_node->m_parent ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->m_parent->m_children.find_item( m_node ) + 1, ~0 )) ; p_found_flag = true; return true; } } else if ( stricmp_utf8_ex( p_name, p_name_length, "_overallindex", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_folder_overall_index()), ~0 ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_nestlevel", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_nest_level()), ~0 ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_isleaf", ~0 ) == 0 ) { if ( m_node->is_leaf() ) { p_out->write( titleformat_inputtypes::meta, "1", ~0 ); p_found_flag = true; return true; } p_found_flag = true; return false; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_isfolder", ~0 ) == 0 ) { if ( m_node->is_folder() ) { p_out->write( titleformat_inputtypes::meta, "1", ~0 ); p_found_flag = true; return true; } p_found_flag = true; return false; } else if ( stricmp_utf8_ex( p_name, p_name_length, "_isquery", ~0 ) == 0 ) { if ( m_node->is_query() ) { p_out->write( titleformat_inputtypes::meta, "1", ~0 ); p_found_flag = true; return true; } p_found_flag = true; return false; } else { /* pfc::string8 str( p_name, p_name_length ); console::printf( "Unknown tag (%s) in node (%s) formatting", (const char *)str, (const char * ) m_node->m_label ); metadb_handle_ptr first; m_node->get_first_entry( first ); if ( first.is_valid() ) { file_info_impl info; first->get_info( info ); int tag_index = info.meta_find( str ); if ( tag_index != ~0 ) { p_out->write( titleformat_inputtypes::meta, info.meta_get( str, tag_index), ~0 ); p_found_flag = true; return true; } } */ } return false; } bool tree_titleformat_hook::process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) { if ( stricmp_utf8_ex( p_name, p_name_length, "avg", ~0 ) == 0 ) { const char *s; pfc::string8 ss; t_size len; p_params->get_param( 0, s, len ); ss.set_string( s, len ); metadb_handle_list lst; m_node->get_entries( lst ); double sum = 0; int count = 0; pfc::string8_fastalloc our_info; for ( unsigned i = 0; i < lst.get_count(); i++ ) { service_ptr_t<titleformat_object> script; static_api_ptr_t<titleformat_compiler>()->compile_safe(script,ss); lst[i]->format_title( NULL, our_info, script, NULL ); sum += atoi(our_info); count++; } double avg = (count>0) ? sum / count : 0; char buff[40]; _snprintf( buff, 40, "%.2f", avg ); buff[ 40 - 1] = 0; p_out->write( titleformat_inputtypes::unknown, buff, ~0 ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "sum", ~0 ) == 0 ) { const char *s; pfc::string8 ss; t_size len; p_params->get_param( 0, s, len ); ss.set_string( s, len ); metadb_handle_list lst; m_node->get_entries( lst ); int sum = 0; pfc::string8_fastalloc our_info; for ( unsigned i = 0; i < lst.get_count(); i++ ) { service_ptr_t<titleformat_object> script; static_api_ptr_t<titleformat_compiler>()->compile_safe(script,ss); lst[i]->format_title( NULL, our_info, script, NULL ); sum += atoi(our_info); } p_out->write( titleformat_inputtypes::unknown, pfc::string_printf( "%d", sum ), ~0 ); p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "playing", ~0 ) == 0 ) { const char *s; pfc::string8 ss; t_size len; p_params->get_param( 0, s, len ); ss.set_string( s, len ); static_api_ptr_t<playback_control> srv; metadb_handle_ptr temp; if ( srv->get_now_playing(temp) ) { pfc::string8_fastalloc str; if ( temp->format_title_legacy( this, str, ss, NULL ) ) { p_out->write( titleformat_inputtypes::unknown, str, ~0 ); p_found_flag = true; } } return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "hidetext", ~0 ) == 0 ) { p_found_flag = true; return true; } else if ( stricmp_utf8_ex( p_name, p_name_length, "parent", ~0 ) == 0 ) { node * parent_node = NULL; if ( p_params->get_param_count() == 1 ) { parent_node = m_node->get_parent(); } else if ( p_params->get_param_count() == 2 ) { int n = p_params->get_param_uint( 1 ); parent_node = m_node->get_parent( n ); } if ( parent_node ) { pfc::string8 ss; t_size len; const char *s; p_params->get_param( 0, s, len ); ss.set_string( s, len ); pfc::string8 parent_out; parent_node->format_title( parent_out, ss ); p_out->write( titleformat_inputtypes::unknown, parent_out, ~0 ); p_found_flag = true; } return true; } return false; } class woot : public initquit { void on_init() { if ( !g_format_hook ) { g_format_hook = new tree_titleformat_hook(); } // scheme_set_stack_base(NULL, 1); g_scheme_environment = scheme_basic_env(); } void on_quit() { g_is_shutting_down = true; int file_count = 0; for ( int p = 0; p < g_active_trees.get_count(); p++ ) { pfc::string8 file; pfc::string_printf foo( "%s\\playlist-tree-%d.pts", core_api::get_profile_path(), file_count ) ; filesystem::g_get_display_path( foo, file ); file_count++; g_active_trees[p]->m_root->write( file ); } for ( int n = 0; n < g_tmp_node_storage.get_count(); n++ ) { pfc::string8 file; pfc::string_printf foo( "%s\\playlist-tree-%d.pts", core_api::get_profile_path(), file_count ) ; file_count++; filesystem::g_get_display_path( foo, file ); g_tmp_node_storage[n]->write( file ); } if ( g_tmp_node_storage.get_count() ) { g_tmp_node_storage.delete_all(); } if ( g_format_hook ) delete g_format_hook; if ( g_scheme_environment ) { } } }; static service_factory_single_t<woot> g_woot; bool get_save_name( pfc::string_base & out_name, bool prompt_overwrite, bool open, bool as_text ) { TCHAR fileName[MAX_PATH]; TCHAR *filters; if ( as_text ) { filters = _T("Text File (*.") _T("txt") _T(")\0") _T("*.") _T("txt") _T("\0") _T("All files (*.*)\0") _T("*.*\0") _T("\0"); } else { filters = _T("Playlist Tree SEXP (*.") _T(PLAYLIST_TREE_EXTENSION) _T(")\0") _T("*.") _T(PLAYLIST_TREE_EXTENSION) _T("\0") _T("All files (*.*)\0") _T("*.*\0") _T("\0"); } OPENFILENAME blip; memset((void*)&blip, 0, sizeof(blip)); memset(fileName, 0, sizeof(fileName)); blip.lpstrFilter = filters; blip.lStructSize = sizeof(OPENFILENAME); blip.lpstrFile = fileName; blip.nMaxFile = sizeof(fileName)/ sizeof(*fileName); blip.lpstrTitle = open ? _T("Select File To Open") : _T("Save Tree As..."); blip.lpstrDefExt = _T(PLAYLIST_TREE_EXTENSION); blip.Flags = prompt_overwrite ? OFN_OVERWRITEPROMPT : 0 ; if ( open ) { if ( GetOpenFileName( &blip ) ) { out_name = pfc::stringcvt::string_utf8_from_wide( blip.lpstrFile ); return true; } } else { if ( GetSaveFileName( &blip ) ) { out_name = pfc::stringcvt::string_utf8_from_wide( blip.lpstrFile ); return true; } } return false; } static BOOL CALLBACK select_icon_callback( HWND wnd, UINT msg, WPARAM wp, LPARAM lp ) { static HWND list_hwnd = 0; static int * selected_icon; switch( msg ) { case WM_INITDIALOG: { selected_icon = (int*)lp; list_hwnd = GetDlgItem( wnd, IDC_ICONLIST ); ListView_SetImageList( list_hwnd, g_imagelist, LVSIL_NORMAL ); ListView_SetImageList( list_hwnd, g_imagelist, LVSIL_SMALL ); ListView_SetBkColor( list_hwnd, cfg_back_color ); ListView_SetTextColor( list_hwnd, cfg_text_color ); ListView_SetTextBkColor( list_hwnd, cfg_back_color ); int max_icon = ImageList_GetImageCount( g_imagelist ); LVITEM item; memset( &item, 0, sizeof(item) ); for ( int i = 0 ; i < max_icon; i++ ) { pfc::stringcvt::string_wide_from_utf8 text( pfc::string_printf( "%d", i ) );; item.iItem = i; item.pszText = (LPWSTR)(const wchar_t *)text; item.iImage = i; item.mask = LVIF_TEXT|LVIF_IMAGE; ListView_InsertItem( list_hwnd, &item ); } } break; case WM_COMMAND: switch ( wp ) { case IDOK: *selected_icon = ListView_GetSelectionMark( list_hwnd ); /* fall through */ case IDCANCEL: EndDialog( wnd, wp ); break; } } return 0; } static int select_icon( HWND parent, HIMAGELIST image_list ) { int result = -1; g_imagelist = image_list; if ( g_imagelist == NULL ) { console::printf( "No Image List Loaded\n" ); return 0; } int res = DialogBoxParam( core_api::get_my_instance(), MAKEINTRESOURCE( IDD_ICONSELECT ), parent, select_icon_callback, (LPARAM)&result ); if ( res == IDOK ) { return result; } return -1; } enum { CM_ADD_ACTIVE, CM_SEND_ACTIVE, CM_NEW, CM_SEND_LIBRARY, CM_SEND_LIBRARY_SELECTED, CM_PLAY_LIBRARY, CM_LAST }; struct { char * label; char * desc; char * global_path; char * local_path; GUID guid; } cm_map[CM_LAST] = { { "Add to active playlist", "Adds item to the active playlist", "Playlist Tree", "Playlist", { 0x58060ff2, 0xaaf, 0x4597, { 0xab, 0xd2, 0x4b, 0xbe, 0x74, 0x45, 0xa8, 0x46 } } }, { "Send to active playlist", "Sends item to active playlist, clearing it", "Playlist Tree", "Playlist", { 0x5c0ab9a7, 0x308d, 0x47bd, { 0x85, 0xd1, 0xc9, 0xca, 0xd1, 0x97, 0x86, 0xee } } }, { "New playlist", "Creates a new playlist from the items and activates it", "Playlist Tree", "Playlist", { 0x9a0fb175, 0x6507, 0x4b7d, { 0xae, 0x45, 0xe0, 0x63, 0xcb, 0x46, 0xfe, 0x97 } } }, { "Send to Library Playlist", "Sends items to designated library playlist", "Playlist Tree", "Playlist", { 0xa830ba23, 0xdef1, 0x4a7c, { 0xbd, 0xc1, 0xb9, 0x1f, 0xed, 0xef, 0xd, 0xf0 } } }, { "Send to Library Playlist (Selected)", "Sends items to designated library playlist", "Playlist Tree", "Playlist", { 0x7e1fea7, 0x3054, 0x4e17, { 0xb2, 0xb9, 0xe2, 0x6f, 0xe6, 0x0, 0x89, 0x6a } } }, { "Play in Library Playlist", "Sends items to designated library playlists and plays it", "Playlist Tree", "Playlist", { 0xded9942c, 0x820b, 0x4225, { 0x88, 0xa6, 0x3b, 0x73, 0xba, 0xbc, 0x4a, 0x50 } } }, }; class tree_context_items : public contextmenu_item_simple { unsigned get_num_items() { return CM_LAST; } GUID get_item_guid( unsigned int n ) { if ( n < CM_LAST ) { return cm_map[n].guid; } else { return pfc::guid_null; } } void get_item_name( unsigned n, pfc::string_base & out ) { if ( n < CM_LAST ) { out.set_string( cm_map[n].label ); } } void get_item_default_path( unsigned n, pfc::string_base & out ) { if ( n < CM_LAST ) { out.set_string( cm_map[n].global_path ); } } bool get_item_description( unsigned n, pfc::string_base & out ) { if ( n < CM_LAST ) { out.set_string( cm_map[n].desc ); return true; } return false; } virtual void context_command(unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID& p_caller) { switch ( p_index ) { case CM_PLAY_LIBRARY: case CM_SEND_LIBRARY: case CM_SEND_LIBRARY_SELECTED: { static_api_ptr_t<playlist_manager> m; bit_array_false f; t_size pl_index = infinite; static pfc::string8_fastalloc playlist_name; if ( has_tags( cfg_library_playlist ) ) { if ( g_context_node ) { pfc::string8 tmp; g_context_node->format_title( tmp, cfg_library_playlist ); if ( g_context_node->is_leaf() ) { playlist_name.set_string( tmp ); } else { folder_node * fn = (folder_node *) g_context_node; fn->process_local_tags( playlist_name, tmp ); } } else { playlist_name.set_string( DEFAULT_LIBRARY_PLAYLIST ); } } else { playlist_name.set_string( cfg_library_playlist ); } int n = infinite; if ( cfg_remove_last_playlist ) { n = m->find_playlist( cfg_last_library, ~0 ); m->playlist_rename( n, playlist_name, ~0 ); } if ( n == infinite ) { n = m->find_or_create_playlist( playlist_name, ~0 ); } m->playlist_undo_backup( n ); m->playlist_clear( n ); m->playlist_add_items( n, p_data, f ); cfg_last_library = playlist_name; if ( cfg_activate_library_playlist ) { m->set_active_playlist( n ); } if ( p_index == CM_SEND_LIBRARY_SELECTED ) { bit_array_true t; m->playlist_set_selection( n, t, t ); console::printf( "Sending and Selection" ); } if ( p_index == CM_PLAY_LIBRARY ) { console::print( "Playing" ); bit_array_true t; m->queue_remove_mask( t ); m->set_playing_playlist( n ); static_api_ptr_t<playback_control> pc; pc->start(); } } break; case CM_NEW: { static_api_ptr_t<playlist_manager> m; bit_array_false f; int n; if ( g_context_node ) { pfc::string8 title; g_context_node->get_display_name( title ); n = m->create_playlist( title, ~0, ~0 ); } else { n = m->create_playlist( "New", ~0, ~0 ); } if ( n != ~0 ) { m->playlist_add_items( n, p_data, f ); m->set_active_playlist( n ); } } break; case CM_SEND_ACTIVE: { static_api_ptr_t<playlist_manager> m; bit_array_false f; m->activeplaylist_undo_backup(); m->activeplaylist_clear(); m->activeplaylist_add_items( p_data, f ); } break; case CM_ADD_ACTIVE: { static_api_ptr_t<playlist_manager> m; bit_array_false f; m->activeplaylist_undo_backup(); m->activeplaylist_add_items( p_data, f ); } break; } } }; static service_factory_single_t<tree_context_items> g_context; #include "mainmenu.h" bool run_context_command( const char * cmd, pfc::list_base_const_t<metadb_handle_ptr> * handles, node * n, const GUID & guid_command, const GUID & guid_subcommand ) { // console::printf( "run_context_command: %s", cmd ); g_context_node = n; const char * local_tag = "[local]"; bool result = false; if ( strcmp( cmd, "" ) != 0 ) { if ( strstr( cmd, local_tag ) ) { for ( int i = 0; i < tabsize(mm_map); i++ ) { if ( ( strlen( mm_map[i].local_path ) > 0 ) && strstr( cmd, mm_map[i].local_path ) ) { // console::printf( "calling mm_command_process on %s", mm_map[i].desc ); mm_command_process( mm_map[i].id, n ); result = true; } } if ( !result ) { // console::printf ( "context_command not found" ); } } else { if ( guid_command == pfc::guid_null && guid_subcommand == pfc::guid_null ) { GUID guid; if ( menu_helpers::find_command_by_name( cmd, guid ) ) { if ( handles ) { result = menu_helpers::run_command_context( guid, pfc::guid_null, *handles ); } else if ( n ) { metadb_handle_list lst; n->get_entries( lst ); result = menu_helpers::run_command_context( guid, pfc::guid_null, lst ); } } } else { if ( handles ) { result = menu_helpers::run_command_context( guid_command, guid_subcommand, *handles ); } else if ( n ) { metadb_handle_list lst; n->get_entries( lst ); result = menu_helpers::run_command_context( guid_command, guid_subcommand, lst ); } } } } g_context_node = false; return result; } HMENU generate_node_menu( node *in_ptr, int & ID ) { HMENU returnme = CreatePopupMenu(); in_ptr->m_id = (int)returnme; //console::printf( "(%s).m_id = %d", (const char *) in_ptr->m_label, in_ptr->m_id ); if ( !returnme ) { console::warning( "CreatePopupMenu failed in genereate_node_menu" ); return NULL; } pfc::string8 title; folder_node * ptr = NULL; if ( !in_ptr->is_leaf() ) { ptr = (folder_node*) in_ptr; } if ( ptr ) { for ( int i = 0; i < ptr->get_num_children(); i++ ) { node *child = ptr->m_children[i]; //child->get_display_name( title ); title = child->m_label; if ( child->is_leaf() ) { if ( child->m_id >= 0 ) { if ( child->m_id == MENU_SEPARATOR ) { uAppendMenu( returnme, MF_SEPARATOR, 0, ""); } else { uAppendMenu( returnme, MF_STRING, child->m_id, title ); } } else { child->m_id = ID; uAppendMenu( returnme, MF_STRING, ID, title ); ID ++; } } else { HMENU child_menu = generate_node_menu( child, ID ); if ( child_menu ) { uAppendMenu( returnme, MF_POPUP, (long)child_menu, title ); } else { return returnme; } } } } return returnme; } HMENU generate_node_menu_complex( node *ptr, int & ID, bool prependAll = false, pfc::ptr_list_t<pfc::string8> *actions = NULL ) { HMENU returnme = CreatePopupMenu(); ptr->m_id = (int)returnme; //console::printf( "(%s).m_id = %d", (const char *) in_ptr->m_label, in_ptr->m_id ); pfc::string8 title; if ( !ptr->is_leaf() ) { folder_node * fn = (folder_node*)ptr; if ( prependAll && fn->get_num_children() > 1 ) { ptr->m_id = ID; if ( actions->get_count() == 1 ) { uAppendMenu( returnme, MF_STRING, ID, "All" ); ID++; } else { HMENU tmp = CreatePopupMenu(); for ( int n = 0; n < actions->get_count(); n ++ ) { uAppendMenu( tmp, MF_STRING, ID, actions->get_item( n )->get_ptr() ); ID++; } uAppendMenu( returnme, MF_POPUP, (long)tmp, "All" ); } uAppendMenu( returnme, MF_SEPARATOR, 0, "" ); } for ( int i = 0; i < fn->get_num_children(); i++ ) { node *child = fn->m_children[i]; title.set_string( child->m_label ); //child->get_display_name( title ); if ( child->is_leaf() ) { if ( child->m_id == MENU_SEPARATOR ) { uAppendMenu( returnme, MF_SEPARATOR, 0, ""); } else { if ( child->m_id >= 0 ) { uAppendMenu( returnme, MF_STRING, child->m_id, title ); } else { child->m_id = ID; if ( actions->get_count() != 1 ) { HMENU tmp = CreatePopupMenu(); for ( int n = 0; n < actions->get_count(); n ++ ) { uAppendMenu( tmp, MF_STRING, ID, actions->get_item( n )->get_ptr() ); ID++; } uAppendMenu( returnme, MF_POPUP, (long)tmp, title ); } else { uAppendMenu( returnme, MF_STRING, ID, title ); ID ++; } } } } else { HMENU child_menu = generate_node_menu_complex( child, ID, prependAll, actions ); uAppendMenu( returnme, MF_POPUP, (long)child_menu, title ); } } } return returnme; } HMENU node::generate_context_menu() { int i; node * n = new folder_node( "Context" ); for ( i = 0; i < tabsize(mm_map); i++ ) { if (( is_query() && mm_map[i].type & TYPE_QUERY ) || ( is_folder() && mm_map[i].type & TYPE_FOLDER ) || ( is_leaf() && mm_map[i].type & TYPE_LEAF ) ) { query_ready_string strings( mm_map[i].local_path ); node * ch = n->add_delimited_child( strings, NULL ); if ( ch ) { ch->m_id = mm_map[i].id; } } } int tmp; HMENU m = generate_node_menu( n, tmp ); delete n; return m; } void node::handle_context_menu_command( int n ) { mm_command_process( n, this ); } #include "preferences.h" static const GUID library_service_guid = { 0x19932591, 0x62ef, 0x4031, { 0x92, 0xf1, 0xc7, 0x79, 0xe3, 0xcc, 0x94, 0x87 } }; class tree_library_service : public library_viewer { GUID get_preferences_page() { return guid_preferences; } GUID get_guid() { return library_service_guid; } bool have_activate() { return false; } void activate() { } const char *get_name() { return "Playlist Tree Panel"; } }; static service_factory_single_t<tree_library_service> g_library_service; class repopulate_callback : public main_thread_callback { int m_reason; WPARAM m_wp; LPARAM m_lp; public: repopulate_callback( int reason, WPARAM wp, LPARAM lp ) : main_thread_callback() { m_reason = reason; m_wp = wp; m_lp = lp; } void callback_run() { for ( int n = 0; n < g_active_trees.get_count(); n++ ) { g_active_trees[n]->m_root->repopulate_auto( m_reason, m_wp, m_lp ); } } }; void static post_repopulate( int reason, WPARAM wp = 0, LPARAM lp = 0 ) { if ( core_api::are_services_available() && !core_api::is_initializing() && !core_api::is_shutting_down() ) { service_ptr_t<repopulate_callback> p_callback = new service_impl_t<repopulate_callback>( reason, wp, lp ); static_api_ptr_t<main_thread_callback_manager> man; man->add_callback( p_callback ); } } #include "tree_search.h" class tree_play_callback : public play_callback_static { virtual unsigned get_flags() { return flag_on_playback_new_track; } //! Playback process is being initialized. on_playback_new_track() should be called soon after this when first file is successfully opened for decoding. virtual void FB2KAPI on_playback_starting(play_control::t_track_command p_command,bool p_paused){} //! Playback advanced to new track. virtual void FB2KAPI on_playback_new_track(metadb_handle_ptr p_track) { post_repopulate( repop_new_track ); } //! Playback stopped virtual void FB2KAPI on_playback_stop(play_control::t_stop_reason p_reason){} //! User has seeked to specific time. virtual void FB2KAPI on_playback_seek(double p_time){} //! Called on pause/unpause. virtual void FB2KAPI on_playback_pause(bool p_state){} //! Called when currently played file gets edited. virtual void FB2KAPI on_playback_edited(metadb_handle_ptr p_track) {} //! Dynamic info (VBR bitrate etc) change. virtual void FB2KAPI on_playback_dynamic_info(const file_info & p_info) {} //! Per-track dynamic info (stream track titles etc) change. Happens less often than on_playback_dynamic_info(). virtual void FB2KAPI on_playback_dynamic_info_track(const file_info & p_info) {} //! Called every second, for time display virtual void FB2KAPI on_playback_time(double p_time) {} //! User changed volume settings. Possibly called when not playing. //! @param p_new_val new volume level in dB; 0 for full volume. virtual void FB2KAPI on_volume_change(float p_new_val) {} }; static service_factory_single_t<tree_play_callback> g_tree_play_callback; class queue_callback : public playback_queue_callback { virtual void on_changed(t_change_origin p_origin) { post_repopulate( repop_queue_change ); } }; static service_factory_single_t<queue_callback> g_queue_callback; class playlist_tree_playlist_callback : public playlist_callback_static { public: playlist_tree_playlist_callback() { } ~playlist_tree_playlist_callback() { } void update_all_playlists_queries() { post_repopulate( repop_playlists_change ); } void update_all_playlist_watchers( t_size p_playlist ) { post_repopulate( repop_playlist_change, p_playlist ); } virtual unsigned get_flags() { return flag_on_items_added | flag_on_items_reordered | flag_on_items_removed | flag_on_items_replaced | flag_on_playlists_removed | flag_on_playlist_created | flag_on_playlist_renamed; } virtual void FB2KAPI on_items_added(t_size p_playlist,t_size p_start, const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const bit_array & p_selection) { update_all_playlist_watchers( p_playlist ); } virtual void FB2KAPI on_items_reordered(t_size p_playlist,const t_size * p_order,t_size p_count) { update_all_playlist_watchers( p_playlist ); } virtual void FB2KAPI on_items_removing(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count) { } virtual void FB2KAPI on_items_removed(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count) { update_all_playlist_watchers( p_playlist ); } virtual void FB2KAPI on_items_selection_change(t_size p_playlist,const bit_array & p_affected,const bit_array & p_state) { } virtual void FB2KAPI on_item_focus_change(t_size p_playlist,t_size p_from,t_size p_to) { } virtual void FB2KAPI on_items_modified(t_size p_playlist,const bit_array & p_mask) { } virtual void FB2KAPI on_items_modified_fromplayback(t_size p_playlist,const bit_array & p_mask,play_control::t_display_level p_level) { } virtual void FB2KAPI on_items_replaced(t_size p_playlist,const bit_array & p_mask,const pfc::list_base_const_t<t_on_items_replaced_entry> & p_data) { update_all_playlist_watchers( p_playlist ); } virtual void FB2KAPI on_item_ensure_visible(t_size p_playlist,t_size p_idx) { } virtual void FB2KAPI on_playlist_activate(t_size p_old,t_size p_new) { } virtual void FB2KAPI on_playlist_created(t_size p_index,const char * p_name,t_size p_name_len) { update_all_playlists_queries(); } virtual void FB2KAPI on_playlists_reorder(const t_size * p_order,t_size p_count) { } virtual void FB2KAPI on_playlists_removing(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) { } virtual void FB2KAPI on_playlists_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) { update_all_playlists_queries(); } virtual void FB2KAPI on_playlist_renamed(t_size p_index,const char * p_new_name,t_size p_new_name_len) { update_all_playlists_queries(); } virtual void FB2KAPI on_default_format_changed() { } virtual void FB2KAPI on_playback_order_changed(t_size p_new_index) { } virtual void FB2KAPI on_playlist_locked(t_size p_playlist,bool p_locked) { } }; static service_factory_single_t<playlist_tree_playlist_callback> g_playlist_callback; class tree_file_callback : public file_operation_callback { public: tree_file_callback() { } ~tree_file_callback() { } //! p_items is a metadb::path_compare sorted list of files that have been deleted. virtual void on_files_deleted_sorted(const pfc::list_base_const_t<const char *> & p_items) { /* console::printf( "Files Deleted:" ); for ( int n = 0; n < p_items.get_count(); n++ ) { console::printf( " %s", p_items[n] ); } */ for ( int i = 0; i < g_active_trees.get_count(); i++ ) { g_active_trees[i]->m_root->files_removed( p_items ); } } //! p_from is a metadb::path_compare sorted list of files that have been moved, p_to is a list of corresponding target locations virtual void on_files_moved_sorted(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to) { /* console::printf( "Files Moved:" ); for ( int n = 0; n < p_from.get_count(); n++ ) { console::printf( " %s", p_from[n] ); } */ for ( int i = 0; i < g_active_trees.get_count(); i++ ) { g_active_trees[i]->m_root->files_moved( p_from, p_to ); } } //! p_from is a metadb::path_compare sorted list of files that have been copied, p_to is a list of corresponding target locations. virtual void on_files_copied_sorted(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to) { } }; service_factory_single_t<tree_file_callback> g_file_callback; void remove_from_queue( const pfc::list_t<metadb_handle_ptr> & handles ) { pfc::list_t<t_playback_queue_item> queue; static_api_ptr_t<playlist_manager> pm; pm->queue_get_contents( queue ); bit_array_bittable bits( queue.get_count() ); for ( int i = 0; i < queue.get_count(); i++ ) { bits.set( i, false ); } for ( int n = 0; n < handles.get_count(); n++ ) { for ( int i = 0; i < queue.get_count(); i++ ) { if ( handles[n] == queue[i].m_handle ) { // console::printf( "Setting bit on %s", handles[n]->get_path() ); bits.set( i, true ); } } } pm->queue_remove_mask( bits ); } void remove_from_playlist( t_size playlist, pfc::list_t<metadb_handle_ptr> handles ) { metadb_handle_list queue; bit_array_true t; static_api_ptr_t<playlist_manager> pm; pm->playlist_get_items( playlist, queue, t ); bit_array_bittable bits( queue.get_count() ); for ( int i = 0; i < queue.get_count(); i++ ) { bits.set( i, false ); } for ( int n = 0; n < handles.get_count(); n++ ) { for ( int i = 0; i < queue.get_count(); i++ ) { if ( handles[n] == queue[i] ) { // console::printf( "Setting bit on %s", handles[n]->get_path() ); bits.set( i, true ); } } } pm->playlist_remove_items( playlist, bits ); } void on_node_removing( node * ptr ) { g_refresh_lock = true; node * p = ptr->m_parent; while ( p ) { if ( p->is_query() ) { query_node * qn = (query_node *) p; if ( strstr( qn->m_source, TAG_QUEUE ) ) { metadb_handle_list handles; ptr->get_entries( handles ); remove_from_queue( handles ); g_nodes_to_update.add_item( qn ); break; } if ( strstr( qn->m_source, TAG_PLAYLIST ) ) { pfc::string8 playlist; if ( string_get_function_param( playlist, qn->m_source, TAG_PLAYLIST ) ) { static_api_ptr_t<playlist_manager> pm; t_size np = pm->find_playlist( playlist, ~0 ); if ( np != infinite ) { metadb_handle_list handles; ptr->get_entries( handles ); remove_from_playlist( np, handles ); } g_nodes_to_update.add_item( qn ); } } } p = p->m_parent; } g_refresh_lock = false; } /* class sample_callback : public titleformatting_variable_callback { public: void on_var_change( const char * var ) { console::printf( "playlist_tree::sample_callback: %s", var ); } }; service_factory_single_t<sample_callback> g_sample_callback; */ node::~node() { remove_tree(); m_tree_item = NULL; m_hwnd_tree = NULL; if ( m_parent ) { m_parent->m_children.remove_item( this ); } } __int64 g_treenode_size; double g_treenode_duration; pfc::string8 g_treenode_displayname; void cache_treenode_variables( node * n ) { g_treenode_size = n->get_file_size(); g_treenode_duration = n->get_play_length(); n->get_display_name( g_treenode_displayname ); } void node::select() { // g_node_hook.get_static_instance().set_node( this ); cache_treenode_variables( this ); post_callback_notification( this ); post_variable_callback_notification( "treenode" ); static_api_ptr_t<metadb> db; db->database_lock(); metadb_handle_list lst; get_entries( lst ); db->database_unlock(); if ( lst.get_count() > 0 ) { bool overLimit = ( lst.get_count() > cfg_selection_action_limit ); if ( cfg_selection_action_limit == 0 || !overLimit ) { run_context_command( cfg_selection_action_1, &lst, this, cfg_selection_action1_guid_command, cfg_selection_action1_guid_subcommand ); run_context_command( cfg_selection_action_2, &lst, this, cfg_selection_action2_guid_command, cfg_selection_action2_guid_subcommand ); } else if ( overLimit ) { console::printf( "%s exceeds selection action limit", (const char *) m_label ); } } } bool return_processed_true( bool & p_found_flag ) { p_found_flag = true; return true; } bool return_processed_false( bool & p_found_flag ) { p_found_flag = false; return true; } bool node_titleformatting_hook::process_function(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_fn_name,t_size p_fn_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) { if ( stricmp_utf8_ex( p_fn_name, p_fn_name_length, "treenode", 8 ) == 0 ) { if ( !g_last_active_tree ) { return return_processed_false( p_found_flag ); } node * m_node = g_last_active_tree->get_selection(); if ( !m_node ) { return return_processed_false( p_found_flag ); } if ( p_params->get_param_count() < 1 ) { return return_processed_false( p_found_flag ); } const char * p_name; t_size p_name_length; p_params->get_param( 0, p_name, p_name_length ); if ( stricmp_utf8_ex( p_name, p_name_length, "name", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, m_node->m_label, m_node->m_label.get_length() ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "displayname", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, g_treenode_displayname, ~0 ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "size", ~0 ) == 0 ) { pfc::format_uint str( g_treenode_size, 3 ); p_out->write( titleformat_inputtypes::meta, str, ~0 ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "duration", ~0 ) == 0 ) { double length = g_treenode_duration; p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", (int) length), ~0 ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "itemcount", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_entry_count()), ~0 ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "foldercount", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_folder_count()), ~0 ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "folderindex", ~0 ) == 0 ) { if ( m_node->m_parent ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->m_parent->m_children.find_item( m_node ) + 1, ~0 )) ; return return_processed_true( p_found_flag ); } } else if ( stricmp_utf8_ex( p_name, p_name_length, "overallindex", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_folder_overall_index()), ~0 ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "nestlevel", ~0 ) == 0 ) { p_out->write( titleformat_inputtypes::meta, pfc::string_printf("%d", m_node->get_nest_level()), ~0 ); return return_processed_true( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "isleaf", ~0 ) == 0 ) { if ( m_node->is_leaf() ) { p_out->write( titleformat_inputtypes::meta, "1", ~0 ); return return_processed_true( p_found_flag ); } return return_processed_false( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "isfolder", ~0 ) == 0 ) { if ( m_node->is_folder() ) { p_out->write( titleformat_inputtypes::meta, "1", ~0 ); return return_processed_true( p_found_flag ); } return return_processed_false( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "isquery", ~0 ) == 0 ) { if ( m_node->is_query() ) { p_out->write( titleformat_inputtypes::meta, "1", ~0 ); return return_processed_true( p_found_flag ); } return return_processed_false( p_found_flag ); } else if ( stricmp_utf8_ex( p_name, p_name_length, "isactive", ~0 ) == 0 ) { HWND hwnd = GetFocus(); bool active = ( hwnd == g_last_active_tree->get_wnd() ) || ( hwnd == g_last_active_tree->get_tree() ); if ( !IsWindowVisible( g_last_active_tree->get_wnd() ) ) active = false; if ( active ) { p_out->write( titleformat_inputtypes::meta, "1", ~0 ); return return_processed_true( p_found_flag ); } return return_processed_false( p_found_flag ); } return false; } return false; } bool node_titleformatting_hook::process_field(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) { return false; }
29.31272
215
0.530814
cwbowron
a4ccdbf46dd6de2789bb3919eefbd84a6fa01fa1
3,412
cpp
C++
Code/Engine/Tools/FBX.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/Tools/FBX.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/Tools/FBX.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#pragma once #include "Engine/General/Core/EngineCommon.hpp" #include "Engine/Utils/ErrorWarningAssert.hpp" #include "Engine/General/Core/BeirusEngine.hpp" #include "Engine/Console/Command.hpp" #include "Engine/Console/Console.hpp" #if defined(TOOLS_BUILD) #include <fbxsdk.h> #pragma comment(lib, "libfbxsdk-md.lib") ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //LOCAL FUNCTIONS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- static String GetAttributeTypeName(FbxNodeAttribute::EType type) { return ""; } //--------------------------------------------------------------------------------------------------------------------------- static void PrintAttribute(FbxNodeAttribute* attribute, int depth) { if (nullptr == attribute) { return; } FbxNodeAttribute::EType type = attribute->GetAttributeType(); String typeName = GetAttributeTypeName(type); String attribName = attribute->GetName(); String output = StringUtils::Stringf("%s- type ='%s', name='%s'", depth, "", typeName, attribName); Console::PrintOutput(output, CONSOLE_VERIFY); } //--------------------------------------------------------------------------------------------------------------------------- static void PrintNode(FbxNode* node, int depth) { String output = StringUtils::Stringf("%*sNode [%s]", depth, " ", node->GetName()); Console::PrintOutput(output, CONSOLE_VERIFY); for (int i = 0; i < node->GetChildCount(); i++) { PrintNode(node->GetChild(i), depth + 1); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //EXTERNAL FUNCTIONS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FbxList(String filename) { FbxManager* fbxManager = FbxManager::Create(); if (nullptr == fbxManager) { Console::PrintOutput("Could not create fbx manager.", CONSOLE_VERIFY); return; } FbxIOSettings* ioSettings = FbxIOSettings::Create(fbxManager, IOSROOT ); fbxManager->SetIOSettings(ioSettings); //Create an importer FbxImporter* importer = FbxImporter::Create(fbxManager, ""); bool result = importer->Initialize(filename.c_str(), -1, fbxManager->GetIOSettings()); if (result) { //We have imported the FBX FbxScene* scene = FbxScene::Create(fbxManager, ""); bool importSuccessful = importer->Import(scene); if (importSuccessful) { FbxNode* root = scene->GetRootNode(); PrintNode(root, 0); } else { Console::PrintOutput("fuck", CONSOLE_VERIFY); } FBX_SAFE_DESTROY(scene); } else { String output = StringUtils::Stringf("Could not import scene: %s", filename.c_str()); Console::PrintOutput(output, CONSOLE_VERIFY); } FBX_SAFE_DESTROY(importer); FBX_SAFE_DESTROY(ioSettings); FBX_SAFE_DESTROY(fbxManager); } #else void FbxList(String) {} #endif //--------------------------------------------------------------------------------------------------------------------------- void FbxListScene(Command& args) { String name; args.GetNextString(name); String filepath = "Data/FBX/" + name + ".fbx"; FbxList(filepath); }
31.018182
125
0.505275
ntaylorbishop
a4ce1d66d89ee509a9a44a5fb854ccf340431624
1,082
cpp
C++
src/classwork/03_assign/decision.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-JustinBrewer22
5756943881ca972a5f2f4fc634dde8b65158e3d5
[ "MIT" ]
null
null
null
src/classwork/03_assign/decision.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-JustinBrewer22
5756943881ca972a5f2f4fc634dde8b65158e3d5
[ "MIT" ]
null
null
null
src/classwork/03_assign/decision.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-JustinBrewer22
5756943881ca972a5f2f4fc634dde8b65158e3d5
[ "MIT" ]
null
null
null
//cpp #include "decision.h" using namespace std; string get_letter_grade_using_if(int numgrade) { string letter_grade; if(numgrade >= 90 && numgrade <= 100) { letter_grade = "A"; } else if(numgrade >=80 && numgrade <= 89) { letter_grade = "B"; } else if(numgrade >=70 && numgrade <= 79) { letter_grade = "C"; } else if(numgrade >=60 && numgrade <= 69) { letter_grade = "D"; } else { letter_grade = "F"; } return letter_grade; } string get_letter_grade_using_switch(int numgrade) { string letter_grade; numgrade = numgrade - (numgrade % 10); switch(numgrade) { case 100: case 90: letter_grade = "A"; break; case 80: letter_grade = "B"; break; case 70: letter_grade = "C"; break; case 60: letter_grade = "D"; break; case 50: case 40: case 30: case 20: case 10: case 0: letter_grade = "F"; break; } return letter_grade; }
19.321429
60
0.519409
acc-cosc-1337-spring-2021
a4d4e3753fb7c2897c61dfdc53edd8ef7aaccdbf
13,718
cpp
C++
Src/ViceConnect.cpp
Sakrac/Step6502
3b8c3058a7997a2ff739e1d2c85fd150c3c33e5e
[ "MIT" ]
8
2017-02-13T06:53:00.000Z
2021-05-21T20:35:56.000Z
Src/ViceConnect.cpp
Sakrac/Step6502
3b8c3058a7997a2ff739e1d2c85fd150c3c33e5e
[ "MIT" ]
null
null
null
Src/ViceConnect.cpp
Sakrac/Step6502
3b8c3058a7997a2ff739e1d2c85fd150c3c33e5e
[ "MIT" ]
null
null
null
// start a telnet connection with a local instance of VICE #include "stdafx.h" #include "winsock2.h" #include <ws2tcpip.h> #include <inttypes.h> #include "machine.h" #include "MainFrm.h" #include "Step6502.h" #include "Expressions.h" #include "Sym.h" class ViceConnect { public: enum { RECEIVE_SIZE = 4096 }; ViceConnect() : activeConnection(false), threadHandle(INVALID_HANDLE_VALUE) {} bool openConnection(char* address, int port); void connectionThread(); bool connect(); void close(); bool open(char* address, int port); struct sockaddr_in addr; SOCKET s; HANDLE threadHandle; bool activeConnection; bool closeRequest; bool viceRunning; bool monitorOn; bool stopRequest; }; static ViceConnect sVice; static const char* sViceRunning = "\n<VICE started>\n"; static const char* sViceStopped = "<VICE stopped>\n"; static const char* sViceConnected = "<VICE connected>\n"; static const char* sViceDisconnected = "<VICE disconnected>\n"; static const char* sViceLost = "<VICE connection lost>\n"; static const int sViceLostLen = (const int)strlen(sViceLost); static const char* sViceRun = "x\n"; static const char* sViceDel = "del\n"; static char sViceExit[64]; static int sViceExitLen; void ViceSend(const char *string, int length) { if (sVice.activeConnection) { if (length&&(string[0]=='x'||string[0]=='X'||string[0]=='g'||string[0]=='G')) { memcpy(sViceExit, string, length); sViceExitLen = length; sVice.viceRunning = true; } send(sVice.s, string, length, NULL); } } bool ViceAction() { if (sVice.activeConnection) { if (sVice.monitorOn) { ViceSend(sViceRun, (int)strlen(sViceRun)); return true; } sVice.close(); if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(sViceDisconnected, (int)strlen(sViceDisconnected)); } return false; } return sVice.connect(); } bool ViceRunning() { return sVice.activeConnection && !sVice.monitorOn; } void ViceBreak() { sVice.stopRequest = true; } void ViceConnectShutdown() { if (sVice.activeConnection) { sVice.close(); } } unsigned long WINAPI ViceConnectThread(void* data) { ((ViceConnect*)data)->connectionThread(); return 0; } bool ViceConnect::connect() { monitorOn = false; closeRequest = false; activeConnection = false; if (openConnection("127.0.0.1", 6510)) { unsigned long threadId; threadHandle = CreateThread(NULL, 16384, ViceConnectThread, this, NULL, &threadId); } return false; } void ViceConnect::close() { if (threadHandle!=INVALID_HANDLE_VALUE) { CloseHandle(threadHandle); threadHandle = INVALID_HANDLE_VALUE; } closesocket(s); WSACleanup(); activeConnection = false; closeRequest = false; } // Open a connection to a remote host bool ViceConnect::open(char* address, int port) { // Make sure the user has specified a port if (port<0||port > 65535) { return false; } WSADATA wsaData = {0}; int iResult = 0; DWORD dwRetval; struct sockaddr_in saGNI; char hostname[NI_MAXHOST]; char servInfo[NI_MAXSERV]; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return false; } //----------------------------------------- // Set up sockaddr_in structure which is passed // to the getnameinfo function saGNI.sin_family = AF_INET; inet_pton(AF_INET, address, &(saGNI.sin_addr.s_addr)); // saGNI.sin_addr.s_addr = // InetPton(AF_INET, strIP, &ipv4addr) // inet_addr(address); saGNI.sin_port = htons(port); //----------------------------------------- // Call getnameinfo dwRetval = getnameinfo((struct sockaddr *) &saGNI, sizeof (struct sockaddr), hostname, NI_MAXHOST, servInfo, NI_MAXSERV, NI_NUMERICSERV); if (dwRetval != 0) { return false; } iResult = ::connect(s, (struct sockaddr *)&saGNI, sizeof(saGNI)); return iResult==0; } bool ViceConnect::openConnection(char* address, int port) { WSADATA ws; // Load the WinSock dll long status = WSAStartup(0x0101,&ws); if (status!=0) { return false; } memset(&addr, 0, sizeof(addr)); s = socket(AF_INET, SOCK_STREAM, 0); // Open the connection if (!open(address, port)) { return false; } activeConnection = true; return true; } enum ViceUpdate { Vice_None, Vice_Start, Vice_Memory, Vice_Labels, Vice_Breakpoints, Vice_Registers, Vice_Wait, Vice_SendBreakpoints, Vice_Return, Vice_Break, }; bool ProcessViceLine(const char* line, int len) { while (len) { if (len>3 && line[0]=='>' && line[1]=='C' && line[2]==':') { char* end; line += 3; len -= 3; uint32_t addr = strtol(line, &end, 16); len += (int)(end-line); line = end; while (len>=3 && !(line[0]==' ' && line[1]==' ' && line[2]==' ') &&line[0]!=0x0a) { while (len && *line==' ') { ++line; --len; } uint32_t byte = strtol(line, &end, 16); len += (int)(end-line); line = end; Set6502Byte(uint16_t(addr++), uint8_t(byte)); if (addr==0x10000) return true; } break; } else { ++line; --len; } } return false; } // (C:$e5d4) shl // $0421 .Label2 // $1234 .Label1 bool ProcessViceLabel(char* line, int len) { if (*line=='$' && line[6]=='.') { wchar_t name[256]; char *end; uint16_t addr = (uint16_t)strtol(line+1, &end, 16); size_t namelen; line[len] = 0; for(int c=6;;++c) { { if (line[c]<=0x20) { line[c]=0; break; } } } mbstowcs_s(&namelen, name, line+6, 256); AddSymbol(addr, name, namelen-1); } return false; } static uint32_t lastBPID = ~0UL; bool ProcessBKLine(char* line, int len) { // check "No breakpoints are set" if( _strnicmp(line, "No breakpoints", 14)==0 ) { return true; } // "BREAK: 3 C:$1300 (Stop on exec)" if( _strnicmp(line, "BREAK:", 6)==0) { while (len>=4&&*line!='$') { ++line; --len; } char *end; lastBPID = SetPCBreakpoint((uint16_t)strtol(line+1, &end, 16)); return false; } // "Condition: A != $00" if( _strnicmp(line, "\tCondition:", 11)==0 && lastBPID != ~0UL ) { while( len && ((uint8_t)line[len-1])<=' ') { --len; } line[len] = 0; wchar_t display[128]; size_t displen; mbstowcs_s(&displen, display, line + 12, 128); uint8_t ops[64]; uint32_t len = BuildExpression(display, ops, sizeof(ops)); SetBPCondition(lastBPID, ops, len); if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->BPDisplayExpression( lastBPID, display ); } return false; } if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(line, len); } return false; } bool ProcessViceRegisters(char* regs, int left) { // ADDR A X Y SP 00 01 NV-BDIZC LIN CYC STOPWATCH // .;e5d1 00 00 0a f3 2f 37 00100010 000 000 9533160 if (regs[0] == '.' && left > 32) { Regs r; char* end = regs + left, *erp = end; r.PC = (uint16_t)strtol(regs+2, &end, 16); end = erp; r.A = (uint8_t)strtol(regs+7, &end, 16); end = erp; r.X = (uint8_t)strtol(regs+10, &end, 16); end = erp; r.Y = (uint8_t)strtol(regs+13, &end, 16); end = erp; r.S = (uint8_t)strtol(regs+16, &end, 16); end = erp; r.P = (uint8_t)strtol(regs+25, &end, 2); SetRegs(r); ResetUndoBuffer(); return true; } return false; } const char* sMemory = "m $0000 $ffff\n"; const char* sRegisters = "r\n"; const char* sLabels = "shl\n"; const char* sBreakpoints = "bk\n"; // waits for vice break after connection is established void ViceConnect::connectionThread() { DWORD timeout = 100;// SOCKET_READ_TIMEOUT_SEC*1000; setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); char recvBuf[RECEIVE_SIZE]; char line[512]; int offs = 0; sViceExit[0] = 0; ViceUpdate state = Vice_None; viceRunning = false; if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(sViceConnected, (int)strlen(sViceConnected)); } uint8_t *RAM = nullptr; int currBreak = 0; stopRequest = false; while(activeConnection) { if (closeRequest) { threadHandle = INVALID_HANDLE_VALUE; close(); break; } if (viceRunning) { state = Vice_SendBreakpoints; currBreak = 0; viceRunning = false; send(s, sViceDel, 4, NULL); } int bytesReceived = recv(s, recvBuf, RECEIVE_SIZE,0); if (bytesReceived==SOCKET_ERROR) { if (WSAGetLastError()==WSAETIMEDOUT) { if (state==Vice_None && stopRequest) { send(s, "\n", 1, NULL); stopRequest = false; } Sleep(100); } else { activeConnection = false; break; } } else { int read = 0; while (read<bytesReceived) { char c = line[offs++] = recvBuf[read++]; // vice prompt = (C:$????) bool prompt = offs>=9&&line[8]==')'&&strncmp(line, "(C:$", 4)==0; // vice sends lines so process one line at a time if (c==0x0a||offs==sizeof(line)||prompt||((state==Vice_Wait) && read==bytesReceived)) { if (state==Vice_Return) { if (prompt) { state = Vice_None; } else if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(line, offs); } } else if (state==Vice_None) { if (prompt) { // first connection => start reading memory send(s, sMemory, (int)strlen(sMemory), NULL); state = Vice_Memory; monitorOn = true; if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(sViceStopped, (int)strlen(sViceStopped)); pFrame->Invalidate(); } } } else if (state==Vice_Memory) { if (prompt || ProcessViceLine(line, offs)) { while (recv(s, recvBuf, RECEIVE_SIZE, 0)!=SOCKET_ERROR) { Sleep(1); } if( RAM ) { free(RAM); } RAM = (uint8_t*)malloc(64*1024); memcpy(RAM, Get6502Mem(), 64*1024); RemoveBreakpointByID(-1); lastBPID = ~0UL; state = Vice_Labels; ShutdownSymbols(); send(s, sLabels, (int)strlen(sLabels), NULL); offs = 0; break; } } else if (state==Vice_Labels) { if (prompt || ProcessViceLabel(line, offs)) { while (recv(s, recvBuf, RECEIVE_SIZE, 0)!=SOCKET_ERROR) { Sleep(1); } RemoveBreakpointByID(-1); lastBPID = ~0UL; state = Vice_Breakpoints; send(s, sBreakpoints, (int)strlen(sBreakpoints), NULL); offs = 0; break; } } else if (state==Vice_Breakpoints) { if (prompt || ProcessBKLine(line, offs)) { if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->BreakpointChanged(); } send(s, sRegisters, (int)strlen(sRegisters), NULL); state = Vice_Registers; offs = 0; break; } } else if (state==Vice_Registers) { if (ProcessViceRegisters(line, offs)) { if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->FocusPC(); pFrame->MachineUpdated(); pFrame->ViceInput(true); } state = Vice_Wait; } } else if( state == Vice_SendBreakpoints ) { if (prompt) { offs = 0; uint16_t numDis; uint16_t *pBP = nullptr; uint32_t *pID = nullptr; uint16_t num = GetPCBreakpointsID(&pBP, &pID, numDis); if ((int)num<=currBreak) { while (recv(s, recvBuf, RECEIVE_SIZE, 0)!=SOCKET_ERROR) { Sleep(1); } // update registers { char reg[64]; const Regs r = GetRegs(); int l = sprintf_s( reg, sizeof(reg), "r pc=$%04x,a=$%02x,x=$%02x,y=$%02x,sp=$%02x,fl=$%02x\n", r.PC, r.A, r.X, r.Y, r.S, r.P ); send(s, reg, l, 0); } while (recv(s, recvBuf, RECEIVE_SIZE, 0)!=SOCKET_ERROR) { Sleep(1); } // update memory if changed if (RAM) { char memstr[6+4*256+4]; int sl = (int)sizeof(memstr); uint16_t a = 0; const uint8_t *m = Get6502Mem(); do { if( RAM[a] != m[a] ) { int bytes = 0; int o = sprintf_s(memstr, sl, ">$%04x", a); uint16_t n = a; while( n && (n-a)<256 ) { o += sprintf_s(memstr+o, sl-o, " $%02x", m[n]); ++n; if( n && RAM[n]==m[n] ) { uint16_t p = n; while( p && (p-n)<4 && RAM[p]==m[p] ) { ++p; } if( !p || (p-n)==4) { break; } } } a = n; o += sprintf_s(memstr+o, sl-o, "\n"); send(s, memstr, o, 0); while (recv(s, recvBuf, RECEIVE_SIZE, 0)!=SOCKET_ERROR) { Sleep(1); } } else { ++a; } } while( a ); free(RAM); RAM = nullptr; } // finally send the exit command send(s, sViceExit, sViceExitLen, 0); sViceExit[0] = 0; monitorOn = false; if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->ViceMonClear(); pFrame->VicePrint(sViceRunning, (int)strlen(sViceRunning)); } state = Vice_None; read = bytesReceived; } else { char buf[256]; int l = sprintf_s(buf, sizeof(buf), "bk $%04x", pBP[currBreak]); if (CMainFrame *pFrame = theApp.GetMainFrame()) { if (const wchar_t *pExpr = pFrame->GetBPExpression(pID[currBreak])) { char expr[128]; size_t lex; wcstombs_s(&lex, expr, pExpr, sizeof(expr)); l += sprintf_s(buf+l, sizeof(buf)-l, " if %s", expr); } } l += sprintf_s(buf+l, sizeof(buf)-l, "\n"); send(sVice.s, buf, l, NULL); if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(buf, l); } ++currBreak; } } } else { if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(line, offs); pFrame->ViceInput(true); } } offs = 0; } } } } if( RAM ) { free(RAM); } if (CMainFrame *pFrame = theApp.GetMainFrame()) { pFrame->VicePrint(sViceLost, sViceLostLen); } }
25.834275
104
0.598411
Sakrac
a4d86f8d122ee0dec820b941e42c8af4899e6e7a
26,544
cpp
C++
src/libcore/src/ccm/io/File.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
6
2018-05-08T10:08:21.000Z
2021-11-13T13:22:58.000Z
src/libcore/src/ccm/io/File.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
1
2018-05-08T10:20:17.000Z
2018-07-23T05:19:19.000Z
src/libcore/src/ccm/io/File.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
4
2018-03-13T06:21:11.000Z
2021-06-19T02:48:07.000Z
//========================================================================= // Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project // // 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 "ccm/core/CoreUtils.h" #include "ccm/core/CRuntimePermission.h" #include "ccm/core/Math.h" #include "ccm/core/StringUtils.h" #include "ccm/core/System.h" #include "ccm/io/CFile.h" #include "ccm/io/DefaultFileSystem.h" #include "ccm/io/DeleteOnExitHook.h" #include "ccm/io/File.h" #include "ccm/util/CArrayList.h" #include "ccm.core.ICharSequence.h" #include "ccm.core.ILong.h" #include "ccm.security.IPermission.h" #include "ccm.util.IList.h" #include <ccmlogger.h> using ccm::core::CoreUtils; using ccm::core::CRuntimePermission; using ccm::core::IID_IComparable; using ccm::core::ICharSequence; using ccm::core::IID_ICharSequence; using ccm::core::ILong; using ccm::core::ISecurityManager; using ccm::core::Math; using ccm::core::StringUtils; using ccm::core::System; using ccm::io::IID_ISerializable; using ccm::security::IPermission; using ccm::security::IID_IPermission; using ccm::util::CArrayList; using ccm::util::IList; using ccm::util::IID_IList; namespace ccm { namespace io { CCM_INTERFACE_IMPL_3(File, SyncObject, IFile, ISerializable, IComparable); AutoPtr<FileSystem> File::GetFS() { static AutoPtr<FileSystem> FS = DefaultFileSystem::GetFileSystem(); return FS; } Boolean File::IsInvalid() { if (mStatus == PathStatus::UNKNOWN) { mStatus = (mPath.IndexOf(U'\0') < 0) ? PathStatus::CHECKED : PathStatus::INVALID; } return mStatus == PathStatus::INVALID; } ECode File::GetPrefixLength( /* [out] */ Integer* length) { VALIDATE_NOT_NULL(length); *length = mPrefixLength; return NOERROR; } Char File::GetSeparatorChar() { Char c; static const Char sSeparatorChar = (GetFS()->GetSeparator(&c), c); return sSeparatorChar; } ECode File::Constructor( /* [in] */ const String& pathname, /* [in] */ Integer prefixLength) { mPath = pathname; mPrefixLength = prefixLength; return NOERROR; } ECode File::Constructor( /* [in] */ const String& child, /* [in] */ IFile* parent) { String ppath; parent->GetPath(&ppath); GetFS()->Resolve(ppath, child, &mPath); parent->GetPrefixLength(&mPrefixLength); return NOERROR; } ECode File::Constructor( /* [in] */ const String& pathname) { if (pathname.IsNull()) { return ccm::core::E_NULL_POINTER_EXCEPTION; } FileSystem* fs = GetFS(); fs->Normalize(pathname, &mPath); fs->PrefixLength(mPath, &mPrefixLength); return NOERROR; } ECode File::Constructor( /* [in] */ const String& parent, /* [in] */ const String& child) { if (child.IsNull()) { return ccm::core::E_NULL_POINTER_EXCEPTION; } FileSystem* fs = GetFS(); if (!parent.IsNullOrEmpty()) { String normPpath, normCpath; fs->Normalize(parent, &normPpath); fs->Normalize(child, &normCpath); fs->Resolve(normPpath, normCpath, &mPath); } else { fs->Normalize(child, &mPath); } fs->PrefixLength(mPath, &mPrefixLength); return NOERROR; } ECode File::Constructor( /* [in] */ IFile* parent, /* [in] */ const String& child) { if (child.IsNull()) { return ccm::core::E_NULL_POINTER_EXCEPTION; } FileSystem* fs = GetFS(); if (parent != nullptr) { String ppath; parent->GetPath(&ppath); if (ppath.Equals("")) { String normPpath, normCpath; fs->GetDefaultParent(&normPpath); fs->Normalize(child, &normCpath); fs->Resolve(normPpath, normCpath, &mPath); } else { String normCpath; fs->Normalize(child, &normCpath); fs->Resolve(ppath, normCpath, &mPath); } } else { fs->Normalize(child, &mPath); } fs->PrefixLength(mPath, &mPrefixLength); return NOERROR; } ECode File::Constructor( /* [in] */ IURI* uri) { Boolean absolute; if (uri->IsAbsolute(&absolute), !absolute) { Logger::E("File", "URI is not absolute"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } Boolean opaque; if (uri->IsOpaque(&opaque), opaque) { Logger::E("File", "URI is not hierarchical"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } String scheme; uri->GetScheme(&scheme); if (scheme.IsNull() || !scheme.EqualsIgnoreCase("file")) { Logger::E("File", "URI scheme is not \"file\""); return E_ILLEGAL_ARGUMENT_EXCEPTION; } String authority; if (uri->GetAuthority(&authority), !authority.IsNull()) { Logger::E("File", "URI has an authority component"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } String fragment; if (uri->GetFragment(&fragment), !fragment.IsNull()) { Logger::E("File", "URI has a fragment component"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } String query; if (uri->GetQuery(&query), !query.IsNull()) { Logger::E("File", "URI has a query component"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } String p; uri->GetPath(&p); if (p.Equals("")) { Logger::E("File", "URI path component is empty"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } FileSystem* fs = GetFS(); fs->FromURIPath(p, &p); if (GetSeparatorChar() != U'/') { p = p.Replace(U'/', GetSeparatorChar()); } fs->Normalize(p, &mPath); fs->PrefixLength(mPath, &mPrefixLength); return NOERROR; } ECode File::GetName( /* [out] */ String* name) { VALIDATE_NOT_NULL(name); Integer index = mPath.LastIndexOf(GetSeparatorChar()); if (index < mPrefixLength) { *name = mPath.Substring(mPrefixLength); } else { *name = mPath.Substring(index + 1); } return NOERROR; } ECode File::GetParent( /* [out] */ String* parent) { VALIDATE_NOT_NULL(parent); Integer index = mPath.LastIndexOf(GetSeparatorChar()); if (index < mPrefixLength) { if (mPrefixLength > 0 && mPath.GetLength() > mPrefixLength) { *parent = mPath.Substring(0, mPrefixLength); return NOERROR; } *parent = nullptr; return NOERROR; } else { *parent = mPath.Substring(0, index); return NOERROR; } } ECode File::GetParentFile( /* [out] */ IFile** parent) { VALIDATE_NOT_NULL(parent); String p; GetParent(&p); if (p.IsNull()) { *parent = nullptr; return NOERROR; } return CFile::New(p, mPrefixLength, IID_IFile, (IInterface**)parent); } ECode File::GetPath( /* [out] */ String* path) { VALIDATE_NOT_NULL(path); *path = mPath; return NOERROR; } ECode File::IsAbsolute( /* [out] */ Boolean* absolute) { return GetFS()->IsAbsolute(this, absolute); } ECode File::GetAbsolutePath( /* [out] */ String* path) { return GetFS()->Resolve(this, path); } ECode File::GetAbsoluteFile( /* [out] */ IFile** f) { VALIDATE_NOT_NULL(f); String absPath; GetAbsolutePath(&absPath); Integer prefLen; GetFS()->PrefixLength(absPath, &prefLen); return CFile::New(absPath, prefLen, IID_IFile, (IInterface**)f); } ECode File::GetCanonicalPath( /* [out] */ String* path) { VALIDATE_NOT_NULL(path); if (IsInvalid()) { Logger::E("File", "Invalid file path"); return E_IO_EXCEPTION; } FileSystem* fs = GetFS(); String p; fs->Resolve(this, &p); return fs->Canonicalize(p, path); } ECode File::GetCanonicalFile( /* [out] */ IFile** f) { VALIDATE_NOT_NULL(f); String canonPath; FAIL_RETURN(GetCanonicalPath(&canonPath)); Integer prefLen; GetFS()->PrefixLength(canonPath, &prefLen); return CFile::New(canonPath, prefLen, IID_IFile, (IInterface**)f); } String File::Slashify( /* [in] */ const String& path, /* [in] */ Boolean isDirectory) { String p = path; if (GetSeparatorChar() != U'/') { p = p.Replace(GetSeparatorChar(), U'/'); } if (!p.StartsWith("/")) { p = String("/") + p; } if (!p.EndsWith("/") && isDirectory) { p = p + "/"; } return p; } ECode File::ToURL( /* [out] */ IURL** url) { return NOERROR; } ECode File::ToURI( /* [out] */ IURI** id) { return NOERROR; } ECode File::CanRead( /* [out] */ Boolean* readable) { VALIDATE_NOT_NULL(readable); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *readable = false; return NOERROR; } return GetFS()->CheckAccess(this, FileSystem::ACCESS_READ, readable); } ECode File::CanWrite( /* [out] */ Boolean* writeable) { VALIDATE_NOT_NULL(writeable); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { *writeable = false; return NOERROR; } return GetFS()->CheckAccess(this, FileSystem::ACCESS_WRITE, writeable); } ECode File::Exists( /* [out] */ Boolean* existed) { VALIDATE_NOT_NULL(existed); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *existed = false; return NOERROR; } return GetFS()->CheckAccess(this, FileSystem::ACCESS_OK, existed); } ECode File::IsDirectory( /* [out] */ Boolean* directory) { VALIDATE_NOT_NULL(directory); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *directory = false; return NOERROR; } Integer attrs; GetFS()->GetBooleanAttributes(this, &attrs); *directory = (attrs & FileSystem::BA_DIRECTORY) != 0; return NOERROR; } ECode File::IsFile( /* [out] */ Boolean* file) { VALIDATE_NOT_NULL(file); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *file = false; return NOERROR; } Integer attrs; GetFS()->GetBooleanAttributes(this, &attrs); *file = (attrs & FileSystem::BA_REGULAR) != 0; return NOERROR; } ECode File::IsHidden( /* [out] */ Boolean* hidden) { VALIDATE_NOT_NULL(hidden); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *hidden = false; return NOERROR; } Integer attrs; GetFS()->GetBooleanAttributes(this, &attrs); *hidden = (attrs & FileSystem::BA_HIDDEN) != 0; return NOERROR; } ECode File::LastModified( /* [out] */ Long* time) { VALIDATE_NOT_NULL(time); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *time = 0; return NOERROR; } return GetFS()->GetLastModifiedTime(this, time); } ECode File::GetLength( /* [out] */ Long* len) { VALIDATE_NOT_NULL(len); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *len = 0; return NOERROR; } return GetFS()->GetLength(this, len); } ECode File::CreateNewFile( /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { Logger::E("File", "Invalid file path"); return E_IO_EXCEPTION; } return GetFS()->CreateFileExclusively(mPath, succeeded); } ECode File::Delete( /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckDelete(mPath)); } if (IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->Delete(this, succeeded); } ECode File::DeleteOnExit() { AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckDelete(mPath)); } if (IsInvalid()) { return NOERROR; } DeleteOnExitHook::Add(mPath); return NOERROR; } ECode File::List( /* [out, callee] */ Array<String>* files) { VALIDATE_NOT_NULL(files); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *files = Array<String>::Null(); return NOERROR; } return GetFS()->List(this, files); } ECode File::List( /* [in] */ IFilenameFilter* filter, /* [out, callee] */ Array<String>* files) { VALIDATE_NOT_NULL(files); Array<String> names; FAIL_RETURN(List(&names)); if (names.IsNull() || filter == nullptr) { *files = names; return NOERROR; } AutoPtr<IList> v; CArrayList::New(IID_IList, (IInterface**)&v); for (Integer i = 0; i < names.GetLength(); i++) { Boolean accepted; if (filter->Accept(this, names[i], &accepted), accepted) { v->Add(CoreUtils::Box(names[i])); } } Array<ICharSequence*> seqs; v->ToArray(IID_ICharSequence, (Array<IInterface*>*)&seqs); *files = CoreUtils::Unbox(seqs); return NOERROR; } ECode File::ListFiles( /* [out, callee] */ Array<IFile*>* files) { VALIDATE_NOT_NULL(files); Array<String> ss; FAIL_RETURN(List(&ss)); if (ss.IsNull()) { *files = Array<IFile*>::Null(); return NOERROR; } Integer n = ss.GetLength(); Array<IFile*> fs(n); for (Integer i = 0; i < n; i++) { AutoPtr<IFile> f; CFile::New(ss[i], this, IID_IFile, (IInterface**)&f); fs.Set(i, f); } *files = fs; return NOERROR; } ECode File::ListFiles( /* [in] */ IFilenameFilter* filter, /* [out, callee] */ Array<IFile*>* files) { VALIDATE_NOT_NULL(files); Array<String> ss; FAIL_RETURN(List(&ss)); if (ss.IsNull()) { *files = Array<IFile*>::Null(); return NOERROR; } AutoPtr<IList> v; CArrayList::New(IID_IList, (IInterface**)&v); for (Integer i = 0; i < ss.GetLength(); i++) { Boolean accepted; if (filter == nullptr || (filter->Accept(this, ss[i], &accepted), accepted)) { AutoPtr<IFile> f; CFile::New(ss[i], this, IID_IFile, (IInterface**)&f); v->Add(f); } } return v->ToArray((Array<IInterface*>*)files); } ECode File::ListFiles( /* [in] */ IFileFilter* filter, /* [out, callee] */ Array<IFile*>* files) { VALIDATE_NOT_NULL(files); Array<String> ss; FAIL_RETURN(List(&ss)); if (ss.IsNull()) { *files = Array<IFile*>::Null(); return NOERROR; } AutoPtr<IList> v; CArrayList::New(IID_IList, (IInterface**)&v); for (Integer i = 0; i < ss.GetLength(); i++) { AutoPtr<IFile> f; CFile::New(ss[i], this, IID_IFile, (IInterface**)&f); Boolean accepted; if (filter == nullptr || (filter->Accept(f, &accepted), accepted)) { v->Add(f); } } return v->ToArray((Array<IInterface*>*)files); } ECode File::Mkdir( /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->CreateDirectory(this, succeeded); } ECode File::Mkdirs( /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); Boolean existed; FAIL_RETURN(Exists(&existed)); if (existed) { *succeeded = false; return NOERROR; } FAIL_RETURN(Mkdir(succeeded)); if (*succeeded) { return NOERROR; } AutoPtr<IFile> canonFile; ECode ec = GetCanonicalFile(&canonFile); if (FAILED(ec)) { *succeeded = false; return NOERROR; } AutoPtr<IFile> parent; canonFile->GetParentFile(&parent); if (parent == nullptr) { *succeeded = false; return NOERROR; } FAIL_RETURN(parent->Mkdirs(succeeded)); if (!*succeeded) { FAIL_RETURN(parent->Exists(&existed)); if (!existed) { *succeeded = false; return NOERROR; } } return canonFile->Mkdir(succeeded); } ECode File::RenameTo( /* [in] */ IFile* dest, /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); if (dest == nullptr) { return ccm::core::E_NULL_POINTER_EXCEPTION; } AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); String dPath; dest->GetPath(&dPath); FAIL_RETURN(security->CheckWrite(dPath)); } if (IsInvalid() || From(dest)->IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->Rename(this, dest, succeeded); } ECode File::SetLastModified( /* [in] */ Long time, /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); if (time < 0) { Logger::E("File", "Negative time"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->SetLastModifiedTime(this, time, succeeded); } ECode File::SetReadOnly( /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->SetReadOnly(this, succeeded); } ECode File::SetWritable( /* [in] */ Boolean writable, /* [in] */ Boolean ownerOnly, /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->SetPermission(this, FileSystem::ACCESS_WRITE, writable, ownerOnly, succeeded); } ECode File::SetWritable( /* [in] */ Boolean writable, /* [out] */ Boolean* succeeded) { return SetWritable(writable, true, succeeded); } ECode File::SetReadable( /* [in] */ Boolean readable, /* [in] */ Boolean ownerOnly, /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->SetPermission(this, FileSystem::ACCESS_READ, readable, ownerOnly, succeeded); } ECode File::SetReadable( /* [in] */ Boolean readable, /* [out] */ Boolean* succeeded) { return SetReadable(readable, true, succeeded); } ECode File::SetExecutable( /* [in] */ Boolean executable, /* [in] */ Boolean ownerOnly, /* [out] */ Boolean* succeeded) { VALIDATE_NOT_NULL(succeeded); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckWrite(mPath)); } if (IsInvalid()) { *succeeded = false; return NOERROR; } return GetFS()->SetPermission(this, FileSystem::ACCESS_EXECUTE, executable, ownerOnly, succeeded); } ECode File::SetExecutable( /* [in] */ Boolean executable, /* [out] */ Boolean* succeeded) { return SetExecutable(executable, true, succeeded); } ECode File::CanExecute( /* [out] */ Boolean* executable) { VALIDATE_NOT_NULL(executable); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { FAIL_RETURN(security->CheckExec(mPath)); } if (IsInvalid()) { *executable = false; return NOERROR; } return GetFS()->CheckAccess(this, FileSystem::ACCESS_EXECUTE, executable); } ECode File::ListRoots( /* [out, callee] */ Array<IFile*>* roots) { return GetFS()->ListRoots(roots); } ECode File::GetTotalSpace( /* [out] */ Long* space) { VALIDATE_NOT_NULL(space); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { AutoPtr<IPermission> perm; CRuntimePermission::New(String("getFileSystemAttributes"), IID_IPermission, (IInterface**)&perm); FAIL_RETURN(security->CheckPermission(perm)); FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *space = 0; return NOERROR; } return GetFS()->GetSpace(this, FileSystem::SPACE_TOTAL, space); } ECode File::GetFreeSpace( /* [out] */ Long* space) { VALIDATE_NOT_NULL(space); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { AutoPtr<IPermission> perm; CRuntimePermission::New(String("getFileSystemAttributes"), IID_IPermission, (IInterface**)&perm); FAIL_RETURN(security->CheckPermission(perm)); FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *space = 0; return NOERROR; } return GetFS()->GetSpace(this, FileSystem::SPACE_FREE, space); } ECode File::GetUsableSpace( /* [out] */ Long* space) { VALIDATE_NOT_NULL(space); AutoPtr<ISecurityManager> security = System::GetSecurityManager(); if (security != nullptr) { AutoPtr<IPermission> perm; CRuntimePermission::New(String("getFileSystemAttributes"), IID_IPermission, (IInterface**)&perm); FAIL_RETURN(security->CheckPermission(perm)); FAIL_RETURN(security->CheckRead(mPath)); } if (IsInvalid()) { *space = 0; return NOERROR; } return GetFS()->GetSpace(this, FileSystem::SPACE_USABLE, space); } ECode File::CreateTempFile( /* [in] */ const String& prefix, /* [in] */ const String& _suffix, /* [in] */ IFile* directory, /* [out] */ IFile** temp) { VALIDATE_NOT_NULL(temp); if (prefix.GetLength() < 3) { Logger::E("File", "Prefix string too short"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } String suffix = _suffix; if (suffix.IsNull()) { suffix = ".tmp"; } AutoPtr<IFile> tmpdir = directory; if (tmpdir == nullptr) { String dir; FAIL_RETURN(System::GetProperty(String("ccm.io.tmpdir"), String("."), &dir)); CFile::New(dir, IID_IFile, (IInterface**)&tmpdir); } AutoPtr<IFile> f; Integer attrs; do { f = nullptr; TempDirectory::GenerateFile(prefix, suffix, tmpdir, &f); } while (GetFS()->GetBooleanAttributes(f, &attrs), (attrs & FileSystem::BA_EXISTS) != 0); String path; f->GetPath(&path); Boolean succeeded; if (GetFS()->CreateFileExclusively(path, &succeeded), !succeeded) { Logger::E("File", "Unable to create temporary file"); return E_IO_EXCEPTION; } f.MoveTo(temp); return NOERROR; } ECode File::CreateTempFile( /* [in] */ const String& prefix, /* [in] */ const String& suffix, /* [out] */ IFile** temp) { return CreateTempFile(prefix, suffix, nullptr, temp); } ECode File::CompareTo( /* [in] */ IInterface* other, /* [out] */ Integer* result) { return GetFS()->Compare(this, IFile::Probe(other), result); } ECode File::Equals( /* [in] */ IInterface* obj, /* [out] */ Boolean* same) { VALIDATE_NOT_NULL(same); if (obj != nullptr && IFile::Probe(obj) != nullptr) { Integer result; CompareTo(obj, &result); *same = result == 0; return NOERROR; } *same = false; return NOERROR; } ECode File::GetHashCode( /* [out] */ Integer* hash) { return GetFS()->GetHashCode(this, hash); } ECode File::ToString( /* [out] */ String* desc) { return GetPath(desc); } //------------------------------------------------------------------------- ECode File::TempDirectory::GenerateFile( /* [in] */ const String& prefix, /* [in] */ const String& suffix, /* [in] */ IFile* dir, /* [out] */ IFile** temp) { Long n = Math::RandomLongInternal(); if (n == ILong::MIN_VALUE) { n = 0; // corner case } else { n = Math::Abs(n); } String name = prefix + StringUtils::ToString(n) + suffix; AutoPtr<IFile> f; CFile::New(dir, name, IID_IFile, (IInterface**)&f); String fName; Boolean invalid; if ((f->GetName(&fName), !name.Equals(fName)) || File::From(f)->IsInvalid()) { Logger::E("File", "Unable to create temporary file"); return E_IO_EXCEPTION; } f.MoveTo(temp); return NOERROR; } } }
25.376673
105
0.600437
sparkoss
a4db2913c015221a0cd18007c7249df6f7c4b09e
4,822
cpp
C++
examples_c++/FrameworkDemo/FrameworkDemo_AGK/jugiAppAGK.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
8
2020-11-23T23:34:39.000Z
2022-02-23T12:14:02.000Z
examples_c++/FrameworkDemo/FrameworkDemo_AGK/jugiAppAGK.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
null
null
null
examples_c++/FrameworkDemo/FrameworkDemo_AGK/jugiAppAGK.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
3
2019-12-19T13:44:43.000Z
2020-05-15T01:02:10.000Z
#include <chrono> #include <assert.h> #include "jugiAppAGK.h" namespace jugiApp{ using namespace jugimap; bool PlatformerSceneAGK::Init() { if(PlatformerScene::Init()==false){ return false; } //--- agk::SetPhysicsGravity(0, 500); return true; } void PlatformerSceneAGK::SetDynamicCrystalsPhysics() { if(dynamicCrystals){ //---- turn ON static physics mode for main world tiles SpriteLayer *layer = dynamic_cast<SpriteLayer*>(FindLayerWithName(worldMap, "Main construction")); assert(layer); for(Sprite* s : layer->GetSprites()){ if(s->GetKind()==SpriteKind::STANDARD){ static_cast<StandardSpriteAGK*>(s)->SetPhysicsMode(StandardSpriteAGK::PhysicsMode::STATIC); } } //---- turn ON static physics mode for characters layer = dynamic_cast<SpriteLayer*>(FindLayerWithName(worldMap, "Characters")); assert(layer); for(Sprite* s : layer->GetSprites()){ if(s->GetKind()==SpriteKind::STANDARD){ static_cast<StandardSpriteAGK*>(s)->SetPhysicsMode(StandardSpriteAGK::PhysicsMode::KINEMATIC); //or static } } //---- turn ON dynamic physics mode for crystals layer = dynamic_cast<SpriteLayer*>(FindLayerWithName(worldMap, "Items")); assert(layer); for(Sprite* s : layer->GetSprites()){ if(s->GetKind()==SpriteKind::STANDARD){ if(s->GetSourceSprite()->GetName()=="Blue star" || s->GetSourceSprite()->GetName()=="Violet star" || s->GetSourceSprite()->GetName()=="Cyan star"){ static_cast<StandardSpriteAGK*>(s)->SetPhysicsMode(StandardSpriteAGK::PhysicsMode::DYNAMIC); s->SetDisabledEngineSpriteUpdate(true); // the sprite is no longer controlled via jugimap interface int spriteAgkId = static_cast<StandardSpriteAGK*>(s)->GetAgkId(); agk::SetSpritePhysicsDensity(spriteAgkId, 1.0, 0); agk::SetSpritePhysicsRestitution(spriteAgkId, 0.3, 0); agk::SetSpritePhysicsFriction(spriteAgkId, 0.7, 0); } } } }else{ //---- turn OFF physics for all sprites in simulation SpriteLayer *layer = dynamic_cast<SpriteLayer*>(FindLayerWithName(worldMap, "Main construction")); assert(layer); for(Sprite* s : layer->GetSprites()){ if(s->GetKind()==SpriteKind::STANDARD){ static_cast<StandardSpriteAGK*>(s)->SetPhysicsMode(StandardSpriteAGK::PhysicsMode::NO_PHYSICS); } } layer = dynamic_cast<SpriteLayer*>(FindLayerWithName(worldMap, "Characters")); assert(layer); for(Sprite* s : layer->GetSprites()){ if(s->GetKind()==SpriteKind::STANDARD){ static_cast<StandardSpriteAGK*>(s)->SetPhysicsMode(StandardSpriteAGK::PhysicsMode::NO_PHYSICS); } } layer = dynamic_cast<SpriteLayer*>(FindLayerWithName(worldMap, "Items")); assert(layer); for(Sprite* s : layer->GetSprites()){ if(s->GetKind()==SpriteKind::STANDARD){ if(s->GetSourceSprite()->GetName()=="Blue star" || s->GetSourceSprite()->GetName()=="Violet star" || s->GetSourceSprite()->GetName()=="Cyan star"){ static_cast<StandardSpriteAGK*>(s)->SetPhysicsMode(StandardSpriteAGK::PhysicsMode::NO_PHYSICS); //s->SetEngineSpriteUsedDirectly(false); // ! The sprite is again used via jugimap interface (so that we can restore it to its initial position) s->SetDisabledEngineSpriteUpdate(false); //--- restore transformation properties from jugimap sprite which were not changed during physics simulation s->SetChangeFlags(Sprite::Property::TRANSFORMATION); s->UpdateEngineObjects(); } } } } } void PlatformerSceneAGK::UpdateTexts() { PlatformerScene::UpdateTexts(); //---- std::string str = "FPS: " + std::to_string(int(std::roundf(agk::ScreenFPS()))); if(str != labels[4]->GetTextString()) labels[4]->SetTextString(str); //---- str = "Managed Sprite Count: " + std::to_string(agk::GetManagedSpriteCount()); if(str != labels[5]->GetTextString()) labels[5]->SetTextString(str); //---- str = "Managed Sprite Draw Calls: " + std::to_string(agk::GetManagedSpriteDrawCalls()); if(str != labels[6]->GetTextString()) labels[6]->SetTextString(str); //---- str = "Managed Sprite Drawn Count: " + std::to_string(agk::GetManagedSpriteDrawnCount()); if(str != labels[7]->GetTextString()) labels[7]->SetTextString(str); } }
34.442857
175
0.603899
Jugilus
a4dcee36b0802530e41244e649eac495452b6879
530
cpp
C++
Software Eng (1)/Library/Bee/artifacts/WebGL/il2cpp/master_WebGL_wasm/ccge_Win321.lump.cpp
HealthSouthern48/Unity-project
ad1956e23f55910dd6f51710d11413ecbf5b7b6d
[ "MIT" ]
null
null
null
Software Eng (1)/Library/Bee/artifacts/WebGL/il2cpp/master_WebGL_wasm/ccge_Win321.lump.cpp
HealthSouthern48/Unity-project
ad1956e23f55910dd6f51710d11413ecbf5b7b6d
[ "MIT" ]
null
null
null
Software Eng (1)/Library/Bee/artifacts/WebGL/il2cpp/master_WebGL_wasm/ccge_Win321.lump.cpp
HealthSouthern48/Unity-project
ad1956e23f55910dd6f51710d11413ecbf5b7b6d
[ "MIT" ]
null
null
null
//Generated lump file. generated by Bee.NativeProgramSupport.Lumping #include "C:/Users/19022/Downloads/Unity/Editor/Data/il2cpp/libil2cpp/os/Win32/Console.cpp" #include "C:/Users/19022/Downloads/Unity/Editor/Data/il2cpp/libil2cpp/os/Win32/Encoding.cpp" #include "C:/Users/19022/Downloads/Unity/Editor/Data/il2cpp/libil2cpp/os/Win32/Image.cpp" #include "C:/Users/19022/Downloads/Unity/Editor/Data/il2cpp/libil2cpp/os/Win32/Locale.cpp" #include "C:/Users/19022/Downloads/Unity/Editor/Data/il2cpp/libil2cpp/os/Win32/Path.cpp"
75.714286
93
0.798113
HealthSouthern48
a4dd7c27eaf1ce01375c74cccfb0447fed95bfe0
1,647
hpp
C++
srcs/boxpp/boxpp/base/opacities/vsprintf.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
2
2019-11-13T13:57:37.000Z
2019-11-25T09:55:17.000Z
srcs/boxpp/boxpp/base/opacities/vsprintf.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
srcs/boxpp/boxpp/base/opacities/vsprintf.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
#pragma once #include <boxpp/base/BaseMacros.hpp> #include <boxpp/base/BaseTypes.hpp> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <wchar.h> namespace boxpp { template<typename CharType> struct TVsprintf { FASTINLINE static void Vsprintf(CharType* Buffer, const CharType* Format, ...) { } FASTINLINE static void Printf(CharType* Buffer, const CharType* Format, ...) { } }; template<> struct TVsprintf<ansi_t> { FASTINLINE static void Vsprintf(ansi_t* Buffer, const ansi_t* Format, va_list va) { ::vsprintf(Buffer, Format, va); } static void Sprintf(ansi_t* Buffer, const ansi_t* Format, ...) { va_list va; va_start(va, Format); ::vsprintf(Buffer, Format, va); va_end(va); } static void Printf(const ansi_t* Format, ...) { va_list va; va_start(va, Format); vprintf(Format, va); va_end(va); } static void Fprintf(FILE* fp, const ansi_t* Format, ...) { va_list va; va_start(va, Format); vfprintf(fp, Format, va); va_end(va); } }; template<> struct TVsprintf<wide_t> { FASTINLINE static void Vsprintf(wide_t* Buffer, const wide_t* Format, va_list va) { ::vswprintf(Buffer, Format, va); } static void Sprintf(wide_t* Buffer, const wide_t* Format, ...) { va_list va; va_start(va, Format); ::vswprintf(Buffer, Format, va); va_end(va); } static void Printf(const wide_t* Format, ...) { va_list va; va_start(va, Format); vwprintf(Format, va); va_end(va); } static void Fprintf(FILE* fp, const wide_t* Format, ...) { va_list va; va_start(va, Format); vfwprintf(fp, Format, va); va_end(va); } }; }
21.115385
85
0.654523
whoamiho1006
a4ddef8ecbf4d42c3cb6625128211139122a44da
2,836
hxx
C++
opencascade/Message_LazyProgressScope.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/Message_LazyProgressScope.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/Message_LazyProgressScope.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2017-2021 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Message_LazyProgressScope_HeaderFiler #define _Message_LazyProgressScope_HeaderFiler #include <Message_ProgressScope.hxx> //! Progress scope with lazy updates and abort fetches. //! //! Although Message_ProgressIndicator implementation is encouraged to spare GUI updates, //! even optimized implementation might show a noticeable overhead on a very small update step (e.g. per triangle). //! //! The class splits initial (displayed) number of overall steps into larger chunks specified in constructor, //! so that displayed progress is updated at larger steps. class Message_LazyProgressScope : protected Message_ProgressScope { public: //! Main constructor. //! @param theRange [in] progress range to scope //! @param theName [in] name of this scope //! @param theMax [in] number of steps within this scope //! @param thePatchStep [in] number of steps to update progress //! @param theIsInf [in] infinite flag Message_LazyProgressScope (const Message_ProgressRange& theRange, const char* theName, const Standard_Real theMax, const Standard_Real thePatchStep, const Standard_Boolean theIsInf = Standard_False) : Message_ProgressScope (theRange, theName, theMax, theIsInf), myPatchStep (thePatchStep), myPatchProgress (0.0), myIsLazyAborted (Standard_False) {} //! Increment progress with 1. void Next() { if (++myPatchProgress < myPatchStep) { return; } myPatchProgress = 0.0; Message_ProgressScope::Next (myPatchStep); IsAborted(); } //! Return TRUE if progress has been aborted - return the cached state lazily updated. Standard_Boolean More() const { return !myIsLazyAborted; } //! Return TRUE if progress has been aborted - fetches actual value from the Progress. Standard_Boolean IsAborted() { myIsLazyAborted = myIsLazyAborted || !Message_ProgressScope::More(); return myIsLazyAborted; } protected: Standard_Real myPatchStep; Standard_Real myPatchProgress; Standard_Boolean myIsLazyAborted; }; #endif // _Message_LazyProgressScope_HeaderFiler
35.012346
115
0.724612
mgreminger
a4dfea183b548fd49d6dc76f8bd7d894538f695e
2,285
cpp
C++
Aven-core/src/math/vec2.cpp
icedmetal57/Aven
3c33b74382a7a6ea4aaaa8b33d000573af80fe3e
[ "Apache-2.0" ]
null
null
null
Aven-core/src/math/vec2.cpp
icedmetal57/Aven
3c33b74382a7a6ea4aaaa8b33d000573af80fe3e
[ "Apache-2.0" ]
null
null
null
Aven-core/src/math/vec2.cpp
icedmetal57/Aven
3c33b74382a7a6ea4aaaa8b33d000573af80fe3e
[ "Apache-2.0" ]
null
null
null
#include "vec2.h" namespace aven { namespace math { Vec2::Vec2() { x = 0.0f; y = 0.0f; } Vec2::Vec2(const float& x, const float& y) { this->x = x; this->y = y; } Vec2::Vec2(const Vec3& vector) { this->x = vector.x; this->y = vector.y; } Vec2& Vec2::add(const Vec2& other) { x += other.x; y += other.y; return *this; } Vec2& Vec2::subtract(const Vec2& other) { x -= other.x; y -= other.y; return *this; } Vec2& Vec2::multiply(const Vec2& other) { x *= other.x; y *= other.y; return *this; } Vec2& Vec2::divide(const Vec2& other) { x /= other.x; y /= other.y; return *this; } Vec2 operator+(Vec2 left, const Vec2& right) { return left.add(right); } Vec2 operator-(Vec2 left, const Vec2& right) { return left.subtract(right); } Vec2 operator*(Vec2 left, const Vec2& right) { return left.multiply(right); } Vec2 operator/(Vec2 left, const Vec2& right) { return left.divide(right); } Vec2 operator+(Vec2 left, float value) { return Vec2(left.x + value, left.y + value); } Vec2 operator*(Vec2 left, float value) { return Vec2(left.x * value, left.y * value); } Vec2& Vec2::operator+=(const Vec2& other) { return add(other); } Vec2& Vec2::operator-=(const Vec2& other) { return subtract(other); } Vec2& Vec2::operator*=(const Vec2& other) { return multiply(other); } Vec2& Vec2::operator/=(const Vec2& other) { return divide(other); } bool Vec2::operator==(const Vec2& other) { return x == other.x && y == other.y; } bool Vec2::operator!=(const Vec2& other) { return !(*this == other); } float Vec2::distance(const Vec2& other) const { float a = x - other.x; float b = y - other.y; return sqrt(a * a + b * b); } float Vec2::dot(const Vec2& other) const { return x * other.x + y * other.y; } float Vec2::magnitude() const { return sqrt(x * x + y * y); } Vec2 Vec2::normalize() const { float length = magnitude(); return Vec2(x / length, y / length); } std::ostream& operator<<(std::ostream& stream, const Vec2& vector) { stream << "Vec2: (" << vector.x << ", " << vector.y << ")"; return stream; } } }
15.650685
68
0.565427
icedmetal57
a4e94d09929308ce4eaadf2203ffed49ad2e6eec
7,705
hpp
C++
include/fl/model/sensor/joint_sensor_id.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
17
2015-07-03T06:53:05.000Z
2021-05-15T20:55:12.000Z
include/fl/model/sensor/joint_sensor_id.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
3
2015-02-20T12:48:17.000Z
2019-12-18T08:45:13.000Z
include/fl/model/sensor/joint_sensor_id.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
15
2015-02-20T11:34:14.000Z
2021-05-15T20:55:13.000Z
/* * This is part of the fl library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2015 Max Planck Society, * Autonomous Motion Department, * Institute for Intelligent Systems * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file joint_sensor_id.hpp * \date Febuary 2015 * \author Jan Issac (jan.issac@gmail.com) */ #pragma once #include <Eigen/Dense> #include <tuple> #include <memory> #include <fl/util/traits.hpp> #include <fl/util/meta.hpp> #include <fl/model/sensor/interface/sensor_function.hpp> namespace fl { // Forward declarations template <typename...Models> class JointSensor; /** * Traits of JointSensor */ template <typename...Models> struct Traits< JointSensor<Models...> > { enum : signed int { ObsrvDim = JoinSizes<Traits<Models>::Obsrv::SizeAtCompileTime...>::Size, NoiseDim = JoinSizes<Traits<Models>::Noise::SizeAtCompileTime...>::Size, ParamDim = JoinSizes<Traits<Models>::Param::SizeAtCompileTime...>::Size, StateDim = Traits< typename FirstTypeIn<Models...>::Type >::State::SizeAtCompileTime }; typedef typename Traits< typename FirstTypeIn<Models...>::Type >::State::Scalar Scalar; typedef Eigen::Matrix<Scalar, ObsrvDim, 1> Obsrv; typedef Eigen::Matrix<Scalar, StateDim, 1> State; typedef Eigen::Matrix<Scalar, NoiseDim, 1> Noise; typedef Eigen::Matrix<Scalar, ParamDim, 1> Param; typedef SensorInterface< Obsrv, State, Noise > SensorBase; typedef AdaptiveModel<Param> AdaptiveModelBase; }; /** * \ingroup sensors * * \brief JointSensor itself is an observation model which contains * internally multiple models. Each of the models must operate on the same state * space. The joint model can be simply summarized as * \f$ h(x, \theta, w) = [ h_1(x, \theta_1, w_1), h_2(x, \theta_2, w_2), * \ldots, h_n(x, \theta_n, w_n) ]^T \f$ * * where \f$x\f$ is the state variate, \f$\theta = [ \theta_1, \theta_2, \ldots, * \theta_n ]^T\f$ and \f$w = [ w_1, w_2, \ldots, w_n ]^T\f$ are the the * parameters and noise terms of each of the \f$n\f$ models. * * JointSensor implements the SensorInterface and the * AdaptiveModel interface. That being said, the JointSensor can be * used as a regular observation model or even as an adaptive observation model * which provides a set of parameters that can be changed at any time. This * implies that all sub-models must implement the the AdaptiveModel * interface. However, if a sub-model is not adaptive, JointSensor * applies a decorator call the NotAdaptive operator on the sub-model. This * operator enables any model to be treated as if it is adaptive without * effecting the model behaviour. */ template <typename ... Models> class JointSensor : public Traits<JointSensor<Models...>>::SensorBase { private: /** Typdef of \c This for #from_traits(TypeName) helper */ typedef JointSensor<Models...> This; public: typedef from_traits(State); typedef from_traits(Noise); typedef from_traits(Obsrv); typedef from_traits(Param); public: /** * Constructor a JointSensor which is a composition of mixture of * fixed and dynamic-size observation models. * * \param models Variadic list of shared pointers of the models */ explicit JointSensor(std::shared_ptr<Models>...models) : models_(models...) { } /** * \brief Overridable default destructor */ virtual ~JointSensor() noexcept { } /** * \copydoc SensorInterface::predict_obsrv */ virtual Obsrv predict_obsrv(const State& state, const Noise& noise, double delta_time) { Obsrv prediction = Obsrv(obsrv_dimension(), 1); predict_obsrv<sizeof...(Models)>( models_, delta_time, state, noise, prediction); return prediction; } /** * \copydoc SensorInterface::state_dimension * * Determines the joint size of the state vector of all models */ virtual int state_dimension() const { return expand_state_dimension(CreateIndexSequence<sizeof...(Models)>()); } /** * \copydoc SensorInterface::noise_dimension * * Determines the joint size of the noise vector of all models */ virtual int noise_dimension() const { return expand_noise_dimension(CreateIndexSequence<sizeof...(Models)>()); } /** * \copydoc SensorInterface::input_dimension * * Determines the joint size of the observation vector of all models */ virtual int obsrv_dimension() const { return expand_obsrv_dimension(CreateIndexSequence<sizeof...(Models)>()); } protected: /** * \brief Contains the points to the sub-models which this joint model * is composed of. */ std::tuple<std::shared_ptr<Models>...> models_; private: /** \cond internal */ template <int...Indices> constexpr int expand_state_dimension(IndexSequence<Indices...>) const { const auto& dims = { std::get<Indices>(models_)->state_dimension()... }; int joint_dim = 0; for (auto dim : dims) { joint_dim += dim; } return joint_dim; } template <int...Indices> constexpr int expand_noise_dimension(IndexSequence<Indices...>) const { const auto& dims = { std::get<Indices>(models_)->noise_dimension()... }; int joint_dim = 0; for (auto dim : dims) { joint_dim += dim; } return joint_dim; } template <int...Indices> constexpr int expand_obsrv_dimension(IndexSequence<Indices...>) const { const auto& dims = { std::get<Indices>(models_)->obsrv_dimension()... }; int joint_dim = 0; for (auto dim : dims) { joint_dim += dim; } return joint_dim; } template < int Size, int k = 0, typename Tuple, typename State, typename Noise, typename Obsrv > void predict_obsrv(Tuple& models_tuple, double delta_time, const State& state, const Noise& noise, Obsrv& prediction, const int obsrv_offset = 0, const int state_offset = 0, const int noise_offset = 0) { auto&& model = std::get<k>(models_tuple); const auto obsrv_dim = model->obsrv_dimension(); const auto state_dim = model->state_dimension(); const auto noise_dim = model->noise_dimension(); prediction.middleRows(obsrv_offset, obsrv_dim) = model->predict_obsrv( state.middleRows(state_offset, state_dim), noise.middleRows(noise_offset, noise_dim), delta_time ); if (Size == k + 1) return; predict_obsrv<Size, k + (k + 1 < Size ? 1 : 0)>( models_tuple, delta_time, state, noise, prediction, obsrv_offset + obsrv_dim, state_offset + state_dim, noise_offset + noise_dim); } /** \endcond */ }; }
28.537037
80
0.599351
aeolusbot-tommyliu
a4f4a5166c36b0f77e9c80e323c1733396bfd8c8
8,724
cpp
C++
examples/datatable.cpp
netcan/meta-value-list
772bb0c091a5b5ea6070f7c6e4f5503d1fccb26a
[ "MIT" ]
24
2021-11-05T16:24:57.000Z
2021-11-08T11:18:02.000Z
examples/datatable.cpp
netcan/meta-value-list
772bb0c091a5b5ea6070f7c6e4f5503d1fccb26a
[ "MIT" ]
null
null
null
examples/datatable.cpp
netcan/meta-value-list
772bb0c091a5b5ea6070f7c6e4f5503d1fccb26a
[ "MIT" ]
null
null
null
// // Created by netcan on 2021/11/7. // #include <meta-list/type.hpp> #include <meta-list/algorithm.hpp> #include <cstdint> #include <concepts> #include <bitset> #include <algorithm> #include <cassert> using namespace META_LIST_NS; /////////////////////////////////////////////////////////////////////////////// // for user to describe key/valuetype Entry // <key, valuetype> template<auto Key, typename ValueType, size_t Dim = 1> struct Entry { constexpr static auto key = Key; constexpr static size_t dim = Dim; constexpr static bool isArray = Dim > 1; using type = ValueType; }; template<auto Key, typename ValueType, size_t Dim> struct Entry<Key, ValueType[Dim]>: Entry<Key, ValueType, Dim> { }; template<typename E> concept KVEntry = requires { typename E::type; requires std::is_standard_layout_v<typename E::type>; requires std::is_trivial_v<typename E::type>; { E::key } -> std::convertible_to<size_t>; { E::dim } -> std::convertible_to<size_t>; }; consteval bool operator==(KVEntry auto el, KVEntry auto er) { using ELType = decltype(el)::type; using ERType = decltype(er)::type; return el.dim == er.dim && sizeof(ELType) == sizeof(ERType) && alignof(ELType) == alignof(ERType); } static_assert(KVEntry<Entry<0, char[10]>>); template<auto Key, typename ValueType> inline constexpr auto entry = Entry<Key, ValueType>{}; /////////////////////////////////////////////////////////////////////////////// template <concepts::list auto entries> class Datatable { template</* KVEntry */ typename EH, /* KVEntry */ typename ...ET> class GenericRegion { constexpr static size_t numberOfEntries = sizeof...(ET) + 1; constexpr static size_t maxSize = std::max(alignof(typename EH::type), sizeof(typename EH::type)) * EH::dim; char data[numberOfEntries][maxSize]; public: bool getData(size_t nthData, void* out, size_t len) { if (nthData >= numberOfEntries) [[unlikely]] { return false; } std::copy_n(data[nthData], std::min(len, maxSize), reinterpret_cast<char*>(out)); return true; } bool setData(size_t nthData, const void* value, size_t len) { if (nthData >= numberOfEntries) [[unlikely]] { return false; } std::copy_n(reinterpret_cast<const char*>(value), std::min(len, maxSize), data[nthData]); return true; } }; template<typename... R> class Regions { std::tuple<R...> regions; template<size_t I, typename OP> bool forData(OP&& op, size_t index) { size_t regionIdx = index >> 16; size_t nthData = index & 0xFFFF; if (I == regionIdx) { return op(std::get<I>(regions), nthData); } return false; } template<typename OP, size_t... Is> bool forData(std::index_sequence<Is...>, OP&& op, size_t index) { return (forData<Is>(std::forward<OP>(op), index) || ...); } public: bool getData(size_t index, void* out, size_t len) { auto op = [&](auto&& region, size_t nthData) { return region.getData(nthData, out, len); }; return forData(std::make_index_sequence<sizeof...(R)>{}, op, index); } bool setData(size_t index, const void* value, size_t len) { auto op = [&](auto&& region, size_t nthData) { return region.setData(nthData, value, len); }; return forData(std::make_index_sequence<sizeof...(R)>{}, op, index); } }; template</* concepts::pair_const */ typename ...KeyWithId> struct Indexer { static constexpr size_t IndexSize = sizeof...(KeyWithId); size_t keyToId[IndexSize]; std::bitset<IndexSize> mask; constexpr Indexer() { static_assert(((KeyWithId::first < IndexSize) && ...), "key is out of size"); (void(keyToId[KeyWithId::first] = KeyWithId::second), ...); } }; template<auto...> struct dump; /////////////////////////////////////////////////////////////////////////////// // meta value list consteval meta programming consteval static concepts::list auto group_entries(concepts::list auto es) { if constexpr (es.empty()) { return value_list<>; } else { constexpr auto e = get_typ<es.head()>{}; constexpr auto group_result = es | partition([]<typename Entry>(TypeConst<Entry>) { return _v<Entry{} == e>; }); return group_entries(group_result.second) | prepend(group_result.first); } } constexpr static auto entry_groups = group_entries(entries); constexpr static auto regions_type = entry_groups | transform([](/* concepts::list */ auto group) { return group | convert_to<GenericRegion>(); }) | convert_to<Regions>() ; constexpr static auto indexer_type = (entry_groups | fold_left(make_pair(_v<0>, type_list<>), [](/* concepts::pair_const */ auto group_list, /* concepts::list */ auto group_entries) { constexpr auto res = group_entries | fold_left(make_pair(_v<0>, type_list<>) , [group_list]<typename E>(concepts::pair_const auto inner_group , TypeConst<E>) { constexpr auto group_id = group_list.first; constexpr auto inner_id = inner_group.first; return make_pair(_v<inner_id + 1> , inner_group.second | append(make_pair(_v<E::key>, _v<group_id << 16 | inner_id>))); }); return make_pair(_v<group_list.first + 1>, concat(group_list.second, res.second)); })).second | convert_to<Indexer>() ; get_typ<regions_type> regions; get_typ<indexer_type> indexer; /////////////////////////////////////////////////////////////////////////////// public: bool getData(size_t key, void* out, size_t len = -1) { if (key >= entries.size() || ! indexer.mask[key]) { return false; } return regions.getData(indexer.keyToId[key], out, len); } bool setData(size_t key, const void* value, size_t len = -1) { if (key >= entries.size()) { return false; } return indexer.mask[key] = regions.setData(indexer.keyToId[key], value, len); } void dumpGroupInfo() { printf("sizeof Datatable = %zu\n", sizeof(Datatable)); printf("sizeof Region = %zu\n", sizeof(regions)); printf("sizeof Indexer = %zu\n", sizeof(indexer)); for (size_t k = 0; k < entries.size(); ++k) { printf("key = %d id = 0x%05x group = %d subgroup = %d\n", k, indexer.keyToId[k], indexer.keyToId[k] >> 16, indexer.keyToId[k] & 0xFFFF); } } }; /////////////////////////////////////////////////////////////////////////////// int main() { constexpr auto all_entries = type_list< Entry<0, int>, Entry<1, char>, Entry<2, char>, Entry<3, short>, Entry<4, char[10]>, Entry<5, char[10]>, Entry<6, int> >; Datatable<all_entries> datatbl; datatbl.dumpGroupInfo(); { int expectedValue = 23; assert(! datatbl.getData(0, &expectedValue)); assert(datatbl.setData(0, &expectedValue)); int value = -1; assert(datatbl.getData(0, &value)); assert(value == expectedValue); } { int expectedValue = 23; assert(! datatbl.getData(6, &expectedValue)); assert(datatbl.setData(6, &expectedValue)); int value = -1; assert(datatbl.getData(6, &value)); assert(value == expectedValue); } { int invalid; assert(! datatbl.getData(7, &invalid)); assert(! datatbl.setData(7, &invalid)); } { std::string_view expectedValue = "hello"; char value[10] {}; assert(! datatbl.getData(4, value)); assert(datatbl.setData(4, expectedValue.data(), expectedValue.length())); assert(datatbl.getData(4, value)); assert(expectedValue == value); } return 0; }
37.766234
107
0.527052
netcan
a4f6bb9ad9743130fcd33b7f80151efa962de7ac
625
cpp
C++
RG-Lab3/Neon/src/Scene/Components.cpp
FilipHusnjak/ComputerGraphics-Labs
5f923735d2dbf9551675a704724e8a5d7128025a
[ "Apache-2.0" ]
3
2021-01-23T20:19:55.000Z
2021-01-25T16:15:46.000Z
RG-Lab3/Neon/src/Scene/Components.cpp
FilipHusnjak/ComputerGraphics-Labs
5f923735d2dbf9551675a704724e8a5d7128025a
[ "Apache-2.0" ]
null
null
null
RG-Lab3/Neon/src/Scene/Components.cpp
FilipHusnjak/ComputerGraphics-Labs
5f923735d2dbf9551675a704724e8a5d7128025a
[ "Apache-2.0" ]
null
null
null
// // Created by Filip on 21.8.2020.. // #include "Components.h" #include <Renderer/VulkanRenderer.h> Neon::WaterRenderer::WaterRenderer() { VulkanRenderer::CreateFrameBuffers( refractionReflectionResolution, m_RefractionSampledColorTextureImage, m_RefractionSampledDepthTextureImage, m_RefractionColorTextureImage, m_RefractionDepthTextureImage, m_RefractionFrameBuffers); VulkanRenderer::CreateFrameBuffers( refractionReflectionResolution, m_ReflectionSampledColorTextureImage, m_ReflectionSampledDepthTextureImage, m_ReflectionColorTextureImage, m_ReflectionDepthTextureImage, m_ReflectionFrameBuffers); }
32.894737
71
0.8528
FilipHusnjak
a4f8b40e939cef7a84843f406d47ea39c2e4bb8c
16,816
cpp
C++
Sources/SolarTears/Rendering/Vulkan/VulkanSharedDescriptorDatabaseBuilder.cpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
4
2021-06-30T16:00:20.000Z
2021-10-13T06:17:56.000Z
Sources/SolarTears/Rendering/Vulkan/VulkanSharedDescriptorDatabaseBuilder.cpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
Sources/SolarTears/Rendering/Vulkan/VulkanSharedDescriptorDatabaseBuilder.cpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
#include "VulkanSharedDescriptorDatabaseBuilder.hpp" #include "VulkanDescriptors.hpp" #include "VulkanSamplers.hpp" #include "Scene/VulkanScene.hpp" #include "VulkanUtils.hpp" #include "VulkanFunctions.hpp" #include <VulkanGenericStructures.h> #include <span> #include <vector> #include <algorithm> Vulkan::SharedDescriptorDatabaseBuilder::SharedDescriptorDatabaseBuilder(DescriptorDatabase* databaseToBuild): mDatabaseToBuild(databaseToBuild) { } Vulkan::SharedDescriptorDatabaseBuilder::~SharedDescriptorDatabaseBuilder() { } void Vulkan::SharedDescriptorDatabaseBuilder::ClearRegisteredSharedSetInfos() { mDatabaseToBuild->mSharedSetCreateMetadatas.clear(); mDatabaseToBuild->mSharedSetFormatsFlat.clear(); } uint32_t Vulkan::SharedDescriptorDatabaseBuilder::RegisterSharedSetInfo(VkDescriptorSetLayout setLayout, std::span<const uint16_t> setBindings) { Span<uint32_t> formatSpan = { .Begin = (uint32_t)mDatabaseToBuild->mSharedSetFormatsFlat.size(), .End = (uint32_t)(mDatabaseToBuild->mSharedSetFormatsFlat.size() + setBindings.size()) }; mDatabaseToBuild->mSharedSetFormatsFlat.resize(mDatabaseToBuild->mSharedSetFormatsFlat.size() + setBindings.size()); for(uint32_t layoutBindingIndex = 0; layoutBindingIndex < setBindings.size(); layoutBindingIndex++) { uint_fast16_t bindingTypeIndex = setBindings[layoutBindingIndex]; mDatabaseToBuild->mSharedSetFormatsFlat[formatSpan.Begin + layoutBindingIndex] = (SharedDescriptorBindingType)bindingTypeIndex; } mDatabaseToBuild->mSharedSetCreateMetadatas.push_back(DescriptorDatabase::SharedSetCreateMetadata { .SetLayout = setLayout, .BindingSpan = formatSpan }); return (uint32_t)(mDatabaseToBuild->mSharedSetCreateMetadatas.size() - 1); } void Vulkan::SharedDescriptorDatabaseBuilder::AddSharedSetInfo(uint32_t setMetadataId) { mDatabaseToBuild->mSharedSetRecords.push_back(DescriptorDatabase::SharedSetRecord { .SetCreateMetadataIndex = setMetadataId, .SetDatabaseIndex = (uint32_t)mDatabaseToBuild->mDescriptorSets.size() }); mDatabaseToBuild->mDescriptorSets.push_back(VK_NULL_HANDLE); } void Vulkan::SharedDescriptorDatabaseBuilder::RecreateSharedSets(const RenderableScene* scene, const SamplerManager* samplerManager) { RecreateSharedDescriptorPool(scene, samplerManager); std::vector<VkDescriptorSet> setsPerLayout; AllocateSharedDescriptorSets(scene, samplerManager, setsPerLayout); UpdateSharedDescriptorSets(scene, setsPerLayout); AssignSharedDescriptorSets(setsPerLayout); } void Vulkan::SharedDescriptorDatabaseBuilder::RecreateSharedDescriptorPool(const RenderableScene* scene, const SamplerManager* samplerManager) { SafeDestroyObject(vkDestroyDescriptorPool, mDatabaseToBuild->mDeviceRef, mDatabaseToBuild->mSharedDescriptorPool); if(mDatabaseToBuild->mSharedSetCreateMetadatas.empty()) { return; } VkDescriptorPoolSize samplerDescriptorPoolSize = {.type = VK_DESCRIPTOR_TYPE_SAMPLER, .descriptorCount = 0}; VkDescriptorPoolSize textureDescriptorPoolSize = {.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, .descriptorCount = 0}; VkDescriptorPoolSize uniformDescriptorPoolSize = {.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .descriptorCount = 0}; std::array<uint32_t, TotalSharedBindings> descriptorCountsPerBinding = std::to_array ({ (uint32_t)samplerManager->GetSamplerVariableArrayLength(), //Sampler descriptor count (uint32_t)scene->mSceneTextures.size(), //Texture descriptor count scene->GetMaterialCount(), //Material descriptor count 1u, //Frame data descriptor count scene->GetStaticObjectCount() + scene->GetRigidObjectCount(), //Object data descriptor count }); for(const DescriptorDatabase::SharedSetCreateMetadata& sharedSetMetadata: mDatabaseToBuild->mSharedSetCreateMetadatas) { std::array<uint32_t, TotalSharedBindings> bindingCountPerSharedType; std::fill(bindingCountPerSharedType.begin(), bindingCountPerSharedType.end(), 0); for(uint32_t bindingIndex = sharedSetMetadata.BindingSpan.Begin; bindingIndex < sharedSetMetadata.BindingSpan.End; bindingIndex++) { uint32_t bindingTypeIndex = (uint32_t)mDatabaseToBuild->mSharedSetFormatsFlat[bindingIndex]; bindingCountPerSharedType[bindingTypeIndex] += descriptorCountsPerBinding[bindingTypeIndex]; } std::array samplerTypes = {SharedDescriptorBindingType::SamplerList}; std::array textureTypes = {SharedDescriptorBindingType::TextureList}; std::array uniformTypes = {SharedDescriptorBindingType::MaterialList, SharedDescriptorBindingType::FrameDataList, SharedDescriptorBindingType::ObjectDataList}; for(SharedDescriptorBindingType samplerType: samplerTypes) { samplerDescriptorPoolSize.descriptorCount += bindingCountPerSharedType[(uint32_t)samplerType]; } for(SharedDescriptorBindingType textureType: textureTypes) { textureDescriptorPoolSize.descriptorCount += bindingCountPerSharedType[(uint32_t)textureType]; } for(SharedDescriptorBindingType uniformType: uniformTypes) { uniformDescriptorPoolSize.descriptorCount += bindingCountPerSharedType[(uint32_t)uniformType]; } } uint32_t poolSizeCount = 0; std::array<VkDescriptorPoolSize, 3> poolSizes; for(const VkDescriptorPoolSize& poolSize: {samplerDescriptorPoolSize, textureDescriptorPoolSize, uniformDescriptorPoolSize}) { if(poolSize.descriptorCount != 0) { poolSizes[poolSizeCount] = poolSize; poolSizeCount++; } } //TODO: inline uniforms... Though do I really need them? VkDescriptorPoolCreateInfo descriptorPoolCreateInfo; descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptorPoolCreateInfo.pNext = nullptr; descriptorPoolCreateInfo.flags = 0; descriptorPoolCreateInfo.maxSets = (uint32_t)mDatabaseToBuild->mSharedSetCreateMetadatas.size(); descriptorPoolCreateInfo.poolSizeCount = poolSizeCount; descriptorPoolCreateInfo.pPoolSizes = poolSizes.data(); ThrowIfFailed(vkCreateDescriptorPool(mDatabaseToBuild->mDeviceRef, &descriptorPoolCreateInfo, nullptr, &mDatabaseToBuild->mSharedDescriptorPool)); } void Vulkan::SharedDescriptorDatabaseBuilder::AllocateSharedDescriptorSets(const RenderableScene* scene, const SamplerManager* samplerManager, std::vector<VkDescriptorSet>& outAllocatedSets) { outAllocatedSets.resize(mDatabaseToBuild->mSharedSetCreateMetadatas.size(), VK_NULL_HANDLE); if(mDatabaseToBuild->mSharedSetCreateMetadatas.empty()) { return; } std::array<uint32_t, TotalSharedBindings> variableCountsPerBindingType = std::to_array ({ (uint32_t)samplerManager->GetSamplerVariableArrayLength(), //Samplers binding (uint32_t)scene->mSceneTextures.size(), //Textures binding scene->GetMaterialCount(), //Materials binding 0u, //Frame data binding scene->GetStaticObjectCount() + scene->GetRigidObjectCount() //Static object datas binding }); std::vector<VkDescriptorSetLayout> layoutsForSets; std::vector<uint32_t> variableCountsForSets; for(const DescriptorDatabase::SharedSetCreateMetadata& sharedSetCreateMetadata: mDatabaseToBuild->mSharedSetCreateMetadatas) { uint32_t lastBindingIndex = (uint32_t)mDatabaseToBuild->mSharedSetFormatsFlat[sharedSetCreateMetadata.BindingSpan.End - 1]; uint32_t variableDescriptorCount = variableCountsPerBindingType[lastBindingIndex]; layoutsForSets.push_back(sharedSetCreateMetadata.SetLayout); variableCountsForSets.push_back(variableDescriptorCount); } VkDescriptorSetVariableDescriptorCountAllocateInfo variableCountAllocateInfo; variableCountAllocateInfo.pNext = nullptr; variableCountAllocateInfo.descriptorSetCount = (uint32_t)variableCountsForSets.size(); variableCountAllocateInfo.pDescriptorCounts = variableCountsForSets.data(); vgs::GenericStructureChain<VkDescriptorSetAllocateInfo> descriptorSetAllocateInfoChain; descriptorSetAllocateInfoChain.AppendToChain(variableCountAllocateInfo); VkDescriptorSetAllocateInfo& setAllocateInfo = descriptorSetAllocateInfoChain.GetChainHead(); setAllocateInfo.descriptorPool = mDatabaseToBuild->mSharedDescriptorPool; setAllocateInfo.descriptorSetCount = (uint32_t)layoutsForSets.size(); setAllocateInfo.pSetLayouts = layoutsForSets.data(); ThrowIfFailed(vkAllocateDescriptorSets(mDatabaseToBuild->mDeviceRef, &setAllocateInfo, outAllocatedSets.data())); } void Vulkan::SharedDescriptorDatabaseBuilder::UpdateSharedDescriptorSets(const RenderableScene* scene, const std::vector<VkDescriptorSet>& setsToWritePerCreateMetadata) { const uint32_t samplerCount = 0; //Immutable samplers are used const uint32_t textureCount = (uint32_t)scene->mSceneTextureViews.size(); const uint32_t materialCount = scene->GetMaterialCount(); const uint32_t frameDataCount = 1u; const uint32_t objectDataCount = scene->GetStaticObjectCount() + scene->GetRigidObjectCount(); std::array<uint32_t, TotalSharedBindings> bindingDescriptorCounts = std::to_array ({ samplerCount, textureCount, materialCount, frameDataCount, objectDataCount }); size_t imageDescriptorCount = 0; size_t bufferDescriptorCount = 0; for(uint32_t bindingTypeIndex = 0; bindingTypeIndex < TotalSharedBindings; bindingTypeIndex++) { size_t bindingCount = bindingDescriptorCounts[bindingTypeIndex]; switch(DescriptorTypesPerSharedBinding[bindingTypeIndex]) { case VK_DESCRIPTOR_TYPE_SAMPLER: break; case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: imageDescriptorCount += bindingCount; break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: bufferDescriptorCount += bindingCount; break; default: assert(false); //Unimplemented break; } } std::vector<VkDescriptorImageInfo> imageDescriptorInfos; std::vector<VkDescriptorBufferInfo> bufferDescriptorInfos; constexpr auto addSamplerBindingsFunc = []([[maybe_unused]] const RenderableScene* sceneToCreateDescriptors, [[maybe_unused]] std::vector<VkDescriptorImageInfo>& imageDescriptorInfos, [[maybe_unused]] std::vector<VkDescriptorBufferInfo>& bufferDescriptorInfos, [[maybe_unused]] uint32_t samplerIndex) { //Do nothing }; constexpr auto addTextureBindingFunc = [](const RenderableScene* sceneToCreateDescriptors, std::vector<VkDescriptorImageInfo>& imageDescriptorInfos, [[maybe_unused]] std::vector<VkDescriptorBufferInfo>& bufferDescriptorInfos, uint32_t textureIndex) { imageDescriptorInfos.push_back(VkDescriptorImageInfo { .sampler = VK_NULL_HANDLE, .imageView = sceneToCreateDescriptors->mSceneTextureViews[textureIndex], .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }); }; constexpr auto addMaterialBindingsFunc = [](const RenderableScene* sceneToCreateDescriptors, [[maybe_unused]] std::vector<VkDescriptorImageInfo>& imageDescriptorInfos, std::vector<VkDescriptorBufferInfo>& bufferDescriptorInfos, uint32_t materialIndex) { bufferDescriptorInfos.push_back(VkDescriptorBufferInfo { .buffer = sceneToCreateDescriptors->mSceneUniformBuffer, .offset = sceneToCreateDescriptors->GetMaterialDataOffset(materialIndex), .range = sceneToCreateDescriptors->mMaterialChunkDataSize }); }; constexpr auto addFrameDataBindingsFunc = [](const RenderableScene* sceneToCreateDescriptors, [[maybe_unused]] std::vector<VkDescriptorImageInfo>& imageDescriptorInfos, std::vector<VkDescriptorBufferInfo>& bufferDescriptorInfos, [[maybe_unused]] uint32_t bindingIndex) { bufferDescriptorInfos.push_back(VkDescriptorBufferInfo { .buffer = sceneToCreateDescriptors->mSceneUniformBuffer, .offset = sceneToCreateDescriptors->GetBaseFrameDataOffset(), .range = sceneToCreateDescriptors->mFrameChunkDataSize }); }; constexpr auto addObjectBindingsFunc = [](const RenderableScene* sceneToCreateDescriptors, [[maybe_unused]] std::vector<VkDescriptorImageInfo>& imageDescriptorInfos, std::vector<VkDescriptorBufferInfo>& bufferDescriptorInfos, uint32_t objectDataIndex) { bufferDescriptorInfos.push_back(VkDescriptorBufferInfo { .buffer = sceneToCreateDescriptors->mSceneUniformBuffer, .offset = sceneToCreateDescriptors->GetObjectDataOffset(objectDataIndex), .range = sceneToCreateDescriptors->mObjectChunkDataSize }); }; using AddBindingFunc = void(*)(const RenderableScene*, std::vector<VkDescriptorImageInfo>&, std::vector<VkDescriptorBufferInfo>&, uint32_t); std::array<AddBindingFunc, TotalSharedBindings> bindingAddFuncs; bindingAddFuncs[(uint32_t)SharedDescriptorBindingType::SamplerList] = addSamplerBindingsFunc; bindingAddFuncs[(uint32_t)SharedDescriptorBindingType::TextureList] = addTextureBindingFunc; bindingAddFuncs[(uint32_t)SharedDescriptorBindingType::MaterialList] = addMaterialBindingsFunc; bindingAddFuncs[(uint32_t)SharedDescriptorBindingType::FrameDataList] = addFrameDataBindingsFunc; bindingAddFuncs[(uint32_t)SharedDescriptorBindingType::ObjectDataList] = addObjectBindingsFunc; std::array<VkDescriptorImageInfo*, TotalSharedBindings> imageDescriptorInfosPerBinding = {VK_NULL_HANDLE}; std::array<VkDescriptorBufferInfo*, TotalSharedBindings> bufferDescriptorInfosPerBinding = {VK_NULL_HANDLE}; std::array<VkBufferView*, TotalSharedBindings> texelBufferDescriptorInfosPerBinding = {VK_NULL_HANDLE}; imageDescriptorInfos.reserve(imageDescriptorCount); bufferDescriptorInfos.reserve(bufferDescriptorCount); for(uint32_t bindingTypeIndex = 0; bindingTypeIndex < TotalSharedBindings; bindingTypeIndex++) { AddBindingFunc addfunc = bindingAddFuncs[bindingTypeIndex]; uint32_t bindingCount = bindingDescriptorCounts[bindingTypeIndex]; //The memory is already reserved, it's safe to assume it won't move anywhere imageDescriptorInfosPerBinding[bindingTypeIndex] = imageDescriptorInfos.data() + imageDescriptorInfos.size(); bufferDescriptorInfosPerBinding[bindingTypeIndex] = bufferDescriptorInfos.data() + bufferDescriptorInfos.size(); texelBufferDescriptorInfosPerBinding[bindingTypeIndex] = nullptr; for(uint32_t bindingIndex = 0; bindingIndex < bindingCount; bindingIndex++) { addfunc(scene, imageDescriptorInfos, bufferDescriptorInfos, bindingIndex); } } uint32_t totalBindingCount = std::accumulate(mDatabaseToBuild->mSharedSetCreateMetadatas.begin(), mDatabaseToBuild->mSharedSetCreateMetadatas.end(), 0, [](const uint32_t acc, const DescriptorDatabase::SharedSetCreateMetadata& createMetadata) { return acc + (createMetadata.BindingSpan.End - createMetadata.BindingSpan.Begin); }); std::vector<VkWriteDescriptorSet> writeDescriptorSets; writeDescriptorSets.reserve(totalBindingCount); for(uint32_t setMetadataIndex = 0; setMetadataIndex < mDatabaseToBuild->mSharedSetCreateMetadatas.size(); setMetadataIndex++) { const DescriptorDatabase::SharedSetCreateMetadata& sharedSetCreateMetadata = mDatabaseToBuild->mSharedSetCreateMetadatas[setMetadataIndex]; for(uint32_t bindingIndex = sharedSetCreateMetadata.BindingSpan.Begin; bindingIndex < sharedSetCreateMetadata.BindingSpan.End; bindingIndex++) { uint32_t layoutBindingIndex = bindingIndex - sharedSetCreateMetadata.BindingSpan.Begin; uint32_t bindingTypeIndex = (uint32_t)mDatabaseToBuild->mSharedSetFormatsFlat[bindingIndex]; if(bindingDescriptorCounts[bindingTypeIndex] == 0) { continue; } VkWriteDescriptorSet writeDescriptorSet; writeDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptorSet.pNext = nullptr; writeDescriptorSet.dstSet = setsToWritePerCreateMetadata[setMetadataIndex]; writeDescriptorSet.dstBinding = layoutBindingIndex; writeDescriptorSet.dstArrayElement = 0; writeDescriptorSet.descriptorCount = bindingDescriptorCounts[bindingTypeIndex]; writeDescriptorSet.descriptorType = DescriptorTypesPerSharedBinding[bindingTypeIndex]; writeDescriptorSet.pImageInfo = imageDescriptorInfosPerBinding[bindingTypeIndex]; writeDescriptorSet.pBufferInfo = bufferDescriptorInfosPerBinding[bindingTypeIndex]; writeDescriptorSet.pTexelBufferView = texelBufferDescriptorInfosPerBinding[bindingTypeIndex]; writeDescriptorSets.push_back(writeDescriptorSet); } } vkUpdateDescriptorSets(mDatabaseToBuild->mDeviceRef, (uint32_t)writeDescriptorSets.size(), writeDescriptorSets.data(), 0, nullptr); } void Vulkan::SharedDescriptorDatabaseBuilder::AssignSharedDescriptorSets(const std::vector<VkDescriptorSet>& setsPerCreateMetadata) { for(const DescriptorDatabase::SharedSetRecord& sharedSetRecord: mDatabaseToBuild->mSharedSetRecords) { mDatabaseToBuild->mDescriptorSets[sharedSetRecord.SetDatabaseIndex] = setsPerCreateMetadata[sharedSetRecord.SetCreateMetadataIndex]; } }
46.711111
301
0.802212
Sixshaman
a4f8e48d27750830a388d1eb6fa4e9ceb463fc0a
11,619
cpp
C++
src/main.cpp
mnltake/soracom_iotstarter_kit_for_arduino
cbb5baedcc13472c92aa3997b57df3677cec8e9c
[ "MIT" ]
null
null
null
src/main.cpp
mnltake/soracom_iotstarter_kit_for_arduino
cbb5baedcc13472c92aa3997b57df3677cec8e9c
[ "MIT" ]
null
null
null
src/main.cpp
mnltake/soracom_iotstarter_kit_for_arduino
cbb5baedcc13472c92aa3997b57df3677cec8e9c
[ "MIT" ]
1
2021-02-10T04:05:51.000Z
2021-02-10T04:05:51.000Z
#include "main.h" void setup() { pinMode(LIGHTSENSORPIN, INPUT); pinMode(SOUNDSENSORPIN, INPUT); pinMode(VOLUMEPIN, INPUT); pinMode(BUTTONPIN, INPUT); pinMode(BG96_RESETPIN, OUTPUT); pinMode(LED_BUILTIN, OUTPUT); pinMode(LEDPIN, OUTPUT); digitalWrite(BG96_RESETPIN, HIGH);//modem reset u8x8.begin(); u8x8.setFlipMode(U8X8_ENABLE_180_DEGREE_ROTATION); u8x8.setFont(u8x8_font_7x14B_1x2_f); u8x8.println("Start:"); u8x8.println("Please wait"); delay(100); digitalWrite(BG96_RESETPIN, LOW);//BG96 start digitalWrite(LED_BUILTIN, HIGH);//LED_BUILTIN ON tone(BUZZERPIN ,440);//beep bg96_initial(); bmp280.init(); oled_write(0); /* LIS.begin(Wire, 0x19); delay(100); LIS.setFullScaleRange(LIS3DHTR_RANGE_8G); LIS.setOutputDataRate(LIS3DHTR_DATARATE_50HZ); LIS.setHighSolution(true); */ savebyte = EEPROM.read(EEPROMINDENX); Serial.println(savebyte, BIN); if (savebyte == 0xff){ //factory default savebyte = 0b10000101; } sendbyte=savebyte; dispflg=bitRead(sendbyte,7); ledflg=bitRead(sendbyte,3); noTone(BUZZERPIN); } void loop() { delay(500); Watchdog.enable(8000); digitalWrite(LED_BUILTIN, HIGH);//wake /* read sensor*/ light= analogRead(LIGHTSENSORPIN); Serial.print("light sensor is:"); Serial.println(light); long sum = 0; for (int i = 0; i < soundSamplingCount; i++) { sum += analogRead(SOUNDSENSORPIN); delay(5); } sound = sum / soundSamplingCount; Serial.print("Sound sensor is:"); Serial.println(sound); DHT.read11(DHT11_PIN); tem = DHT.temperature*1.0; //float(℃) Serial.print("Tmperature is:"); Serial.println(tem); hum = DHT.humidity* 1.0; //int(%) Serial.print("Humidity is:"); Serial.println(hum); press = bmp280.getPressure() ;//long(Pa) Serial.print("AirPress is:"); Serial.println(press); /* float sumx=0,sumy=0,sumz=0; for (int i = 0; i < accelSamplingCount; i++) { sumx += LIS.getAccelerationX(); sumy += LIS.getAccelerationY(); sumz += LIS.getAccelerationZ(); delay(5); } x = sumx / accelSamplingCount; y = sumy / accelSamplingCount; z = sumz / accelSamplingCount; Serial.print("Acceleratin is:"); Serial.print("x:"); Serial.print(x); Serial.print(" "); Serial.print(", y:"); Serial.print(y); Serial.print(" "); Serial.print(", z:"); Serial.println(z); movex=(abs(x) >0.5)?true:false; movey=(abs(y) >0.5)?true:false; movez=(abs(z) >0.5)?true:false; */ volume=analogRead(VOLUMEPIN); Serial.print("Volume is:"); Serial.println(volume); tempbmp = bmp280.getTemperature() ;//flaot(℃) Serial.print("TempBMP280 is:"); Serial.println(tempbmp); Serial.print("upcount is:"); Serial.println(upcount); bitWrite(sendbyte,7,dispflg); bitWrite(sendbyte,6,movex); bitWrite(sendbyte,5,movey); bitWrite(sendbyte,4,movez); bitWrite(sendbyte,3,ledflg); bitWrite(sendbyte,2,1); bitWrite(sendbyte,1,0); bitWrite(sendbyte,0,1); if (sendbyte != savebyte){ Serial.println("Save byte to EEPROM"); EEPROM.write(EEPROMINDENX, sendbyte); } Serial.println(sendbyte, BIN); savebyte = sendbyte; //start send data //tcp_protocal(); tcp_send_dat(); delay(2000); if(strstr(return_dat,"OK") == NULL && strstr(return_dat,"ok") == NULL ){ tone(BUZZERPIN ,440);//ERROR beep tcp_close(); mqtt_close(); delay(8000); //WDT restart } tcp_receive_dat(); //sleep loop digitalWrite(LED_BUILTIN, LOW); for(int i=0 ;i<18;i++){ Watchdog.disable(); //Serial.println(i), bg96_serial_clearbuf(); bg96_serial_read(); const char *p_msg; if(strstr(return_dat,"QMTRECV") != NULL ){ Watchdog.reset(); Serial.print("rcvmsg= "); p_msg=strstr(return_dat,"{\"cmd\""); Serial.println(p_msg); i=99; DeserializationError error = deserializeJson(doc, p_msg); if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.f_str()); return; } subcmd=doc["cmd"]; Serial.println(subcmd); oled_write(0); delay(1000); if (subcmd==1){ ledflg=true; }else if(subcmd==0){ ledflg=false; }else if(subcmd==2){ dispflg= !dispflg; } } digitalWrite(LEDPIN, ledflg); //OLED display if (digitalRead(BUTTONPIN)==HIGH){ dispflg = !dispflg; } if (dispflg){ oled_write(i); }else{ u8x8.clear(); } Watchdog.reset(); Watchdog.sleep(4000); } upcount++; } void oled_write(int i){ u8x8.clear(); u8x8.setCursor(0, 1); switch (i%9){ case 0: if(strstr(return_dat,"OK")!=NULL){ u8x8.println("return:"); u8x8.println(); u8x8.println("OK"); }else if(strstr(return_dat,"ERROR")!=NULL){ u8x8.println("return:"); u8x8.println(); u8x8.println("ERROR"); }else { u8x8.println(i); u8x8.println("subcmd:"); u8x8.println(subcmd); } return; case 1: u8x8.println(i); u8x8.println("Temperture:"); u8x8.print(tem);u8x8.println(" \"C"); return; case 2: u8x8.println(i); u8x8.println("Humidity:"); u8x8.print(hum);u8x8.println(" %"); return; case 3: u8x8.println(i); u8x8.println("Air Pressure:"); u8x8.print(press*0.01);u8x8.println(" hPa"); return; case 4: u8x8.println(i); u8x8.println("Light:"); u8x8.println(light); return; case 5: u8x8.println(i); u8x8.println("Sound:"); u8x8.println(sound); return; case 6: u8x8.println(i); u8x8.println("Volume:"); u8x8.println(volume); return; case 7: u8x8.println(i); u8x8.println("TempBMP280:"); u8x8.println(tempbmp); return; case 8: u8x8.println(i); u8x8.println("Up Count:"); u8x8.println(upcount); return; default: return; } return; } /********tcp protocol*********/ void tcp_protocal() { tcp_send_dat(); delay(2000); tcp_receive_dat(); } void tcp_send_dat(){ int tem_x100,hum_x100,tempbmp_x100; tem_x100 = (int)(tem*100); hum_x100 = hum*100; tempbmp_x100 = tempbmp*100; int press_c = (int)(press-100000); char cmd[64]={"0"}; snprintf(cmd,sizeof(cmd),"AT+QISENDEX=0,\"%04x%04x%04x%04x%04x%04x%02x%04x%04x\"", tem_x100,hum_x100,press_c,upcount,light,sound,sendbyte,volume,tempbmp_x100); bg96_serial_clearbuf(); bg96_serial.println(cmd); delay(500); bg96_serial_read(); //Serial.println(cmd); //Serial.println("println the tcp send data"); Watchdog.reset(); } void tcp_receive_dat() { Serial.println("receive TCP data:"); bg96_serial_clearbuf(); bg96_serial.println("AT+QIRD=0,1500"); delay(500); bg96_serial_read(); } void bg96_initial(){ delay(1000); Serial.begin(USB_BAUD); bg96_serial.begin(BG96_BAUD); //open the Serial ,BAUD is 9600bps Serial.println("start the serial port,BAUD is 9600bps."); delay(500); //bg96_at_cmd(); /* delay(500); bg96_ate_cmd(); delay(500); bg96_at_cimi(); bg96_at_csq(); delay(500);*/ //bg96_at_cereg(); //delay(500); //bg96_at_cgpaddr(); //delay(500); Watchdog.reset(); //tcp_config(); tcp_close(); delay(500); tcp_config(); mqtt_config(); bg96_powersave_enable(); } void bg96_serial_read() { delay(500); int i = 0; memset(return_dat, 0, sizeof(return_dat)); bg96_serial.flush(); delay(2000); while (bg96_serial.available() && i < (int)sizeof(return_dat) - 1) { return_dat[i] = bg96_serial.read(); i = i + 1; } return_dat[i] = '\0'; Serial.println(return_dat); } void bg96_serial_clearbuf() { bg96_serial.flush(); while (bg96_serial.available()) { bg96_serial.read(); } } /********tcp config*********/ void tcp_config(){ start_tcp(); } void start_tcp(){ char cmd[64]={"0"}; snprintf(cmd,sizeof(cmd),"AT+QIOPEN=1,0,\"TCP\",\"%s\",%d,0,0",TCP_server,TCP_port);//TCP cliant Buffer access mode while(1){ bg96_serial_clearbuf(); Serial.println(cmd); bg96_serial.println(cmd); bg96_serial_read(); if(strstr(return_dat,"OK")!=NULL){ Serial.println("the tcp already connect"); break;} } } void tcp_close() { Serial.println("close tcp server."); bg96_serial_clearbuf(); bg96_serial.println("AT+QICLOSE=0"); bg96_serial_read(); } /********mqtt protocol*********/ void mqtt_config() { bg96_serial_clearbuf(); bg96_serial.println("AT+QMTOPEN=1,\"beam.soracom.io\",1883");//MQTT bg96_serial_read(); bg96_serial_clearbuf(); bg96_serial.println("AT+QMTCONN=1,\"soracom\""); bg96_serial_read(); bg96_serial_clearbuf(); bg96_serial.println("AT+QMTSUB=1,1,\"soracom/cmd/1\",0"); bg96_serial_read(); } void mqtt_close() { Serial.println("disconnect mqtt"); bg96_serial_clearbuf(); bg96_serial.println("AT+QMTDISC=1"); bg96_serial_read(); Serial.println("close mqtt."); bg96_serial_clearbuf(); bg96_serial.println("AT+QMTCLOSE=1"); bg96_serial_read(); } /**********AT comade*******/ void bg96_at_cmd(){ Serial.println("\n"); Serial.println("send the at command,wait for return \"OK\""); while(1){ bg96_serial_clearbuf();//clear the return data buffer bg96_serial.println("AT"); bg96_serial_read(); if(strstr(return_dat,"OK") != NULL){ Serial.println("<----------------------->"); break;} else delay(1000); } } void bg96_ate_cmd(){ Serial.println("close the return display"); while(1){ bg96_serial_clearbuf();//clear the return data buffer bg96_serial.println("ATE0"); bg96_serial_read(); if(strstr(return_dat,"OK") != NULL){ Serial.println("<----------------------->"); break;} else delay(1000); }} void bg96_at_cimi(){ Serial.println("sent the \"AT+CIMI\" command"); bg96_serial_clearbuf(); bg96_serial.println("AT+CIMI"); bg96_serial_read(); delay(1000); Serial.println("sent the \"AT+CGSN\" command"); bg96_serial_clearbuf(); bg96_serial.println("AT+CGSN"); bg96_serial_read(); delay(1000); } void bg96_at_csq(){ Serial.println("\n"); Serial.println("the module look for the signal strenght:"); while(1){ bg96_serial_clearbuf(); bg96_serial.println("AT+CSQ"); bg96_serial_read(); // if(strstr(return_dat,"+CSQ: 99,99") != NULL){ // Serial.println("config the NB modlue"); //bianixe cheng xu // } if(strstr(return_dat,"+CSQ: 99,99") != NULL){ bg96_serial.println("AT+QCFG=\"nwscanmode\",0,1"); Serial.println("AT+QCFG=\"nwscanmode\",0,1"); Serial.println("wait for 5 second"); delay(5000); } else{ Serial.println("the module has signal"); break;} } } void bg96_at_cereg() { Serial.println("\n"); Serial.println("look for network already register."); while(1){ bg96_serial_clearbuf(); bg96_serial.println("AT+CEREG?"); delay(500); bg96_serial_read(); if(strstr(return_dat,"+CEREG: 0,1") != NULL) { Serial.println("the module already register"); break; } else{ delay(5000); } } } void bg96_at_cgpaddr(){ Serial.println("\n"); Serial.println("look for the temporary IP"); bg96_serial_clearbuf(); bg96_serial.println("AT+CGPADDR"); delay(500); bg96_serial_read(); } void bg96_powersave_enable(){ Serial.println("Power save mode setting"); bg96_serial_clearbuf(); bg96_serial.println("AT+CPSMS=1,,,\"01111110\",\"00000000\"");//60sec powersave 0sec active delay(300); bg96_serial_read(); }
23.760736
117
0.623031
mnltake
a4fa9de161df7de310b8f8ce01e2b2f4154d8155
682
cpp
C++
Source/Engine/Scene/Scene.cpp
amerkoleci/alimer
f47b80e0790a42a65366c88c3024a0dfdafb1e1b
[ "MIT" ]
291
2017-09-30T09:07:49.000Z
2022-03-22T13:09:21.000Z
Source/Engine/Scene/Scene.cpp
amerkoleci/alimer
f47b80e0790a42a65366c88c3024a0dfdafb1e1b
[ "MIT" ]
12
2018-01-14T01:54:53.000Z
2021-02-19T06:14:01.000Z
Source/Engine/Scene/Scene.cpp
amerkoleci/alimer
f47b80e0790a42a65366c88c3024a0dfdafb1e1b
[ "MIT" ]
16
2018-05-03T08:15:31.000Z
2022-02-25T09:03:16.000Z
// Copyright © Amer Koleci and Contributors. // Licensed under the MIT License (MIT). See LICENSE in the repository root for more information. #include "Scene/Scene.h" #include "Scene/Camera.h" #include "Core/Log.h" #include "Core/Assert.h" using namespace Alimer; void Scene::Register() { RegisterFactory<Scene>(); } Scene::Scene(const std::string_view& name) : name{ name } { root = new Node("Root"); root->scene = this; } Scene::~Scene() { root.Reset(); } void RegisterSceneLibrary() { static bool registered = false; if (registered) return; registered = true; Node::Register(); Scene::Register(); Camera::Register(); }
17.487179
97
0.652493
amerkoleci
a4faefb10fd7a4068cbfe7b05d43658a5133fc14
1,010
hpp
C++
include/apex/mixin/singleton.hpp
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
4
2020-12-14T18:07:28.000Z
2021-04-21T18:10:26.000Z
include/apex/mixin/singleton.hpp
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
11
2020-07-21T03:27:10.000Z
2021-03-22T20:24:44.000Z
include/apex/mixin/singleton.hpp
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
3
2020-12-14T17:40:07.000Z
2022-03-18T15:43:10.000Z
#ifndef APEX_MIXIN_SINGLETON_HPP #define APEX_MIXIN_SINGLETON_HPP #include <apex/core/concepts.hpp> // This requires more work. The singleton<T> type should, honestly, be hidden // behind a detail:: namespace. Additionally, this isn't really a mixin, is it? namespace apex { template <default_initializable T> struct singleton { singleton (singleton const&) = delete; singleton () = delete; ~singleton () = delete; singleton& operator = (singleton const&) = delete; static T& global () noexcept { static T instance; return instance; }; static T& local () noexcept { static thread_local T instance; return instance; } }; template <class T> inline auto& global = singleton<T>::global(); template <class T> inline auto& local = singleton<T>::local(); template <class T> inline auto const& global<T const> = singleton<T>::global(); template <class T> inline auto const& local<T const> = singleton<T>::local(); } /* namespace apex */ #endif /* APEX_MIXIN_SINGLETON_HPP */
25.897436
79
0.70495
slurps-mad-rips
a4fec632caff18d927af87f6ca59e8201feedb02
2,383
cpp
C++
source/Window.cpp
amanb014/NxReader
f7c74b78e3c676cab29da78079d4c2d12c9065a1
[ "MIT" ]
3
2018-12-14T17:36:21.000Z
2020-11-06T19:29:49.000Z
source/Window.cpp
amanb014/NxReader
f7c74b78e3c676cab29da78079d4c2d12c9065a1
[ "MIT" ]
null
null
null
source/Window.cpp
amanb014/NxReader
f7c74b78e3c676cab29da78079d4c2d12c9065a1
[ "MIT" ]
null
null
null
#include "Window.hpp" #include "Util.hpp" #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> // TODO TEMP includes to be moved #include <SDL2/SDL_events.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_mixer.h> Window::Window() { createBaseWindow(); setWidthHeight(); // _textureTarget = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, w, h); // SDL_SetRenderTarget(renderer, _textureTarget); } Window::Window(const char* title) { createBaseWindow(); setWidthHeight(); // _textureTarget = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, w, h); // SDL_SetRenderTarget(renderer, _textureTarget); } Window::Window(const char* title, int* wx, int* hy) { w = *wx; h = *hy; window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_BORDERLESS); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_SOFTWARE); // _textureTarget = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, w, h); // SDL_SetRenderTarget(renderer, _textureTarget); } Window::~Window() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); } void Window::createBaseWindow() { window = SDL_CreateWindow("NxReader-Main", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_FULLSCREEN_DESKTOP); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE | SDL_RENDERER_TARGETTEXTURE); } void Window::update() { // Clear the render target so it displays on the screen // SDL_SetRenderTarget(renderer, NULL); // SDL_RenderClear(renderer); // Copy the textureTarget to the real screen renderer, with any flips // if(Util::getOrientation() == PORT) { // SDL_RenderCopyEx(renderer, _textureTarget, NULL, NULL, 0, NULL, SDL_FLIP_HORIZONTAL); // } // else { // SDL_RenderCopy(renderer, _textureTarget); // } // Display to the screen SDL_RenderPresent(renderer); // Set the texture target to internal texture for next frame // SDL_SetRenderTarget(renderer, _textureTarget); } void Window::setWidthHeight() { SDL_GetRendererOutputSize(renderer, &w, &h); } SDL_Renderer* Window::getRenderer() { return renderer; } void Window::clearWindow() { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); }
29.060976
135
0.74444
amanb014
350e5dd28931f6876f9da660c1cf7d1bf0fde934
7,962
cpp
C++
tutoriales_basicos/src/robot_cleaner_ios.cpp
lfzarazuaa/LiderSeguidorA
5714ac3c025ab2f7b83f427004c05071ed3f3689
[ "MIT" ]
1
2020-05-09T23:07:36.000Z
2020-05-09T23:07:36.000Z
tutoriales_basicos/src/robot_cleaner_ios.cpp
lfzarazuaa/LiderSeguidorA
5714ac3c025ab2f7b83f427004c05071ed3f3689
[ "MIT" ]
null
null
null
tutoriales_basicos/src/robot_cleaner_ios.cpp
lfzarazuaa/LiderSeguidorA
5714ac3c025ab2f7b83f427004c05071ed3f3689
[ "MIT" ]
null
null
null
#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "turtlesim/Pose.h" #include <sstream> ros::Publisher velocity_publisher; ros::Subscriber pose_subscriber; turtlesim::Pose turtlesim_pose; using namespace std; const double x_min = 0.0; const double y_min = 0.0; const double x_max = 11.0; const double y_max = 11.0; const double PI=3.14159265359; void move(double speed,double distance,bool isForward); void rotate(double angular_speed,double angle,bool clockwise); double degrees2radians(double angle_in_degrees); double setDesiredOrientation(double desired_angle_degrees); void poseCallback(const turtlesim::Pose::ConstPtr & pose_message); double getDistance(double x1, double y1, double x2, double y2); void moveGoal(turtlesim::Pose goal_pose, double distance_tolerance); void gridClean(); void spiralClean(); int main(int argc, char **argv) { // Initiate new ROS node named "robot_cleaner" ros::init(argc, argv, "robot_cleaner"); ros::NodeHandle n; ros::Rate loop_rate(10); double speed,angular_speed; double distance,angle; bool isForward,clockwise; velocity_publisher = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",10); pose_subscriber = n.subscribe("/turtle1/pose",1000,poseCallback); /* cout << "enter speed: "; cin >> speed; cout << "enter distance: "; cin >> distance; cout << "enter isForward(0/1): "; cin >> isForward; move(speed, distance, isForward); //Angular cout << "enter angular speed: "; cin >> angular_speed; cout << "enter angle: "; cin >> angle; cout << "enter clockwise(0/1): "; cin >> clockwise; rotate(angular_speed, angle, clockwise); cout << "rotation finished"; */ //ros::Rate loop_rate(0.5); /* setDesiredOrientation(120); loop_rate.sleep(); setDesiredOrientation(270); loop_rate.sleep(); setDesiredOrientation(0); */ /* turtlesim::Pose goal_pose; goal_pose.x=1; goal_pose.y=1; goal_pose.theta=0; moveGoal(goal_pose,0.5); goal_pose.x=4; goal_pose.y=8; goal_pose.theta=0; moveGoal(goal_pose,0.5); goal_pose.x=8; goal_pose.y=10; goal_pose.theta=0; moveGoal(goal_pose,0.5); goal_pose.x=5.544; goal_pose.y=5.544; goal_pose.theta=0; moveGoal(goal_pose,0.2); loop_rate.sleep(); */ //gridClean(); spiralClean(); ros::spin(); return 0; } /** * @brief move- makes the robot move with a certain linear velocity in a certain distance * @param speed- linear velocity * @param distance- relative distance to move * @param isForward- direction of the move */ void move(double speed,double distance,bool isForward){ //distance=speed*time geometry_msgs::Twist vel_msg; if (isForward) vel_msg.linear.x=abs(speed); else vel_msg.linear.x=-abs(speed); vel_msg.linear.y=0; vel_msg.linear.z=0; //set to zero angular velocities for a straigth line vel_msg.angular.x=0; vel_msg.angular.y=0; vel_msg.angular.z=0; //t0: current time //loop //publish velocity // estimate the distance = speed * (t1-t0) //current_distance_moved_by_robot <= distance double t0 = ros::Time::now().toSec(); double current_distance=0; ros::Rate loop_rate(100); do{ velocity_publisher.publish(vel_msg); double t1=ros::Time::now().toSec(); current_distance = speed * (t1-t0); ros::spinOnce(); }while(current_distance<distance); vel_msg.linear.x=0; velocity_publisher.publish(vel_msg); } void rotate(double angular_speed,double angle,bool clockwise){ //angular_speed=degrees2radians(angular_speed); //angle=degrees2radians(angle); //cout<<"angular_speed= "<<angular_speed<<endl; //cout<<"angle= "<<angle<<endl; geometry_msgs::Twist vel_msg; //set a random linear velocity in the x-axis vel_msg.linear.x=0; vel_msg.linear.y=0; vel_msg.linear.z=0; //set a random angular velocity in the z-axis vel_msg.angular.x=0; vel_msg.angular.y=0; if (clockwise){ vel_msg.angular.z=-abs(angular_speed); } else{ vel_msg.angular.z=abs(angular_speed); } double current_angle=0; double t0=ros::Time::now().toSec(),t1; ros::Rate loop_rate(100); do { velocity_publisher.publish(vel_msg); t1=ros::Time::now().toSec(); current_angle=angular_speed*(t1-t0); ros::spinOnce(); loop_rate.sleep(); } while (current_angle<angle); vel_msg.angular.z=0; velocity_publisher.publish(vel_msg); } double degrees2radians(double angle_in_degrees){ return angle_in_degrees*PI/180.0; } double setDesiredOrientation(double desired_angle_degrees){ double desired_angle_radians=degrees2radians(desired_angle_degrees); double relative_angle_radians=desired_angle_radians-turtlesim_pose.theta; bool clockwise=((relative_angle_radians<0)?true:false); cout<<desired_angle_radians<<" ,"<<turtlesim_pose.theta<<" ,"<<relative_angle_radians<<endl; rotate (abs(relative_angle_radians)/10,abs(relative_angle_radians),clockwise); cout<<"rotation finished at: "<<desired_angle_degrees<<endl; } void poseCallback(const turtlesim::Pose::ConstPtr & pose_message){ turtlesim_pose.x=pose_message->x; turtlesim_pose.y=pose_message->y; turtlesim_pose.theta=pose_message->theta; } double getDistance(double x1, double y1, double x2, double y2){ return sqrt(pow((x1-x2),2)+pow((y1-y2),2)); } void moveGoal(turtlesim::Pose goal_pose,double distance_tolerance){ geometry_msgs::Twist vel_msg; ros::Rate loop_rate(20); do{ /****** Proportional Controller ******/ //linear velocity in the x-axis vel_msg.linear.x = 1.5*getDistance(turtlesim_pose.x,turtlesim_pose.y,goal_pose.x,goal_pose.y); vel_msg.linear.y =0; vel_msg.linear.z =0; //angular velocity in the z-axis vel_msg.angular.x = 0; vel_msg.angular.y = 0; vel_msg.angular.z =4*(atan2(goal_pose.y-turtlesim_pose.y, goal_pose.x-turtlesim_pose.x)-turtlesim_pose.theta); velocity_publisher.publish(vel_msg); ros::spinOnce(); loop_rate.sleep(); }while(getDistance(turtlesim_pose.x, turtlesim_pose.y, goal_pose.x, goal_pose.y)>distance_tolerance); vel_msg.linear.x =0; vel_msg.angular.z = 0; velocity_publisher.publish(vel_msg); cout<<"end move goal"<<endl; } void gridClean(){ ros::Rate loop(0.5); turtlesim::Pose pose; pose.x=1; pose.y=1; pose.theta=0; moveGoal(pose,0.01); loop.sleep(); setDesiredOrientation(0); loop.sleep(); move(2,9,true); loop.sleep(); rotate (degrees2radians(10),degrees2radians(90),false); loop.sleep(); move(2,9,true); rotate(degrees2radians(10),degrees2radians(90),false); loop.sleep(); move(2,1,true); rotate(degrees2radians(10),degrees2radians(90),false); loop.sleep(); move(2,9,true); rotate(degrees2radians(10),degrees2radians(90),false); loop.sleep(); move(2,1,true); rotate(degrees2radians(10),degrees2radians(90),false); loop.sleep(); move(2,9,true); } void spiralClean(){ geometry_msgs::Twist vel_msg; double count=0; double constant_speed=4; double vk=1, wk=2, rk=0.5; ros::Rate loop(1); do{ rk=rk+0.5; //linear velocity in the x-axis vel_msg.linear.x = rk; vel_msg.linear.y =0; vel_msg.linear.z =0; //angular velocity in the z-axis vel_msg.angular.x = 0; vel_msg.angular.y = 0; vel_msg.angular.z =constant_speed; cout<<"vel_msg.linear.x = "<<vel_msg.linear.x<<endl; cout<<"vel_msg.linear.z = "<<vel_msg.angular.z<<endl; velocity_publisher.publish(vel_msg); ros::spinOnce(); loop.sleep(); }while((turtlesim_pose.x<10.5)&&(turtlesim_pose.y<10.5)); vel_msg.linear.x =0; vel_msg.angular.z =0; velocity_publisher.publish(vel_msg); }
29.164835
112
0.670686
lfzarazuaa
3512232f23d2202e09a7ba3ae318510366c305c3
513
cpp
C++
test/parser_unittest.cpp
sequoia-mso/sequoia-core
d2a6a461ffbe38dc8abb005b2c8f1f3bc1dc2bbe
[ "Apache-2.0" ]
7
2016-11-12T17:55:03.000Z
2021-04-28T20:23:27.000Z
test/parser_unittest.cpp
sequoia-mso/sequoia-core
d2a6a461ffbe38dc8abb005b2c8f1f3bc1dc2bbe
[ "Apache-2.0" ]
null
null
null
test/parser_unittest.cpp
sequoia-mso/sequoia-core
d2a6a461ffbe38dc8abb005b2c8f1f3bc1dc2bbe
[ "Apache-2.0" ]
4
2015-05-12T13:51:54.000Z
2020-06-07T22:01:28.000Z
#include "parseformula.h" #include "logic/vocabulary.h" #include "gtest/gtest.h" #include <iostream> using namespace sequoia; TEST(ParserTests, ParserTest) { Vocabulary *voc = new Vocabulary(); voc->add_symbol(new Symbol("adj", 2, false, 0)); Formula* res = NULL; res = parse_file(voc, "parser_unittest.mso"); ASSERT_TRUE(res != NULL); std::cout << res->toString() << std::endl; } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
23.318182
52
0.664717
sequoia-mso
3518f496ffdae095bb56a78ce51c1156f596ecb5
231
hpp
C++
src/kalman/numerical.hpp
ENGN2912B-2018/EE-A
f3017265535b0f619c06f54167fd4b8939195a8f
[ "MIT" ]
null
null
null
src/kalman/numerical.hpp
ENGN2912B-2018/EE-A
f3017265535b0f619c06f54167fd4b8939195a8f
[ "MIT" ]
null
null
null
src/kalman/numerical.hpp
ENGN2912B-2018/EE-A
f3017265535b0f619c06f54167fd4b8939195a8f
[ "MIT" ]
null
null
null
#ifndef NUM_INT #define NUM_INT // Performs numerical integration on data. // Implementation performs two stage integration where // area is represented as float * numerical_int(float* data); #endif /* end of include guard: */
23.1
54
0.753247
ENGN2912B-2018
3519db8d64709170a19c33f9b3a7447d56648ded
813
cpp
C++
test/unit/math/opencl/prim/divide_test.cpp
tiagocabaco/math
1b300c592b680fbfde289f08dc75d1da9c61901d
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/prim/divide_test.cpp
tiagocabaco/math
1b300c592b680fbfde289f08dc75d1da9c61901d
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/prim/divide_test.cpp
tiagocabaco/math
1b300c592b680fbfde289f08dc75d1da9c61901d
[ "BSD-3-Clause" ]
null
null
null
#ifdef STAN_OPENCL #include <stan/math/prim.hpp> #include <stan/math/opencl/opencl.hpp> #include <gtest/gtest.h> #include <algorithm> #define EXPECT_MATRIX_NEAR(A, B, DELTA) \ for (int i = 0; i < A.size(); i++) \ EXPECT_NEAR(A(i), B(i), DELTA); TEST(MathMatrixCL, divide_exception_pass) { stan::math::matrix_cl<double> m; EXPECT_NO_THROW(stan::math::divide(m, 2)); } TEST(MathMatrixCL, divide_val) { using stan::math::divide; stan::math::matrix_d a(10, 1); a << 4, 6, 8, 10, -21, -55, -5, 0.5, 0, 1; stan::math::matrix_cl<double> a_cl(a); stan::math::matrix_cl<double> res_cl = stan::math::divide(a_cl, 1.5); stan::math::matrix_d res = stan::math::from_matrix_cl(res_cl); stan::math::matrix_d res_cpu = stan::math::divide(a, 1.5); EXPECT_MATRIX_NEAR(res_cpu, res, 1E-8); } #endif
29.035714
71
0.664207
tiagocabaco
3523f3f3378b03f88908215cd6b157ba958a4f36
2,591
cpp
C++
Engine/src/engine/Object.cpp
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
2
2015-04-21T05:36:12.000Z
2017-04-16T19:31:26.000Z
Engine/src/engine/Object.cpp
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
null
null
null
Engine/src/engine/Object.cpp
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
null
null
null
/* ----------------------------------------------------------------------------- KG game engine (http://katoun.github.com/kg_engine) is made available under the MIT License. Copyright (c) 2006-2013 Catalin Alexandru Nastase 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 <engine/Object.h> #include <core/Utils.h> namespace engine { unsigned int Object::msNextGeneratedObjectIndex = 0; unsigned int Object::mIndexCounter = 0; Object::Object() { mID = mIndexCounter++; mName = "Object_" + core::intToString(msNextGeneratedObjectIndex++); mObjectType = OT_UNDEFINED; mChangeableName = true; mInitialized = false; } Object::Object(const std::string& name) { mID = mIndexCounter++; mName = name; mObjectType = OT_UNDEFINED; mChangeableName = true; mInitialized = false; } Object::~Object() {} const unsigned int& Object::getID() const { return mID; } const ObjectType& Object::getObjectType() const { return mObjectType; } void Object::setName(const std::string& name) { if (mChangeableName) mName = name; } const std::string& Object::getName() const { return mName; } void Object::initialize() { initializeImpl(); mInitialized = true; } void Object::uninitialize() { uninitializeImpl(); mInitialized = true; } void Object::update(float elapsedTime) { updateImpl(elapsedTime); } bool Object::isInitialized() const { return mInitialized; } void Object::initializeImpl() {} void Object::uninitializeImpl() {} void Object::updateImpl(float elapsedTime) {} } // end namespace engine
22.530435
92
0.710536
katoun
3524f93c5154338efa1b3be6badc23ff0e0fe496
4,469
hpp
C++
Nacro/SDK/FN_PlayerZoneTeamScoreContributionWidget_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_PlayerZoneTeamScoreContributionWidget_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_PlayerZoneTeamScoreContributionWidget_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass PlayerZoneTeamScoreContributionWidget.PlayerZoneTeamScoreContributionWidget_C // 0x02B8 (0x04F8 - 0x0240) class UPlayerZoneTeamScoreContributionWidget_C : public UFortUserWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0240(0x0008) (Transient, DuplicateTransient) class UWidgetAnimation* IntroAnim; // 0x0248(0x0008) (BlueprintVisible, ExportObject, BlueprintReadOnly, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UCommonBorder* Border_Shell; // 0x0250(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UPlayerBanner_C* PlayerBanner; // 0x0258(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UCommonTextBlock* TextPlayerName; // 0x0260(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UCommonTextBlock* TextPlayerScoreCounter; // 0x0268(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) struct FFortPlayerScoreReport ScoreReport; // 0x0270(0x0288) (Edit, BlueprintVisible) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass PlayerZoneTeamScoreContributionWidget.PlayerZoneTeamScoreContributionWidget_C"); return ptr; } void Update_Contribution_LERP(float LERP_Factor); void Initialize(); void Construct(); void ExecuteUbergraph_PlayerZoneTeamScoreContributionWidget(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
95.085106
663
0.741105
Milxnor
352b5c20dc5d8dff5f960434d8b520a665fde2d0
50
hpp
C++
src/boost_mpl_map_aux__value_type_impl.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_map_aux__value_type_impl.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_map_aux__value_type_impl.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/map/aux_/value_type_impl.hpp>
25
49
0.8
miathedev
352d80f37ef171785ef7ad40b04d619efa20c252
234
cpp
C++
libraries/chain/required_action_evaluator.cpp
DunnCreativeSS/ccd
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
[ "MIT" ]
1
2021-09-02T16:09:26.000Z
2021-09-02T16:09:26.000Z
libraries/chain/required_action_evaluator.cpp
DunnCreativeSS/ccd
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
[ "MIT" ]
null
null
null
libraries/chain/required_action_evaluator.cpp
DunnCreativeSS/ccd
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
[ "MIT" ]
null
null
null
#include <CreateCoin/chain/required_action_evaluator.hpp> namespace CreateCoin { namespace chain { #ifdef IS_TEST_NET void example_required_evaluator::do_apply( const example_required_action& a ) {} #endif } } //CreateCoin::chain
21.272727
80
0.794872
DunnCreativeSS
352fea63e27040680eb3f800049e7b5a9b271d69
3,707
cpp
C++
src/dxvk/dxvk_buffer_res.cpp
0x8080/dxvk
92f3648efab8406924a5737e8f988a07d5923826
[ "Zlib" ]
3
2018-10-06T19:02:08.000Z
2021-06-27T16:17:08.000Z
src/dxvk/dxvk_buffer_res.cpp
0x8080/dxvk
92f3648efab8406924a5737e8f988a07d5923826
[ "Zlib" ]
null
null
null
src/dxvk/dxvk_buffer_res.cpp
0x8080/dxvk
92f3648efab8406924a5737e8f988a07d5923826
[ "Zlib" ]
null
null
null
#include "dxvk_buffer_res.h" namespace dxvk { DxvkPhysicalBuffer::DxvkPhysicalBuffer( const Rc<vk::DeviceFn>& vkd, const DxvkBufferCreateInfo& createInfo, DxvkMemoryAllocator& memAlloc, VkMemoryPropertyFlags memFlags) : m_vkd(vkd) { VkBufferCreateInfo info; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.pNext = nullptr; info.flags = 0; info.size = createInfo.size; info.usage = createInfo.usage; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; info.queueFamilyIndexCount = 0; info.pQueueFamilyIndices = nullptr; if (m_vkd->vkCreateBuffer(m_vkd->device(), &info, nullptr, &m_handle) != VK_SUCCESS) { throw DxvkError(str::format( "DxvkPhysicalBuffer: Failed to create buffer:" "\n size: ", info.size, "\n usage: ", info.usage)); } VkMemoryDedicatedRequirementsKHR dedicatedRequirements; dedicatedRequirements.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR; dedicatedRequirements.pNext = VK_NULL_HANDLE; dedicatedRequirements.prefersDedicatedAllocation = VK_FALSE; dedicatedRequirements.requiresDedicatedAllocation = VK_FALSE; VkMemoryRequirements2KHR memReq; memReq.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR; memReq.pNext = &dedicatedRequirements; VkBufferMemoryRequirementsInfo2KHR memReqInfo; memReqInfo.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR; memReqInfo.buffer = m_handle; memReqInfo.pNext = VK_NULL_HANDLE; VkMemoryDedicatedAllocateInfoKHR dedMemoryAllocInfo; dedMemoryAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR; dedMemoryAllocInfo.pNext = VK_NULL_HANDLE; dedMemoryAllocInfo.buffer = m_handle; dedMemoryAllocInfo.image = VK_NULL_HANDLE; m_vkd->vkGetBufferMemoryRequirements2KHR( m_vkd->device(), &memReqInfo, &memReq); bool useDedicated = dedicatedRequirements.prefersDedicatedAllocation; m_memory = memAlloc.alloc(&memReq.memoryRequirements, useDedicated ? &dedMemoryAllocInfo : nullptr, memFlags); if (m_vkd->vkBindBufferMemory(m_vkd->device(), m_handle, m_memory.memory(), m_memory.offset()) != VK_SUCCESS) throw DxvkError("DxvkPhysicalBuffer: Failed to bind device memory"); } DxvkPhysicalBuffer::~DxvkPhysicalBuffer() { if (m_handle != VK_NULL_HANDLE) m_vkd->vkDestroyBuffer(m_vkd->device(), m_handle, nullptr); } DxvkPhysicalBufferView::DxvkPhysicalBufferView( const Rc<vk::DeviceFn>& vkd, const DxvkPhysicalBufferSlice& slice, const DxvkBufferViewCreateInfo& info) : m_vkd(vkd), m_slice(slice.subSlice(info.rangeOffset, info.rangeLength)) { VkBufferViewCreateInfo viewInfo; viewInfo.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO; viewInfo.pNext = nullptr; viewInfo.flags = 0; viewInfo.buffer = m_slice.handle(); viewInfo.format = info.format; viewInfo.offset = m_slice.offset(); viewInfo.range = m_slice.length(); if (m_vkd->vkCreateBufferView(m_vkd->device(), &viewInfo, nullptr, &m_view) != VK_SUCCESS) { throw DxvkError(str::format( "DxvkPhysicalBufferView: Failed to create buffer view:", "\n Offset: ", viewInfo.offset, "\n Range: ", viewInfo.range, "\n Format: ", viewInfo.format)); } } DxvkPhysicalBufferView::~DxvkPhysicalBufferView() { m_vkd->vkDestroyBufferView( m_vkd->device(), m_view, nullptr); } }
37.07
108
0.683032
0x8080
3533e969325f4ed52fad605a7ee812258dd6ac42
6,451
cpp
C++
src/SolarFlare.cpp
bitwitch/Prototype
c05e9c9fb5cf862de8d907354bd068d6191d9e19
[ "MIT" ]
73
2015-02-01T17:58:34.000Z
2022-02-07T07:49:16.000Z
src/SolarFlare.cpp
bitwitch/Prototype
c05e9c9fb5cf862de8d907354bd068d6191d9e19
[ "MIT" ]
1
2018-06-05T19:48:54.000Z
2018-06-05T20:48:22.000Z
src/SolarFlare.cpp
bitwitch/Prototype
c05e9c9fb5cf862de8d907354bd068d6191d9e19
[ "MIT" ]
24
2015-02-09T02:04:39.000Z
2022-02-01T01:41:22.000Z
#include "SolarFlare.h" #include "Engine.h" SolarFlare::SolarFlare() { IsActive = false; fRotation = 0; } //================================================================================================// /******************* ** SolarFlare spawn ** ********************/ //================================================================================================// void SolarFlare::Spawn(Vec2 pos) { IsActive = true; bStartDirection? frame = 11: frame = 3; bStartDirection? fRotation = -90: fRotation = -270; bStartDirection? pos.y = 512: pos.y=-32; oPos = Pos = pos; if(gpEngine->bRecording && gpEngine->pRecordEnt == this) return; SelfControl(); mSections.clear(); iTickSection = 10; StartPos = pos; IsHead = true; fStartRotation = fRotation; for(int n = SolarFlare_LENGTH; n>0; n--) { SolarFlare s; s.bStartDirection = this->bStartDirection; s.mKeyBuffer = this->mKeyBuffer; s.fStartRotation = this->fStartRotation; s.IsActive = false; mSections.push_back(s); } iCurSection = SolarFlare_LENGTH; fStartLife = fLife = 30; mSphere = Sphere(25,pos+Vec2(60,10)); iTakeDamageTicks = 0; mWaterticks=0; } //================================================================================================// /*********************** ** SolarFlare body spawn ** ************************/ //================================================================================================// void SolarFlare::SpawnSection(Vec2 pos) { IsActive = true; oPos = Pos = pos; bStartDirection? frame = 11: frame = 3; bStartDirection? fRotation = -90: fRotation = -270; fRotation = fStartRotation; SelfControl(); IsHead = false; mSphere = Sphere(25,pos+Vec2(60,10)); mWaterticks = 0; } //================================================================================================// /******************* ** SolarFlare Clone ** ********************/ //================================================================================================// SolarFlare* SolarFlare::Clone()const { return new SolarFlare(*this); } //================================================================================================// /******************** ** SolarFlare update ** *********************/ //================================================================================================// void SolarFlare::Update() { iTakeDamageTicks--; if(!gpEngine->bRecording || (gpEngine->bRecording && gpEngine->pRecordEnt != this)) PlayBack(); oPos = Pos; frame<3?frame+=0.075f:frame-=3; if(KEY_RIGHT.state == PRESSED) { fRotation += 1.0f; } if(KEY_LEFT.state == PRESSED) { fRotation -= 1.0f; } fRotation = UTIL_Misc::Wrap(fRotation,360); // if(KEY_UP.state == PRESSED) { Vec2 u,r; UTIL_Misc::MakeVectors(fRotation,u,r); Pos+=u*4.5f; } if(frame>15) frame-=15; else if(frame<0) frame+=15; vector<SolarFlare>::iterator iter; for(iter = mSections.begin(); iter < mSections.end(); iter++) { if((*iter).IsActive) (*iter).PreUpdate(); } if(gpEngine->bRecording && gpEngine->pRecordEnt == this) return; iTickSection--; if((IsHead && iTickSection == 0) || (IsHead && iTickSection==7 && iCurSection == SolarFlare_LENGTH)) { if(iCurSection>=0) { mSections[iCurSection].SpawnSection(StartPos); iCurSection--; iTickSection = 10; } } } //================================================================================================// /****************** ** ladybird draw ** *******************/ //================================================================================================// void SolarFlare::Draw(const float interp) { // UTIL_GL::SetBlend(GL_SRC_ALPHA, GL_ONE); if(iTakeDamageTicks>0) { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); glColor4f(1,1,0,1); } else glColor4f(1,1,1,1); UTIL_GL::SetBlend(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); Vec2 p; vector<SolarFlare>::iterator iter; int n=0; for(iter = mSections.begin(); iter < mSections.end(); iter++,n++) { if(!(*iter).IsActive) continue; p = UTIL_Misc::Interpolate((*iter).Pos,(*iter).oPos,interp); if(n==0) RenderRotatedSprite(gpEngine->sprSolarFlare,(int)(*iter).frame,p.x+64,p.y,-80,80,(*iter).fRotation+90); else RenderRotatedSprite(gpEngine->sprSolarFlare,(int)(*iter).frame,p.x+64,p.y,-80,80,(*iter).fRotation+90); /* glDisable(GL_TEXTURE_2D); glColor4f(1,1,0,1); GeoDraw2D::DrawSphere((*iter).mSphere, 15);//*/ } p = UTIL_Misc::Interpolate(Pos,oPos,interp); RenderRotatedSprite(gpEngine->sprSolarFlare,(int)frame,p.x+64,p.y,-80,80,fRotation+90); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); /* glDisable(GL_TEXTURE_2D); glColor4f(1,1,0,1); GeoDraw2D::DrawSphere(mSphere, 15);//*/ } //================================================================================================// /****************************** ** if its buffer has ran out ** *******************************/ //================================================================================================// void SolarFlare::NeedsToBeRemoved() { if(gpEngine->bRecording && gpEngine->pRecordEnt == this) return; if(!IsHead) return; if(Pos.x<(gpEngine->Scroll-100)) { vector<SolarFlare>::iterator iter; for(iter = mSections.begin(); iter < mSections.end(); iter++) { if((*iter).Pos.x>=(gpEngine->Scroll-100)) return; } IsActive = false; } if(mSections.front().mKeyBuffer.empty()) { IsActive = false; } } //================================================================================================// /**************** ** Take damage ** *****************/ //================================================================================================// bool SolarFlare::CheckCollided(Sphere s, float damage) { if(!IsActive) return false; vector<SolarFlare>::iterator iter; for(iter = mSections.begin(); iter!=mSections.end(); iter++) { if(Collision::SphereSphereOverlap(s,(*iter).mSphere)) return true; } if(!Collision::SphereSphereOverlap(s,mSphere)) return false; return true; } void SolarFlare::LoadFromFile(CFileIO &fIO) { fIO.ReadBinary(&bStartDirection,1); ReadBufferFromFile(fIO); } void SolarFlare::WriteToFile(CFileIO &fIO) { fIO.WriteBinary(&bStartDirection,1); WriteBufferToFile(fIO); } int SolarFlare::InWater() { return 0; }
28.170306
107
0.486281
bitwitch
3536989b267560ba80054d3d9240397e51b16f34
1,653
cpp
C++
tests/test-semaphore.cpp
fabricetriboix/semaphore
dc2f4c2a9a74444ccdb2396535151f3031d7805a
[ "Unlicense" ]
null
null
null
tests/test-semaphore.cpp
fabricetriboix/semaphore
dc2f4c2a9a74444ccdb2396535151f3031d7805a
[ "Unlicense" ]
null
null
null
tests/test-semaphore.cpp
fabricetriboix/semaphore
dc2f4c2a9a74444ccdb2396535151f3031d7805a
[ "Unlicense" ]
null
null
null
#include "semaphore.hpp" #include <thread> #include <gtest/gtest.h> TEST(Semaphore, ShouldUnlockThread) { ft::semaphore_t sem; bool taken = false; std::thread thread( [&sem, &taken] () { sem.take(); taken = true; }); std::this_thread::sleep_for(std::chrono::milliseconds(10)); ASSERT_FALSE(taken); sem.post(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); ASSERT_TRUE(taken); thread.join(); } TEST(Semaphore, TakeWithTimeoutShouldSucceed) { ft::semaphore_t sem; bool taken = false; std::thread thread( [&sem, &taken] () { if (sem.take(std::chrono::milliseconds(20))) { taken = true; } }); std::this_thread::sleep_for(std::chrono::milliseconds(10)); ASSERT_FALSE(taken); sem.post(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); ASSERT_TRUE(taken); thread.join(); } TEST(Semaphore, TakeWithTimeoutShouldTimeout) { ft::semaphore_t sem; bool taken = false; std::thread thread( [&sem, &taken] () { if (sem.take(std::chrono::milliseconds(10))) { taken = true; } }); std::this_thread::sleep_for(std::chrono::milliseconds(15)); ASSERT_FALSE(taken); sem.post(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); ASSERT_FALSE(taken); thread.join(); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
22.04
63
0.554749
fabricetriboix
35389fb30feba5bd78465f1e56266cfcd2103ea7
4,663
cpp
C++
CodeChef/ZCO12002.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
6
2018-11-26T02:38:07.000Z
2021-07-28T00:16:41.000Z
CodeChef/ZCO12002.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
1
2021-05-30T09:25:53.000Z
2021-06-05T08:33:56.000Z
CodeChef/ZCO12002.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
4
2020-04-16T07:15:01.000Z
2020-12-04T06:26:07.000Z
/*Zonal Computing Olympiad 2012, 26 Nov 2011 The year is 2102 and today is the day of ZCO. This year there are N contests and the starting and ending times of each contest is known to you. You have to participate in exactly one of these contests. Different contests may overlap. The duration of different contests might be different. There is only one examination centre. There is a wormhole V that transports you from your house to the examination centre and another wormhole W that transports you from the examination centre back to your house. Obviously, transportation through a wormhole does not take any time; it is instantaneous. But the wormholes can be used at only certain fixed times, and these are known to you. So, you use a V wormhole to reach the exam centre, possibly wait for some time before the next contest begins, take part in the contest, possibly wait for some more time and then use a W wormhole to return back home. If you leave through a V wormhole at time t1 and come back through a W wormhole at time t2, then the total time you have spent is (t2 - t1 + 1). Your aim is to spend as little time as possible overall while ensuring that you take part in one of the contests. You can reach the centre exactly at the starting time of the contest, if possible. And you can leave the examination centre the very second the contest ends, if possible. You can assume that you will always be able to attend at least one contest–that is, there will always be a contest such that there is a V wormhole before it and a W wormhole after it. For instance, suppose there are 3 contests with (start,end) times (15,21), (5,10), and (7,25), respectively. Suppose the V wormhole is available at times 4, 14, 25, 2 and the W wormhole is available at times 13 and 21. In this case, you can leave by the V wormhole at time 14, take part in the contest from time 15 to 21, and then use the W wormhole at time 21 to get back home. Therefore the time you have spent is (21 - 14 + 1) = 8. You can check that you cannot do better than this. Input format The first line contains 3 space separated integers N, X, and Y, where N is the number of contests, X is the number of time instances when wormhole V can be used and Y is the number of time instances when wormhole W can be used. The next N lines describe each contest. Each of these N lines contains two space separated integers S and E, where S is the starting time of the particular contest and E is the ending time of that contest, with S < E. The next line contains X space separated integers which are the time instances when the wormhole V can be used. The next line contains Y space separated integers which are the time instances when the wormhole W can be used. Output format Print a single line that contains a single integer, the minimum time needed to be spent to take part in a contest. Testdata All the starting and ending times of contests are distinct and no contest starts at the same time as another contest ends. The time instances when wormholes are available are all distinct, but may coincide with starting and ending times of contests. All the time instances (the contest timings and the wormhole timings) will be integers between 1 and 1000000 (inclusive). Subtask 1 (30 marks) Subtask 2 (70 marks) You may assume that 1 ≤ N ≤ 105, 1 ≤ X ≤ 105, and 1 ≤ Y ≤ 105. In 30% of the cases, 1 ≤ N ≤ 103, 1 ≤ X ≤ 103, and 1 ≤ Y ≤ 103. Sample Input 3 4 2 15 21 5 10 7 25 4 14 25 2 13 21 Sample Output 8 */ #include <algorithm> #include <iostream> #include <limits> #include <vector> struct Contest { int start; int finish; }; int main() { int n, x, y; std::cin >> n >> x >> y; std::vector<Contest> vec (n); for (auto& elem : vec) std::cin >> elem.start >> elem.finish; std::vector<int> worm_go (x); for (auto& elem : worm_go) std::cin >> elem; std::vector<int> worm_back(y); for (auto& elem : worm_back) std::cin >> elem; std::sort(worm_go.begin(), worm_go.end()); std::sort(worm_back.begin(), worm_back.end()); long res = std::numeric_limits<int>::max(); for (auto& elem : vec) { auto go = std::lower_bound(worm_go.begin(), worm_go.end(), elem.start); if (go == worm_go.end() || *go != elem.start) go = std::prev(go); if (*go > elem.start) continue; auto back = std::lower_bound(worm_back.begin(), worm_back.end(), elem.finish); if (back == worm_back.end()) continue; res = std::min(res, *back - *go + 1L); } std::cout << res << std::endl; return 0; }
47.581633
669
0.706627
ravirathee
353ac9d1d17a5367243aac930a018d9b13b8fa09
4,886
cpp
C++
edbee-lib/edbee/io/baseplistparser.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
445
2015-01-04T16:30:56.000Z
2022-03-30T02:27:05.000Z
edbee-lib/edbee/io/baseplistparser.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
305
2015-01-04T09:20:03.000Z
2020-10-01T08:45:45.000Z
edbee-lib/edbee/io/baseplistparser.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
49
2015-02-14T01:43:38.000Z
2022-02-15T17:03:55.000Z
/** * Copyright 2011-2013 - Reliable Bits Software by Blommers IT. All Rights Reserved. * Author Rick Blommers */ #include <QXmlStreamReader> #include "baseplistparser.h" #include "edbee/debug.h" namespace edbee { /// The constructor for the parser BasePListParser::BasePListParser() : xml_(0) { } /// the default desctructor BasePListParser::~BasePListParser() { delete xml_; } /// Returns the last error message of the parsed file QString BasePListParser::lastErrorMessage() const { return lastErrorMessage_; } /// Sets the last error message. /// To correctly set the last error message while parsing please use raiseError void BasePListParser::setLastErrorMessage(const QString& str) { lastErrorMessage_ = str; } /// Start the parsing of the plist. If it isn't a valid plist this method return false. /// (it only checks and reads the existence of <plist>) bool BasePListParser::beginParsing(QIODevice* device) { lastErrorMessage_.clear(); elementStack_.clear(); xml_ = new QXmlStreamReader(device); if( readNextElement("plist" ) ) { return true; } else { raiseError( QObject::tr("Start element not found!")); return false; } } /// Closes the parsers /// @return true if the parsing was succesful bool BasePListParser::endParsing() { bool result = !xml_->error(); if( !result ) { lastErrorMessage_ = QObject::tr("line %1: %2").arg(xml_->lineNumber()).arg(xml_->errorString()); result = false; } delete xml_; xml_ = 0; return result; } /// Call this method to raise an error and stop the xml parsing /// @param str the error to raise void BasePListParser::raiseError( const QString& str ) { xml_->raiseError(str); } /// reads a list of qvariants QList<QVariant> BasePListParser::readList() { QList<QVariant> result; QVariant value; int level = currentStackLevel(); while( ( value = readNextPlistType(level) ).isValid() ) { result.append(value); } return result; } /// reads a dictionary QHash<QString, QVariant> BasePListParser::readDict() { QHash<QString, QVariant> result; int level = currentStackLevel(); while( readNextElement("key",level) ) { QString key = readElementText(); QVariant data = readNextPlistType(); result.insert(key,data); } return result; } /// reads the next plist type /// @param level the level we're currently parsing QVariant BasePListParser::readNextPlistType( int level ) { if( readNextElement("",level) ) { // reads a dictionary if( xml_->name().compare( QLatin1String("dict"), Qt::CaseInsensitive ) == 0 ) { return readDict(); // reads an array } else if( xml_->name().compare( QLatin1String("array"), Qt::CaseInsensitive ) == 0 ) { return readList( ); // reads a string } else if( xml_->name().compare( QLatin1String("string"), Qt::CaseInsensitive ) == 0 ) { return readElementText(); } } return QVariant(); } /// Reads the next element and optionally expects it to be the given name /// @param name the name taht's expected. Use '' to not check the name /// @param minimum level the level the element should be. -1 means ignore this argument bool BasePListParser::readNextElement( const QString& name, int level ) { //qlog_info() << "* readNextElement(" << name << ","<<level<<")"; while( !xml_->atEnd() ) { switch( xml_->readNext() ) { case QXmlStreamReader::StartElement: elementStack_.push( xml_->name().toString() ); //qlog_info() << "- <" << elementStack_.top() << " (" << elementStack_.size() << "/" << level << ")"; if( name.isEmpty() ) return true; // name doesn't matter if( xml_->name().compare( name, Qt::CaseInsensitive ) == 0 ) return true; xml_->raiseError( QObject::tr("Expected %1 while parsing").arg(name) ); return false; case QXmlStreamReader::EndElement: //qlog_info() << "- </" << (elementStack_.isEmpty()?elementStack_.top():"") << " (" << elementStack_.size() << "/" << level << ")"; if( !elementStack_.isEmpty() ) { elementStack_.pop(); } // end level detected if( level >=0 && elementStack_.size() < level ) { return false; } break; default: // ignore break; } } return false; } /// Reads the element text contents QString BasePListParser::readElementText() { QString result = xml_->readElementText(); if( !elementStack_.isEmpty() ) { elementStack_.pop(); } return result; } /// returns the current stack-level int BasePListParser::currentStackLevel() { return elementStack_.size(); } } // edbee
25.989362
131
0.618707
UniSwarm
353c7d55f37ba983aec143863a84dbc06f12c221
1,391
cpp
C++
src/vulkan/vulkan_shader_module.cpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/vulkan/vulkan_shader_module.cpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/vulkan/vulkan_shader_module.cpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
#include "vulkan_shader_module.hpp" #include "instrumentor.hpp" #include "vulkan_check.hpp" namespace cl::vulkan { #pragma warning(push) #pragma warning(disable : 26812) VkShaderModule CreateShaderModule(VulkanContextData* context, const SpvCode& code) { CALCIUM_PROFILE_FUNCTION(); VkShaderModuleCreateInfo create_info { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO }; create_info.codeSize = code.size() * sizeof(uint32_t); create_info.pCode = code.data(); VkShaderModule shader_module; VK_CHECK(vkCreateShaderModule(context->device, &create_info, context->allocator, &shader_module)); return shader_module; } VkShaderStageFlagBits FindVulkanShaderStage(ShaderStage stage) { switch (stage) { case ShaderStage::kComputeShader: return VK_SHADER_STAGE_COMPUTE_BIT; case ShaderStage::kFragmentShader: return VK_SHADER_STAGE_FRAGMENT_BIT; case ShaderStage::kGeometryShader: return VK_SHADER_STAGE_GEOMETRY_BIT; case ShaderStage::kMeshShader: return VK_SHADER_STAGE_MESH_BIT_NV; case ShaderStage::kTaskShader: return VK_SHADER_STAGE_TASK_BIT_NV; case ShaderStage::kTesselationShader: return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT; case ShaderStage::kVertexShader: return VK_SHADER_STAGE_VERTEX_BIT; default: return VK_SHADER_STAGE_FLAG_BITS_MAX_ENUM; } } #pragma warning(pop) }
35.666667
100
0.774982
zfccxt
353d18d45d1acd3e1aa99afe5e78bb2fc842bc3b
39,662
cpp
C++
source/comms/comm_files.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
[ "BSD-3-Clause" ]
4
2020-08-20T11:31:22.000Z
2020-12-05T13:30:03.000Z
source/comms/comm_files.cpp
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
null
null
null
source/comms/comm_files.cpp
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
4
2020-08-20T14:33:19.000Z
2022-03-07T10:29:34.000Z
/// \file comm_files.cc /// /// \brief Contains comms class for multi-process communication using /// files (no MPI!). /// /// \author Jonathan Mackey /// \date 2009-01-27. /// /// Modifications:\n /// - 2010.11.15 JM: replaced endl with c-style newline chars. /// - 2012.05.15 JM: Added function for global-reduce (max/min/sum) of arrays, /// but it is not yet implemented. If I ever need it, I will write it... /// - 2015.01.26 JM: Removed mpiPM (no longer global), added COMM /// setup, and added get_rank_nproc() function #ifdef PARALLEL #ifdef USE_FILE_COMMS #ifdef INTEL #include <mathimf.h #else #include <cmath> #endif // INTEL #include <sstream> using namespace std; class comms_base *COMM = new comm_files (); // ################################################################## // ################################################################## comm_files::comm_files() { cout <<"*** comm_files constructor. ***\n"; // // standard name for all the files: // comm_files::dir = "filecomms/"; comm_files::ini = "INITIALISED"; comm_files::bar = "_BARRIER_"; go_order = "master_says_go"; go_response = "_going"; comm_global = "GLOBAL_"; celldata = "cell_data_step_"; doubledata = "dubl_data_step_"; finished_with_file = "_FINISHED"; myrank = -1; nproc = -1; barrier_count=0; } // ################################################################## // ################################################################## comm_files::~comm_files() { cout <<"*** comm_files destructor. ***\n"; } // ################################################################## // ################################################################## int comm_files::init(int *argc, ///< number of program arguments. char ***argv ///< character list of arguments. ) { // // Get rank and nproc from command-line args. // string args[(*argc)]; for (int i=0;i<(*argc);i++) { args[i] = (*argv)[i]; } myrank = nproc = -1; for (int i=0;i<(*argc); i++) { if (args[i].find("myrank=") != string::npos) { cout <<"found myrank as "<<i<<"th arg.\n"; string rank= args[i].substr(7); myrank = atoi(rank.c_str()); } else if (args[i].find("nproc=") != string::npos) { cout <<"found nproc as "<<i<<"th arg.\n"; string np= args[i].substr(6); nproc = atoi(np.c_str()); } } if (myrank<0 || nproc<0) rep.error("failed to find rank and nproc in command-line args",myrank); // // reduce number of args by 2, since myrank and nproc must be last two args. // (*argc) -= 2; // // If I'm the root processor, create the directory, and then a file in it // if (myrank==0) { // // create a directory for all the files we will create and destroy // string tmp="mkdir "+dir; system(tmp.c_str()); // // create a file to let everyone know that I am present // string s(dir); s += ini; ofstream outf(s.c_str()); outf.close(); } else { // // wait for initialised file... // string s(dir); s += ini; wait_for_file(s); } ostringstream oss; oss<<dir<<ini<<"_rank_"<<myrank<<"_of_"<<nproc<<"_present_and_correct"; ofstream outf(oss.str().c_str()); outf.close(); // // Now make sure everyone exists and is ready to go: // barrier("comm_files_init_end"); cout << "comm_files::init(): rank: "<<myrank<<" nproc: "<<nproc<<"\n"; return 0; } // ################################################################## // ################################################################## int comm_mpi::get_rank_nproc( int *r, ///< rank. int *n ///< nproc ) { *r = comm_files::myrank; *n = comm_files::nproc; return err; } // ################################################################## // ################################################################## int comm_files::finalise() { // // In case stuff didn't get initialised right... // if (myrank <0 || nproc<0) return 1; // // Otherwise set up a barrier and wait. // barrier("comm_files_finalise"); if (myrank==0) { cout <<"comm_files::finalise() removing _initialised_ file\n"; string s(dir); s += ini; remove(s.c_str()); } cout << "comm_files::finalise(): rank: "<<myrank<<" nproc: "<<nproc<<"\n"; return 0; } // ################################################################## // ################################################################## int comm_files::abort() { ostringstream s; s<<dir<<"ERROR_ABORTABORTABORT"; ofstream outf(s.str().c_str()); outf.close(); return 0; } // ################################################################## // ################################################################## int comm_files::barrier(const std::string msg) { #ifdef TESTING cout <<"comm_files::barrier(): "<<msg<<"\n"; #endif // // Need a counter on the barrier name, so that processes don't jump two barriers // while the master is waiting for the others. // comm_files::barrier_count ++; ostringstream tmp; tmp <<dir<<"rank_"<< myrank << bar << barrier_count << msg; ofstream outf(tmp.str().c_str()); outf.close(); // // Need to identify barriers uniquely -- one way is to have a counter for // what barrier we are on. // ostringstream bname; bname << bar << barrier_count << msg; if (myrank==0) { master_wait_on_slave_files("barrier",bname.str()); master_send_go_signal(bname.str()); } else { slave_recv_go_signal(bname.str()); } remove(tmp.str().c_str()); #ifdef TESTING cout <<"comm_files::barrier(): barrier crossed: "<<msg<<"\n"; #endif return 0; } // ################################################################## // ################################################################## double comm_files::global_operation_double( const string s, ///< Either Max or Min const double d ///< this process's max/min value. ) { double local=d, global=0.0; // // Every process writes their value to file. // ostringstream f; f<<dir<<"rank_"<<myrank<<"_"<<s; fs.acquire_lock(f.str()); ofstream outf(f.str().c_str(),ios_base::binary); outf.write(reinterpret_cast<char *>(&local),sizeof(double)); outf.close(); fs.release_lock(f.str()); // // Root process reads all these in and does the calculation. // if (myrank==0) { // // Read in all values: // double vals[nproc]; for (int r=0;r<nproc;r++) { f.str(""); f<<dir<<"rank_"<<r<<"_"<<s; wait_for_file(f.str()); fs.acquire_lock(f.str()); ifstream infile(f.str().c_str(), ios_base::binary); //infile >> vals[r]; infile.read(reinterpret_cast<char *>(&(vals[r])),sizeof(double)); #ifdef TESTING cout <<"global_operation_double() "<<s<<" got value "<<vals[r]<<" from file "<<f.str()<<"\n"; #endif infile.close(); fs.release_lock(f.str()); remove(f.str().c_str()); } // // Do the operation on all the values: // if (s=="MAX") { global = -HUGEVALUE; for (int r=0;r<nproc;r++) global = max(global,vals[r]); } else if (s=="MIN") { global = HUGEVALUE; for (int r=0;r<nproc;r++) global = min(global,vals[r]); } else if (s=="SUM") { global=0.0; for (int r=0;r<nproc;r++) global += vals[r]; } else rep.error("comm_files:global_operation_double: Bad identifier",s); // // Write the global value to file. // f.str(""); f<<dir<<comm_global<<barrier_count<<s; fs.acquire_lock(f.str()); ofstream outfile(f.str().c_str(),ios_base::binary); //outfile << global; outfile.write(reinterpret_cast<char *>(&global),sizeof(double)); outfile.close(); fs.release_lock(f.str()); #ifdef TESTING cout <<"global_operation_double() "<<s<<" : global value = "<<global<<"\n"; #endif } // if myrank==0 else { // // wait for global value to be written by root proc: // f.str(""); f<<dir<<comm_global<<barrier_count<<s; wait_for_file(f.str()); if (fs.file_is_locked(f.str())) { usleep(FDELAY_USECS); while (fs.file_is_locked(f.str())) { usleep(FDELAY_USECS); } } ifstream infile(f.str().c_str(), ios_base::binary); if (!infile.is_open()) rep.error("failed to open infile for global max,min",f.str()); //infile >>global; infile.read(reinterpret_cast<char *>(&global),sizeof(double)); infile.close(); #ifdef TESTING cout <<"global_operation_double() "<<s<<" : read global value = "<<global<<"\n"; #endif } // not root proc. barrier("global_operation_double__end"); if (myrank==0) { remove(f.str().c_str()); } return global; } // ################################################################## // ################################################################## void comm_files::global_op_double_array( const std::string s, ///< MAX,MIN,SUM const size_t Nel, ///< Number of elements in array. double *data ///< pointer to this process's data array. ) { rep.error("comm_files:global_op_double_array: Not implemented in file-comms",); return; } // ################################################################## // ################################################################## int comm_files::broadcast_data( const int sender, ///< rank of sender. const std::string type, ///< Type of data INT,DOUBLE,etc. const int n_el, ///< number of elements void *data ///< pointer to data. ) { int err=0; string fn="broadcast_"; ostringstream f; f<<dir<<comm_global<<fn<<type; if (myrank==0) { // // Open global file, cast pointer to correct type, and write data to file. // fs.acquire_lock(f.str()); ofstream outfile(f.str().c_str(), ios_base::binary); if (type=="DOUBLE") { double *d = static_cast<double *>(data); for (int i=0; i<n_el; i++) outfile.write(reinterpret_cast<char *>(&(d[i])),sizeof(double)); //outfile<<d[i]; } else if (type=="INT") { int *d = static_cast<int *>(data); for (int i=0; i<n_el; i++) outfile.write(reinterpret_cast<char *>(&(d[i])),sizeof(int)); //outfile<<d[i]; } else if (type=="FLOAT") { float *d = static_cast<float *>(data); for (int i=0; i<n_el; i++) outfile.write(reinterpret_cast<char *>(&(d[i])),sizeof(float)); //outfile<<d[i]; } else rep.error("Bad type of data to send",type); outfile.close(); fs.release_lock(f.str()); } else { // // wait for file. // wait_for_file(f.str()); fs.acquire_lock(f.str()); ifstream infile(f.str().c_str(), ios_base::binary); #ifdef TESTING cout <<"broadcast_data() "<<type<<": received data: ["; #endif if (type=="DOUBLE") { double *d = static_cast<double *>(data); for (int i=0; i<n_el; i++) infile.read( reinterpret_cast<char *>(&(d[i])),sizeof(double)); //infile>>d[i]; #ifdef TESTING for (int i=0; i<n_el; i++) cout << d[i]<<", "; #endif } else if (type=="INT") { int *d = static_cast<int *>(data); for (int i=0; i<n_el; i++) infile.read( reinterpret_cast<char *>(&(d[i])),sizeof(int)); //infile>>d[i]; #ifdef TESTING for (int i=0; i<n_el; i++) cout << d[i]<<", "; #endif } else if (type=="FLOAT") { float *d = static_cast<float *>(data); for (int i=0; i<n_el; i++) infile.read( reinterpret_cast<char *>(&(d[i])),sizeof(float)); //infile>>d[i]; #ifdef TESTING for (int i=0; i<n_el; i++) cout << d[i]<<", "; #endif } else rep.error("Bad type of data to send",type); infile.close(); cout <<"] ... "<<n_el<<" elements\n"; fs.release_lock(f.str()); } barrier("comm_files__broadcast_data__end"); if (myrank==0) { remove(f.str().c_str()); } return err; } // ################################################################## // ################################################################## int comm_files::send_cell_data( const int to_rank, ///< rank to send to. std::list<cell *> *l, ///< list of cells to get data from. long int nc, ///< number of cells in list (extra checking!) const int ndim, ///< ndim const int nvar, ///< nvar string &id, ///< identifier for send, for tracking delivery later. const int comm_tag ///< comm_tag, to say what kind of send this is. ) { #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::send_cell_data() starting. \n"; #endif //TESTING // // First initialise everything and check we have cells to get data from. // if(!id.empty()) id.erase(); if (nc==0 || (l->empty()) ) { cout <<myrank<<"\t Nothing to send to rank: "<<to_rank<<" !!!\n"; return 1; } if (to_rank<0 || to_rank>nproc) rep.error("to_rank is out of bounds",to_rank); list<cell *>::iterator c=l->begin(); int err=0; // // Determine size of send buffer needed // int unitsize = ndim*sizeof(CI.get_ipos(*c,0)) + nvar*sizeof((*c)->P[0]) + sizeof((*c)->id); long int totalsize = 0; totalsize = sizeof(int) + nc*unitsize; // // Allocate memory for the record of the send. // struct sent_info *si = 0; #ifdef TESTING si = mem.myalloc(si,1, "comm_files:send_cell_data: si"); #else si = mem.myalloc(si,1); #endif //TESTING // // ALL SAME AS MPI VERSION UP TO HERE, NOW WE PACK+SEND DATA DIFFERENTLY IN WHAT FOLLOWS // // write data to file. Format = [comm_tag,n_cells, totalsize(bytes), ALL_CELLS[c->id,c->x,c->Ph]] // int ct=0; ostringstream f; f<<dir<<celldata<<SimPM.timestep<<"_rank_"<<myrank<<"_to_rank_"<<to_rank; // // Create record of the send. // si->comm_tag = comm_tag; si->from_rank = myrank; si->to_rank = to_rank; //si->data = 0; si->type = COMM_CELLDATA; id = f.str(); si->id = id; comm_files::sent_list.push_back(si); fs.acquire_lock(f.str()); ofstream outfile(f.str().c_str(), ios_base::binary); outfile.write(reinterpret_cast<char *>(&(si->comm_tag)),sizeof(int)); outfile.write(reinterpret_cast<char *>(&(nc)) ,sizeof(long int)); outfile.write(reinterpret_cast<char *>(&(totalsize)) ,sizeof(long int)); int ipos[MAX_DIM]; do { CI.get_ipos(*c,ipos); outfile.write(reinterpret_cast<char *>(&((*c)->id)),sizeof(int)); for (int i=0;i<ndim;i++) outfile.write(reinterpret_cast<char *>(&(ipos[i])),sizeof(int)); for (int v=0;v<nvar;v++) outfile.write(reinterpret_cast<char *>(&((*c)->Ph[v])),sizeof(double)); ct++; ++c; // next cell in list. } while ( c != l->end() ); // // Check that we packed the right amount of data: // // cout <<myrank<<"\tcomm_pack_send_data: bufsiz: "; // cout <<totalsize<<" nc="<<nc<<" ct="<<ct<<"\n"; if (ct != nc) rep.error("Length of list doesn't match nc",ct-nc); if (err) rep.error("MPI_Pack returned abnormally",err); // // Close file and release lock // outfile.close(); fs.release_lock(f.str()); f.str(""); #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::send_cell_data() comm_tag="<<comm_tag<<" nc="<<nc<<" \n"; cout <<"rank: "<<myrank<<" comm_files::send_cell_data() returning.\n"; #endif //TESTING return 0; } // ################################################################## // ################################################################## int comm_files::wait_for_send_to_finish( string &id ///< identifier for the send we are waiting on. ) { #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::wait_for_send_to_finish() starting\n"; #endif //TESTING // // Find the send in the list of active sends, based on the identifier string. // int el=0; list<sent_info *>::iterator i; struct sent_info *si=0; #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::wait_for_send_to_finish() more than one send, so finding in list.\n"; cout <<"\t\tsend id="<<id<<"\n"; #endif //TESTING for (i=sent_list.begin(); i!=sent_list.end(); ++i) { si = (*i); el++; if (si->id==id) break; } if (i==sent_list.end()) rep.error("Failed to find send with id:",id); #ifdef TESTING cout <<"found send id="<<si->id<<" and looking for id="<<id<<"\n"; cout <<"rank: "<<myrank<<" comm_files::wait_for_send_to_finish() found this send.\n"; #endif //TESTING // // Now we have the record of the send, so we wait for receiver to finish with the file. // wait_for_peer_to_read_file(si->id); remove((si->id).c_str()); #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::wait_for_send_to_finish() peer has read file, and I deleted it.\n"; #endif #ifdef TESTING si = mem.myfree(si,"comm_files::wait_for_send_to_finish(): si"); #else si = mem.myfree(si); #endif sent_list.erase(i); #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::wait_for_send_to_finish() returning\n"; #endif //TESTING return 0; } // ################################################################## // ################################################################## int comm_files::look_for_data_to_receive( int *from_rank, ///< rank of sender string &id, ///< identifier for receive. int *comm_tag, ///< comm_tag associated with data. const int req_tag, ///< comm_tag requested const int type ///< type of data we are looking for. ) { int err=0; #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::look_for_data_to_receive() starting\n"; #endif //TESTING // // Create a new received info record. // // struct recv_info *ri=0; #ifdef TESTING ri = mem.myalloc(ri,1, "comm_files:look_for_data_to_receive: ri"); #else ri = mem.myalloc(ri,1); #endif ri->to_rank = myrank; if (type!=COMM_CELLDATA && type!=COMM_DOUBLEDATA) rep.error("only know two types of data to look for!",type); ri->type = type; // // Now look for data being sent to us: // This is a very inefficient method, but speed it not of the essence here... // #ifdef TESTING cout <<"rank: "<<myrank<<" comm_files::look_for_data_to_receive() looking for source\n"; #endif //TESTING ostringstream f; bool found=false; do { usleep(FDELAY_USECS); usleep(FDELAY_USECS); for (int rank=0; rank<nproc; rank++) { if (!found) { if (type==COMM_CELLDATA) { f.str(""); f<<dir<<celldata <<SimPM.timestep<<"_rank_"<<rank<<"_to_rank_"<<myrank; } else if (type==COMM_DOUBLEDATA) { f.str(""); f<<dir<<doubledata<<SimPM.timestep<<"_rank_"<<rank<<"_to_rank_"<<myrank; } if (fs.file_exists(f.str()) && !fs.file_exists(f.str()+finished_with_file)) { // // Need to check for 'finished' file (in if statement above) in case there // is a queue of data and we could re-find the data we just finished reading. // #ifdef TESTING cout <<"comm_files::look_for_data_to_receive: found data file : "<< f.str()<<"\n"; #endif found=true; *from_rank = rank; id = f.str(); } } // if (!found) look for file. } // loop over all ranks } while (!found); // // Wait for file to be ready, and read comm_tag from start of file. // wait_for_file(f.str()); fs.acquire_lock(f.str()); ifstream infile(f.str().c_str(), ios_base::binary); if (!infile.is_open()) rep.error("failed to open file for reading",f.str()); infile.read( reinterpret_cast<char *>(comm_tag),sizeof(int)); #ifdef TESTING cout <<"comm_files::look_for_data_to_receive: got comm_tag: "<<*comm_tag<<" from file.\n"; #endif infile.close(); fs.release_lock(f.str()); ri->id = id; ri->comm_tag = *comm_tag; ri->from_rank = *from_rank; comm_files::recv_list.push_back(ri); #ifdef TESTING cout <<"comm_files::look_for_data_to_receive: returning.\n"; #endif //TESTING return err; } int comm_files::receive_cell_data( const int from_rank, ///< rank of process we are receiving from. std::list<cell *> *l, ///< list of cells to get data for. const long int nc, ///< number of cells in list (extra checking!) const int ndim, ///< ndim const int nvar, ///< nvar const int comm_tag, ///< comm_tag: what sort of comm we are looking for (PER,MPI,etc.) const string &id ///< identifier for receive, for any book-keeping that might be needed. ) { // int err=0; #ifdef TESTING cout <<"comm_files::receive_cell_data: starting.\n"; #endif //TESTING // // Find the recv in the list of active receives. I use a string identifier for // sends and receives, and the look_for_data() function returns a string which // should be passed to this function. // #ifdef TESTING cout <<"comm_files::receive_cell_data: recv_list size="<<recv_list.size()<<"\n"; #endif //TESTING if (recv_list.empty()) rep.error("Call look4data before receive_data",recv_list.size()); struct recv_info *info=0; list<recv_info *>::iterator i; for (i=recv_list.begin(); i!=recv_list.end(); ++i) { info = (*i); if (info->id==id) break; } if (i==recv_list.end()) rep.error("Failed to find recv with id:",id); #ifdef TESTING cout <<"found recv id="<<info->id<<" and looking for id="<<id<<"\n"; cout <<"comm_files::receive_cell_data: found recv id\n"; #endif //TESTING // // Check that everthing matches. // if (from_rank != info->from_rank) rep.error("from_ranks don't match",from_rank-info->from_rank); if (comm_tag != info->comm_tag ) rep.error("Bad comm_tag",comm_tag); if (id != info->id ) rep.error("Bad id",id); // // DIFFERENT FROM MPI COMMS BELOW THIS POINT // // Open file: // fs.acquire_lock(info->id); ifstream infile((info->id).c_str(), ios_base::binary); if (!infile.is_open()) rep.error("failed to open file for reading",info->id); // // Skip comm_tag, read in n_cells, totalsize, and then start reading data into cells. // Format = [comm_tag, n_cells, totalsize(bytes), ALL_CELLS[c->id,c->x,c->Ph]] // int tmp=0; int tmp2=0; long int n_cells=0, totalsize=0; infile.read( reinterpret_cast<char *>(&(tmp)) ,sizeof(int)); infile.read( reinterpret_cast<char *>(&(n_cells)) ,sizeof(long int)); infile.read( reinterpret_cast<char *>(&(totalsize)),sizeof(long int)); #ifdef TESTING cout <<"comm_files::receive_cell_data: got comm:"<<tmp<<" n_cells="<<n_cells<<" size="<<totalsize<<"\n"; #endif //TESTING if (n_cells != nc) rep.error("comm_files::receive_cell_data: n_cells has unexpected value",n_cells-nc); // // For data, i send id,position,state_vec, but id and position aren't used, so I just // read them into temp arrays here. i used them for debugging to make sure the cells // were ordered the same way by sender and receiver. I should really get rid of them // now but haven't bothered. // list<cell*>::iterator c=l->begin(); int ct=0; do { if (c==l->end()) rep.error("Got too many cells!",ct); infile.read( reinterpret_cast<char *>(&(tmp)) ,sizeof(int)); for (int i=0;i<ndim;i++) infile.read( reinterpret_cast<char *>(&(tmp2)) ,sizeof(int)); for (int v=0;v<nvar;v++) infile.read( reinterpret_cast<char *>(&((*c)->Ph[v])) ,sizeof(double)); ++c; ct++; } while (c!=l->end()); if (ct != nc) rep.error("got wrong number of cells", ct-nc); // // Close file, release lock, and create 'finished' file // infile.close(); fs.release_lock(info->id); ostringstream f; f<<info->id<<finished_with_file; ofstream outf(f.str().c_str()); outf.close(); f.str(""); // // DIFFERENT FROM MPI COMMS ABOVE HERE // // // Free memory and delete entry from recv_list // #ifdef TESTING cout <<"comm_files::receive_cell_data: freeing memory\n"; #endif //TESTING if (recv_list.size()==1) { recv_list.pop_front(); } else rep.error("recv list is big!",recv_list.size()); #ifdef TESTING info= mem.myfree(info,"comm_files::receive_cell_data() info"); #else info= mem.myfree(info); #endif //TESTING #ifdef TESTING cout <<"comm_files::receive_cell_data: returning\n"; #endif //TESTING return 0; } int comm_files::send_double_data( const int to_rank, ///< rank to send to. const long int n_el, ///< size of buffer, in number of doubles. const double *data, ///< pointer to double array. string &id, ///< identifier for send, for tracking delivery later. const int comm_tag ///< comm_tag, to say what kind of send this is. ) { if (!data) rep.error("comm_files::send_double_data() null pointer!",data); // // Allocate memory for a record of the send // struct sent_info *si=0; #ifdef TESTING si = mem.myalloc(si,1, "comm_files:send_double_data: si"); #else si = mem.myalloc(si,1); #endif //TESTING // // filename for send: I tag with timestep just to be sure. Set string identifier // to be the filename. This id is used by the caller to track the send. // ostringstream f; f<<dir<<doubledata<<SimPM.timestep<<"_rank_"<<myrank<<"_to_rank_"<<to_rank; id = f.str(); // // Add info to send record. // si->comm_tag = comm_tag; si->from_rank = myrank; si->to_rank = to_rank; si->type = COMM_DOUBLEDATA; si->id = id; comm_files::sent_list.push_back(si); // // open file and write data to file: // I cast some of the data to (const char *) because it is const data. // Doesn't seem to make any difference. // fs.acquire_lock(id); ofstream outfile(id.c_str(), ios_base::binary); outfile.write(reinterpret_cast<char *>(&(si->comm_tag)),sizeof(int)); outfile.write(reinterpret_cast<const char *>(&(n_el)),sizeof(long int)); //outfile << comm_tag << n_el; for (int i=0;i<n_el;i++) outfile.write(reinterpret_cast<const char *>(&(data[i])),sizeof(double)); //outfile << data[i]; outfile.close(); fs.release_lock(id); // // All done, so return. // return 0; } int comm_files::receive_double_data(const int from_rank, ///< rank of process we are receiving from. const int comm_tag, ///< comm_tag: what sort of comm we are looking for (PER,MPI,etc.) const string &id, ///< identifier for receive, for any book-keeping that might be needed. const long int nel, ///< number of doubles to receive double *data ///< Pointer to array to write to (must be already initialised). ) { #ifdef TESTING cout <<"comm_files::receive_double_data: starting.\n"; #endif //TESTING // // Find the recv in the list of active receives, based on the id string passed to // the function. This should have been obtained by the look_for_data() function. // #ifdef TESTING cout <<"comm_files::receive_double_data: recv_list size="<<recv_list.size()<<"\n"; #endif //TESTING if (recv_list.empty()) rep.error("Call look4data before receive_data",recv_list.size()); struct recv_info *info=0; list<recv_info *>::iterator i; for (i=recv_list.begin(); i!=recv_list.end(); ++i) { info = (*i); if (info->id==id) break; } if (i==recv_list.end()) rep.error("Failed to find recv with id:",id); #ifdef TESTING cout <<"found recv id="<<info->id<<" and looking for id="<<id<<"\n"; cout <<"comm_files::receive_double_data: found recv id\n"; #endif //TESTING // // Check that everthing matches. // if (from_rank != info->from_rank) rep.error("from_ranks don't match",from_rank-info->from_rank); if (comm_tag != info->comm_tag ) rep.error("Bad comm_tag",comm_tag); if (id != info->id ) rep.error("Bad id",id); if (info->type!= COMM_DOUBLEDATA) rep.error("data is not double array!",info->type); // // DIFFERENT FROM MPI COMMS BELOW HERE // // Open file: // fs.acquire_lock(info->id); ifstream infile((info->id).c_str(), ios_base::binary); // // Skip comm_tag, read in n_el, and then start reading data into array. // Format = [comm_tag,n_el, data[]] // int tmp=0; long int ct=0; infile.read( reinterpret_cast<char *>(&(tmp)),sizeof(int)); infile.read( reinterpret_cast<char *>(&(ct)) ,sizeof(long int)); // infile >> tmp >> ct; #ifdef TESTING cout <<"comm_files::receive_cell_data: got comm:"<<tmp<<" n_el="<<ct<<"\n"; #endif //TESTING if (nel != ct) rep.error("comm_files::receive_cell_data: n_el has unexpected value",nel-ct); for (int v=0;v<nel;v++) infile.read( reinterpret_cast<char *>(&(data[v])),sizeof(double)); //infile >> data[v]; // // Close file, release lock, and create 'finished' file // infile.close(); fs.release_lock(info->id); ostringstream f; f<<info->id<<finished_with_file; ofstream outf(f.str().c_str()); outf.close(); f.str(""); // // DIFFERENT FROM MPI COMMS ABOVE HERE // // // Free memory and delete entry from recv_list // #ifdef TESTING cout <<"comm_files::receive_cell_data: freeing memory\n"; #endif //TESTING if (recv_list.size()==1) { recv_list.pop_front(); } else rep.error("recv list is big!",recv_list.size()); #ifdef TESTING info= mem.myfree(info,"comm_files::receive_cell_data() info"); #else info= mem.myfree(info); #endif //TESTING return 0; } #ifdef SILO int comm_files::silo_pllel_init(const int n_files, ///< number of files to write const std::string iotype, ///< READ or WRITE const std::string session_id, ///< identifier for this read/write. int *group_rank, ///< rank of group (nth file). int *rank_in_group ///< rank in group (nth proc in file i). ) { comm_files::silo_id = session_id; comm_files::num_files = n_files; comm_files::silo_filetype = DB_PDB; comm_files::silo_iotype = iotype; // // Silo's parallel interface writes nf files by np processes. So I need // to create nf groups of processes, and assign each process a rank in its // group. In principle this code is very easy to modify to work for any file // I/O method, if I wrote file open/close/create functions that could be // redefined. The wait_for_file() and finish_with_file() functions // could take void ** pointers instead of DBfile **, so that it really // is a general interface. // int ngrp=nproc/num_files; // integer division if (!GS.equalD(static_cast<double>(ngrp), static_cast<double>(nproc)/num_files)) rep.error("comm_files::silo_pllel_init() choose number of files to divide into nproc evenly!", static_cast<double>(nproc)/num_files); *group_rank = myrank/ngrp; *rank_in_group = myrank % ngrp; comm_files::grp_rank = *group_rank; comm_files::rank_in_grp = *rank_in_group; #ifdef TESTING cout <<"comm_files::silo_pllel_init() grp_rank="<<grp_rank<<" and rank_in_grp="<<rank_in_grp<<"\n"; #endif barrier("silo_pllel_init__end"); return 0; } int comm_files::silo_pllel_wait_for_file(const std::string s_id, ///< identifier for this read/write. const std::string s_filename, ///< File Name const std::string s_dir, ///< Directory to open in file. DBfile **dbfile ///< pointer that file gets returned in. ) { #ifdef TESTING cout <<"comm_files::silo_pllel_wait_for_file() opening file: "<<s_filename<<" into directory: "<<s_dir<<"\n"; #endif if (s_id!=silo_id) rep.error(s_id, silo_id); if (*dbfile) rep.error("please pass in null file pointer!",*dbfile); // // Silo's parallel interface has one process reading from/writing to each file at a time, so // the first process can start immediately, and the others have to wait for a signal that // the previous one has finished with the file. All the read/write operations are then done // with no communication by other code. The wait_for_file() and finish_with_file() functions // could take void ** pointers instead of DBfile **, so that it really is a general interface. // if (rank_in_grp==0) { #ifdef TESTING cout <<"comm_files::silo_pllel_wait_for_file() i'm first in group, creating/opening file and returning.\n"; #endif if (silo_iotype=="READ") { // // Open file for reading. // *dbfile = DBOpen(s_filename.c_str(), silo_filetype, DB_READ); if (!(*dbfile)) rep.error("open silo file failed.",*dbfile); DBSetDir(*dbfile,"/"); DBSetDir(*dbfile,s_dir.c_str()); } else if (silo_iotype=="WRITE") { // // Create file for writing. // *dbfile = DBCreate(s_filename.c_str(), DB_CLOBBER, DB_LOCAL, "comment about data", silo_filetype); if (!(*dbfile)) rep.error("create silo file failed.",*dbfile); // // Create directory in file, and move to that directory. // DBSetDir(*dbfile,"/"); DBMkDir(*dbfile,s_dir.c_str()); DBSetDir(*dbfile,s_dir.c_str()); } else rep.error("need either READ or WRITE as iotype",silo_iotype); } else { // // Wait for my turn to open file -- previous process will write a 'finished' file. // ostringstream f; f<<dir<<silo_id<<"_grp_"<<grp_rank<<"_rank_"<<rank_in_grp-1<<finished_with_file; wait_for_file(f.str()); fs.acquire_lock(f.str()); #ifdef TESTING cout <<"comm_files::silo_pllel_wait_for_file(): found file: "<<f.str()<<", so my turn to write file.\n"; #endif remove(f.str().c_str()); fs.release_lock(f.str()); if (silo_iotype=="READ") { // // Open file for reading. // *dbfile = DBOpen(s_filename.c_str(), silo_filetype, DB_READ); if (!(*dbfile)) rep.error("open silo file failed.",*dbfile); DBSetDir(*dbfile,"/"); DBSetDir(*dbfile,s_dir.c_str()); } else if (silo_iotype=="WRITE") { // // Open file for writing. // *dbfile = DBOpen(s_filename.c_str(), silo_filetype, DB_APPEND); if (!(*dbfile)) rep.error("open silo file failed.",*dbfile); DBSetDir(*dbfile,"/"); DBMkDir(*dbfile,s_dir.c_str()); DBSetDir(*dbfile,s_dir.c_str()); } else rep.error("need either READ or WRITE as iotype",silo_iotype); } return 0; } int comm_files::silo_pllel_finish_with_file(const std::string s_id, ///< identifier for this read/write. DBfile **dbfile ///< pointer to file we have been working on. ) { #ifdef TESTING cout <<"comm_files::silo_pllel_finish_with_file() passing file on to next proc.\n"; #endif if (s_id!=silo_id) rep.error(s_id, silo_id); if (!(*dbfile)) rep.error("file pointer i s null!",*dbfile); // // Last process in each group needs to close the file and return. // All others need to write a 'finished' message for the next process // in the group to read and take its turn with the file. // int ngrp=nproc/num_files; // integer division if (rank_in_grp==(ngrp-1) || myrank==(nproc-1)) { // // I am last file in group, so just close file and return // DBClose(*dbfile); *dbfile=0; #ifdef TESTING cout <<"comm_files::silo_pllel_finish_with_file() I'm last proc in group, returning.\n"; #endif } else { // // Have someone to pass file onto, so close silo file and create handoff file. // DBClose(*dbfile); *dbfile=0; ostringstream f; f<<dir<<silo_id<<"_grp_"<<grp_rank<<"_rank_"<<rank_in_grp<<finished_with_file; fs.acquire_lock(f.str()); ofstream outfile(f.str().c_str()); outfile.close(); fs.release_lock(f.str()); #ifdef TESTING cout <<"comm_files::silo_pllel_finish_with_file() closed file and created finished file, so returning.\n"; #endif } silo_id.erase(); return 0; } void comm_files::silo_pllel_get_ranks(const std::string id, ///< identifier for this read/write. const int proc, ///< processor rank int *group, ///< rank of group processor is in. int *rank ///< rank of processor within group. ) { if (id!=silo_id) rep.error(id, silo_id); int ngrp=nproc/num_files; // integer division *group = proc/ngrp; *rank = proc % ngrp; return; } #endif // SILO /*************************************************************************************/ /********************* PRIVATE FUNCTIONS -- PRIVATE FUNCTIONS ************************/ /*************************************************************************************/ void comm_files::wait_for_file(const string filename) { // // Waits for filename to appear. // int stop=0; do { usleep(FDELAY_USECS); if (!fs.file_exists(filename)) { #ifdef TESTING cout <<" rank "<<myrank<<": ...still waiting for file "<<filename<<"\n"; #endif } else { #ifdef TESTING cout <<" rank "<<myrank<<": recieved signal ("<<filename<<") - proceeding\n"; #endif stop=1; } } while (!stop); return; } void comm_files::wait_for_file_to_disappear(const string filename) { // // Does exactly what it says on the tin. // int stop=0; do { usleep(FDELAY_USECS); if (fs.file_exists(filename)) { #ifdef TESTING cout <<" rank "<<myrank<<": ...still waiting for file "<<filename<<" to be deleted\n"; #endif } else { #ifdef TESTING cout <<" rank "<<myrank<<": file "<<filename<<" has been deleted -- proceeding.\n"; #endif stop=1; } } while (!stop); return; } void comm_files::master_send_go_signal(const std::string identifier) { // // Informs all other nodes that we are ready to proceed to the next stage. // // // Send the go signal // ostringstream tmp; tmp <<dir<<go_order<<identifier; fs.acquire_lock(tmp.str()); ofstream outf(tmp.str().c_str()); outf.close(); fs.release_lock(tmp.str()); // // Wait for replies (don't need to wait for rank 0 - that's us!) // string response = go_response+identifier; master_wait_on_slave_files("master_send_go_signal()",response); // // All slaves should have replied - clean up the files. // remove(tmp.str().c_str()); for (int rank=1; rank<nproc; rank++) { tmp.str(""); tmp <<dir<<"rank_"<<rank<<response; //sprintf(filename,"filecomms/slave_%03d_going",rank); remove(tmp.str().c_str()); } tmp.str(""); return ; } void comm_files::slave_recv_go_signal(const std::string identifier) { // // Recieves the go signal from the master node. (BLOODY WELL BETTER HOPE // THAT IT DOESN'T PROCEED UNTIL IT GETS THE SIGNAL!!!!) // //DbgMsg("node %02i, slave %03d: waiting for go signal\n",gd->M_rank,gd->M_rank); ostringstream tmp; tmp <<dir<<go_order<<identifier; wait_for_file(tmp.str()); //DbgMsg("node %02i, slave %03d: acknowledging signal\n",gd->M_rank,gd->M_rank); tmp.str(""); tmp<<dir<<"rank_"<<myrank<<go_response<<identifier; ofstream outf(tmp.str().c_str()); outf.close(); //DbgMsg("node %02i, slave %03d: commencing graft\n",gd->M_rank,gd->M_rank); return; } void comm_files::master_wait_on_slave_files(const std::string msg, ///< message. const std::string identifier ///< what slave files are called. ) { #ifdef TESTING cout <<"master_wait_on_slave_files: "<<msg<<": starting.\n"; #endif ostringstream tmp; // // Don't need to wait for my own signal, so start at 1! // for (int rank=1;rank<nproc;rank++) { tmp.str(""); tmp<<dir<<"rank_"<<rank<<identifier; wait_for_file(tmp.str()); #ifdef TESTING cout <<"master_wait_on_slave_files:"<<msg<<" got file:"<<tmp.str()<<"\n"; #endif } tmp.str(""); return; } void comm_files::wait_for_peer_to_read_file(const std::string f ///< name of file ) { ostringstream tmp; tmp<<f<<finished_with_file; wait_for_file(tmp.str()); #ifdef TESTING cout <<"wait_for_peer_to_read_file: got file: "<<tmp.str()<<" ...deleting it\n"; #endif remove(tmp.str().c_str()); return; } #endif // USE_FILE_COMMS #endif //PARALLEL
29.099046
111
0.592507
jfbucas
3542eef550492727ca54c2222b5051f2f954fdb4
1,841
cpp
C++
solutions_cpp/implement_a_trie.cpp
aaishikasb/Leetcoding
c6ad25486716d43c780d840cc80aa20ef51a8674
[ "MIT" ]
null
null
null
solutions_cpp/implement_a_trie.cpp
aaishikasb/Leetcoding
c6ad25486716d43c780d840cc80aa20ef51a8674
[ "MIT" ]
null
null
null
solutions_cpp/implement_a_trie.cpp
aaishikasb/Leetcoding
c6ad25486716d43c780d840cc80aa20ef51a8674
[ "MIT" ]
null
null
null
class TrieNode { public: // Initialize your data structure here. TrieNode() { value = 0; for (int i = 0; i < 26; i++) { children[i] = NULL; } } int value; TrieNode *children[26]; }; class Trie { public: Trie() { root = new TrieNode(); count = 0; } // Inserts a word into the trie. void insert(string s) { TrieNode *p = root; int len = s.size(); for (int i = 0; i < len; i++) { int idx = s[i] - 'a'; if (!p->children[idx]) { p->children[idx] = new TrieNode(); } p = p->children[idx]; } count++; p->value = count; } // Returns if the word is in the trie. bool search(string key) { TrieNode *p = root; int len = key.size(); for (int i = 0; i < len; i++) { int idx = key[i] - 'a'; if (p->children[idx]) { p = p->children[idx]; } else { return false; } } if (p->value != 0) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { TrieNode *p = root; int len = prefix.size(); for (int i = 0; i < len; i++) { int idx = prefix[i] - 'a'; if (p->children[idx]) { p = p->children[idx]; } else { return false; } } return true; } private: TrieNode *root; int count; };
19.378947
50
0.380228
aaishikasb
35458d36a7d6d8d181867df91720f28259cb00f7
1,504
hpp
C++
atom/trader/trader.hpp
liu1009xf/atom
ec8b9fad38d0fb3da7eecf87d30c314d1bf09fef
[ "MIT" ]
null
null
null
atom/trader/trader.hpp
liu1009xf/atom
ec8b9fad38d0fb3da7eecf87d30c314d1bf09fef
[ "MIT" ]
null
null
null
atom/trader/trader.hpp
liu1009xf/atom
ec8b9fad38d0fb3da7eecf87d30c314d1bf09fef
[ "MIT" ]
null
null
null
#ifndef ATOM_AGENT_TRADER_TRADER_HPP #define ATOM_AGENT_TRADER_TRADER_HPP #include <optional> #include "atom/basic/validator/trival.hpp" #include "atom/basic/authoriser/trival.hpp" #include "atom/basic/visitor/event_notify.hpp" #include "atom/basic.hpp" namespace atom::detail { template<typename S> class Trader_ { public: Trader_(const S& strategy) :strategy_(strategy) {}; template<typename T> void process(T&& event) const { strategy_.actOn(std::forward<T>(event)); } auto _strategy() const { return strategy_; } private: S strategy_; }; template<typename S, typename C, typename OO, typename LP, typename AF > class Trader { public: Trader(const S& strategy); Trader(const S& strategy, const C& baseCurrency); template<typename T> void process(T&& event) const; // template<typename O, // std::enable_if_t< // std::is_convertible_v<O, OO>, // std::nullptr_t // > = nullptr // > void addOrderObserver(const OO& observer) const; private: S strategy_; C baseCurrency_; std::optional<LP> tradingLimitation_; std::optional<AF> authorisationFlow_; std::vector<OO> orderObservers_; }; #include "impl/trader.ipp" } // namespace atom::detail #endif //!ATOM_AGENT_TRADER_TRADER_HPP
23.873016
59
0.59375
liu1009xf
35472d54e677bc1ac6f6edb0853c907727035317
139
cpp
C++
Seagull-Core/src/Platform/DirectX/DirectX12Resource.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
Seagull-Core/src/Platform/DirectX/DirectX12Resource.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
Seagull-Core/src/Platform/DirectX/DirectX12Resource.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
#include "sgpch.h" #include "DirectX12Resource.h" namespace SG { void DirectX12Resource::Reset() noexcept { m_Resource.Reset(); } }
11.583333
41
0.705036
ILLmew
3547b7068ef2429cd731e5cdceeaf9ab4d8919a1
1,283
cpp
C++
code/130.solve.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
1
2020-10-04T13:39:34.000Z
2020-10-04T13:39:34.000Z
code/130.solve.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
code/130.solve.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<bool>> st; int n, m; void solve(vector<vector<char>>& board) { if (board.empty()) return; n = board.size(), m = board[0].size(); for (int i = 0; i < n; i ++ ) { vector<bool> temp; for (int j = 0; j < m; j ++ ) temp.push_back(false); st.push_back(temp); } for (int i = 0; i < n; i ++ ) { if (board[i][0] == 'O') dfs(i, 0, board); if (board[i][m - 1] == 'O') dfs(i, m - 1, board); } for (int i = 0; i < m; i ++ ) { if (board[0][i] == 'O') dfs(0, i, board); if (board[n - 1][i] == 'O') dfs(n - 1, i, board); } for (int i = 0; i < n; i ++ ) for (int j = 0; j < m; j ++ ) if (!st[i][j]) board[i][j] = 'X'; } void dfs(int x, int y, vector<vector<char>>&board) { st[x][y] = true; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; for (int i = 0; i < 4; i ++ ) { int a = x + dx[i], b = y + dy[i]; if (a >= 0 && a < n && b >= 0 && b < m && !st[a][b] && board[a][b] == 'O') dfs(a, b, board); } } };
28.511111
86
0.342167
T1mzhou
3549564aef53060f99c1c79219133d07a0e204b3
2,267
cpp
C++
HW3/hw3-5/hw3-5.cpp
Liuian/1101_DATA-STRUCTURE
303b8aa903f53abc9d5ec83f19432ebc5a7cfca4
[ "MIT" ]
1
2022-01-15T08:28:18.000Z
2022-01-15T08:28:18.000Z
HW3/hw3-5/hw3-5.cpp
Liuian/1101_DATA-STRUCTURE
303b8aa903f53abc9d5ec83f19432ebc5a7cfca4
[ "MIT" ]
null
null
null
HW3/hw3-5/hw3-5.cpp
Liuian/1101_DATA-STRUCTURE
303b8aa903f53abc9d5ec83f19432ebc5a7cfca4
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <fstream> #include <queue> using namespace std; //use these variable in the funvtion, so we set these as global variable queue<int> q; int numOfVertex; fstream OutputFile; void bfs(int startVertex, int *adjMatrix[numOfVertex], int visited[numOfVertex], string output){ for(int i = 0; i < numOfVertex; i++){ if(adjMatrix[startVertex][i] != 0 && visited[i] == -1){ q.push(i); //if this vertex connect to another never visited vertex, add the weight into recorded weight visited[i] = visited[startVertex] + adjMatrix[startVertex][i]; } } if(!q.empty()){ q.pop(); bfs(q.front(), adjMatrix, visited, output); } } int main(){ cout << "please type input file's name : "; string input; cin >> input; ifstream InputFile(input); if(!InputFile.is_open()) cout << "fild open fail"; //create output's filename string output = "out"; int length = input.length(); output.append(input, 2, length - 2); OutputFile.open(output, ios::out); OutputFile.close(); InputFile >> numOfVertex; //create the adjMatrix to record the weight between two vertex int *adjMatrix[numOfVertex]; for(int i = 0; i < numOfVertex; i++){ adjMatrix[i] = new int[numOfVertex]; } //create an array - pathLength to record the shortest path's weight(-1 : no path to this vertex from the start vertex) int pathLength[numOfVertex]; for(int j = 0; j < numOfVertex; j++){ for(int k = 0; k < numOfVertex; k++){ adjMatrix[j][k] = 0; } pathLength[j] = -1; } int start; int end; int weight; //read the weight into the adj matrix for(int i = 0; i < numOfVertex - 1; i++){ InputFile >> start; InputFile >> end; InputFile >> weight; adjMatrix[start - 1][end - 1] = weight; adjMatrix[end - 1][start - 1] = weight; } int startVertex; InputFile >> startVertex; //push the start vertex into the queue and atart the function q.push(startVertex); //set path length of start vertex as 0 pathLength[startVertex - 1] = 0; //do bfs function bfs(startVertex - 1, adjMatrix, pathLength, output); //write the result into the output file for(int i = 0; i < numOfVertex; i++){ OutputFile.open(output, ios::app); OutputFile << i + 1 << " " << pathLength[i] << '\n'; OutputFile.close(); } return 0; }
27.987654
119
0.669607
Liuian
354b906765d5682a15358115eefd1cc000d8b264
9,549
hpp
C++
src/base/include/vector3.hpp
N4G170/generic
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
[ "MIT" ]
null
null
null
src/base/include/vector3.hpp
N4G170/generic
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
[ "MIT" ]
null
null
null
src/base/include/vector3.hpp
N4G170/generic
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
[ "MIT" ]
null
null
null
#ifndef VECTOR2_HPP #define VECTOR2_HPP #include <type_traits> #include <cmath> #include <utility> #include <string> template<typename T = float> class Vector3 { private: T m_x; T m_y; T m_z; public: //check if we initialize the vector with the right values static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "Vector3 template can only integrals of floating point types"); //<f> Constructos & operator= Vector3(): m_x{0}, m_y{0}, m_z{0} {} Vector3(const T& x , const T& y, const T& z): m_x{x}, m_y{y}, m_z{z} {} virtual ~Vector3() noexcept {} Vector3(const Vector3& other): m_x{other.X()}, m_y{other.Y()}, m_z{other.Z()} {} Vector3( Vector3&& other) noexcept: m_x{std::move(other.X())}, m_y{std::move(other.Y())}, m_z{std::move(other.Z())} {} Vector3& operator= (const Vector3& other) { if(this != &other) { auto tmp{other}; *this = std::move(tmp); } return *this; } Vector3& operator= (Vector3&& other) noexcept { if(this != &other) { m_x = std::move(other.X()); m_y = std::move(other.Y()); m_z = std::move(other.Z()); } return *this; } //</f> /Constructos & operator= //<f> Get/Set T X() const { return m_x; } void X(const T& x) { m_x = x; } void X(T&& x) { m_x = std::move(x); } T Y() const { return m_y; } void Y(const T& y) { m_y = y; } void Y(T&& y) { m_y = std::move(y); } T Z() const { return m_z; } void Z(const T& z) { m_z = z; } void Z(T&& z) { m_z = std::move(z); } void Set(const T& x, const T& y, const T& z){ m_x = x; m_y = y; m_z = z; } void Set(T&& x, T&& y, T&& z){ m_x = std::move(x); m_y = std::move(y); m_z = std::move(z); } //</f> /Get/Set //<f> Operators //the second function (of each) is to allow the use of init lists ex: vector += {1,2,3}; //<f> Vector Sum/Subtraction/Multiplication/Division template<typename U> Vector3 operator+ (const Vector3<U>& other) const { return { m_x + other.X(), m_y + other.Y(), m_z + other.Z() }; } Vector3 operator+ (const Vector3& other) const { return { m_x + other.X(), m_y + other.Y(), m_z + other.Z() }; } template<typename U> Vector3 operator- (const Vector3<U>& other) const { return { m_x - other.X(), m_y - other.Y(), m_z - other.Z() }; } Vector3 operator- (const Vector3& other) const { return { m_x - other.X(), m_y - other.Y(), m_z - other.Z() }; } template<typename U> Vector3& operator+= (const Vector3<U>& other) { return *this = *this + other; } Vector3& operator+= (const Vector3& other) { return *this = *this + other; } template<typename U> Vector3& operator-= (const Vector3<U>& other) { return *this = *this - other; } template<typename U> Vector3 operator* (const Vector3<U>& other) const { return { m_x * other.X(), m_y * other.Y(), m_z * other.Z() }; } Vector3 operator* (const Vector3& other) const { return { m_x * other.X(), m_y * other.Y(), m_z * other.Z() }; } /** \brief No denominator == 0 check is performed */ template<typename U> Vector3 operator/ (const Vector3<U>& other) const { return { m_x / other.X(), m_y / other.Y(), m_z / other.Z() }; } Vector3 operator/ (const Vector3& other) const { return { m_x / other.X(), m_y / other.Y(), m_z / other.Z() }; } template<typename U> Vector3& operator*= (const Vector3<U>& other) { return *this = *this * other; } Vector3& operator*= (const Vector3& other) { return *this = *this * other; } /** \brief No denominator == 0 check is performed */ template<typename U> Vector3& operator/= (const Vector3<U>& other) { return *this = *this / other; } Vector3& operator/= (const Vector3& other) { return *this = *this / other; } //</f> /Vector Sum/Subtraction/Multiplication/Division //<f> Logic Operators template<typename U> bool operator== (const Vector3<U>& other) const { return (m_x == other.X() && m_y == other.Y() && m_z == other.Z()); } bool operator== (const Vector3& other) const { return (m_x == other.X() && m_y == other.Y() && m_z == other.Z()); } template<typename U> bool operator!= (const Vector3<U>& other) const { return (m_x != other.X() || m_y != other.Y() || m_z != other.Z()); } bool operator!= (const Vector3& other) const { return (m_x != other.X() || m_y != other.Y() || m_z != other.Z()); } template<typename U> bool operator< (const Vector3<U>& other) const { return (m_x < other.X() && m_y < other.Y() && m_z < other.Z()); } bool operator< (const Vector3& other) const { return (m_x < other.X() && m_y < other.Y() && m_z < other.Z()); } template<typename U> bool operator> (const Vector3<U>& other) const { return (m_x > other.X() && m_y > other.Y() && m_z > other.Z()); } bool operator> (const Vector3& other) const { return (m_x > other.X() && m_y > other.Y() && m_z > other.Z()); } template<typename U> bool operator<= (const Vector3<U>& other) const { return (*this < other || *this == other); } bool operator<= (const Vector3& other) const { return (*this < other || *this == other); } template<typename U> bool operator>= (const Vector3<U>& other) const { return (*this > other || *this == other); } bool operator>= (const Vector3& other) const { return (*this > other || *this == other); } //</f> /Logic Operators //<f> Scalar Operations template<typename V> Vector3 operator* (const V& scalar) const { return {m_x * scalar, m_y * scalar, m_z * scalar}; } /** \brief No denominator == 0 check is performed */ template<typename V> Vector3 operator/ (const V& scalar) const { return {m_x / scalar, m_y / scalar, m_z / scalar}; } template<typename V> Vector3& operator*= (const V& scalar) { return *this = *this * scalar; } /** \brief No denominator == 0 check is performed */ template<typename V> Vector3& operator/= (const V& scalar) { return *this = *this / scalar; } //</f> /Scalar Operations //</f> /Operators //<f> Other /** * \brief Normalizes the vector but does not save the result. * \return The not saved normalized vector */ Vector3 Normalized() { auto length = this->Length(); if(length == 0) return {0,0,0}; return { m_x / length, m_y / length, m_z / length }; } /** * \brief Normalizes the vector and stores the result in itself */ void Normalize() { *this = Normalized(); } float Length() { return std::sqrt( m_x * m_x + m_y * m_y + m_z * m_z); } float LengthSquared() { return m_x * m_x + m_y * m_y + m_z * m_z; } template<typename U>//the target might be of a different numerical type float Distance(const Vector3<U>& target) { return (target - *this).Length(); } float Distance(const Vector3& target) { return (target - *this).Length(); } template<typename U>//the target might be of a different numerical type float DistanceSquared(const Vector3<U>& target) { return (target - *this).LengthSquared(); } float DistanceSquared(const Vector3& target) { return (target - *this).LengthSquared(); } std::string ToString() const { return ("("+std::to_string(m_x)+", "+std::to_string(m_y)+", "+std::to_string(m_z)+")"); }; /** * \brief lerp between two Vector3. Note: this vector will be the min of the range, if you want other to be the min, change the call order * @param other the other vector * @param t the ratio * \return The value between min and max corresponding to the ratio t */ template<typename U> Vector3 Lerp(const Vector3<U>& other, const float& t = 0.5f) { return { t * m_x + (1 - t) * other.X(), t * m_y + (1 - t) * other.Y(), t * m_z + (1 - t) * other.Z() }; } Vector3 Lerp(const Vector3& other, const float& t = 0.5f) { return { t * m_x + (1 - t) * other.X(), t * m_y + (1 - t) * other.Y(), t * m_z + (1 - t) * other.Z() }; } template<typename U> float Dot(const Vector3<U>& other) { return m_x * other.X() + m_y * other.Y() + m_z * other.Z(); } float Dot(const Vector3& other) { return m_x * other.X() + m_y * other.Y() + m_z * other.Z(); } //</f> /Other }; /** * \brief Lerp using two vectors, return type will use start vector type */ template<typename T, typename U> Vector3<T> Lerp(const Vector3<T>& start, const Vector3<U>& end, const float& t = 0.5f) { return { (1 - t) * start.m_x + t * end.m_x, (1 - t) * start.m_y + t * end.m_y }; } /** * \brief Lerp using two vectors, return type will use end vector type */ template<typename T, typename U> Vector3<T> Lerp(const Vector3<U>& start, const Vector3<T>& end, const float& t = 0.5f) { return { (1 - t) * start.m_x + t * end.m_x, (1 - t) * start.m_y + t * end.m_y }; } #endif //VECTOR2_HPP
46.130435
149
0.549901
N4G170
354c1fa53e88e8298ccecfb890f2dc4be2371dae
1,308
cpp
C++
Pdf/pdfix_sdk_example_cpp-master/src/SetFieldFlags.cpp
laoola/ProjectCode
498a66cb9274f6bb7cca0d6e6052304d61740ba2
[ "Unlicense" ]
1
2021-08-23T05:56:09.000Z
2021-08-23T05:56:09.000Z
Pdf/pdfix_sdk_example_cpp-master/src/SetFieldFlags.cpp
laoola/ProjectCode
498a66cb9274f6bb7cca0d6e6052304d61740ba2
[ "Unlicense" ]
null
null
null
Pdf/pdfix_sdk_example_cpp-master/src/SetFieldFlags.cpp
laoola/ProjectCode
498a66cb9274f6bb7cca0d6e6052304d61740ba2
[ "Unlicense" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // SetFieldFlags.cpp // Copyright (c) 2018 Pdfix. All Rights Reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// #include "pdfixsdksamples/SetFieldFlags.h" #include <string> #include <iostream> #include "Pdfix.h" using namespace PDFixSDK; void SetFieldFlags( const std::wstring& open_path, // source PDF document const std::wstring& save_path // output PDF doucment ) { // initialize Pdfix if (!Pdfix_init(Pdfix_MODULE_NAME)) throw std::runtime_error("Pdfix initialization fail"); Pdfix* pdfix = GetPdfix(); if (!pdfix) throw std::runtime_error("GetPdfix fail"); PdfDoc* doc = pdfix->OpenDoc(open_path.c_str(), L""); if (!doc) throw PdfixException(); for (int i = 0; i < doc->GetNumFormFields(); i++) { std::wstring name, value; PdfFormField* field = doc->GetFormField(i); if (!field) throw PdfixException(); auto flags = field->GetFlags(); flags |= kFieldFlagReadOnly; if (!field->SetFlags(flags)) throw PdfixException(); } if (!doc->Save(save_path.c_str(), kSaveFull)) throw PdfixException(); doc->Close(); pdfix->Destroy(); }
28.434783
100
0.54893
laoola
35582b2e8bbcc290d9d2afa28e9e0cc3132a2925
634
cpp
C++
01. Easy/01. Array/04. Contains_Duplicate.cpp
premnaaath/leetcode-TIQ
90f9d7216b596dc42fe0d559f3ecdaa448b258d1
[ "MIT" ]
null
null
null
01. Easy/01. Array/04. Contains_Duplicate.cpp
premnaaath/leetcode-TIQ
90f9d7216b596dc42fe0d559f3ecdaa448b258d1
[ "MIT" ]
null
null
null
01. Easy/01. Array/04. Contains_Duplicate.cpp
premnaaath/leetcode-TIQ
90f9d7216b596dc42fe0d559f3ecdaa448b258d1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; bool containsDuplicate(vector<int> &nums) { vector<int> hash; for (int i = 0; i < nums.size(); ++i) { if (find(hash.begin(), hash.end(), nums[i]) != hash.end()) return true; hash.push_back(nums[i]); } return false; } void solve() { vector<int> nums{1, 2, 3, 1}; if (containsDuplicate(nums)) cout << "TRUE\n"; else cout << "FALSE\n"; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
18.114286
66
0.525237
premnaaath
35587bd723ed42e65f1974b2e909e96c587437d2
239
hpp
C++
source/sill/pch.hpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
15
2018-02-26T08:20:03.000Z
2022-03-06T03:25:46.000Z
source/sill/pch.hpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
32
2018-02-26T08:26:38.000Z
2020-09-12T17:09:38.000Z
source/sill/pch.hpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
null
null
null
#include "../pch-glm.hpp" #include "../pch-stl.hpp" #include <nlohmann/json.hpp> #include <lava/chamber.hpp> #include <lava/core.hpp> #include <lava/crater.hpp> #include <lava/dike.hpp> #include <lava/flow.hpp> #include <lava/magma.hpp>
19.916667
28
0.702929
Breush
355b887f43bd38238ead0a4d55a9248f2b8367f0
59
hpp
C++
src/boost_log_sources_exception_handler_feature.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_log_sources_exception_handler_feature.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_log_sources_exception_handler_feature.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/log/sources/exception_handler_feature.hpp>
29.5
58
0.847458
miathedev
355b91ea50f25298a24aa7675e5271290de9c2fb
5,199
cpp
C++
master/core/third/cxxtools/src/atomicity.gcc.arm.cpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:48.000Z
2019-10-26T21:44:59.000Z
master/core/third/cxxtools/src/atomicity.gcc.arm.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
null
null
null
master/core/third/cxxtools/src/atomicity.gcc.arm.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:49.000Z
2018-12-27T03:20:31.000Z
/* * Copyright (C) 2006 by Marc Boris Duerner * Copyright (C) 2006 by Aloysius Indrayanto * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/atomicity.gcc.arm.h> #include <csignal> #include <cstdio> namespace cxxtools { atomic_t atomicGet(volatile atomic_t& val) { asm volatile ("" : : : "memory"); return val; } void atomicSet(volatile atomic_t& val, atomic_t n) { val = n; asm volatile ("" : : : "memory"); } atomic_t atomicIncrement(volatile atomic_t& dest) { int a, b, c; asm volatile ( "0:\n\t" "ldr %0, [%3]\n\t" "add %1, %0, %4\n\t" "swp %2, %1, [%3]\n\t" "cmp %0, %2\n\t" "swpne %1, %2, [%3]\n\t" "bne 0b" : "=&r" (a), "=&r" (b), "=&r" (c) : "r" (&dest), "r" (1) : "cc", "memory"); return b; } atomic_t atomicDecrement(volatile atomic_t& dest) { int a, b, c; asm volatile ( "0:\n\t" "ldr %0, [%3]\n\t" "add %1, %0, %4\n\t" "swp %2, %1, [%3]\n\t" "cmp %0, %2\n\t" "swpne %1, %2, [%3]\n\t" "bne 0b" : "=&r" (a), "=&r" (b), "=&r" (c) : "r" (&dest), "r" (-1) : "cc", "memory"); return b; } atomic_t atomicCompareExchange(volatile atomic_t& dest, atomic_t exch, atomic_t comp) { int a, b; asm volatile ( "0:\n\t" "ldr %1, [%2]\n\t" "cmp %1, %4\n\t" "mov %0, %1\n\t" "bne 1f\n\t" "swp %0, %3, [%2]\n\t" "cmp %0, %1\n\t" "swpne %3, %0, [%2]\n\t" "bne 0b\n\t" "1:" : "=&r" (a), "=&r" (b) : "r" (&dest), "r" (exch), "r" (comp) : "cc", "memory"); return a; } void* atomicCompareExchange(void* volatile& dest, void* exch, void* comp) { volatile void* a; volatile void* b; asm volatile ( "0:\n\t" "ldr %1, [%2]\n\t" "cmp %1, %4\n\t" "mov %0, %1\n\t" "bne 1f\n\t" "swpeq %0, %3, [%2]\n\t" "cmp %0, %1\n\t" "swpne %3, %0, [%2]\n\t" "bne 0b\n\t" "1:" : "=&r" (a), "=&r" (b) : "r" (&dest), "r" (exch), "r" (comp) : "cc", "memory"); return (void*)a; } atomic_t atomicExchange(volatile atomic_t& dest, atomic_t exch) { int a; asm volatile ( "swp %0, %2, [%1]" : "=&r" (a) : "r" (&dest), "r" (exch)); return a; } void* atomicExchange(void* volatile& dest, void* exch) { void* a; asm volatile ( "swp %0, %2, [%1]" : "=&r" (a) : "r" (&dest), "r" (exch)); return a; } atomic_t atomicExchangeAdd(volatile atomic_t& dest, atomic_t add) { int a, b, c; asm volatile ( "0:\n\t" "ldr %0, [%3]\n\t" "add %1, %0, %4\n\t" "swp %2, %1, [%3]\n\t" "cmp %0, %2\n\t" "swpne %1, %2, [%3]\n\t" "bne 0b" : "=&r" (a), "=&r" (b), "=&r" (c) : "r" (&dest), "r" (add) : "cc", "memory"); return a; } } // namespace cxxtools
30.052023
85
0.43643
importlib
355c5704f28eb9b687953ab62c2c64f6939c0d58
4,952
cpp
C++
benchmark/ordering.cpp
zborffs/AsterionEngine
029624cba19cd7fbc407bb24b9beb33efd089c5b
[ "MIT" ]
1
2018-12-29T10:39:56.000Z
2018-12-29T10:39:56.000Z
benchmark/ordering.cpp
zborffs/AsterionEngine
029624cba19cd7fbc407bb24b9beb33efd089c5b
[ "MIT" ]
3
2021-11-12T06:44:46.000Z
2021-11-12T06:47:56.000Z
benchmark/ordering.cpp
zborffs/AsterionEngine
029624cba19cd7fbc407bb24b9beb33efd089c5b
[ "MIT" ]
null
null
null
/// Project Includes #include "defines.hpp" #include "globals.hpp" #include "board.hpp" #include "chess_clock.hpp" #include "search.hpp" #include "book.hpp" /// Standard Library Includes #include <iostream> #include <string> /// Third-Party Includes #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/sinks/daily_file_sink.h> #include <cereal/archives/binary.hpp> #include <spdlog/sinks/basic_file_sink.h> #define LOG_FAILURE -1 // flesh out all the quit flags later bool init_logger(const std::string& path) noexcept; void create_book(const std::string& filename, Book& book); int main([[maybe_unused]] int argc, char **argv) { std::string path(argv[0]); #ifdef WINDOWS std::string base(path.substr(0, path.find_last_of("\\"))); #else std::string base(path.substr(0, path.find_last_of('/'))); #endif // WINDOWS /// Initialize the logger variables, if it fails to initialize, then quit. std::string logfile_path(base + "/../../logs/TestSuiteBenchmark.log"); if (!init_logger(logfile_path)) { return LOG_FAILURE; } /// Create local variables at the top std::string basic_tester_path; std::string output_file_path; std::string book_path; Board board; ChessClock chess_clock; SearchState search_state(16384); EvaluationState eval_state; UCIOptions options; Book book; /// Get path to the input file, "BasicTests.fen", and output file, "tools/data/ordering_output.txt", from executable directory and command line arguments bool first_is_slash = path[0] == '/'; auto splitvec = split(path, '/'); std::string s{""}; assert(!splitvec.empty()); if (first_is_slash) { s += "/" + splitvec[0]; } else { s += splitvec[0]; } for (int i = 1; i < splitvec.size() - 1; i++) { s += std::string("/" + splitvec[i]); } basic_tester_path = std::string(s + "/../../" + argv[1]); output_file_path = std::string(s + "/../../" + argv[2]); book_path = std::string(s + "/../../data/PrometheusOpening.book"); /// redirect std::cout to the output file std::ofstream output(output_file_path); std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf std::cout.rdbuf(output.rdbuf()); //redirect std::cout to out.txt! /// initialize the uci game options before starting options.reset_game_state_vars(); options.infinite = true; // at some point change this to max depth = ~6 create_book(book_path, book); chess_clock.start(); try { /// read all the FENs from the input file auto fens = read_all_fen_from_file(basic_tester_path); /// Think for each position (inside of "think" it will cout some useful information) for (auto & fen : fens) { auto separated_fen = split(fen, ';'); std::string fen_string = separated_fen[0]; board.set_board(fen_string); think(board, options, search_state, eval_state, book); search_state.tt.clear(); } } catch (const std::exception& e) { throw; } chess_clock.stop(); std::cout.rdbuf(coutbuf); // reset to standard output again std::cout << "Data Acquisition Successful! Program took " << (chess_clock.duration() / 1000000.) << " [ms]" << std::endl; return 0; } /** * initializes the logger; assumes that the folder containing the executable is in the same directory as the folder * storing the log text files. * @param path the path to the executable of this program * @return boolean representing the success of the function */ bool init_logger(const std::string& path) noexcept { try { /// Setup the console sink auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); console_sink->set_level(spdlog::level::trace); console_sink->set_pattern("[%D %H:%M:%S] [%^%l%$] [Thread %t] [File:Line %@] [Function: %!] %v"); console_sink->set_color_mode(spdlog::color_mode::always); /// setup the file sink auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(path, true); file_sink->set_level(spdlog::level::trace); /// setup the logger using both sinks spdlog::logger logger(logger_name, {console_sink, file_sink}); logger.set_level(spdlog::level::debug); spdlog::set_default_logger(std::make_shared<spdlog::logger>(logger_name, spdlog::sinks_init_list({console_sink, file_sink}))); } catch (const spdlog::spdlog_ex& ex) { std::cout << "Logger initialization failed: " << ex.what() << std::endl; return false; // if we fail to initialize the logger, return false } return true; } /** * * @param filename * @param book */ void create_book(const std::string& filename, Book& book) { std::ifstream f(filename, std::ios::binary); cereal::BinaryInputArchive iarchive(f); iarchive(book); }
34.388889
157
0.651454
zborffs
356276796716b69838e68ef804051aacab68b05f
200
hpp
C++
falcon/mpl/size_fwd.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
2
2018-02-02T14:19:59.000Z
2018-05-13T02:48:24.000Z
falcon/mpl/size_fwd.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
falcon/mpl/size_fwd.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
#ifndef FALCON_MPL_SIZE_FWD_HPP #define FALCON_MPL_SIZE_FWD_HPP namespace falcon { namespace mpl { template< typename Tag > struct size_impl; template< typename Sequence > struct size; }} #endif
16.666667
42
0.79
jonathanpoelen
8319f1d5bedc12d9ab7aa418fc40c026b81a2057
7,356
cpp
C++
src/main.cpp
kirillochnev/ecs-benchmark
ea8feea0e0d449982f6f365e641142840c297109
[ "MIT" ]
null
null
null
src/main.cpp
kirillochnev/ecs-benchmark
ea8feea0e0d449982f6f365e641142840c297109
[ "MIT" ]
null
null
null
src/main.cpp
kirillochnev/ecs-benchmark
ea8feea0e0d449982f6f365e641142840c297109
[ "MIT" ]
null
null
null
#include <mustache/ecs/ecs.hpp> #include <entt/entt.hpp> #include <entityx/entityx.h> #include "components.hpp" #include <numeric> #include <iostream> constexpr uint32_t entity_count = 10000000; constexpr uint32_t create_iterations = 10; constexpr uint32_t run_iterations = 100; class BenchMark { public: template<typename _F, typename _BeforeRun> void run(_F&& function, uint32_t iterations = 1, _BeforeRun&& before_run = []{}) { dt_array_.reserve(dt_array_.size() + iterations); for (uint32_t i = 0; i < iterations; ++i) { before_run(); const auto begin = Clock::now(); function(); const auto end = Clock::now(); dt_array_.push_back(1000.0 * getSeconds(end - begin)); } } void printTimes(std::ostream& out) const noexcept { for (const auto dt : dt_array_) { out << dt << " "; } out.flush(); } void reset() noexcept { dt_array_.clear(); } void show(std::ostream& out) noexcept { if(dt_array_.empty()) { return; } if(dt_array_.size() < 2) { out<<"Time: " << dt_array_.front() << "ms" << std::endl; return; } const auto sum = std::accumulate(dt_array_.begin(), dt_array_.end(), 0.0); std::sort(dt_array_.begin(), dt_array_.end()); auto med = dt_array_[dt_array_.size() / 2]; if(dt_array_.size() % 2 == 0) { med = (med + dt_array_[dt_array_.size() / 2 - 1]) * 0.5; } const auto avr = sum / static_cast<double>(dt_array_.size()); double variance = 0.0; for (auto x : dt_array_) { variance += (avr - x) * (avr - x) / static_cast<double>(dt_array_.size()); } out << "Call count: " << dt_array_.size() << ", Arv: " << avr << "ms, med: " << med << "ms, min:" << dt_array_.front() << "ms, max: " << dt_array_.back() << "ms, variance: " << variance << ", sigma: " << sqrt(variance) << std::endl; } private: using Clock = std::chrono::high_resolution_clock; using TimePoint = Clock::time_point; template<typename T> static double getSeconds(const T& pDur) noexcept { constexpr double Microseconds2SecondConvertK = 0.000001; const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(pDur).count(); return static_cast<double>(microseconds) * Microseconds2SecondConvertK; } std::vector<double> dt_array_; }; template <typename... Unused> void updatePositionOOP(std::ostream& create, std::ostream& iterate) { std::vector<bench::MovableObject<Unused...> > objects; BenchMark benchmark; benchmark.run([&objects] { for (uint32_t i = 0; i < entity_count; ++i) { objects.emplace_back(); } }, create_iterations, [&objects]{ objects.clear(); }); benchmark.show(create); benchmark.reset(); benchmark.run([&objects] { for (auto &object : objects) { object.update(); } }, run_iterations, []{}); benchmark.show(iterate); } template <typename... _Unused> void updatePositionMustache(std::ostream& create, std::ostream& iterate) { struct MoveObjectJob : public mustache::PerEntityJob<MoveObjectJob> { void operator()(bench::Position& position, const bench::Velocity& velocity, const bench::Rotation& orientation) const { updatePositionFunction(position, velocity, orientation); } }; MoveObjectJob move_job; BenchMark benchmark; mustache::World world { mustache::WorldId::make(0)}; auto& entities = world.entities(); auto& arch = entities.getArchetype<bench::Position, bench::Velocity, bench::Rotation, _Unused...>(); benchmark.run([&arch, &entities] { for (uint32_t i = 0; i < entity_count; ++i) { (void) entities.create(arch); } }, create_iterations, [&entities]{ entities.clear(); }); benchmark.show(create); benchmark.reset(); benchmark.run([&move_job, &world]{ move_job.run(world, mustache::JobRunMode::kCurrentThread); }, run_iterations, []{}); benchmark.show(create); } template <typename... ARGS> void unused(ARGS&&...) { } template <typename... _Unused> void updatePositionEnTT(std::ostream& create, std::ostream& iterate) { BenchMark benchmark; entt::registry registry; benchmark.run([&registry] { for (uint32_t i = 0; i < entity_count; ++i) { entt::entity entity = registry.create(); registry.emplace<bench::Position>(entity); registry.emplace<bench::Velocity>(entity); registry.emplace<bench::Rotation>(entity); unused(registry.emplace<_Unused>(entity)...); } }, create_iterations, [&registry]{ registry.clear<>(); }); benchmark.show(create); benchmark.reset(); benchmark.run([&registry]{ registry.view<bench::Position, const bench::Velocity, const bench::Rotation>().each(&bench::updatePositionFunction); }, run_iterations, []{}); benchmark.show(create); } template <typename... _Unused> void updatePositionEntityX(std::ostream& create, std::ostream& iterate) { BenchMark benchmark; entityx::EventManager event_manager; entityx::EntityManager entity_manager{event_manager}; benchmark.run([&entity_manager] { for (uint32_t i = 0; i < entity_count; ++i) { auto entity = entity_manager.create(); entity.assign<bench::Position>(); entity.assign<bench::Velocity>(); entity.assign<bench::Rotation>(); unused (entity_manager.template assign<_Unused>(entity.id())...); } }, create_iterations, [&entity_manager]{ entity_manager.reset(); }); benchmark.show(create); benchmark.reset(); benchmark.run([&entity_manager]{ entityx::ComponentHandle<bench::Position> position; entityx::ComponentHandle<bench::Velocity> velocity; entityx::ComponentHandle<bench::Rotation> rotation; for (auto entity : entity_manager.entities_with_components(position, velocity, rotation)) { bench::updatePositionFunction(*position, *velocity, *rotation); } }, run_iterations, []{}); benchmark.show(create); } template <typename... _Unused> void runAll() { const std::string names[] { mustache::type_name<_Unused>()..., std::string{} }; std::string name = ""; for (uint32_t i = 0; i < sizeof...(_Unused); ++i) { if (i > 0) { name += ", "; } name += names[i]; } std::cout << "\n------------- unused components: " << name << std::endl; std::cout << "OOP-style:" << std::endl; updatePositionOOP<_Unused...>(std::cout, std::cout); std::cout << "Mustache:" << std::endl; updatePositionMustache<_Unused...>(std::cout, std::cout); std::cout << "EnTT:" << std::endl; updatePositionEnTT<_Unused...>(std::cout, std::cout); std::cout << "EntityX:" << std::endl; updatePositionEntityX<_Unused...>(std::cout, std::cout); } int main() { runAll(); runAll<bench::UnusedComponent<0, sizeof(glm::vec3)> >(); runAll<bench::UnusedComponent<0, sizeof(glm::mat4)> >(); }
31.982609
124
0.597336
kirillochnev
831a13e1d158bb902034c78d8a868e59025c1d1b
1,581
cpp
C++
001-100/005-Longest_Palindromic_Substring-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
001-100/005-Longest_Palindromic_Substring-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
001-100/005-Longest_Palindromic_Substring-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Given a string s, find the longest palindromic substring in s. You may assume // that the maximum length of s is 1000. // Example: // Input: "babad" // Output: "bab" // Note: "aba" is also a valid answer. // Example: // Input: "cbbd" // Output: "bb" // TODO: Manacher's algorithm // expand from center class Solution { // return start index and size of substr pair<int, int> expand(const string &s, int l, int r) { while (l >= 0 && r < s.size() && s[l] == s[r]) { --l; ++r; } return make_pair(l + 1, r - l - 1); } void update(string &ret, const string &s, const pair<int, int> &st_sz) { if (st_sz.second > ret.size()) ret = s.substr(st_sz.first, st_sz.second); } public: string longestPalindrome(string s) { string ret; for (int i = 0; i < s.size(); ++i) { update(ret, s, expand(s, i, i)); update(ret, s, expand(s, i, i + 1)); } return ret; } }; class Solution { bool checkPalindrome(const string &s, int start, int end) { while (start < end) if (s[start++] != s[end--]) return false; return true; } public: string longestPalindrome(string s) { int len = s.size(), i; if (len == 0) return ""; for (int substrlen = len; substrlen > 0; --substrlen) for (i = 0; i < len - substrlen + 1; ++i) if (checkPalindrome(s, i, i + substrlen - 1)) return s.substr(i, substrlen); } };
26.35
80
0.510436
ysmiles
831a2a4d4620a949eaaa8ee2292b85bc9c88f507
32,373
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AnimatingButtonsMenu/animating_buttons_menu_icons_game_2d_tiny.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AnimatingButtonsMenu/animating_buttons_menu_icons_game_2d_tiny.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AnimatingButtonsMenu/animating_buttons_menu_icons_game_2d_tiny.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
// Generated by imageconverter. Please, do not edit! #include <touchgfx/hal/Config.hpp> LOCATION_EXTFLASH_PRAGMA KEEP extern const unsigned char _animating_buttons_menu_icons_game_2d_tiny[] LOCATION_EXTFLASH_ATTRIBUTE = { // 40x40 ARGB8888 pixels. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x1c,0x08,0x10,0x28,0x1c,0x08,0x55,0x28,0x24,0x10,0x9a,0x30,0x2c,0x20,0xcf,0x30,0x28,0x18,0xef,0x30,0x28,0x18,0xf7,0x30,0x24,0x18,0xff,0x28,0x24,0x18,0xf7,0x30,0x2c,0x18,0xe7,0x38,0x2c,0x20,0xc3,0x28,0x20,0x10,0x82, 0x28,0x1c,0x08,0x3c,0x28,0x1c,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x1c,0x08,0x34,0x28,0x24,0x10,0xae,0x28,0x20,0x18,0xf7,0x28,0x24,0x18,0xff,0x30,0x24,0x18,0xff, 0x30,0x28,0x20,0xff,0x30,0x28,0x18,0xff,0x30,0x28,0x18,0xff,0x30,0x28,0x20,0xff,0x30,0x28,0x18,0xff,0x30,0x28,0x18,0xff,0x30,0x28,0x20,0xff,0x30,0x28,0x18,0xff,0x28,0x24,0x18,0xff,0x30,0x28,0x18,0xef,0x28,0x24,0x10,0x86,0x28,0x1c,0x08,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x28,0x1c,0x08,0x20,0x28,0x20,0x10,0xb6,0x28,0x24,0x18,0xff,0x30,0x2c,0x20,0xff,0x30,0x2c,0x20,0xff,0x30,0x2c,0x20,0xff,0x30,0x28,0x18,0xff,0x30,0x30,0x28,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x28,0xff,0x30,0x28,0x18,0xff,0x38,0x34,0x28,0xff,0x38,0x34,0x28,0xff,0x38,0x34,0x28,0xff, 0x38,0x30,0x28,0xff,0x30,0x2c,0x18,0xff,0x38,0x2c,0x20,0xff,0x30,0x28,0x18,0xfb,0x28,0x20,0x10,0x82,0x28,0x1c,0x08,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x1c,0x08,0x61,0x28,0x24,0x18,0xf7,0x28,0x24,0x18,0xff,0x30,0x2c,0x20,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x20,0xff,0x38,0x30,0x28,0xff,0x30,0x28,0x20,0xff, 0x38,0x30,0x20,0xff,0x38,0x30,0x28,0xff,0x48,0x44,0x38,0xff,0x58,0x58,0x48,0xff,0x60,0x5c,0x58,0xff,0x68,0x68,0x60,0xff,0x60,0x60,0x58,0xff,0x50,0x4c,0x40,0xff,0x40,0x38,0x28,0xff,0x30,0x2c,0x20,0xff,0x38,0x34,0x28,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x20,0xff,0x30,0x28,0x18,0xdf,0x28,0x1c,0x08,0x2c,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x1c,0x08,0x04,0x28,0x20,0x08,0x96, 0x30,0x24,0x18,0xff,0x30,0x2c,0x20,0xff,0x30,0x28,0x18,0xff,0x30,0x2c,0x20,0xff,0x38,0x2c,0x28,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x28,0xff,0x30,0x2c,0x20,0xff,0x58,0x50,0x48,0xff,0x78,0x74,0x70,0xff,0x80,0x80,0x78,0xff,0x80,0x84,0x80,0xff,0x80,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x88,0x84,0x80,0xff,0x88,0x84,0x80,0xff, 0x80,0x7c,0x78,0xff,0x48,0x44,0x38,0xff,0x40,0x38,0x28,0xff,0x38,0x34,0x28,0xff,0x38,0x34,0x28,0xff,0x38,0x34,0x28,0xff,0x30,0x28,0x18,0xf7,0x28,0x1c,0x08,0x4d,0x00,0x00,0x00,0x00,0x80,0x7c,0x80,0x00,0x78,0x7c,0x78,0xa6,0x80,0x7c,0x80,0xc3,0x80,0x7c,0x80,0xbe,0x80,0x80,0x80,0xbe,0x80,0x80,0x80,0x92,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x1c,0x08,0x04,0x28,0x20,0x10,0xaa,0x30,0x28,0x18,0xff,0x30,0x2c,0x20,0xff,0x30,0x2c,0x20,0xff,0x30,0x28,0x20,0xff,0x30,0x30,0x20,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x20,0xff,0x48,0x44,0x38,0xff,0x70,0x70,0x68,0xff, 0x80,0x80,0x78,0xff,0x80,0x80,0x78,0xff,0x80,0x80,0x78,0xff,0x68,0x60,0x58,0xff,0x48,0x3c,0x30,0xff,0x40,0x38,0x30,0xff,0x60,0x58,0x48,0xff,0x88,0x84,0x80,0xff,0x90,0x8c,0x88,0xff,0x88,0x84,0x80,0xff,0x58,0x54,0x48,0xff,0x40,0x38,0x28,0xff,0x40,0x38,0x28,0xff,0x40,0x38,0x28,0xff,0x30,0x2c,0x20,0xff,0x30,0x28,0x18,0xff, 0x28,0x20,0x08,0x59,0x78,0x7c,0x80,0x51,0x80,0x7c,0x80,0xdf,0x80,0x80,0x80,0xdf,0x80,0x7c,0x80,0xdf,0x80,0x80,0x80,0xdb,0x80,0x80,0x80,0x3c,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x20,0x10,0x92,0x28,0x24,0x18,0xff,0x30,0x28,0x18,0xff, 0x30,0x28,0x20,0xff,0x30,0x24,0x20,0xff,0x30,0x28,0x18,0xff,0x30,0x28,0x20,0xff,0x30,0x2c,0x20,0xff,0x58,0x50,0x48,0xff,0x78,0x7c,0x78,0xff,0x80,0x7c,0x78,0xff,0x80,0x80,0x78,0xff,0x78,0x74,0x70,0xff,0x38,0x30,0x28,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x40,0x3c,0x30,0xff, 0x90,0x88,0x80,0xff,0x90,0x8c,0x88,0xff,0x88,0x88,0x80,0xff,0x50,0x44,0x38,0xff,0x38,0x34,0x20,0xff,0x38,0x30,0x20,0xff,0x38,0x30,0x20,0xff,0x38,0x30,0x20,0xff,0x30,0x28,0x18,0xfb,0x78,0x74,0x70,0xd3,0x80,0x80,0x80,0xdf,0x80,0x80,0x80,0xdb,0x80,0x80,0x80,0xdb,0x80,0x84,0x80,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x20,0x08,0x59,0x28,0x24,0x10,0xff,0x38,0x2c,0x20,0xff,0x30,0x30,0x20,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x20,0xff,0x30,0x28,0x20,0xff,0x38,0x34,0x28,0xff,0x60,0x60,0x58,0xff,0x80,0x7c,0x78,0xff,0x80,0x80,0x78,0xff,0x80,0x80,0x78,0xff, 0x78,0x74,0x70,0xff,0x30,0x28,0x18,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x68,0x64,0x58,0xff,0x90,0x90,0x88,0xff,0x90,0x90,0x90,0xff,0x88,0x80,0x78,0xff,0x48,0x40,0x30,0xff,0x48,0x3c,0x30,0xff,0x38,0x34,0x20,0xff,0x40,0x38,0x28,0xff, 0x58,0x54,0x48,0xff,0x78,0x7c,0x78,0xfb,0x80,0x7c,0x78,0xe3,0x80,0x80,0x80,0xdb,0x80,0x84,0x80,0xdb,0x88,0x88,0x88,0x2c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x20,0x10,0x1c,0x30,0x24,0x10,0xf3,0x30,0x28,0x20,0xff,0x38,0x30,0x28,0xff,0x38,0x30,0x20,0xff, 0x38,0x30,0x20,0xff,0x38,0x30,0x28,0xff,0x30,0x2c,0x20,0xff,0x60,0x60,0x58,0xff,0x80,0x7c,0x78,0xff,0x80,0x80,0x78,0xff,0x88,0x80,0x78,0xff,0x80,0x78,0x70,0xff,0x38,0x2c,0x20,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff, 0x40,0x34,0x28,0xff,0x98,0x90,0x88,0xff,0x98,0x94,0x90,0xff,0x98,0x94,0x90,0xff,0x60,0x5c,0x50,0xff,0x48,0x40,0x30,0xff,0x40,0x34,0x28,0xff,0x48,0x40,0x30,0xff,0x78,0x78,0x78,0xff,0x80,0x80,0x78,0xff,0x80,0x7c,0x78,0xf7,0x88,0x84,0x88,0xdb,0x88,0x88,0x88,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x20,0x08,0xa2,0x30,0x2c,0x20,0xff,0x30,0x28,0x18,0xff,0x38,0x30,0x28,0xff,0x38,0x34,0x28,0xff,0x38,0x34,0x28,0xff,0x40,0x34,0x28,0xff,0x50,0x4c,0x40,0xff,0x80,0x80,0x78,0xff,0x80,0x80,0x78,0xff,0x80,0x80,0x80,0xff,0x88,0x84,0x80,0xff,0x48,0x3c,0x30,0xff, 0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x88,0x84,0x80,0xff,0x98,0x98,0x90,0xff,0x98,0x94,0x90,0xff,0x80,0x80,0x78,0xff,0x48,0x40,0x30,0xff,0x40,0x38,0x20,0xff,0x68,0x60,0x58,0xff, 0x88,0x84,0x80,0xff,0x88,0x80,0x80,0xff,0x80,0x80,0x78,0xff,0x88,0x84,0x80,0xe3,0x90,0x90,0x90,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x20,0x08,0x28,0x30,0x24,0x10,0xff,0x38,0x30,0x28,0xff,0x30,0x2c,0x18,0xff,0x38,0x34,0x28,0xff,0x38,0x34,0x28,0xff, 0x40,0x38,0x28,0xff,0x48,0x44,0x30,0xff,0x78,0x78,0x78,0xff,0x80,0x80,0x78,0xff,0x88,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x68,0x68,0x60,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x30,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff, 0x28,0x20,0x08,0xff,0x78,0x70,0x68,0xff,0x98,0x94,0x90,0xff,0x98,0x98,0x90,0xff,0x98,0x94,0x90,0xff,0x50,0x48,0x38,0xff,0x48,0x3c,0x28,0xff,0x88,0x84,0x80,0xff,0x88,0x88,0x80,0xff,0x88,0x88,0x80,0xff,0x88,0x88,0x80,0xff,0x68,0x64,0x58,0xeb,0x30,0x24,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x24,0x10,0x9a,0x30,0x28,0x18,0xff,0x30,0x2c,0x18,0xff,0x30,0x2c,0x20,0xff,0x38,0x2c,0x20,0xff,0x38,0x30,0x20,0xff,0x38,0x30,0x20,0xff,0x68,0x68,0x60,0xff,0x80,0x7c,0x78,0xff,0x80,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x88,0x80,0x80,0xff,0x38,0x2c,0x20,0xff,0x28,0x20,0x10,0xff, 0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x30,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x70,0x64,0x58,0xff,0x98,0x90,0x88,0xff,0x98,0x94,0x90,0xff,0x98,0x94,0x90,0xff,0x58,0x4c,0x38,0xff,0x70,0x68,0x58,0xff,0x90,0x8c,0x88,0xff, 0x88,0x88,0x80,0xff,0x88,0x88,0x80,0xff,0x88,0x88,0x80,0xff,0x40,0x34,0x20,0xff,0x30,0x20,0x10,0x45,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x30,0x24,0x10,0x08,0x30,0x24,0x10,0xf3,0x38,0x30,0x20,0xff,0x40,0x34,0x28,0xff,0x38,0x2c,0x20,0xff,0x40,0x38,0x28,0xff,0x40,0x38,0x28,0xff, 0x50,0x4c,0x40,0xff,0x88,0x80,0x80,0xff,0x88,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x88,0x88,0x80,0xff,0x70,0x68,0x60,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff, 0x28,0x20,0x10,0xff,0x68,0x60,0x50,0xff,0x98,0x94,0x88,0xff,0x98,0x94,0x90,0xff,0xa0,0x9c,0x90,0xff,0x68,0x64,0x58,0xff,0x98,0x90,0x88,0xff,0x98,0x94,0x90,0xff,0x98,0x90,0x88,0xff,0x98,0x90,0x88,0xff,0x70,0x6c,0x60,0xff,0x40,0x30,0x20,0xff,0x30,0x24,0x10,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x30,0x24,0x10,0x49,0x30,0x28,0x10,0xff,0x38,0x34,0x28,0xff,0x40,0x34,0x28,0xff,0x38,0x30,0x20,0xff,0x40,0x38,0x28,0xff,0x48,0x3c,0x28,0xff,0x70,0x6c,0x60,0xff,0x88,0x84,0x80,0xff,0x80,0x84,0x80,0xff,0x88,0x88,0x80,0xff,0x90,0x8c,0x88,0xff,0x38,0x34,0x20,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff, 0x28,0x1c,0x08,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x68,0x60,0x58,0xff,0x90,0x8c,0x88,0xff,0x98,0x94,0x90,0xff,0x98,0x98,0x90,0xff,0x90,0x8c,0x80,0xff,0x98,0x98,0x90,0xff,0x98,0x98,0x90,0xff, 0x98,0x98,0x90,0xff,0x98,0x90,0x90,0xff,0x50,0x48,0x38,0xff,0x40,0x38,0x28,0xff,0x30,0x28,0x10,0xef,0x30,0x24,0x08,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x30,0x24,0x08,0x8a,0x38,0x2c,0x18,0xff,0x40,0x34,0x28,0xff,0x40,0x38,0x28,0xff,0x38,0x30,0x20,0xff,0x40,0x38,0x28,0xff,0x50,0x44,0x38,0xff, 0x88,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x88,0x84,0x80,0xff,0x90,0x8c,0x88,0xff,0x80,0x7c,0x70,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x28,0x20,0x10,0xff, 0x28,0x20,0x10,0xff,0x70,0x64,0x58,0xff,0x90,0x8c,0x88,0xff,0x98,0x94,0x88,0xff,0xa0,0x98,0x90,0xff,0xa0,0x9c,0x98,0xff,0xa0,0x98,0x90,0xff,0xa0,0x9c,0x98,0xff,0xa0,0x9c,0x98,0xff,0x78,0x6c,0x60,0xff,0x50,0x44,0x30,0xff,0x40,0x38,0x28,0xff,0x38,0x30,0x18,0xff,0x30,0x24,0x10,0x34,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x30,0x24,0x10,0xba,0x38,0x30,0x20,0xff,0x40,0x34,0x28,0xff,0x40,0x38,0x28,0xff,0x40,0x34,0x20,0xff,0x48,0x3c,0x28,0xff,0x60,0x5c,0x50,0xff,0x88,0x84,0x80,0xff,0x88,0x88,0x80,0xff,0x88,0x88,0x80,0xff,0x98,0x90,0x88,0xff,0x60,0x58,0x48,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff, 0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x78,0x70,0x68,0xff,0x90,0x8c,0x80,0xff,0x90,0x90,0x88,0xff,0x98,0x98,0x90,0xff,0xa0,0x9c,0x98,0xff,0xa0,0x9c,0x90,0xff,0xa0,0xa0,0x98,0xff, 0xa0,0x98,0x90,0xff,0x50,0x48,0x38,0xff,0x50,0x44,0x30,0xff,0x48,0x3c,0x28,0xff,0x40,0x34,0x20,0xff,0x30,0x24,0x10,0x69,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x30,0x28,0x10,0xdf,0x38,0x2c,0x18,0xff,0x38,0x30,0x20,0xff,0x38,0x30,0x20,0xff,0x40,0x34,0x20,0xff,0x40,0x38,0x20,0xff,0x70,0x6c,0x60,0xff, 0x88,0x84,0x80,0xff,0x88,0x84,0x80,0xff,0x90,0x8c,0x88,0xff,0x98,0x90,0x88,0xff,0x38,0x30,0x20,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x30,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x10,0xff,0x28,0x1c,0x10,0xff, 0x28,0x20,0x10,0xff,0x80,0x7c,0x78,0xff,0x88,0x88,0x80,0xff,0x90,0x8c,0x88,0xff,0x98,0x94,0x90,0xff,0xa0,0x98,0x90,0xff,0xa0,0x9c,0x98,0xff,0xa8,0xa0,0x98,0xff,0x70,0x64,0x50,0xff,0x48,0x3c,0x28,0xff,0x48,0x3c,0x28,0xff,0x48,0x3c,0x28,0xff,0x40,0x34,0x18,0xff,0x38,0x28,0x10,0x8a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x38,0x28,0x10,0xef,0x40,0x38,0x20,0xff,0x40,0x38,0x28,0xff,0x48,0x3c,0x28,0xff,0x40,0x38,0x20,0xff,0x48,0x40,0x30,0xff,0x80,0x7c,0x78,0xff,0x90,0x88,0x80,0xff,0x90,0x8c,0x80,0xff,0x90,0x8c,0x88,0xff,0x90,0x8c,0x80,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff, 0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x38,0x30,0x20,0xff,0x88,0x80,0x78,0xff,0x90,0x88,0x80,0xff,0x90,0x90,0x88,0xff,0x98,0x98,0x90,0xff,0xa8,0xa0,0x98,0xff,0xa0,0xa0,0x98,0xff,0xa0,0x98,0x90,0xff, 0x50,0x48,0x30,0xff,0x50,0x48,0x30,0xff,0x58,0x48,0x30,0xff,0x48,0x3c,0x28,0xff,0x48,0x3c,0x20,0xff,0x38,0x28,0x10,0x9a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x38,0x28,0x10,0xff,0x40,0x34,0x20,0xff,0x40,0x38,0x28,0xff,0x48,0x3c,0x28,0xff,0x40,0x38,0x20,0xff,0x50,0x44,0x30,0xff,0x88,0x84,0x80,0xff, 0x88,0x88,0x80,0xff,0x90,0x8c,0x88,0xff,0x98,0x90,0x88,0xff,0x80,0x78,0x68,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x30,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff, 0x58,0x4c,0x38,0xff,0x88,0x84,0x80,0xff,0x90,0x88,0x80,0xff,0x98,0x90,0x88,0xff,0x98,0x98,0x90,0xff,0xa8,0xa0,0x98,0xff,0xa8,0xa0,0x98,0xff,0x70,0x68,0x58,0xff,0x50,0x48,0x30,0xff,0x50,0x48,0x30,0xff,0x50,0x48,0x30,0xff,0x48,0x40,0x28,0xff,0x48,0x3c,0x28,0xff,0x38,0x28,0x10,0xa6,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x38,0x28,0x10,0xf3,0x40,0x38,0x20,0xff,0x40,0x3c,0x28,0xff,0x48,0x3c,0x28,0xff,0x40,0x38,0x28,0xff,0x58,0x50,0x40,0xff,0x88,0x84,0x80,0xff,0x90,0x8c,0x80,0xff,0x90,0x90,0x88,0xff,0x98,0x94,0x90,0xff,0x68,0x60,0x50,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff, 0x28,0x1c,0x08,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x70,0x64,0x58,0xff,0x80,0x84,0x78,0xff,0x90,0x8c,0x88,0xff,0x90,0x90,0x88,0xff,0xa0,0x98,0x90,0xff,0xa8,0xa0,0x98,0xff,0x90,0x8c,0x80,0xff,0x50,0x4c,0x30,0xff, 0x58,0x4c,0x30,0xff,0x58,0x4c,0x38,0xff,0x58,0x48,0x30,0xff,0x48,0x40,0x28,0xff,0x48,0x3c,0x20,0xff,0x38,0x28,0x10,0x9e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x38,0x28,0x10,0xe3,0x40,0x34,0x20,0xff,0x40,0x3c,0x28,0xff,0x48,0x40,0x28,0xff,0x48,0x38,0x28,0xff,0x58,0x54,0x40,0xff,0x88,0x88,0x80,0xff, 0x90,0x8c,0x88,0xff,0x98,0x90,0x88,0xff,0x98,0x98,0x90,0xff,0x60,0x54,0x40,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x30,0x24,0x10,0xff, 0x80,0x7c,0x78,0xff,0x88,0x80,0x78,0xff,0x90,0x8c,0x80,0xff,0x98,0x94,0x90,0xff,0xa0,0x9c,0x90,0xff,0xa0,0xa0,0x98,0xff,0x68,0x5c,0x48,0xff,0x58,0x48,0x30,0xff,0x50,0x48,0x30,0xff,0x58,0x4c,0x30,0xff,0x50,0x4c,0x30,0xff,0x50,0x40,0x28,0xff,0x48,0x38,0x20,0xff,0x38,0x2c,0x10,0x8e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x38,0x2c,0x10,0xbe,0x38,0x30,0x18,0xff,0x40,0x34,0x20,0xff,0x40,0x38,0x20,0xff,0x48,0x38,0x28,0xff,0x58,0x4c,0x38,0xff,0x88,0x84,0x78,0xff,0x90,0x88,0x80,0xff,0x98,0x90,0x88,0xff,0x98,0x98,0x90,0xff,0x50,0x48,0x38,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x30,0x1c,0x08,0xff,0x28,0x20,0x10,0xff, 0x28,0x20,0x10,0xff,0x30,0x1c,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x50,0x44,0x38,0xff,0x80,0x80,0x78,0xff,0x88,0x80,0x78,0xff,0x88,0x88,0x80,0xff,0x90,0x90,0x88,0xff,0x98,0x98,0x90,0xff,0x90,0x8c,0x80,0xff,0x50,0x40,0x28,0xff,0x50,0x40,0x28,0xff, 0x50,0x40,0x28,0xff,0x48,0x40,0x28,0xff,0x50,0x40,0x28,0xff,0x50,0x40,0x28,0xff,0x40,0x30,0x18,0xff,0x38,0x2c,0x10,0x6d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x38,0x2c,0x10,0x92,0x40,0x30,0x18,0xff,0x48,0x3c,0x28,0xff,0x48,0x40,0x30,0xff,0x48,0x3c,0x28,0xff,0x60,0x54,0x40,0xff,0x88,0x88,0x80,0xff, 0x90,0x8c,0x88,0xff,0x98,0x94,0x88,0xff,0xa0,0x9c,0x90,0xff,0x50,0x44,0x30,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x78,0x70,0x68,0xff, 0x88,0x84,0x78,0xff,0x88,0x84,0x80,0xff,0x90,0x8c,0x88,0xff,0x98,0x94,0x88,0xff,0xa0,0x9c,0x98,0xff,0xa0,0x9c,0x90,0xff,0x50,0x44,0x28,0xff,0x58,0x4c,0x30,0xff,0x58,0x4c,0x38,0xff,0x58,0x48,0x38,0xff,0x58,0x4c,0x30,0xff,0x50,0x44,0x28,0xff,0x38,0x2c,0x18,0xff,0x38,0x2c,0x10,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x38,0x2c,0x10,0x55,0x40,0x2c,0x10,0xff,0x48,0x3c,0x28,0xff,0x48,0x40,0x28,0xff,0x48,0x3c,0x28,0xff,0x58,0x50,0x38,0xff,0x90,0x88,0x80,0xff,0x90,0x90,0x88,0xff,0x98,0x94,0x90,0xff,0xa0,0x98,0x90,0xff,0x50,0x48,0x38,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff, 0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x48,0x40,0x30,0xff,0x88,0x80,0x78,0xff,0x88,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x90,0x90,0x88,0xff,0xa0,0x94,0x90,0xff,0xa8,0xa0,0x98,0xff,0xa8,0xa4,0x98,0xff,0x60,0x54,0x40,0xff,0x58,0x48,0x30,0xff, 0x58,0x4c,0x38,0xff,0x58,0x48,0x30,0xff,0x58,0x48,0x30,0xff,0x48,0x3c,0x28,0xff,0x48,0x40,0x28,0xf7,0x78,0x78,0x78,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x40,0x2c,0x10,0x10,0x40,0x2c,0x10,0xf7,0x40,0x38,0x20,0xff,0x50,0x40,0x30,0xff,0x48,0x38,0x20,0xff,0x58,0x48,0x30,0xff,0x88,0x84,0x80,0xff, 0x90,0x90,0x88,0xff,0xa0,0x98,0x90,0xff,0xa0,0x98,0x90,0xff,0x60,0x54,0x40,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x20,0x08,0xff,0x30,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x08,0xff,0x30,0x20,0x10,0xff,0x78,0x70,0x68,0xff,0x88,0x84,0x78,0xff, 0x88,0x84,0x80,0xff,0x88,0x84,0x80,0xff,0x90,0x90,0x88,0xff,0x98,0x94,0x90,0xff,0x90,0x88,0x78,0xff,0xa8,0xa0,0x98,0xff,0x78,0x70,0x60,0xff,0x58,0x4c,0x30,0xff,0x58,0x48,0x30,0xff,0x58,0x4c,0x38,0xff,0x58,0x4c,0x38,0xff,0x40,0x34,0x18,0xff,0x70,0x68,0x60,0xdf,0x78,0x7c,0x78,0x8e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x30,0x10,0xaa,0x40,0x34,0x18,0xff,0x48,0x40,0x30,0xff,0x48,0x3c,0x28,0xff,0x58,0x48,0x30,0xff,0x80,0x78,0x70,0xff,0x90,0x90,0x88,0xff,0xa0,0x94,0x90,0xff,0xa0,0x9c,0x90,0xff,0x70,0x68,0x58,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff, 0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x58,0x50,0x40,0xff,0x88,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x88,0x88,0x80,0xff,0x90,0x88,0x80,0xff,0x98,0x94,0x88,0xff,0x70,0x6c,0x58,0xff,0x70,0x68,0x58,0xff,0xa8,0xa4,0x98,0xff,0x98,0x94,0x88,0xff,0x58,0x4c,0x38,0xff, 0x58,0x48,0x30,0xff,0x58,0x48,0x30,0xff,0x58,0x48,0x30,0xff,0x50,0x44,0x30,0xff,0x80,0x7c,0x78,0xeb,0x78,0x78,0x78,0x5d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x2c,0x10,0x3c,0x40,0x30,0x10,0xff,0x40,0x34,0x20,0xff,0x48,0x3c,0x28,0xff,0x48,0x40,0x28,0xff,0x68,0x5c,0x48,0xff, 0x90,0x8c,0x80,0xff,0x98,0x94,0x88,0xff,0xa0,0x9c,0x90,0xff,0x88,0x80,0x78,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x1c,0x08,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x40,0x34,0x20,0xff,0x80,0x7c,0x78,0xff,0x88,0x80,0x78,0xff,0x88,0x84,0x78,0xff, 0x88,0x88,0x80,0xff,0x90,0x8c,0x88,0xff,0x78,0x70,0x60,0xff,0x50,0x40,0x28,0xff,0x58,0x48,0x38,0xff,0xa8,0xa0,0x98,0xff,0xa0,0xa0,0x98,0xff,0x68,0x60,0x50,0xff,0x50,0x44,0x28,0xff,0x50,0x40,0x28,0xff,0x50,0x44,0x30,0xff,0x80,0x78,0x70,0xf7,0x78,0x7c,0x78,0xdf,0x78,0x7c,0x78,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x30,0x10,0xba,0x40,0x30,0x18,0xff,0x48,0x38,0x20,0xff,0x50,0x44,0x30,0xff,0x58,0x4c,0x38,0xff,0x90,0x8c,0x80,0xff,0xa0,0x98,0x90,0xff,0xa0,0x9c,0x90,0xff,0xa8,0xa0,0x98,0xff,0x40,0x34,0x20,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x30,0x1c,0x10,0xff, 0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x30,0x20,0x10,0xff,0x38,0x2c,0x18,0xff,0x80,0x74,0x68,0xff,0x88,0x80,0x80,0xff,0x88,0x84,0x80,0xff,0x88,0x88,0x80,0xff,0x90,0x8c,0x88,0xff,0x78,0x70,0x60,0xff,0x58,0x48,0x30,0xff,0x50,0x48,0x30,0xff,0x58,0x48,0x30,0xff,0x98,0x90,0x88,0xff,0xa0,0x9c,0x98,0xff,0xa0,0x98,0x90,0xff, 0x70,0x68,0x58,0xff,0x70,0x6c,0x60,0xff,0x80,0x80,0x70,0xff,0x80,0x80,0x80,0xef,0x80,0x7c,0x80,0x96,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x30,0x10,0x2c,0x40,0x30,0x10,0xfb,0x48,0x34,0x18,0xff,0x50,0x44,0x30,0xff,0x58,0x48,0x30,0xff, 0x70,0x64,0x50,0xff,0x98,0x94,0x90,0xff,0xa0,0x9c,0x90,0xff,0xa8,0xa4,0x98,0xff,0x88,0x80,0x70,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x10,0xff,0x28,0x20,0x08,0xff,0x28,0x1c,0x10,0xff,0x28,0x20,0x10,0xff,0x38,0x30,0x20,0xff,0x80,0x78,0x70,0xff,0x88,0x80,0x78,0xff,0x88,0x84,0x80,0xff,0x88,0x88,0x80,0xff,0x90,0x8c,0x80,0xff, 0x78,0x6c,0x60,0xff,0x50,0x44,0x28,0xff,0x58,0x48,0x30,0xff,0x50,0x48,0x30,0xff,0x50,0x48,0x30,0xff,0x78,0x70,0x60,0xff,0xa0,0x9c,0x90,0xff,0xa0,0x98,0x90,0xff,0x98,0x98,0x90,0xff,0x90,0x8c,0x80,0xff,0x88,0x84,0x80,0xf7,0x88,0x84,0x80,0xdb,0x80,0x80,0x80,0x1c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x30,0x18,0x79,0x40,0x30,0x10,0xff,0x50,0x40,0x28,0xff,0x58,0x48,0x30,0xff,0x58,0x4c,0x30,0xff,0x78,0x70,0x60,0xff,0xa0,0x98,0x90,0xff,0xa8,0xa0,0x98,0xff,0xa8,0xa4,0x98,0xff,0x80,0x78,0x68,0xff,0x38,0x2c,0x18,0xff,0x28,0x20,0x10,0xff, 0x38,0x28,0x18,0xff,0x68,0x58,0x48,0xff,0x88,0x84,0x78,0xff,0x88,0x84,0x78,0xff,0x88,0x84,0x78,0xff,0x88,0x88,0x80,0xff,0x88,0x80,0x78,0xff,0x68,0x5c,0x48,0xff,0x58,0x4c,0x30,0xff,0x50,0x44,0x28,0xff,0x58,0x4c,0x38,0xff,0x58,0x48,0x30,0xff,0x58,0x48,0x30,0xff,0x60,0x54,0x40,0xff,0x98,0x94,0x90,0xff,0x98,0x98,0x90,0xff, 0x98,0x90,0x88,0xff,0x90,0x8c,0x80,0xfb,0x88,0x88,0x88,0xe7,0x88,0x88,0x88,0x59,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x34,0x10,0x00,0x48,0x34,0x10,0xb2,0x40,0x30,0x18,0xff,0x50,0x40,0x28,0xff, 0x58,0x48,0x30,0xff,0x58,0x4c,0x38,0xff,0x68,0x5c,0x48,0xff,0x98,0x94,0x88,0xff,0xa8,0xa4,0x98,0xff,0xa8,0xa4,0x98,0xff,0xa8,0xa0,0x98,0xff,0x98,0x90,0x88,0xff,0x98,0x90,0x88,0xff,0x90,0x8c,0x80,0xff,0x90,0x88,0x80,0xff,0x88,0x88,0x80,0xff,0x80,0x78,0x70,0xff,0x70,0x64,0x50,0xff,0x60,0x4c,0x38,0xff,0x58,0x4c,0x38,0xff, 0x58,0x4c,0x30,0xff,0x50,0x44,0x28,0xff,0x58,0x48,0x38,0xff,0x58,0x4c,0x30,0xff,0x58,0x4c,0x30,0xff,0x58,0x48,0x30,0xff,0x70,0x6c,0x58,0xff,0x98,0x90,0x88,0xff,0x90,0x8c,0x80,0xff,0x90,0x8c,0x88,0xeb,0x90,0x8c,0x90,0x6d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x30,0x10,0x08,0x40,0x34,0x10,0xc7,0x40,0x34,0x18,0xff,0x48,0x3c,0x20,0xff,0x50,0x44,0x28,0xff,0x58,0x48,0x28,0xff,0x58,0x48,0x30,0xff,0x68,0x5c,0x48,0xff,0x80,0x70,0x60,0xff,0x88,0x7c,0x70,0xff,0x88,0x7c,0x68,0xff, 0x80,0x78,0x68,0xff,0x78,0x70,0x60,0xff,0x70,0x64,0x50,0xff,0x60,0x50,0x38,0xff,0x58,0x48,0x30,0xff,0x58,0x48,0x28,0xff,0x58,0x44,0x28,0xff,0x58,0x44,0x28,0xff,0x50,0x44,0x28,0xff,0x50,0x44,0x28,0xff,0x50,0x40,0x28,0xff,0x50,0x40,0x30,0xff,0x50,0x44,0x28,0xff,0x50,0x40,0x28,0xff,0x48,0x3c,0x20,0xff,0x68,0x5c,0x48,0xff, 0x80,0x78,0x68,0xc3,0x90,0x90,0x90,0x3c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x34,0x10,0x10,0x48,0x30,0x10,0xba, 0x48,0x34,0x18,0xff,0x50,0x3c,0x20,0xff,0x50,0x40,0x28,0xff,0x60,0x50,0x38,0xff,0x60,0x50,0x38,0xff,0x60,0x50,0x38,0xff,0x60,0x54,0x38,0xff,0x58,0x48,0x28,0xff,0x60,0x50,0x38,0xff,0x60,0x50,0x38,0xff,0x60,0x54,0x38,0xff,0x60,0x50,0x38,0xff,0x58,0x48,0x28,0xff,0x58,0x50,0x38,0xff,0x60,0x50,0x38,0xff,0x58,0x4c,0x38,0xff, 0x60,0x4c,0x38,0xff,0x50,0x44,0x28,0xff,0x58,0x48,0x38,0xff,0x58,0x4c,0x30,0xff,0x58,0x48,0x30,0xff,0x48,0x38,0x20,0xff,0x48,0x34,0x10,0xff,0x48,0x30,0x10,0x71,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x34,0x18,0x04,0x48,0x34,0x10,0x8e,0x40,0x34,0x10,0xff,0x48,0x34,0x18,0xff,0x50,0x44,0x28,0xff,0x60,0x4c,0x30,0xff,0x60,0x50,0x38,0xff,0x60,0x54,0x38,0xff,0x58,0x48,0x28,0xff, 0x60,0x54,0x38,0xff,0x60,0x54,0x38,0xff,0x60,0x54,0x38,0xff,0x60,0x50,0x38,0xff,0x58,0x48,0x28,0xff,0x60,0x50,0x38,0xff,0x60,0x50,0x38,0xff,0x58,0x4c,0x38,0xff,0x60,0x4c,0x30,0xff,0x50,0x44,0x28,0xff,0x58,0x48,0x30,0xff,0x50,0x40,0x20,0xff,0x48,0x34,0x18,0xff,0x48,0x34,0x10,0xeb,0x40,0x34,0x10,0x4d,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x48,0x34,0x10,0x41,0x48,0x34,0x10,0xd3,0x48,0x34,0x10,0xff,0x48,0x38,0x18,0xff,0x50,0x40,0x20,0xff,0x60,0x4c,0x30,0xff,0x58,0x48,0x30,0xff,0x60,0x50,0x38,0xff,0x60,0x54,0x38,0xff,0x60,0x50,0x38,0xff,0x60,0x54,0x38,0xff,0x58,0x48,0x28,0xff,0x60,0x50,0x38,0xff,0x60,0x50,0x38,0xff,0x58,0x50,0x30,0xff, 0x58,0x48,0x30,0xff,0x50,0x38,0x20,0xff,0x48,0x34,0x18,0xff,0x48,0x34,0x10,0xff,0x48,0x34,0x18,0xa6,0x48,0x34,0x18,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x34,0x18,0x04,0x48,0x34,0x10,0x61,0x48,0x34,0x10,0xcf,0x48,0x34,0x18,0xff,0x48,0x34,0x10,0xff,0x48,0x38,0x18,0xff, 0x50,0x3c,0x20,0xff,0x50,0x40,0x20,0xff,0x58,0x44,0x28,0xff,0x50,0x44,0x28,0xff,0x50,0x3c,0x20,0xff,0x50,0x40,0x20,0xff,0x48,0x3c,0x20,0xff,0x48,0x34,0x18,0xff,0x48,0x34,0x10,0xff,0x48,0x34,0x18,0xfb,0x48,0x34,0x10,0xae,0x48,0x34,0x10,0x38,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x34,0x18,0x34,0x48,0x34,0x10,0x7d,0x48,0x34,0x10,0xbe,0x48,0x34,0x18,0xef,0x48,0x34,0x10,0xff,0x48,0x34,0x10,0xff,0x48,0x34,0x10,0xff,0x48,0x34,0x10,0xff,0x48,0x34,0x10,0xff,0x48,0x34,0x18,0xdf,0x48,0x34,0x10,0xaa, 0x48,0x34,0x10,0x65,0x48,0x34,0x10,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x48,0x34,0x18,0x0c,0x48,0x34,0x10,0x20,0x48,0x34,0x18,0x20,0x48,0x34,0x18,0x18,0x48,0x34,0x10,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
250.953488
320
0.797146
ramkumarkoppu
831cdbbdec94c1b39855143515fe2e3bb97ba6ca
76,056
cpp
C++
src/ui95/chandler.cpp
Terebinth/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
117
2015-01-13T14:48:49.000Z
2022-03-16T01:38:19.000Z
src/ui95/chandler.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
4
2015-05-01T13:09:53.000Z
2017-07-22T09:11:06.000Z
src/ui95/chandler.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
78
2015-01-13T09:27:47.000Z
2022-03-18T14:39:09.000Z
#include <cISO646> #include <windows.h> #include <process.h> #include "dispcfg.h" #include "chandler.h" #include "sim/include/ascii.h" // OW needed for restoring textures after task switch #include "graphics/include/texbank.h" #include "graphics/include/fartex.h" #include "graphics/include/terrtex.h" #define UI_ABS(x) (((x) < 0)? -(x):(x)) long _LOAD_ART_RESOURCES_ = 1; // Take Screenshot HACK stuff long gUI_TakeScreenShot = 0; // MN 020104 always allow UI screenshots long gScreenShotEnabled = 1; WORD *gScreenShotBuffer = NULL; void SaveScreenShot(); // OW 11-08-2000 extern bool g_bCheckBltStatusBeforeFlip; // M.N. 2001-11-13 extern bool g_bHiResUI; extern void Transmit(int com); extern int gameCompressionRatio; extern int g_nMaxUIRefresh; // 2002-02-23 S.G. extern WORD RGB8toRGB565(DWORD);//XX extern DWORD RGB565toRGB8(WORD sc); extern C_Handler *gMainHandler; C_Handler::C_Handler() { UI_Critical = NULL; MouseCallback_ = NULL; Root_ = NULL; // Root pointer to windows in handler AppWindow_ = NULL; Primary_ = NULL; // primary surface pointer Front_ = NULL; // Surface to blit to FrontRect_.left = 0; FrontRect_.top = 0; FrontRect_.right = 0; FrontRect_.bottom = 0; // PrimaryRect_.left=0; // PrimaryRect_.top=0; // PrimaryRect_.right=0; // PrimaryRect_.bottom=0; surface_.mem = NULL; surface_.width = 0; surface_.height = 0; MouseDown_ = 0; MouseDownTime_ = 0; LastUp_ = 0; LastUpTime_ = 0; DoubleClickTime_ = GetDoubleClickTime(); TimerLoop_ = 0; ControlLoop_ = 0; OutputLoop_ = 0; OutputWait_ = 80; TimerSleep_ = 1; ControlSleep_ = 1; TimerThread_ = 0; ControlThread_ = 0; OutputThread_ = 0; WakeOutput_ = NULL; WakeControl_ = NULL; memset(&Grab_, 0, sizeof(GRABBER)); memset(&Drag_, 0, sizeof(GRABBER)); OverControl_ = NULL; OverLast_.Control_ = NULL; OverLast_.Tip_ = NULL; OverLast_.Time_ = 0; OverLast_.HelpFont_ = 17; OverLast_.HelpOn_ = 0; MouseControl_ = NULL; CurWindow_ = NULL; UpdateFlag = 0; HandlingMessage = 0; UserRoot_ = NULL; KeyboardMode_ = FALSE; DrawFlags = 0; } C_Handler::~C_Handler() { if (Root_) Cleanup(); } void C_Handler::EnterCritical() { F4EnterCriticalSection(UI_Critical); } void C_Handler::LeaveCritical() { F4LeaveCriticalSection(UI_Critical); } static ImageBuffer *m_pMouseImage; RECT m_rcMouseImage; void C_Handler::Setup(HWND hwnd, ImageBuffer *, ImageBuffer *Primary) { Primary_ = Primary; // PrimaryRect_=PrimaryRect; AppWindow_ = hwnd; int dispXres = 800, dispYres = 600; if (g_bHiResUI) { dispXres = 1024; dispYres = 768; } // OW V2 #if 1 if (FalconDisplay.displayFullScreen) { // OW 11-08-2000 #if 0 Front_ = Primary_; #else Front_ = new ImageBuffer; BOOL bResult; if (FalconDisplay.theDisplayDevice.IsHardware()) bResult = Front_->Setup(&FalconDisplay.theDisplayDevice, dispXres, dispYres, VideoMem, None, FALSE); else bResult = Front_->Setup(&FalconDisplay.theDisplayDevice, dispXres, dispYres, SystemMem, None, FALSE); #endif // OW now handled by running in software mode on V1 and V2 #if 0 // OW FIXME: hack export a function from device or somewhere DXContext *pCtx = FalconDisplay.theDisplayDevice.GetDefaultRC(); if ( not (pCtx->m_pcapsDD->dwCaps2 bitand DDCAPS2_CANRENDERWINDOWED)) { int nWidth = 16; int nHeight = 16; m_rcMouseImage.left = 0; m_rcMouseImage.top = 0; m_rcMouseImage.bottom = nWidth; m_rcMouseImage.right = nHeight; // prolly voodoo 1 or 2 m_pMouseImage = new ImageBuffer; if (m_pMouseImage->Setup(&FalconDisplay.theDisplayDevice, nWidth, nHeight, SystemMem, None, AppWindow_, FALSE, FALSE)) { WORD *pSurface = (WORD *) m_pMouseImage->Lock(); int nStride = m_pMouseImage->targetStride() / m_pMouseImage->PixelSize(); int nHeight = m_pMouseImage->targetYres(); ShiAssert(pSurface); if (pSurface) { static WORD cursorImage[16][16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xffff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; memcpy(pSurface, cursorImage, 256 * 2); m_pMouseImage->Unlock(); m_pMouseImage->SetChromaKey(0); } } } #endif } //windowed else { Front_ = new ImageBuffer; BOOL bResult; if (FalconDisplay.theDisplayDevice.IsHardware()) bResult = Front_->Setup(&FalconDisplay.theDisplayDevice, dispXres, dispYres, VideoMem, None, FALSE); else bResult = Front_->Setup(&FalconDisplay.theDisplayDevice, dispXres, dispYres, SystemMem, None, FALSE); if ( not bResult) { MonoPrint("Can't create back surface for UI\n"); Front_ = Primary_; } } #else Front_ = new ImageBuffer; BOOL bResult; if (FalconDisplay.theDisplayDevice.IsHardware()) bResult = Front_->Setup(&FalconDisplay.theDisplayDevice, 800, 600, VideoMem, None, FALSE); else bResult = Front_->Setup(&FalconDisplay.theDisplayDevice, 800, 600, SystemMem, None, FALSE); if ( not bResult) { MonoPrint("Can't create back surface for UI\n"); Front_ = Primary_; } #endif // OW - WM_MOVE does not get sent to the app in response to SetWindowPos if ( not FalconDisplay.displayFullScreen) { RECT dest; GetClientRect(hwnd, &dest); ClientToScreen(hwnd, (LPPOINT)&dest); ClientToScreen(hwnd, (LPPOINT)&dest + 1); if (Primary_ and Primary_->frontSurface()) { Primary_->UpdateFrontWindowRect(&dest); } InvalidateRect(hwnd, &dest, FALSE); } // This will be correct UNLESS the work surface is a FLIPPING backbuffer of the primary // AND the application is running in a window. Not likly... // By the way, this means this rect could really go away entirely... FrontRect_.top = 0;; FrontRect_.left = 0;; FrontRect_.bottom = Front_->targetYres(); FrontRect_.right = Front_->targetXres(); Root_ = NULL; rectcount_ = 0; UI_Critical = F4CreateCriticalSection("UI_Critical"); StartOutputThread(); StartControlThread(80); } void C_Handler::Cleanup() { WHLIST *cur, *prev; CBLIST *cbs, *last; // Make ALL winders invisible so they won't draw cur = Root_; while (cur) { cur->Flags and_eq compl C_BIT_ENABLED; cur = cur->Next; } // Kill the threads EndControlThread(); EndOutputThread(); EndTimerThread(); EnterCritical(); cur = Root_; while (cur) { prev = cur; cur = cur->Next; if (prev->Flags bitand C_BIT_REMOVE) { prev->win->Cleanup(); delete prev->win; } delete prev; } Root_ = NULL; cbs = UserRoot_; while (cbs) { last = cbs; cbs = cbs->Next; delete last; } UserRoot_ = NULL; if (Front_ and Front_ not_eq Primary_) { Front_->Cleanup(); delete Front_; } Primary_ = NULL; Front_ = NULL; if (m_pMouseImage) { m_pMouseImage->Cleanup(); delete m_pMouseImage; m_pMouseImage = NULL; } LeaveCritical(); F4DestroyCriticalSection(UI_Critical); UI_Critical = NULL; // JB 010108 } void *C_Handler::Lock() { if (Front_) { surface_.mem = (WORD *)Front_->Lock(); // surface_.width = (short)Front_->targetXres(); // surface_.width = (short)Front_->targetStride() / Front_->PixelSize(); // OW surface_.height = (short)Front_->targetYres(); // //XX surface_.bpp = Front_->PixelSize() << 3;//bytes->bits surface_.owner = Front_; } return(surface_.mem); } void C_Handler::Unlock() { if (Front_) { Front_->Unlock(); surface_.mem = NULL; surface_.width = 0; surface_.height = 0; //XX surface_.bpp = 0; } } BOOL C_Handler::AddWindow(C_Window *thewin, long Flags) { WHLIST *newwin, *cur; cur = Root_; while (cur) { if (cur->win == thewin) return(FALSE); cur = cur->Next; } newwin = new WHLIST; if (newwin == NULL) return(FALSE); newwin->win = thewin; newwin->Flags = Flags; newwin->Next = NULL; newwin->Prev = NULL; EnterCritical(); if (Root_ == NULL) { Root_ = newwin; } else if (thewin->GetDepth() < Root_->win->GetDepth() and thewin->GetDepth() or (thewin->GetFlags() bitand C_BIT_CANTMOVE and not (Root_->win->GetFlags() bitand C_BIT_CANTMOVE))) { newwin->Next = Root_; Root_->Prev = newwin; Root_ = newwin; } else { cur = Root_; while (cur and newwin) { if (thewin->GetDepth() < cur->win->GetDepth() and thewin->GetDepth() or (thewin->GetFlags() bitand C_BIT_CANTMOVE and not (cur->win->GetFlags() bitand C_BIT_CANTMOVE))) { newwin->Next = cur; newwin->Prev = cur->Prev; newwin->Prev->Next = newwin; newwin->Next->Prev = newwin; newwin = NULL; } else if (cur->Next == NULL) { cur->Next = newwin; newwin->Prev = cur; newwin = NULL; } else cur = cur->Next; } } thewin->SetHandler(this); thewin->update_ or_eq C_DRAW_REFRESHALL; thewin->RefreshWindow(); if (thewin->GetFlags() bitand C_BIT_ENABLED) CurWindow_ = thewin; // sfr: before adding window, correct its constraints to screen thewin->ConstraintsCorrection(GetW(), GetH()); LeaveCritical(); return(TRUE); } BOOL C_Handler::ShowWindow(C_Window *thewin) { WHLIST *cur; cur = Root_; while (cur) { if (cur->win == thewin and not (cur->Flags bitand C_BIT_ENABLED)) { cur->win->SetCritical(UI_Critical); cur->Flags or_eq C_BIT_ENABLED; cur->win->update_ = C_DRAW_REFRESHALL; cur->win->RefreshWindow(); cur->win->SetSection(CurrentSection_); return(TRUE); } cur = cur->Next; } return(FALSE); } BOOL C_Handler::HideWindow(C_Window *thewin) { WHLIST *cur; cur = Root_; while (cur) { if (cur->win == thewin and (cur->Flags bitand C_BIT_ENABLED)) { cur->Flags and_eq compl C_BIT_ENABLED; SetBehindWindow(cur->win); cur->win->SetCritical(NULL); if (CurWindow_ == thewin) CurWindow_ = NULL; return(TRUE); } cur = cur->Next; } return(FALSE); } C_Window *C_Handler::FindWindow(long ID) { if (F4IsBadReadPtr(this, sizeof(C_Handler))) // JB 010317 CTD return NULL; WHLIST *cur; cur = Root_; while (cur) { if (cur->win->GetID() == ID) return(cur->win); cur = cur->Next; } return(NULL); } long C_Handler::GetWindowFlags(long ID) { WHLIST *cur; cur = Root_; while (cur) { if (cur->win->GetID() == ID) return(cur->Flags); cur = cur->Next; } return(0); } C_Window *C_Handler::_GetFirstWindow() { EnterCritical(); LeaveCritical(); if (Root_) return(Root_->win); return(NULL); } C_Window *C_Handler::_GetNextWindow(C_Window *win) { WHLIST *cur; EnterCritical(); cur = Root_; while (cur) { if (cur->win == win) { LeaveCritical(); if (cur->Next == NULL) return(NULL); return(cur->Next->win); } cur = cur->Next; } LeaveCritical(); return(NULL); } BOOL C_Handler::RemoveWindow(C_Window *thewin) { WHLIST *cur; EnterCritical(); SetBehindWindow(thewin); thewin->SetCritical(NULL); if (Grab_.Window_ == thewin) { Grab_.Window_ = NULL; Grab_.Control_ = NULL; } if (Drag_.Window_ == thewin) { Drag_.Window_ = NULL; Drag_.Control_ = NULL; } if (thewin == Root_->win) { cur = Root_; Root_ = Root_->Next; Root_->Prev = NULL; delete cur; } else { cur = Root_->Next; while (cur) { if (cur->win == thewin) { if (cur->Prev) cur->Prev->Next = cur->Next; if (cur->Next) cur->Next->Prev = cur->Prev; delete cur; cur = NULL; } else cur = cur->Next; } } if (thewin == CurWindow_) { if (Root_ == NULL) CurWindow_ = NULL; else { cur = Root_; while (cur) { CurWindow_ = cur->win; cur = cur->Next; } } } LeaveCritical(); return(TRUE); } void C_Handler::WindowToFront(C_Window *thewin) // move to end of list { WHLIST *cur, *found; if (Root_ == NULL) return; if (Root_->Next == NULL) return; CurWindow_ = thewin; if (Root_->win == thewin) { if (Root_->Flags bitand C_BIT_CANTMOVE or not (Root_->Flags bitand C_BIT_ENABLED)) return; found = Root_; Root_ = Root_->Next; Root_->Prev = NULL; cur = Root_; while (cur->Next) cur = cur->Next; EnterCritical(); cur->Next = found; found->Next = NULL; found->Prev = cur; LeaveCritical(); } else { cur = Root_; found = NULL; while (cur->Next) { if (cur->Next->win == thewin and found == NULL) { if (cur->Next->Flags bitand C_BIT_CANTMOVE or not (cur->Next->Flags bitand C_BIT_ENABLED)) return; found = cur->Next; if (found->Next) { found->Next->Prev = found->Prev; if (found->Prev) found->Prev->Next = found->Next; } else found = NULL; } cur = cur->Next; } if (found == NULL) return; EnterCritical(); cur->Next = found; found->Prev = cur; found->Next = NULL; LeaveCritical(); } thewin->SetUpdateRect(0, 0, thewin->GetW(), thewin->GetH(), C_BIT_ABSOLUTE, 0); } void C_Handler::HelpOff() { if (OverLast_.HelpOn_) { RefreshAll(&OverLast_.Area_); // Tell windows to refresh this area } OverLast_.HelpOn_ = 0; OverLast_.Control_ = NULL; OverLast_.Time_ = 0; OverLast_.Tip_ = NULL; OverLast_.MouseX_ = 0; OverLast_.MouseY_ = 0; } void C_Handler::CheckHelpText(SCREEN *surface) { C_Fontmgr *font; if (OverLast_.Control_ and OverLast_.Tip_ and GetCurrentTime() > (DWORD)(OverLast_.Time_ + 1000)) { font = gFontList->Find(OverLast_.HelpFont_); if ( not OverLast_.HelpOn_ and font) { OverLast_.HelpOn_ = 1; OverLast_.Area_.left = OverLast_.MouseX_ - font->Width(OverLast_.Tip_) / 2; OverLast_.Area_.top = OverLast_.MouseY_ - font->Height() - 4; if (OverLast_.Area_.left < 0) OverLast_.Area_.left = 0; if (OverLast_.Area_.top < 0) OverLast_.Area_.top = 0; OverLast_.Area_.right = OverLast_.Area_.left + font->Width(OverLast_.Tip_) + 4; OverLast_.Area_.bottom = OverLast_.Area_.top + font->Height() + 4; if (OverLast_.Area_.right > GetW()) { OverLast_.Area_.left -= OverLast_.Area_.right - GetW(); OverLast_.Area_.right = GetW(); } if (OverLast_.Area_.bottom > GetH()) { OverLast_.Area_.top -= OverLast_.Area_.bottom - GetH(); OverLast_.Area_.bottom = GetH(); } } if (font) { Fill(surface, 0xffffff, &OverLast_.Area_); Fill(surface, 0, OverLast_.Area_.left, OverLast_.Area_.top, OverLast_.Area_.right, OverLast_.Area_.top + 1); Fill(surface, 0, OverLast_.Area_.left, OverLast_.Area_.bottom - 1, OverLast_.Area_.right, OverLast_.Area_.bottom); Fill(surface, 0, OverLast_.Area_.left, OverLast_.Area_.top, OverLast_.Area_.left + 1, OverLast_.Area_.bottom); Fill(surface, 0, OverLast_.Area_.right - 1, OverLast_.Area_.top, OverLast_.Area_.right, OverLast_.Area_.bottom); font->Draw(surface, OverLast_.Tip_, 0, OverLast_.Area_.left + 2, OverLast_.Area_.top + 2); SetUpdateRect(&OverLast_.Area_); } } } void C_Handler::CheckTranslucentWindows() { WHLIST *cur, *infront; UI95_RECT src; short i; EnterCritical(); cur = Root_; while (cur) { infront = cur->Next; if (cur->Flags bitand C_BIT_ENABLED) while (infront) { if ((infront->win->GetFlags() bitand C_BIT_TRANSLUCENT) and (infront->win->update_ bitand (C_DRAW_COPYWINDOW bitor C_DRAW_REFRESH bitor C_DRAW_REFRESHALL)) and (infront->Flags bitand C_BIT_ENABLED)) { for (i = 0; i < infront->win->rectcount_; i++) { if (infront->win->rectflag_[i]) { src = infront->win->rectlist_[i]; src.left += infront->win->GetX() - cur->win->GetX(); src.top += infront->win->GetY() - cur->win->GetY(); src.right += infront->win->GetX() - cur->win->GetX(); src.bottom += infront->win->GetY() - cur->win->GetY(); cur->win->SetUpdateRect(src.left, src.top, src.right, src.bottom, C_BIT_ABSOLUTE, 0); } } } infront = infront->Next; } cur = cur->Next; } LeaveCritical(); } enum { _CHR_ClipLeft = 0x01, _CHR_ClipTop = 0x02, _CHR_ClipRight = 0x04, _CHR_ClipBottom = 0x08, _CHR_RemoveAll = _CHR_ClipLeft bitor _CHR_ClipTop bitor _CHR_ClipRight bitor _CHR_ClipBottom, }; BOOL C_Handler::ClipRect(UI95_RECT *src, UI95_RECT *dst, UI95_RECT *ClientArea) { long offset; if (dst->left < ClientArea->left) { offset = ClientArea->left - dst->left; src->left += offset; dst->left += offset; } if (dst->top < ClientArea->top) { offset = ClientArea->top - dst->top; src->top += offset; dst->top += offset; } if (dst->right > ClientArea->right) { offset = dst->right - ClientArea->right; src->right -= offset; dst->right -= offset; } if (dst->bottom > ClientArea->bottom) { offset = dst->bottom - ClientArea->bottom; src->bottom -= offset; dst->bottom -= offset; } if (dst->left < dst->right and dst->top < dst->bottom) return(TRUE); // Draw it return(FALSE); } void C_Handler::SetUpdateRect(UI95_RECT *upd) { short i; if (rectcount_ < 1) { rectlist_[rectcount_] = *upd; rectcount_++; UpdateFlag or_eq C_DRAW_COPYWINDOW; } else if (rectcount_ < HND_MAX_RECTS) { for (i = 0; i < rectcount_; i++) { if (rectlist_[i].left <= upd->left and rectlist_[i].top <= upd->top and rectlist_[i].right > upd->right and rectlist_[i].bottom >= upd->bottom) return; } rectlist_[rectcount_].left = upd->left; rectlist_[rectcount_].top = upd->top; rectlist_[rectcount_].right = upd->right; rectlist_[rectcount_].bottom = upd->bottom; rectcount_++; UpdateFlag or_eq C_DRAW_COPYWINDOW; } else { rectcount_ = 1; rectlist_[0].left = 0; rectlist_[0].top = 0; rectlist_[0].right = GetW(); rectlist_[0].bottom = GetH(); UpdateFlag or_eq C_DRAW_COPYWINDOW; } } void C_Handler::RefreshAll(UI95_RECT *updaterect) { WHLIST *cur; UI95_RECT rect; cur = Root_; while (cur) { if (cur->Flags bitand C_BIT_ENABLED) { rect = *updaterect; rect.left -= cur->win->GetX(); rect.right -= cur->win->GetX(); rect.top -= cur->win->GetY(); rect.bottom -= cur->win->GetY(); if (rect.left < 0) rect.left = 0; if (rect.top < 0) rect.top = 0; if (rect.right > 0 and rect.bottom > 0) cur->win->SetUpdateRect(rect.left, rect.top, rect.right, rect.bottom, C_BIT_ABSOLUTE, 0); } cur = cur->Next; } } void C_Handler::ClearHiddenRects(WHLIST *me) { WHLIST *cur; if (me) { cur = me->Next; while (cur) { if ((cur->Flags bitand C_BIT_ENABLED) and not (cur->win->GetFlags() bitand C_BIT_TRANSLUCENT)) { me->win->ClearUpdateRect(cur->win->GetX() - me->win->GetX(), cur->win->GetY() - me->win->GetY(), cur->win->GetX() + cur->win->GetW() - me->win->GetX(), cur->win->GetY() + cur->win->GetH() - me->win->GetY()); } cur = cur->Next; } } } void C_Handler::ClearAllHiddenRects() { WHLIST *me, *cur; me = Root_; while (me) { if (me->Flags bitand C_BIT_ENABLED) { cur = me->Next; while (cur) { if ((cur->Flags bitand C_BIT_ENABLED) and not (cur->win->GetFlags() bitand C_BIT_TRANSLUCENT)) { me->win->ClearUpdateRect(cur->win->GetX() - me->win->GetX(), cur->win->GetY() - me->win->GetY(), cur->win->GetX() + cur->win->GetW() - me->win->GetX(), cur->win->GetY() + cur->win->GetH() - me->win->GetY()); } cur = cur->Next; } } me = me->Next; } } void C_Handler::Fill(SCREEN *surface, COLORREF Color, long x1, long y1, long x2, long y2) //void C_Handler::Fill(SCREEN *surface,COLORREF Color,short x1,short y1,short x2,short y2) { UI95_RECT dst; dst.left = x1; dst.top = y1; dst.right = x2; dst.bottom = y2; Fill(surface, Color, &dst); } void C_Handler::Fill(SCREEN *surface, COLORREF Color, UI95_RECT *dst) { if (surface->bpp == 32) //XX { long start, i, len; DWORD color; DWORD *dest; dest = (DWORD*) surface->mem; color = RGB565toRGB8(UI95_RGB24Bit(Color)); i = dst->top; len = dst->right - dst->left; start = (dst->top * surface->width + dst->left) * sizeof(DWORD); while (i < dst->bottom) { __asm { mov eax, color mov ecx, len mov edi, dest add edi, start rep stosd }; i++; start += surface->width * sizeof(DWORD); } } else { long start, i, len; WORD color; WORD *dest; dest = surface->mem; color = UI95_RGB24Bit(Color); i = dst->top; len = dst->right - dst->left; start = (dst->top * surface->width + dst->left) * sizeof(WORD); while (i < dst->bottom) { __asm { mov AX, color mov ECX, len mov EDI, dest add EDI, start rep stosw }; i++; start += surface->width * sizeof(WORD); } } } void C_Handler::CheckDrawThrough() { WHLIST *me, *cur; UI95_RECT src; short i; me = Root_; while (me) { if ((me->Flags bitand C_BIT_ENABLED) and (me->win->update_ bitand C_DRAW_REFRESH)) { cur = me->Next; while (cur) { if ((cur->Flags bitand C_BIT_ENABLED) and (cur->win->GetFlags() bitand C_BIT_TRANSLUCENT)) { for (i = 0; i < me->win->rectcount_; i++) { if (me->win->rectflag_[i]) { src = me->win->rectlist_[i]; src.left += (me->win->GetX() - cur->win->GetX()); src.right += (me->win->GetX() - cur->win->GetX()); src.top += (me->win->GetY() - cur->win->GetY()); src.bottom += (me->win->GetY() - cur->win->GetY()); cur->win->SetUpdateRect(src.left, src.top, src.right, src.bottom, C_BIT_ABSOLUTE, 0); } } } cur = cur->Next; } } me = me->Next; } } void C_Handler::Update() { WHLIST *cur; //#if 0 WHLIST *infront; //#endif UI95_RECT src, dst; short i; if ( not (UpdateFlag bitand C_DRAW_REFRESH) or not DrawFlags) return; Lock(); if ( not surface_.mem) return; // CheckDrawThrough(); CheckTranslucentWindows(); // ClearAllHiddenRects(); cur = Root_; while (cur) { if ((cur->Flags bitand C_BIT_ENABLED) and (cur->win->update_ bitand C_DRAW_REFRESH)) { if (cur->win->update_ bitand C_DRAW_REFRESH) { //#if 0 ClearHiddenRects(cur); //#endif cur->win->DrawWindow(&surface_); } if (cur->win->update_ bitand C_DRAW_COPYWINDOW) { for (i = 0; i < cur->win->rectcount_; i++) { if (cur->win->rectflag_[i]) { src = cur->win->rectlist_[i]; dst = src; dst.left += cur->win->GetX(); dst.top += cur->win->GetY(); dst.right += cur->win->GetX(); dst.bottom += cur->win->GetY(); SetUpdateRect(&dst); //#if 0 infront = cur->Next; while (infront) { if (infront->Flags bitand C_BIT_ENABLED and (infront->win->GetFlags() bitand C_BIT_TRANSLUCENT)) infront->win->SetUpdateRect(dst.left - infront->win->GetX(), dst.top - infront->win->GetY(), dst.right - infront->win->GetX(), dst.bottom - infront->win->GetY(), C_BIT_ABSOLUTE, 0); infront = infront->Next; } //#endif } } } cur->win->rectcount_ = 0; cur->win->update_ = 0; } cur = cur->Next; } if (OverLast_.Time_) CheckHelpText(&surface_); if (gScreenShotEnabled and gUI_TakeScreenShot == 1) { // Copy Front_ surface to a secondary buffer int xsize = 800; if (g_bHiResUI) xsize = 1024; //memcpy(gScreenShotBuffer,surface_.mem,surface_.width * surface_.height * sizeof(WORD)); // MN somehow this D3D stuff for surface_.width creates a width of 1024 for an 800x600 UI... if (surface_.bpp == 32)//XX { for (int i = 0; i < xsize * surface_.height; i++) gScreenShotBuffer[i] = RGB8toRGB565(((DWORD*)surface_.mem)[ i ]); } else memcpy(gScreenShotBuffer, surface_.mem, xsize * surface_.height * sizeof(WORD)); gUI_TakeScreenShot = 2; } Unlock(); } void C_Handler::CopyToPrimary() { short i; RECT src, dest; if ( not DrawFlags) return; // OW now handled by running in software mode on V1 and V2 #if 0 if (Primary_ == Front_) { if (FalconDisplay.displayFullScreen and rectcount_ <= 1) { Primary_->SwapBuffers(true); // dont flip, it would interfere with our clipping / update mechanics rectcount_ = 0; UpdateFlag = 0; return; } } #endif // Make sure the drivers isnt buffering any data if (g_bCheckBltStatusBeforeFlip) { while (true) { HRESULT hres = Primary_->frontSurface()->GetBltStatus(DDGBS_ISBLTDONE); if (hres not_eq DDERR_WASSTILLDRAWING) { break; } // Let all the other threads have some CPU. Sleep(0); } } for (i = 0; i < rectcount_; i++) { src.left = rectlist_[i].left; src.top = rectlist_[i].top; src.right = rectlist_[i].right; src.bottom = rectlist_[i].bottom; dest = src; // ImageBuf should handle this... // dest.left+=PrimaryRect_.left; // dest.right+=PrimaryRect_.left; // dest.top+=PrimaryRect_.top; // dest.bottom+=PrimaryRect_.top; // ShowCursor(FALSE); if (src.left < src.right and src.top < src.bottom) Primary_->Compose(Front_, &src, &dest); // ShowCursor(TRUE); // MonoPrint("CopyToPrimary(%1d,%1d,%1d,%1d)\n",dest.left,dest.top,dest.right,dest.bottom); } rectcount_ = 0; UpdateFlag = 0; // MonoPrint("HDNLR->CopyToPrimary() Done\n"); // OW now handled by running in software mode on V1 and V2 #if 0 if (m_pMouseImage) { POINT pt; GetCursorPos(&pt); ScreenToClient(AppWindow_, &pt); // center pt.x -= m_pMouseImage->targetXres() / 2; pt.y -= m_pMouseImage->targetYres() / 2; // clip if (pt.x < 0) pt.x = 0; else if (pt.x > Primary_->targetXres() - m_pMouseImage->targetXres()) pt.x = Primary_->targetXres() - m_pMouseImage->targetXres(); if (pt.y < 0) pt.y = 0; else if (pt.y > Primary_->targetYres() - m_pMouseImage->targetYres()) pt.y = Primary_->targetYres() - m_pMouseImage->targetYres(); m_rcMouseImage.left = pt.x; m_rcMouseImage.top = pt.y; m_rcMouseImage.right = m_rcMouseImage.left + m_pMouseImage->targetXres(); m_rcMouseImage.bottom = m_rcMouseImage.top + m_pMouseImage->targetYres(); RECT rcSrc = { 0, 0, m_pMouseImage->targetXres(), m_pMouseImage->targetYres() }; Primary_->ComposeTransparent(m_pMouseImage, &rcSrc, &m_rcMouseImage); // refresh next time UI95_RECT upme; upme.left = m_rcMouseImage.left; upme.top = m_rcMouseImage.top; upme.right = m_rcMouseImage.right; upme.bottom = m_rcMouseImage.bottom; SetUpdateRect(&upme); } #endif } void C_Handler::UpdateTimerControls(void) { WHLIST *cur; cur = Root_; while (cur) { if (cur->Flags bitand C_BIT_ENABLED) { if (cur->win->UpdateTimerControls()) cur->win->DrawTimerControls(); } cur = cur->Next; } if (UpdateFlag bitand (C_DRAW_REFRESH bitor C_DRAW_REFRESHALL)) SetEvent(WakeOutput_); } void C_Handler::EnableGroup(long ID) { WHLIST *cur; cur = Root_; while (cur) { cur->win->EnableGroup(ID); cur = cur->Next; } } void C_Handler::DisableGroup(long ID) { WHLIST *cur; cur = Root_; while (cur) { cur->win->DisableGroup(ID); cur = cur->Next; } } void C_Handler::EnableWindowGroup(long ID) { WHLIST *cur, *next; EnterCritical(); cur = Root_; while (cur) { if (cur->win->GetGroup() == ID and not (cur->Flags bitand C_BIT_ENABLED)) { ShowWindow(cur->win); if ( not (cur->win->GetFlags() bitand C_BIT_CANTMOVE)) { next = cur->Next; WindowToFront(cur->win); cur->win->SetUpdateRect(0, 0, cur->win->GetW(), cur->win->GetH(), C_BIT_ABSOLUTE, 0); cur = next; continue; } } cur = cur->Next; } LeaveCritical(); } void C_Handler::DisableWindowGroup(long ID) { WHLIST *cur; EnterCritical(); cur = Root_; while (cur) { if (cur->win->GetGroup() == ID and (cur->Flags bitand C_BIT_ENABLED)) HideWindow(cur->win); cur = cur->Next; } LeaveCritical(); } void C_Handler::DisableSection(long ID) { WHLIST *cur; EnterCritical(); cur = Root_; while (cur) { if (cur->win->GetSection() == ID and (cur->Flags bitand C_BIT_ENABLED)) HideWindow(cur->win); cur = cur->Next; } LeaveCritical(); } BOOL C_Handler::AddUserCallback(void (*cb)()) { CBLIST *cur, *newcb; if (cb == NULL) return(FALSE); cur = UserRoot_; while (cur) { if (cur->Callback == cb) return(FALSE); cur = cur->Next; } newcb = new CBLIST; newcb->Callback = cb; newcb->Next = NULL; EnterCritical(); if (UserRoot_ == NULL) { UserRoot_ = newcb; } else { cur = UserRoot_; while (cur->Next) cur = cur->Next; cur->Next = newcb; } LeaveCritical(); return(TRUE); } BOOL C_Handler::RemoveUserCallback(void (*cb)()) { CBLIST *cur, *last; BOOL retval = FALSE; if (cb == NULL or UserRoot_ == NULL) return(FALSE); EnterCritical(); if (UserRoot_->Callback == cb) { SuspendTimer(); last = UserRoot_; UserRoot_ = UserRoot_->Next; delete last; ResumeTimer(); retval = TRUE; } else { cur = UserRoot_; last = UserRoot_; while ((cur) and (cur->Next) and ( not retval)) { if (cur->Next->Callback == cb) { SuspendTimer(); last = cur->Next; cur->Next = cur->Next->Next; delete last; ResumeTimer(); retval = TRUE; } else cur = cur->Next; } } LeaveCritical(); return(retval); } C_Window *C_Handler::GetWindow(short x, short y) { WHLIST *cur; C_Window *overme; overme = NULL; cur = Root_; while (cur) { if (cur->Flags bitand C_BIT_ENABLED) { if (x >= cur->win->GetX() and y >= cur->win->GetY() and x <= (cur->win->GetX() + cur->win->GetW()) and y <= (cur->win->GetY() + cur->win->GetH())) overme = cur->win; if (cur->win->GetType() == C_TYPE_EXCLUSIVE) overme = cur->win; } cur = cur->Next; } return(overme); } void C_Handler::SetBehindWindow(C_Window *thewin) { long x, y, w, h; WHLIST *cur; if (thewin == NULL) return; x = thewin->GetX(); y = thewin->GetY(); w = x + thewin->GetW(); h = y + thewin->GetH(); cur = Root_; while (cur) { if (cur->win not_eq thewin) { if (cur->Flags bitand C_BIT_ENABLED) cur->win->SetUpdateRect(x - cur->win->GetX(), y - cur->win->GetY(), w - cur->win->GetX(), h - cur->win->GetY(), C_BIT_ABSOLUTE, 0); cur = cur->Next; } else cur = NULL; } } void C_Handler::PostTimerMessage() { while (TimerLoop_ > 0) { PostMessage(AppWindow_, FM_TIMER_UPDATE, 0, 0); // JB 020217 Speed up UI refresh when using a higher time acceleration Sleep(TimerSleep_ / min(max(gameCompressionRatio, 1), g_nMaxUIRefresh)); // 2002-02-23 MODIFIED BY S.G. Added the min(... g_nMaxUIRefresh) to prevent the UI to refresh too much and end up running out of resources because it can't keep up } TimerLoop_ = -1; } void C_Handler::DoControlLoop() { while (ControlLoop_ > 0) { WaitForSingleObject(WakeControl_, ControlSleep_); if (ControlLoop_ > 0) { PostMessage(AppWindow_, C_WM_TIMER, 0, 0); EnterCritical(); UpdateTimerControls(); LeaveCritical(); } } ControlLoop_ = -1; } unsigned int __stdcall C_Handler::ControlLoop(void *myself) { #ifdef _MSC_VER // Set the FPU to Truncate _controlfp(_RC_CHOP, MCW_RC); // Set the FPU to 24bit precision _controlfp(_PC_24, MCW_PC); #endif ((C_Handler *)myself)->DoControlLoop(); _endthreadex(0); return (0); } unsigned int __stdcall C_Handler::TimerLoop(void *myself) { #ifdef _MSC_VER // Set the FPU to Truncate _controlfp(_RC_CHOP, MCW_RC); // Set the FPU to 24bit precision _controlfp(_PC_24, MCW_PC); #endif ((C_Handler *)myself)->PostTimerMessage(); _endthreadex(0); return (0); } unsigned int __stdcall C_Handler::OutputLoop(void *myself) { #ifdef _MSC_VER // Set the FPU to Truncate _controlfp(_RC_CHOP, MCW_RC); // Set the FPU to 24bit precision _controlfp(_PC_24, MCW_PC); #endif ((C_Handler *)myself)->DoOutputLoop(); _endthreadex(0); return (0); } void C_Handler::DoOutputLoop() { while (OutputLoop_ > 0) { WaitForSingleObject(WakeOutput_, 40/*OutputWait_*/); if (OutputLoop_ > 0) { // OW DXContext *pCtx = FalconDisplay.theDisplayDevice.GetDefaultRC(); HRESULT hr = pCtx->TestCooperativeLevel(); if (FAILED(hr)) continue; if (hr == S_FALSE) { Primary_->RestoreAll(); TheTextureBank.RestoreAll(); TheTerrTextures.RestoreAll(); TheFarTextures.RestoreAll(); // Surfaces have been restored UI95_RECT upme; upme.left = FrontRect_.left; upme.top = FrontRect_.top; upme.right = FrontRect_.right; upme.bottom = FrontRect_.bottom; rectcount_ = 0; RefreshAll(&upme); } EnterCritical(); if (UpdateFlag bitand C_DRAW_REFRESH) Update(); if (UpdateFlag bitand C_DRAW_COPYWINDOW) CopyToPrimary(); LeaveCritical(); } } OutputLoop_ = -1; } void C_Handler::ProcessUserCallbacks() { CBLIST *cur, *me; EnterCritical(); cur = UserRoot_; while (cur) { me = cur; cur = cur->Next; if (me->Callback) (*me->Callback)(); } LeaveCritical(); } void C_Handler::StartOutputThread() { if (OutputThread_) return; WakeOutput_ = CreateEvent(NULL, FALSE, FALSE, "Awaken Output Thread"); if ( not WakeOutput_) return; OutputLoop_ = 1; OutputThread_ = (HANDLE)_beginthreadex(NULL, 0, OutputLoop, this, 0, &OutputID_); } #pragma auto_inline (off) void C_Handler::EndOutputThread() { if (OutputThread_) { OutputLoop_ = 0; SetEvent(WakeOutput_); // Wait for thread to end while (OutputLoop_ == 0) { Sleep(1); } CloseHandle(OutputThread_); OutputThread_ = 0; } if (WakeOutput_) { CloseHandle(WakeOutput_); WakeOutput_ = NULL; } } #pragma auto_inline (on) void C_Handler::SuspendOutput() { EnterCritical(); if (TimerThread_) { SuspendThread(OutputThread_); } LeaveCritical(); } void C_Handler::ResumeOutput() { EnterCritical(); if (TimerThread_) { ResumeThread(OutputThread_); } LeaveCritical(); } void C_Handler::StartControlThread(long sleeptime) { if (ControlThread_) return; WakeControl_ = CreateEvent(NULL, FALSE, FALSE, "Awaken Control Thread"); if ( not WakeControl_) { return; } ControlLoop_ = 1; ControlSleep_ = sleeptime; ControlThread_ = (HANDLE)_beginthreadex(NULL, 0, ControlLoop, this, 0, &ControlID_); } #pragma auto_inline (off) void C_Handler::EndControlThread() { if (ControlThread_) { ControlLoop_ = 0; SetEvent(WakeControl_); // Wait for thread to end while (ControlLoop_ == 0) Sleep(1); CloseHandle(ControlThread_); ControlThread_ = 0; } if (WakeControl_) { CloseHandle(WakeControl_); WakeControl_ = NULL; } } #pragma auto_inline (on) void C_Handler::SuspendControl() { EnterCritical(); if (TimerThread_) SuspendThread(ControlThread_); LeaveCritical(); } void C_Handler::ResumeControl() { EnterCritical(); if (TimerThread_) ResumeThread(ControlThread_); LeaveCritical(); } void C_Handler::StartTimerThread(long interval) { if (TimerThread_) return; TimerLoop_ = 1; TimerSleep_ = interval; TimerThread_ = (HANDLE)_beginthreadex(NULL, 0, TimerLoop, this, 0, &TimerID_); } #pragma auto_inline (off) void C_Handler::EndTimerThread() { if (TimerThread_) { TimerLoop_ = 0; // Wait for thread to end while (TimerLoop_ == 0) Sleep(1); CloseHandle(TimerThread_); TimerThread_ = 0; } } #pragma auto_inline (on) void C_Handler::SuspendTimer() { if (TimerThread_) SuspendThread(TimerThread_); } void C_Handler::ResumeTimer() { if (TimerThread_) ResumeThread(TimerThread_); } BOOL C_Handler::CheckHotKeys(unsigned char DKScanCode, unsigned char Ascii, unsigned char ShiftStates, long RepeatCount) { WHLIST *cur; cur = Root_; if (cur == NULL) return(FALSE); while (cur->Next) cur = cur->Next; while (cur) { if (cur->Flags bitand C_BIT_ENABLED) if (cur->win->CheckHotKeys(DKScanCode, Ascii, ShiftStates, RepeatCount)) return(TRUE); if (cur->win->GetType() == C_TYPE_EXCLUSIVE) cur = NULL; else cur = cur->Prev; } return(FALSE); } long C_Handler::GetDragX(WORD MouseX) // { long retval = Drag_.ItemX_ + MouseX - Drag_.StartX_; return(retval); } long C_Handler::GetDragY(WORD MouseY) // { long retval = Drag_.ItemY_ + MouseY - Drag_.StartY_; return(retval); } // returns FALSE if NOT grabbing a control BOOL C_Handler::GrabItem(WORD MouseX, WORD MouseY, C_Window *overme, long GrabType) //not BOOL C_Handler::GrabItem(WORD MouseX,WORD MouseY,C_Window *overme,short GrabType) { Grab_.Control_ = overme->GetControl(&Grab_.ID_, MouseX - overme->GetX(), MouseY - overme->GetY()); Grab_.StartX_ = MouseX; Grab_.StartY_ = MouseY; Grab_.GrabType_ = GrabType; if (Grab_.Control_) { Grab_.Window_ = overme; Grab_.Control_->GetItemXY(Grab_.ID_, &Grab_.ItemX_, &Grab_.ItemY_); } else { if (overme->GetFlags() bitand C_BIT_DRAGABLE) { if (MouseX < overme->GetX() or MouseY < overme->GetY() or MouseX > (overme->GetX() + overme->GetW()) or MouseY > (overme->GetY() + overme->GetDragH())) { Grab_.Window_ = NULL; return(FALSE); } Grab_.Window_ = overme; Grab_.ItemX_ = overme->GetX(); Grab_.ItemY_ = overme->GetY(); } return(FALSE); } return(TRUE); } void C_Handler::ReleaseControl(C_Base *control) { if (OverControl_ == control) OverControl_ = NULL; if (OverLast_.Control_ == control) HelpOff(); if (Grab_.Control_ == control) Grab_.Control_ = NULL; if (Drag_.Control_ == control) Drag_.Control_ = NULL; } void C_Handler::StartDrag() { if (Grab_.GrabType_ not_eq C_TYPE_LMOUSEDOWN) return; if (Grab_.Control_) { if (Grab_.Control_->Dragable(Grab_.ID_)) { Drag_ = Grab_; //ShowCursor(FALSE); } } else if (Grab_.Window_) { if (Grab_.Window_->GetFlags() bitand C_BIT_DRAGABLE) { Drag_ = Grab_; //ShowCursor(FALSE); } } } BOOL C_Handler::DragItem(WORD MouseX, WORD MouseY, C_Window *overme) { if (Drag_.GrabType_ not_eq C_TYPE_LMOUSEDOWN) return(FALSE); if (Drag_.Control_) return(Drag_.Control_->Drag(&Drag_, MouseX, MouseY, overme)); else if (Drag_.Window_) return(Drag_.Window_->Drag(&Drag_, MouseX, MouseY, overme)); return(FALSE); } BOOL C_Handler::DropItem(WORD MouseX, WORD MouseY, C_Window *overme) { long relX, relY; // BOOL retval = FALSE; relX = MouseX - overme->GetX(); relY = MouseY - overme->GetY(); if (Drag_.Control_) { retval = Drag_.Control_->Drop(&Drag_, MouseX, MouseY, overme); //ShowCursor(TRUE); } else if (Drag_.Window_) { retval = Drag_.Window_->Drop(&Drag_, MouseX, MouseY, overme); //ShowCursor(TRUE); } Drag_.Control_ = NULL; Drag_.Window_ = NULL; Drag_.GrabType_ = 0; return(retval); } void C_Handler::BlitWindowNow(C_Window *win) { RECT src, dest; if (win == NULL) return; src.left = 0; src.top = 0; src.right = win->GetW(); src.bottom = win->GetH(); dest = src; dest.left += win->GetX(); dest.right += win->GetX(); dest.top += win->GetY(); dest.bottom += win->GetY(); // ImageBuf should handle this... // dest.left+=PrimaryRect_.left; // dest.right+=PrimaryRect_.left; // dest.top+=PrimaryRect_.top; // dest.bottom+=PrimaryRect_.top; Primary_->Compose(win->GetSurface(), &src, &dest); } void C_Handler::PostUpdate() { // UpdateFlag or_eq C_DRAW_UPDATE; // PostMessage(AppWindow_,C_WM_UPDATE,0,0); } void C_Handler::SendUpdate() { // UpdateFlag or_eq C_DRAW_UPDATE; // SendMessage(AppWindow_,C_WM_UPDATE,0,0); } // Check to make sure message post time < 1 second for mouse/keyboard input... if not... ignore it :) BOOL C_Handler::OldInputMessage() { if (GetMessageTime() < EnabledTime_) return(TRUE); return(FALSE); } void C_Handler::DropControl() { Grab_.Control_ = NULL; Grab_.Window_ = NULL; } void C_Handler::RemovingControl(C_Base *control) { // Warn chandler that a control it might be referncing is being deleted if (MouseControl_ == control) { MouseControl_->Refresh(); MouseControl_ = NULL; } if (OverControl_ == control) OverControl_ = NULL; if (Grab_.Control_ == control) { Grab_.Control_ = NULL; Grab_.Window_ = NULL; } if (Drag_.Control_ == control) { Drag_.Control_ = NULL; Drag_.Window_ = NULL; } if (gPopupMgr->AMenuOpened()) { if (gPopupMgr->GetCallingControl() and gPopupMgr->GetCallingControl() == control) gPopupMgr->CloseMenu(); } } long C_Handler::EventHandler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { C_Window *overme; C_Base *OldMouseControl_; WORD MouseX, MouseY; RECT dest; long retval = 1; BOOL ret = TRUE; unsigned char Key; unsigned char Ascii; unsigned char ShiftStates; long Repeat; long MessageType, DblClk; static int InTimer = 0; HandlingMessage = message; switch (message) { // sfr: added mouse wheel case WM_MOUSEWHEEL: { WORD MouseZ; HelpOff(); if (OldInputMessage()) { retval = 0; break; } MessageType = C_TYPE_MOUSEWHEEL; // we have to correct mouse position, since this is relative to screen // lparam is cursor x/y (low hi) POINT p; p.x = LOWORD(lParam); p.y = HIWORD(lParam); ScreenToClient(hwnd, &p); MouseX = (WORD)p.x; MouseY = (WORD)p.y; overme = GetWindow(MouseX, MouseY); if (overme == NULL) { break; } // so we are rolling wheel inside an active window // grab component we are over if ( not GrabItem(MouseX, MouseY, overme, MessageType)) { break; } // wparam is distance rolled/ key modifiers (low hi) // here we found a component. process event // check hi bit of MouseZ, since word is unsigned MouseZ = 1 << ((sizeof(WORD) * 8) - 1); MouseZ and_eq HIWORD(wParam); // here we invert, since positive in mouse wheel // is forward, and forward is up in screen coordinates (neg values) Grab_.Control_->Wheel(MouseZ ? 1 : -1, MouseX, MouseY); ret = TRUE; } break; case WM_LBUTTONDOWN: HelpOff(); if (OldInputMessage()) { retval = 0; break; } MessageType = C_TYPE_LMOUSEDOWN; MouseDown_ = C_TYPE_LMOUSEDOWN; MouseDownTime_ = GetCurrentTime(); MouseX = LOWORD(lParam); MouseY = HIWORD(lParam); overme = GetWindow(MouseX, MouseY); if (overme == NULL) { retval = 0; break; } if (CurWindow_ and CurWindow_ not_eq overme) { CurWindow_->Deactivate(); overme->Activate(); } CurWindow_ = overme; if (gPopupMgr->AMenuOpened() and not overme->IsMenu()) gPopupMgr->CloseMenu(); if (Dragging()) { DropItem(MouseX, MouseY, overme); } if (GrabItem(MouseX, MouseY, overme, MessageType)) { if (MouseCallback_) { ret = (*MouseCallback_)(Grab_.Control_, MouseX, MouseY, overme, (short)MessageType); // } else { ret = TRUE; } if (ret) { overme->SetControl(Grab_.ID_); WindowToFront(overme); Grab_.Control_->Process(Grab_.ID_, (short)MessageType); // } } else { overme->DeactivateControl(); if (MouseCallback_) ret = (*MouseCallback_)(NULL, MouseX, MouseY, overme, (short)MessageType); // if (ret) WindowToFront(overme); } retval = 0; break; case WM_LBUTTONUP: if (OldInputMessage()) { retval = 0; break; } MouseDown_ = 0; MouseX = LOWORD(lParam); MouseY = HIWORD(lParam); overme = GetWindow(MouseX, MouseY); if (overme == NULL) { retval = 0; break; } if (LastUp_ == C_TYPE_LMOUSEUP and (GetMessageTime() - LastUpTime_) < DoubleClickTime_) DblClk = C_TYPE_LMOUSEDBLCLK; else DblClk = 0; MessageType = C_TYPE_LMOUSEUP; LastUp_ = MessageType; LastUpTime_ = GetMessageTime(); if (Dragging()) { DropItem(MouseX, MouseY, overme); MessageType = C_TYPE_LDROP; } if (Grab_.Control_) { if (this not_eq gMainHandler) { ret = TRUE; } if (MouseCallback_ and Grab_.Control_) { ret = (*MouseCallback_)(Grab_.Control_, MouseX, MouseY, overme, (short)MessageType); // } else { ret = TRUE; } if (this not_eq gMainHandler) { ret = TRUE; } if (ret and Grab_.Control_) { if (Grab_.Control_->GetFlags() bitand C_BIT_ABSOLUTE) { Grab_.Control_->SetRelXY( MouseX - Grab_.Window_->GetX() - Grab_.Control_->GetX(), MouseY - Grab_.Window_->GetY() - Grab_.Control_->GetY() ); } else { Grab_.Control_->SetRelXY( MouseX - Grab_.Window_->GetX() - Grab_.Window_->ClientArea_[Grab_.Control_->GetClient()].left - Grab_.Control_->GetX(), MouseY - Grab_.Window_->GetY() - Grab_.Window_->ClientArea_[Grab_.Control_->GetClient()].top - Grab_.Control_->GetY() ); } Grab_.Control_->Process(Grab_.ID_, (short)MessageType); // if (DblClk and Grab_.Control_) { Grab_.Control_->Process(Grab_.ID_, (short)DblClk); // } } if (this not_eq gMainHandler) { ret = TRUE; } Grab_.Control_ = NULL; Grab_.Window_ = NULL; } else { overme->DeactivateControl(); if (MouseCallback_) { ret = (*MouseCallback_)(NULL, MouseX, MouseY, overme, (short)MessageType); // } if (ret) { WindowToFront(overme); } if (MouseX < overme->GetX() or MouseY < overme->GetY() or MouseX > (overme->GetX() + overme->GetW()) or MouseY > (overme->GetY() + overme->GetH())) { if (overme->GetOwner()) { if (overme->GetOwner()->CloseWindow()) { overme = NULL; } } } Grab_.Window_ = NULL; } overme = GetWindow(MouseX, MouseY); if (overme) { OverControl_ = overme->MouseOver(MouseX - overme->GetX(), MouseY - overme->GetY(), OverControl_); if (OverLast_.Control_ not_eq OverControl_) { HelpOff(); OverLast_.Control_ = OverControl_; if (OverControl_) { OverLast_.Time_ = GetCurrentTime(); OverLast_.Tip_ = gStringMgr->GetString(OverControl_->GetHelpText()); OverLast_.MouseX_ = MouseX; OverLast_.MouseY_ = MouseY; } } } retval = 0; break; case WM_LBUTTONDBLCLK: break; HelpOff(); if (OldInputMessage()) { retval = 0; break; } MouseX = LOWORD(lParam); MouseY = HIWORD(lParam); overme = GetWindow(MouseX, MouseY); if (overme == NULL) { retval = 0; break; } CurWindow_ = overme; if (Dragging()) DropItem(MouseX, MouseY, overme); if (GrabItem(MouseX, MouseY, overme, C_TYPE_LMOUSEDBLCLK)) { if (MouseCallback_) ret = (*MouseCallback_)(Grab_.Control_, MouseX, MouseY, overme, C_TYPE_LMOUSEDBLCLK); else ret = TRUE; if (ret) { overme->SetControl(Grab_.ID_); WindowToFront(overme); Grab_.Control_->Process(Grab_.ID_, C_TYPE_LMOUSEDBLCLK); } } else { if (MouseCallback_) ret = (*MouseCallback_)(NULL, MouseX, MouseY, overme, C_TYPE_LMOUSEDBLCLK); else ret = TRUE; if (ret) WindowToFront(overme); Grab_.Window_ = NULL; } retval = 0; break; case WM_MOUSEMOVE: HelpOff(); if (OldInputMessage()) { retval = 0; break; } MessageType = C_TYPE_MOUSEMOVE; LastUp_ = 0; LastUpTime_ = 0; OldMouseControl_ = MouseControl_; MouseX = LOWORD(lParam); MouseY = HIWORD(lParam); overme = GetWindow(MouseX, MouseY); if (overme == NULL) { if (OldMouseControl_ and OldMouseControl_->GetFlags() bitand C_BIT_MOUSEOVER) { OldMouseControl_->SetMouseOver(0); OldMouseControl_->Refresh(); } retval = 0; break; } if ( not Dragging() and (Grab_.Control_ or Grab_.Window_) and Grab_.GrabType_ == C_TYPE_LMOUSEDOWN) StartDrag(); if (Dragging()) { if (DragItem(MouseX, MouseY, overme) and Drag_.Control_) Drag_.Window_->RefreshWindow(); OverControl_ = NULL; if (Drag_.Control_) { if (Drag_.Control_->GetDragCursorID()) SetCursor(gCursors[Drag_.Control_->GetDragCursorID()]); else if (Drag_.Control_->GetCursorID()) SetCursor(gCursors[Drag_.Control_->GetCursorID()]); else SetCursor(gCursors[overme->GetCursorID()]); } else SetCursor(gCursors[overme->GetCursorID()]); } else if (MouseDown_) { if (Grab_.Control_ and Grab_.Window_) { if (Grab_.Control_->GetFlags() bitand C_BIT_ABSOLUTE) Grab_.Control_->SetRelXY(MouseX - Grab_.Window_->GetX() - Grab_.Control_->GetX(), MouseY - Grab_.Window_->GetY() - Grab_.Control_->GetY()); else Grab_.Control_->SetRelXY(MouseX - Grab_.Window_->GetX() - Grab_.Window_->ClientArea_[Grab_.Control_->GetClient()].left - Grab_.Control_->GetX(), MouseY - Grab_.Window_->GetY() - Grab_.Window_->ClientArea_[Grab_.Control_->GetClient()].top - Grab_.Control_->GetY()); } OverControl_ = NULL; } else { MouseControl_ = overme->MouseOver(MouseX - overme->GetX(), MouseY - overme->GetY(), OldMouseControl_); if (OldMouseControl_ and MouseControl_ not_eq OldMouseControl_ and OldMouseControl_->GetFlags() bitand C_BIT_MOUSEOVER) { OldMouseControl_->SetMouseOver(0); OldMouseControl_->Refresh(); } if (MouseControl_ and MouseControl_ not_eq OldMouseControl_ and MouseControl_->GetFlags() bitand C_BIT_MOUSEOVER) { MouseControl_->SetMouseOver(1); MouseControl_->Refresh(); } OverControl_ = MouseControl_; if (OverControl_) { if (OverControl_->GetCursorID()) SetCursor(gCursors[OverControl_->GetCursorID()]); else SetCursor(gCursors[overme->GetCursorID()]); } else { SetCursor(gCursors[overme->GetCursorID()]); } } if (OverLast_.Control_ not_eq OverControl_) { HelpOff(); OverLast_.Control_ = OverControl_; if (OverControl_) { OverLast_.Time_ = GetCurrentTime(); OverLast_.Tip_ = gStringMgr->GetString(OverControl_->GetHelpText()); OverLast_.MouseX_ = MouseX; OverLast_.MouseY_ = MouseY; } } if (MouseCallback_) (*MouseCallback_)(NULL, MouseX, MouseY, overme, (short)MessageType); // retval = 0; break; case WM_RBUTTONDOWN: HelpOff(); if (OldInputMessage()) { retval = 0; break; } MessageType = C_TYPE_RMOUSEDOWN; MouseX = LOWORD(lParam); MouseY = HIWORD(lParam); overme = GetWindow(MouseX, MouseY); if (overme == NULL) { retval = 0; break; } if (CurWindow_ and CurWindow_ not_eq overme) { CurWindow_->Deactivate(); overme->Activate(); } CurWindow_ = overme; if (Dragging()) DropItem(MouseX, MouseY, overme); if (GrabItem(MouseX, MouseY, overme, MessageType)) { if (MouseCallback_) ret = (*MouseCallback_)(Grab_.Control_, MouseX, MouseY, overme, (short)MessageType); // else ret = TRUE; if (ret) { overme->SetControl(Grab_.ID_); WindowToFront(overme); Grab_.Control_->Process(Grab_.ID_, (short)MessageType); // } } else { overme->DeactivateControl(); if (MouseCallback_) ret = (*MouseCallback_)(NULL, MouseX, MouseY, overme, (short)MessageType); // else ret = TRUE; // if(ret) // WindowToFront(overme); Grab_.Window_ = NULL; } retval = 0; break; case WM_RBUTTONUP: if (OldInputMessage()) { retval = 0; break; } if (LastUp_ == C_TYPE_RMOUSEUP and (GetMessageTime() - LastUpTime_) < DoubleClickTime_) DblClk = C_TYPE_RMOUSEDBLCLK; else DblClk = 0; MessageType = C_TYPE_RMOUSEUP; LastUp_ = MessageType; LastUpTime_ = GetMessageTime(); MouseDown_ = 0; MouseX = LOWORD(lParam); MouseY = HIWORD(lParam); overme = GetWindow(MouseX, MouseY); if (overme == NULL) { retval = 0; break; } if (Dragging()) { DropItem(MouseX, MouseY, overme); } else if (Grab_.Control_) { if (MouseCallback_) ret = (*MouseCallback_)(Grab_.Control_, MouseX, MouseY, overme, (short)MessageType); // else ret = TRUE; if (ret and overme->IsMenu()) { Grab_.Control_->Process(Grab_.ID_, (short)MessageType); // if (DblClk and Grab_.Control_) Grab_.Control_->Process(Grab_.ID_, (short)DblClk); // Grab_.Control_ = NULL; } else if (UI_ABS(MouseX - Grab_.StartX_) < 3 and UI_ABS(MouseY - Grab_.StartY_) < 3) gPopupMgr->OpenMenu(Grab_.Control_->GetMenu(), MouseX, MouseY, Grab_.Control_); } else { overme->DeactivateControl(); if (MouseCallback_) ret = (*MouseCallback_)(NULL, MouseX, MouseY, overme, (short)MessageType); // gPopupMgr->OpenWindowMenu(overme, MouseX, MouseY); } overme = GetWindow(MouseX, MouseY); if (overme) { OverControl_ = overme->MouseOver(MouseX - overme->GetX(), MouseY - overme->GetY(), OverControl_); if (OverLast_.Control_ not_eq OverControl_) { HelpOff(); OverLast_.Control_ = OverControl_; if (OverControl_) { OverLast_.Time_ = GetCurrentTime(); OverLast_.Tip_ = gStringMgr->GetString(OverControl_->GetHelpText()); OverLast_.MouseX_ = MouseX; OverLast_.MouseY_ = MouseY; } } } retval = 0; break; case WM_RBUTTONDBLCLK: break; HelpOff(); if (OldInputMessage()) { retval = 0; break; } MouseX = LOWORD(lParam); MouseY = HIWORD(lParam); overme = GetWindow(MouseX, MouseY); if (overme == NULL) { retval = 0; break; } CurWindow_ = overme; if (Dragging()) DropItem(MouseX, MouseY, overme); if (GrabItem(MouseX, MouseY, overme, C_TYPE_RMOUSEDBLCLK)) { if (MouseCallback_) ret = (*MouseCallback_)(Grab_.Control_, MouseX, MouseY, overme, C_TYPE_RMOUSEDBLCLK); else ret = TRUE; if (ret) { overme->SetControl(Grab_.ID_); WindowToFront(overme); Grab_.Control_->Process(Grab_.ID_, C_TYPE_RMOUSEDBLCLK); } } else { if (MouseCallback_) ret = (*MouseCallback_)(NULL, MouseX, MouseY, overme, C_TYPE_RMOUSEDBLCLK); if (ret) WindowToFront(overme); Grab_.Window_ = NULL; } retval = 0; break; case C_WM_TIMER: if (MouseDown_ and (GetCurrentTime() - MouseDownTime_) > 250) { if (Grab_.Control_ and not InTimer) { if (GetAsyncKeyState(VK_LBUTTON)) { InTimer = 1; Grab_.Control_->Process(Grab_.ID_, C_TYPE_REPEAT); InTimer = 0; } else { InTimer = 1; MouseDown_ = 0; if (Drag_.Window_ not_eq NULL and Drag_.Control_ not_eq NULL) { DropItem((WORD)(Drag_.Window_->GetX() + Drag_.Control_->GetX()), // (WORD)(Drag_.Window_->GetY() + Drag_.Control_->GetY()), // Drag_.Window_); Grab_.Control_->Process(Grab_.ID_, C_TYPE_LDROP); } else { Grab_.Control_->Process(Grab_.ID_, C_TYPE_LMOUSEUP); } Grab_.Control_ = NULL; InTimer = 0; } } } if (gScreenShotEnabled and gUI_TakeScreenShot == 2) { SaveScreenShot(); gUI_TakeScreenShot = 0; } break; case WM_SYSKEYUP: case WM_KEYUP: Transmit(0);// voice stuff me123 if (wParam == VK_SNAPSHOT) // fall through to KEYDOWN also { if (gScreenShotEnabled) gUI_TakeScreenShot = 1; // Set to take screen shot after screen is refreshed (2=Save to file)... lParam = (lParam bitand 0xff00ffff) bitor DIK_SYSRQ; } else break; case WM_SYSKEYDOWN: case WM_KEYDOWN: ShiftStates = 0; if (OldInputMessage()) { retval = 0; break; } Repeat = lParam bitand 0xffff; Key = (uchar)(((lParam >> 16) bitand 0xff) bitor ((lParam >> 17) bitand 0x80)); // if (GetKeyState(VK_SHIFT) bitand 0x80) ShiftStates or_eq _SHIFT_DOWN_; if (GetKeyState(VK_MENU) bitand 0x80) ShiftStates or_eq _ALT_DOWN_; if (GetKeyState(VK_CONTROL) bitand 0x80) ShiftStates or_eq _CTRL_DOWN_; if (GetKeyState(VK_CAPITAL) bitand 0x01) if ((Key >= DIK_Q and Key <= DIK_P) or (Key >= DIK_A and Key <= DIK_L) or (Key >= DIK_Z and Key <= DIK_M)) ShiftStates xor_eq _SHIFT_DOWN_; if (GetKeyState(VK_NUMLOCK) bitand 0x01) if ((Key >= DIK_NUMPAD7 and Key <= DIK_NUMPAD9) or (Key >= DIK_NUMPAD4 and Key <= DIK_NUMPAD6) or (Key >= DIK_NUMPAD1 and Key <= DIK_DECIMAL)) ShiftStates or_eq _SHIFT_DOWN_; Ascii = AsciiChar(Key, ShiftStates); // Handle Hot Keys bitand Keyboard input if (CurWindow_) { if ( not CurWindow_->CheckKeyboard(Key, Ascii, ShiftStates, Repeat)) CheckHotKeys(Key, Ascii, ShiftStates, Repeat); } else CheckHotKeys(Key, Ascii, ShiftStates, Repeat); retval = 0; ////// me123 voice stuff added if (Key == DIK_F1) Transmit(1); else if (Key == DIK_F2) Transmit(2); ///////////////// break; /* case WM_CHAR: // NOLONGER USED retval=0; if(OldInputMessage()) break; // Handle Hot Keys bitand Keyboard input if(CurWindow_ == NULL) break; if( not CurWindow_->CheckKeyboard(message,wParam,lParam)) CheckHotKeys(message,wParam,lParam); retval=0; break; */ case C_WM_UPDATE: //if(UpdateFlag bitand C_DRAW_REFRESH) // SetEvent(WakeOutput_); retval = 0; break; case WM_MOVE: // get the client rectangle if (FalconDisplay.displayFullScreen) { SetRect(&dest, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); } else { GetClientRect(hwnd, &dest); ClientToScreen(hwnd, (LPPOINT)&dest); ClientToScreen(hwnd, (LPPOINT)&dest + 1); if (Primary_ and Primary_->frontSurface()) { Primary_->UpdateFrontWindowRect(&dest); #if 0 // Don't know how to get rc if (rc) MPRSwapBuffers(rc, fronthandle); #endif } InvalidateRect(hwnd, &dest, FALSE); } break; case WM_PAINT: if (GetUpdateRect(hwnd, &dest, FALSE)) { ValidateRect(hwnd, NULL); if (Primary_ not_eq Front_) { UI95_RECT upme; upme.left = FrontRect_.left; upme.top = FrontRect_.top; upme.right = FrontRect_.right; upme.bottom = FrontRect_.bottom; EnterCritical(); rectcount_ = 0; RefreshAll(&upme); LeaveCritical(); //if(UpdateFlag bitand C_DRAW_REFRESH) // SetEvent(WakeOutput_); } } retval = 0; break; } HandlingMessage = 0; return(retval); }
25.729364
245
0.497909
Terebinth
831e7e56b36e0dd9fd1cb10bb3a9a06ac1264b1f
61
cc
C++
src/eic_evgen/main.cc
sjdkay/DEMPgen
36279b9890e53d9e803e5c2757a220a86ebb605d
[ "MIT" ]
1
2020-03-04T19:48:54.000Z
2020-03-04T19:48:54.000Z
src/eic_evgen/main.cc
sjdkay/DEMPgen
36279b9890e53d9e803e5c2757a220a86ebb605d
[ "MIT" ]
1
2022-03-07T21:30:26.000Z
2022-03-07T21:30:26.000Z
src/eic_evgen/main.cc
sjdkay/DEMPgen
36279b9890e53d9e803e5c2757a220a86ebb605d
[ "MIT" ]
3
2022-03-07T21:19:40.000Z
2022-03-10T15:37:25.000Z
#include "eic.h" int main() { eic(); return 0; }
5.545455
16
0.459016
sjdkay
8321db9f6a1a01e249c3f0e445aeeb7018c1c8a3
2,055
cpp
C++
Source/System/Graphics/DX11/Texture/TextureArrayDX11.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
2
2020-01-09T07:48:24.000Z
2020-01-09T07:48:26.000Z
Source/System/Graphics/DX11/Texture/TextureArrayDX11.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
Source/System/Graphics/DX11/Texture/TextureArrayDX11.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
#include "TextureArrayDX11.hpp" #include "../../../Core/Utility/CoreDef.hpp" #include "../../Common/Texture/TextureArrayCommon.hpp" #include "../../Common/Texture/TextureCommon.hpp" namespace Engine5 { TextureArrayDX11::TextureArrayDX11() { } TextureArrayDX11::~TextureArrayDX11() { } ID3D11ShaderResourceView** TextureArrayDX11::Data() { return m_textures.data(); } ID3D11ShaderResourceView* const* TextureArrayDX11::Data() const { return m_textures.data(); } TextureArrayCommon::TextureArrayCommon() { } TextureArrayCommon::~TextureArrayCommon() { } void TextureArrayCommon::PushFront(TextureCommon* texture) { m_front = texture; m_textures.insert(m_textures.begin(), texture->GetTexture()); if (texture->m_device_context != nullptr) { m_device_context = texture->m_device_context; } } void TextureArrayCommon::PushBack(TextureCommon* texture) { if (m_front == nullptr || m_textures.empty()) { m_front = texture; } m_textures.push_back(texture->GetTexture()); if (texture->m_device_context != nullptr) { m_device_context = texture->m_device_context; } } void TextureArrayCommon::Erase(TextureCommon* texture) { auto found = std::find(m_textures.begin(), m_textures.end(), texture->GetTexture()); m_textures.erase(found); if (m_textures.empty()) { m_front = nullptr; } } void TextureArrayCommon::Clear() { m_textures.clear(); m_front = nullptr; } TextureCommon* TextureArrayCommon::Front() const { return m_front; } size_t TextureArrayCommon::Size() const { return m_textures.size(); } void TextureArrayCommon::Bind() const { U32 count = (U32)m_textures.size(); m_device_context->PSSetShaderResources(0, count, m_textures.data()); } }
22.582418
92
0.603893
arian153
832741fd3d7da97338e75d0ee0e82c0ee76c9c06
304
cpp
C++
console-tank-game/console-tank-game/tile_wall_crumbly.cpp
Amakazor/console-tank-game
e286aa49966f4a74832847caccc07fcf20db15f4
[ "MIT" ]
1
2019-10-04T09:28:13.000Z
2019-10-04T09:28:13.000Z
console-tank-game/console-tank-game/tile_wall_crumbly.cpp
Amakazor/console-tank-game
e286aa49966f4a74832847caccc07fcf20db15f4
[ "MIT" ]
null
null
null
console-tank-game/console-tank-game/tile_wall_crumbly.cpp
Amakazor/console-tank-game
e286aa49966f4a74832847caccc07fcf20db15f4
[ "MIT" ]
1
2019-10-10T20:58:26.000Z
2019-10-10T20:58:26.000Z
#include "tile_wall_crumbly.h" tile_wall_crumbly::tile_wall_crumbly():tile::tile() { tile::type = "Destructible Wall"; tile::symbol = (char)197; tile::passable = false; tile::ap_cost = 0; tile::cover = 100; tile::destructible = true; tile::hp = 2; tile::after_destruct_type = "tile_rubble"; }
19
51
0.690789
Amakazor
8328023d760996d39d2d37fee8a1613a473ec5a6
4,139
cpp
C++
med/roads_in_hackerland/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
med/roads_in_hackerland/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
med/roads_in_hackerland/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; string solve(int n, int m, map<int, set<int>> &edges, map<pair<int, int>, int> &costs); int main() { int n, m; cin >> n >> m; // cout << n << " " << m << endl; map<int, set<int>> edges; map<pair<int, int>, int> costs; for (int i = 0; i < m; ++i) { int a, b, c; cin >> a >> b >> c; a--; b--; edges[a].insert(b); edges[b].insert(a); if (costs.count({a, b}) == 0) { costs[{a, b}] = c; costs[{b, a}] = c; } else { costs[{a, b}] = min(costs[{a, b}], c); costs[{b, a}] = min(costs[{a, b}], c); } } auto ans = solve(n, m, edges, costs); cout << ans << endl; return 0; } struct N { N *parent = nullptr; int count = 1; N() : count(1), parent(nullptr) {} N *find() { if (parent) { parent = parent->find(); return parent; } else { return this; } } void merge(N *other) { if (!other || other == this) { return; } N *p = find(); N *p2 = other->find(); if (p->count > p2->count) { p->count += p2->count; p2->parent = p; } else { p2->count += p->count; p->parent = p2; } } }; void count_tree_edges(int n, map<int, set<int>> &tree, int root, map<pair<int, int>, uint64_t> &count); string solve(int n, int m, map<int, set<int>> &edges, map<pair<int, int>, int> &costs) { string ret{""}; // construct mst vector<N *> ns; for (int i = 0; i < n; ++i) { ns.push_back(new N()); } vector<pair<int, pair<int, int>>> ranked_cost; for (auto [k, v] : costs) { ranked_cost.push_back({v, k}); } sort(ranked_cost.begin(), ranked_cost.end()); map<int, set<int>> tree; for (auto [cost, nodes] : ranked_cost) { assert(nodes.first >= 0 && nodes.first < n); assert(nodes.second >= 0 && nodes.second < n); N *p1 = ns[nodes.first]->find(); N *p2 = ns[nodes.second]->find(); if (p1 != p2) { ns[nodes.first]->merge(ns[nodes.second]); tree[nodes.first].insert(nodes.second); tree[nodes.second].insert(nodes.first); if (ns[nodes.first]->find()->count == n) { break; } } } // count number of times each edge in tree is traversed int root = 0; map<pair<int, int>, uint64_t> count; count_tree_edges(n, tree, root, count); vector<uint64_t> buckets( m * 2, 0LL); // costs[{n1,n2}] (power of 2) -> accumulation of combinations for (auto &[k, v] : count) { assert(costs.count(k) == 1); buckets[costs[k]] += v; // ans += pow(2, costs[k]) * v; } // add and carry over for (int i = 0; i + 1 < buckets.size(); ++i) { buckets[i + 1] += buckets[i] / 2LL; buckets[i] %= 2LL; } bool started = false; for (int i = buckets.size() - 1; i >= 0; --i) { if (buckets[i] == 1LL || started) { started = true; ret.push_back((buckets[i] == 1 ? '1' : '0')); } } for (auto i : ns) delete i; return ret; } void dfs(int n, map<int, set<int>> &tree, int cur, int parent, vector<int> &count_subtree, map<pair<int, int>, uint64_t> &count) { // cout << "dfs: " << cur << endl; int subtree = 1; for (auto c : tree[cur]) { if (c != parent) { dfs(n, tree, c, cur, count_subtree, count); uint64_t combo = (uint64_t)count_subtree[c] * (uint64_t)(n - count_subtree[c]); count[{cur, c}] = combo; subtree += count_subtree[c]; } } count_subtree[cur] = subtree; } void count_tree_edges(int n, map<int, set<int>> &tree, int root, map<pair<int, int>, uint64_t> &count) { vector<int> count_children(n, 0); dfs(n, tree, root, -1, count_children, count); }
26.196203
78
0.467746
exbibyte
832a5c71b100835572246cc052f74958ccc5647c
1,622
cpp
C++
cpp/LocoThread.cpp
jbitoniau/SensorMonitor
f6d425bc331a0df364a15e654bbc90267cfae5aa
[ "MIT" ]
null
null
null
cpp/LocoThread.cpp
jbitoniau/SensorMonitor
f6d425bc331a0df364a15e654bbc90267cfae5aa
[ "MIT" ]
null
null
null
cpp/LocoThread.cpp
jbitoniau/SensorMonitor
f6d425bc331a0df364a15e654bbc90267cfae5aa
[ "MIT" ]
null
null
null
#include "LocoThread.h" #ifdef _WIN32 #include <assert.h> #include <Windows.h> #else #include <time.h> #endif namespace Loco { #ifdef _WIN32 class ThreadInitializer { public: ThreadInitializer() { // Sets the minimum timer resolution to the minimum available on this machine // This is used by Windows for its Sleep() method. On some machine, if we don't do // that, the minimum time slice for a sleep can be as long as 16ms! // http://www.eggheadcafe.com/software/aspnet/31952897/high-resolution-sleep.aspx TIMECAPS timeCaps; memset( &timeCaps, 0, sizeof(timeCaps) ); MMRESULT res = timeGetDevCaps( &timeCaps, sizeof(timeCaps) ); assert(res==TIMERR_NOERROR); mTimePeriodDefined = timeCaps.wPeriodMin; res = timeBeginPeriod( mTimePeriodDefined ); assert(res==TIMERR_NOERROR); } ~ThreadInitializer() { MMRESULT res = timeEndPeriod( mTimePeriodDefined ); assert(res==TIMERR_NOERROR); } private: UINT mTimePeriodDefined; static ThreadInitializer mThreadInitializer; }; ThreadInitializer ThreadInitializer::mThreadInitializer; #endif void Thread::sleep( unsigned int milliseconds ) { #ifdef _WIN32 ::Sleep( milliseconds ); #else struct timespec l_TimeSpec; l_TimeSpec.tv_sec = milliseconds / 1000; l_TimeSpec.tv_nsec = (milliseconds % 1000) * 1000000; struct timespec l_Ret; nanosleep(&l_TimeSpec,&l_Ret); #endif } /* void Thread::usleep( unsigned int microseconds ) { #ifdef _WIN32 unsigned int milliseconds = microseconds / 1000; ::Sleep( milliseconds ); #else usleep( microseconds ); #endif }*/ }
23.507246
85
0.709618
jbitoniau
832c1b165169753b50de1c8469a2ca25d15ef4a6
1,688
cpp
C++
src/Input_pattern_class.cpp
fercer/artificial_neural_network
5425310965f16cee7e84b19783764e6c5e05b3ff
[ "MIT" ]
null
null
null
src/Input_pattern_class.cpp
fercer/artificial_neural_network
5425310965f16cee7e84b19783764e6c5e05b3ff
[ "MIT" ]
null
null
null
src/Input_pattern_class.cpp
fercer/artificial_neural_network
5425310965f16cee7e84b19783764e6c5e05b3ff
[ "MIT" ]
null
null
null
#include "Input_pattern_class.h" Input_pattern::Input_pattern() { input_pointer = NULL; global_node_index = 0; } Input_pattern::Input_pattern(const unsigned int src_global_node_index) { input_pointer = NULL; global_node_index = src_global_node_index; } Input_pattern::Input_pattern(const Input_pattern & src_input_pattern) { this->input_pointer = src_input_pattern.input_pointer; this->global_node_index = src_input_pattern.global_node_index; } Input_pattern & Input_pattern::operator= (const Input_pattern & src_input_pattern) { if (this != &src_input_pattern) { this->input_pointer = src_input_pattern.input_pointer; this->global_node_index = src_input_pattern.global_node_index; } return *this; } Input_pattern::~Input_pattern() { } void Input_pattern::setInputPointer(double ** src_input_pointer) { input_pointer = src_input_pointer; } void Input_pattern::setInputPointerPosition(const unsigned int src_global_node_index) { global_node_index = src_global_node_index; } double Input_pattern::getInputWithDerivatives(const unsigned long long current_time) { return *(*input_pointer + global_node_index); } double Input_pattern::getInput(const unsigned long long current_time) { return *(*input_pointer + global_node_index); } void Input_pattern::addNodeErrorContribution(const double src_error_contribution, const unsigned int src_output_index) { // This node has no error contribution ... } void Input_pattern::backpropagateNodeError() { // This node cannot backpropagate further ... } void Input_pattern::dumpNodeData(FILE * fp_network_data) { fprintf(fp_network_data, "\t<Input position = \"%i\"></Input>\n", global_node_index); }
19.402299
118
0.783768
fercer
832d6505c9cb7b0909110140c6ceee68d8fd3fa4
310
cpp
C++
login_form/FormSplash.cpp
gcf89/qt_learn
ebb2a6f3b56779c93a2514bd1ff9596bb347353a
[ "Artistic-2.0" ]
null
null
null
login_form/FormSplash.cpp
gcf89/qt_learn
ebb2a6f3b56779c93a2514bd1ff9596bb347353a
[ "Artistic-2.0" ]
null
null
null
login_form/FormSplash.cpp
gcf89/qt_learn
ebb2a6f3b56779c93a2514bd1ff9596bb347353a
[ "Artistic-2.0" ]
null
null
null
#include "FormSplash.h" #include "ui_FormSplash.h" FormSplash::FormSplash(QWidget *parent) : QWidget(parent), ui(new Ui::FormSplash) { ui->setupUi(this); setWindowFlags(Qt::FramelessWindowHint); ui->label->setPixmap(QPixmap(":/icons/icons/Logo.png")); } FormSplash::~FormSplash() { delete ui; }
17.222222
58
0.703226
gcf89
83394b1e0c965eb2b5dccd7c105539abc03f071a
708
cpp
C++
test/containers/sequences/array/array.tuple/tuple_size.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
1,244
2015-01-02T21:08:56.000Z
2022-03-22T21:34:16.000Z
test/containers/sequences/array/array.tuple/tuple_size.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
125
2015-01-22T01:08:00.000Z
2020-05-25T08:28:17.000Z
test/containers/sequences/array/array.tuple/tuple_size.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
124
2015-01-12T15:06:17.000Z
2022-03-26T07:48:53.000Z
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <array> // tuple_size<array<T, N> >::value #include <array> int main() { { typedef double T; typedef std::array<T, 3> C; static_assert((std::tuple_size<C>::value == 3), ""); } { typedef double T; typedef std::array<T, 0> C; static_assert((std::tuple_size<C>::value == 0), ""); } }
24.413793
80
0.430791
caiohamamura
834311a88cc9d47a1be2e758bc15aae36d2a25c1
44,942
cc
C++
src/outlinermath.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
4
2021-09-02T16:52:23.000Z
2022-02-07T16:39:50.000Z
src/outlinermath.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
87
2021-09-12T06:09:57.000Z
2022-02-15T00:05:43.000Z
src/outlinermath.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
1
2021-09-28T21:38:30.000Z
2021-09-28T21:38:30.000Z
/////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // // CCC AAA V V EEEEE OOO UU UU TTTTTT LL II NN NN EEEEE RRRRR // CC CC AA AA V V EE OO OO UU UU TT LL II NNN NN EE RR RR // CC AA AA V V EEE OO OO UU UU TT LL II NN N NN EEE RRRRR // CC CC AAAAAA V V EE OO OO UU UU TT LL II NN NNN EE RR R // CCc AA AA V EEEEE OOO UUUUU TT LLLLL II NN NN EEEEE RR R // // CAVE OUTLINER -- Cave 3D model processing software // // Copyright (C) 2021 by Jari Arkko -- See LICENSE.txt for license information. // /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // Includes /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <cassert> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "outlinertypes.hh" #include "outlinerconstants.hh" #include "outlinermath.hh" #include "outlinerdebug.hh" /////////////////////////////////////////////////////////////////////////////////////////////// // Debugs ///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// bool debugbbit3 = 0; # define debugreturn(f,why,x) { \ bool drv = (x); \ deepdeepdebugf("%s returns %u due to %s", (f), drv, (why)); \ return(drv); \ } /////////////////////////////////////////////////////////////////////////////////////////////// // Math functions ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void OutlinerMath::triangleDescribe(const OutlinerTriangle3D& triangle, char* buf, unsigned int bufSize, bool full) { assert(buf != 0); assert(bufSize > 0); memset(buf,0,bufSize); if (full) { snprintf(buf,bufSize-1," (%f,%f,%f) (%f,%f,%f) (%f,%f,%f) ", triangle.a.x, triangle.a.y, triangle.a.z, triangle.b.x, triangle.b.y, triangle.b.z, triangle.c.x, triangle.c.y, triangle.c.z); } else { outlinerreal xlow = outlinermin3(triangle.a.x,triangle.b.x,triangle.c.x); outlinerreal xhigh = outlinermax3(triangle.a.x,triangle.b.x,triangle.c.x); outlinerreal ylow = outlinermin3(triangle.a.y,triangle.b.y,triangle.c.y); outlinerreal yhigh = outlinermax3(triangle.a.y,triangle.b.y,triangle.c.y); outlinerreal zlow = outlinermin3(triangle.a.z,triangle.b.z,triangle.c.z); outlinerreal zhigh = outlinermax3(triangle.a.z,triangle.b.z,triangle.c.z); if (zlow == zhigh) { snprintf(buf,bufSize-1,"horizontal along z at %.2f, x %.2f..%.2f y %.2f..%.2f", zlow, xlow, xhigh, ylow, yhigh); } else if (xlow == xhigh) { snprintf(buf,bufSize-1,"vertical along x at %.2f, y %.2f..%.2f, z %.2f..%.2f", xlow, ylow, yhigh, zlow, zhigh); } else if (ylow == yhigh) { snprintf(buf,bufSize-1,"vertical along y at %.2f, x %.2f..%.2f, z %.2f..%.2f", ylow, xlow, xhigh, zlow, zhigh); } else { snprintf(buf,bufSize-1,"irregular, x %.2f..%.2f y %.2f..%.2f z %.2f..%.2f", xlow, xhigh, ylow, yhigh, zlow, zhigh); } } } void OutlinerMath::triangleDescribe(const OutlinerTriangle2D& triangle, char* buf, unsigned int bufSize, bool full) { assert(buf != 0); assert(bufSize > 0); memset(buf,0,bufSize); if (full) { snprintf(buf,bufSize-1," (%f,%f) (%f,%f) (%f,%f)", triangle.a.x, triangle.a.y, triangle.b.x, triangle.b.y, triangle.c.x, triangle.c.y); } else { outlinerreal xlow = outlinermin3(triangle.a.x,triangle.b.x,triangle.c.x); outlinerreal xhigh = outlinermax3(triangle.a.x,triangle.b.x,triangle.c.x); outlinerreal ylow = outlinermin3(triangle.a.y,triangle.b.y,triangle.c.y); outlinerreal yhigh = outlinermax3(triangle.a.y,triangle.b.y,triangle.c.y); if (xlow == xhigh) { snprintf(buf,bufSize-1,"vertical along x at %.2f, y %.2f..%.2f", xlow, ylow, yhigh); } else if (ylow == yhigh) { snprintf(buf,bufSize-1,"vertical along y at %.2f, x %.2f..%.2f", ylow, xlow, xhigh); } else { snprintf(buf,bufSize-1,"irregular, x %.2f..%.2f y %.2f..%.2f", xlow, xhigh, ylow, yhigh); } } } void OutlinerMath::boxDescribe(const OutlinerBox3D& box, char* buf, unsigned int bufSize, bool full) { assert(buf != 0); assert(bufSize > 0); memset(buf,0,bufSize); snprintf(buf,bufSize-1,"x %.2f..%.2f y %.2f..%.2f z %.2f..%.2f", box.start.x, box.end.x, box.start.y, box.end.y, box.start.z, box.end.z); } void OutlinerMath::boxDescribe(const OutlinerBox2D& box, char* buf, unsigned int bufSize, bool full) { assert(buf != 0); assert(bufSize > 0); memset(buf,0,bufSize); snprintf(buf,bufSize-1,"x %.2f..%.2f y %.2f..%.2f", box.start.x, box.end.x, box.start.y, box.end.y); } void OutlinerMath::triangleBoundingBox2D(const OutlinerTriangle2D& triangle, OutlinerBox2D& boundingBox) { const OutlinerVector2D* nth1; const OutlinerVector2D* nth2; const OutlinerVector2D* nth3; outlinerreal xStart; outlinerreal xEnd; outlinerreal yStart; outlinerreal yEnd; // Order the points a,b,c so that the one with smallest x comes first sortVectorsX2D(&triangle.a,&triangle.b,&triangle.c,&nth1,&nth2,&nth3); // Fill in xStart and xEnd xStart = nth1->x; xEnd = nth3->x; // Order the points a,b,c so that the one with smallest y comes first sortVectorsY2D(&triangle.a,&triangle.b,&triangle.c,&nth1,&nth2,&nth3); // Fill in yStart and yEnd yStart = nth1->y; yEnd = nth3->y; // Construct the result boundingBox.start.x = xStart; boundingBox.start.y = yStart; boundingBox.end.x = xEnd; boundingBox.end.y = yEnd; } void OutlinerMath::triangleBoundingBox3D(const OutlinerTriangle3D& triangle, OutlinerBox3D& boundingBox) { const OutlinerVector3D* nth1; const OutlinerVector3D* nth2; const OutlinerVector3D* nth3; outlinerreal xStart; outlinerreal xEnd; outlinerreal yStart; outlinerreal yEnd; outlinerreal zStart; outlinerreal zEnd; // Order the points a,b,c so that the one with smallest x comes first sortVectorsX3D(&triangle.a,&triangle.b,&triangle.c,&nth1,&nth2,&nth3); // Fill in xStart and xEnd xStart = nth1->x; xEnd = nth3->x; // Order the points a,b,c so that the one with smallest y comes first sortVectorsY3D(&triangle.a,&triangle.b,&triangle.c,&nth1,&nth2,&nth3); // Fill in yStart and yEnd yStart = nth1->y; yEnd = nth3->y; // Order the points a,b,c so that the one with smallest z comes first sortVectorsZ3D(&triangle.a,&triangle.b,&triangle.c,&nth1,&nth2,&nth3); // Fill in zStart and zEnd zStart = nth1->z; zEnd = nth3->z; if (debugbbit3) debugf(" z range %.2f...%.2f from %.2f, %.2f, %.2f", zStart, zEnd, triangle.a.z, triangle.b.z, triangle.c.z); // Construct the result boundingBox.start.x = xStart; boundingBox.start.y = yStart; boundingBox.start.z = zStart; boundingBox.end.x = xEnd; boundingBox.end.y = yEnd; boundingBox.end.z = zEnd; } bool OutlinerMath::pointInsideTriangle2D(const OutlinerTriangle2D& triangle, const OutlinerVector2D& point) { // Check for a special case: all points are equal (resulting in // comparing to a point, not a triangle). if (triangle.a.equal(triangle.b) && triangle.a.equal(triangle.c)) { //deepdeepdebugf("pit2 special case all equal"); debugreturn(" pit2","vectorEqual",triangle.a.equal(point)); } // Check for a special case: triangle collapses to a line (at least // in 2D). if (triangle.a.equal(triangle.b)) { OutlinerLine2D ac(triangle.a,triangle.c); debugreturn(" pit2","point on AB line",ac.pointOnLine(point)); } else if (triangle.a.equal(triangle.c)) { OutlinerLine2D ab(triangle.a,triangle.b); debugreturn(" pit2","point on AC line",ab.pointOnLine(point)); } else if (triangle.b.equal(triangle.c)) { OutlinerLine2D ab(triangle.a,triangle.b); debugreturn(" pit2","point on BC line",ab.pointOnLine(point)); } // Not a special case. For the general case, we take the algorithm // from https://mathworld.wolfram.com/TriangleInterior.html //deepdeepdebugf("pit2 regular case"); OutlinerVector2D v = point; OutlinerVector2D v0(triangle.a); OutlinerVector2D v1; vectorTo(triangle.a,triangle.b,v1); OutlinerVector2D v2; vectorTo(triangle.a,triangle.c,v2); //deepdeepdebugf("pit2 triangle v = (%.2f,%.2f)", v.x, v.y); //deepdeepdebugf("pit2 triangle v0 = (%.2f,%.2f)", v0.x, v0.y); //deepdeepdebugf("pit2 triangle v1 = (%.2f,%.2f)", v1.x, v1.y); //deepdeepdebugf("pit2 triangle v2 = (%.2f,%.2f)", v2.x, v2.y); outlinerreal a = (determinant2x2(v,v2) - determinant2x2(v0,v2)) / determinant2x2(v1,v2); outlinerreal b = -((determinant2x2(v,v1) - determinant2x2(v0,v1)) / determinant2x2(v1,v2)); debugreturn(" pit2","regular",a >= 0 && b >= 0 && a+b <= 1); } bool OutlinerMath::boundingBoxIntersectsTriangle2D(const OutlinerTriangle2D& triangle, const OutlinerBox2D& box) { // Debugs deepdeepdebugf(" boundingBoxIntersectsTriangle2D (%.2f,%.2f)-(%.2f,%.2f)-(%.2f,%.2f) and (%.2f,%.2f)-(%.2f,%.2f)", triangle.a.x, triangle.a.y, triangle.b.x, triangle.b.y, triangle.c.x, triangle.c.y, box.start.x, box.start.y, box.end.x, box.end.y); // First, if triangle corners are in the box, they intersect if (box.pointInside(triangle.a)) debugreturn(" bbit2","corner a",1); if (box.pointInside(triangle.b)) debugreturn(" bbit2","corner b",1); if (box.pointInside(triangle.c)) debugreturn(" bbit2","corner c",1); // Otherwise, (for now just an approximation) check if the box corners or middle are in the triangle OutlinerVector2D boxUpperRight(box.end.x,box.start.y); OutlinerVector2D boxLowerLeft(box.start.x,box.end.y); OutlinerVector2D boxMiddle((box.start.x + box.end.x) / 2,(box.start.y + box.end.y) / 2); if (pointInsideTriangle2D(triangle,box.start)) debugreturn(" bbit2","start",1); if (pointInsideTriangle2D(triangle,box.end)) debugreturn(" bbit2","end",1); if (pointInsideTriangle2D(triangle,boxUpperRight)) debugreturn(" bbit2","upper",1); if (pointInsideTriangle2D(triangle,boxLowerLeft)) debugreturn(" bbit2","lower",1); if (pointInsideTriangle2D(triangle,boxMiddle)) debugreturn(" bbit2","middle",1); // Otherwise no debugreturn(" bbit2","fallback",0); } bool OutlinerMath::boundingBoxIntersectsTriangle3D(const OutlinerTriangle3D& triangle, const OutlinerBox3D& box) { // Sanity checks deepdeepdebugf(" bbit3 starts"); assert(box.start.x <= box.end.x); assert(box.start.y <= box.end.y); assert(box.start.z <= box.end.z); // NEW: // Approximate algorithm, check if the triangle's bounding box intersects OutlinerBox3D triangleBoundingBox; if (debugbbit3) { debugf(" bbit3 triangle ys %.2f, %.2f, %.2f", triangle.a.y, triangle.b.y, triangle.c.y); debugf(" bbit3 triangle zs %.2f, %.2f, %.2f", triangle.a.z, triangle.b.z, triangle.c.z); } triangleBoundingBox3D(triangle,triangleBoundingBox); bool ans = triangleBoundingBox.doesIntersect(box); if (debugbbit3) { char buf[150]; triangleDescribe(triangle,buf,sizeof(buf),1); debugf(" triangle = %s", buf); boxDescribe(triangleBoundingBox,buf,sizeof(buf),1); debugf(" triangle box = %s", buf); boxDescribe(box,buf,sizeof(buf),1); debugf(" box = %s", buf); debugf(" bbit3 return %u", ans); } return(ans); // OLD: // Heuristic algorithm, first check if there's an xy-plane match deepdeepdebugf(" bbit3 2d"); OutlinerVector2D a2(triangle.a.x,triangle.a.y); OutlinerVector2D b2(triangle.b.x,triangle.b.y); OutlinerVector2D c2(triangle.c.x,triangle.c.y); deepdeepdebugf(" bbit3 boxes"); OutlinerVector2D box2Start(box.start.x,box.start.y); OutlinerVector2D box2End(box.end.x,box.end.y); OutlinerBox2D box2(box2Start,box2End); deepdeepdebugf(" bbit3 xy plane check"); OutlinerTriangle2D t2(a2,b2,c2); if (!boundingBoxIntersectsTriangle2D(t2,box2)) { if (debugbbit3) { char buf[120]; triangleDescribe(t2,buf,sizeof(buf),1); debugf(" t2 = %s", buf); boxDescribe(box2,buf,sizeof(buf),1); debugf(" box2 = %s", buf); debugf(" bbit3 2d zero return"); } return(0); } deepdeepdebugf(" bbit2 call returned"); // If there was a match, check if the range of the triangle in // z axis overlaps with the given bounding box outlinerreal zlow = outlinermin3(triangle.a.z,triangle.b.z,triangle.c.z); outlinerreal zhigh = outlinermax3(triangle.a.z,triangle.b.z,triangle.c.z); deepdeepdebugf(" bbit3 z overlap check %.2f..%.2f", zlow, zhigh); bool overlapval = outlineroverlapepsilon(zlow,zhigh,box.start.z,box.end.z); if (debugbbit3) debugf(" bbit3 z check returns %u", overlapval); debugreturn(" bbit3","final",overlapval); } bool OutlinerBox3D::doesIntersect(const OutlinerBox3D& boundingBox2) const { // Following the algorithm from // https://math.stackexchange.com/questions/2651710/simplest-way-to-determine-if-two-3d-boxes-intersect bool xOverlap = (outlinerbetweenepsilon( start.x, boundingBox2.start.x, end.x) || outlinerbetweenepsilon( start.x, boundingBox2.end.x, end.x) || outlinerbetweenepsilon(boundingBox2.start.x, start.x,boundingBox2.end.x) || outlinerbetweenepsilon(boundingBox2.start.x, end.x, boundingBox2.end.x)); if (debugbbit3) debugf(" bbi3 xOverlap %u", xOverlap); if (!xOverlap) return(0); bool yOverlap = (outlinerbetweenepsilon( start.y, boundingBox2.start.y, end.y) || outlinerbetweenepsilon( start.y, boundingBox2.end.y, end.y) || outlinerbetweenepsilon(boundingBox2.start.y, start.y,boundingBox2.end.y) || outlinerbetweenepsilon(boundingBox2.start.y, end.y, boundingBox2.end.y)); if (debugbbit3) debugf(" bbi3 yOverlap %u %.2f..%.2f and %.2f...%.2f", yOverlap, start.y, end.y, boundingBox2.start.y, boundingBox2.end.y); if (debugbbit3) debugf(" bbi3 yOverlap components %u, %u, %u, %u", outlinerbetweenepsilon( start.y, boundingBox2.start.y, end.y), outlinerbetweenepsilon( start.y, boundingBox2.end.y, end.y), outlinerbetweenepsilon(boundingBox2.start.y, start.y,boundingBox2.end.y), outlinerbetweenepsilon(boundingBox2.start.y, end.y, boundingBox2.end.y)); if (debugbbit3) debugf(" bbi3 yOverlap tests %u %u box1 ydiff %f box12 diff %f", start.y <= boundingBox2.start.y, boundingBox2.start.y <= end.y, end.y - start.y, end.y - boundingBox2.start.y); if (!yOverlap) return(0); bool zOverlap = (outlinerbetweenepsilon( start.z, boundingBox2.start.z, end.z) || outlinerbetweenepsilon( start.z, boundingBox2.end.z, end.z) || outlinerbetweenepsilon(boundingBox2.start.z, start.z,boundingBox2.end.z) || outlinerbetweenepsilon(boundingBox2.start.z, end.z, boundingBox2.end.z)); if (debugbbit3) debugf(" bbi3 zOverlap %u %.2f..%2.f and %.2f...%.2f", zOverlap, start.z, end.z, boundingBox2.start.z, boundingBox2.end.z); if (!zOverlap) return(0); // Done. They intersect. return(1); } bool OutlinerMath::lineIntersectsVerticalLine2D(const OutlinerLine2D& line, const OutlinerLine2D& verticalLine, OutlinerVector2D& intersectionPoint) { assert(verticalLine.start.x == verticalLine.end.x); // Fetch basic values outlinerreal verticalStartY = outlinermin(verticalLine.start.y,verticalLine.end.y); outlinerreal verticalEndY = outlinermax(verticalLine.start.y,verticalLine.end.y); outlinerreal verticalX = verticalLine.start.x; // Order line points such that X grows from start to end outlinerreal lineStartX; outlinerreal lineStartY; outlinerreal lineEndX; outlinerreal lineEndY; if (line.start.x <= line.end.x) { lineStartX = line.start.x; lineStartY = line.start.y; lineEndX = line.end.x; lineEndY = line.end.y; } else { lineStartX = line.end.x; lineStartY = line.end.y; lineEndX = line.start.x; lineEndY = line.start.y; } // Calculate line equation // // y(x) = lineStartY + (x - lineStartX) * (equationTotalDifferenceY / equationTotalDifferenceX) // outlinerreal equationBaseY = lineStartY; outlinerreal equationTotalDifferenceY = lineEndY - lineStartY; // positive or negative outlinerreal equationTotalDifferenceX = lineEndX - lineStartX; // positive // Check for the case of parallel lines if (equationTotalDifferenceX == 0) { if (lineStartX != verticalX) return(0); if (outlineroverlapepsilon(lineStartY,lineEndY,verticalStartY,verticalEndY)) { intersectionPoint.x = verticalX; if (lineStartY <= verticalStartY && verticalStartY <= lineEndY) intersectionPoint.y = verticalStartY; else if (verticalStartY <= lineStartY && lineStartY <= verticalEndY) intersectionPoint.y = lineStartY; else assert(0); return(1); } return(0); } // Continue calculating the line equation outlinerreal equationFactor = equationTotalDifferenceY / equationTotalDifferenceX; // positive or negative outlinerreal verticalLineDifferenceX = verticalX - lineStartX; // positive or negative // Check if vertical line is in the range on X if (!outlinerbetweenepsilon(lineStartX,verticalX,lineEndX)) return(0); // Calculate resulting Y at vertical line position outlinerreal lineY = equationBaseY + verticalLineDifferenceX * equationFactor; // Check if the resulting position is within the vertical line Y range if (!outlinerbetweenepsilon(verticalStartY,lineY,verticalEndY)) return(0); // Lines intersect! Set the intersection point intersectionPoint.x = verticalX; intersectionPoint.y = lineY; return(1); } bool OutlinerMath::lineIntersectsHorizontalLine2D(const OutlinerLine2D& line, const OutlinerLine2D& horizontalLine, OutlinerVector2D& intersectionPoint) { assert(horizontalLine.start.y == horizontalLine.end.y); // Fetch basic values outlinerreal horizontalStartX = outlinermin(horizontalLine.start.x,horizontalLine.end.x); outlinerreal horizontalEndX = outlinermax(horizontalLine.start.x,horizontalLine.end.x); outlinerreal horizontalY = horizontalLine.start.y; // Order line points such that Y grows from start to end outlinerreal lineStartX; outlinerreal lineStartY; outlinerreal lineEndX; outlinerreal lineEndY; if (line.start.y <= line.end.y) { lineStartX = line.start.x; lineStartY = line.start.y; lineEndX = line.end.x; lineEndY = line.end.y; } else { lineStartX = line.end.x; lineStartY = line.end.y; lineEndX = line.start.x; lineEndY = line.start.y; } // Calculate line equation // // x(y) = lineStartX + (y - lineStartY) * (equationTotalDifferenceX / equationTotalDifferenceY) // outlinerreal equationBaseX = lineStartX; outlinerreal equationTotalDifferenceX = lineEndX - lineStartX; // positive or negative outlinerreal equationTotalDifferenceY = lineEndY - lineStartY; // positive // Check for the case of parallel lines if (equationTotalDifferenceY == 0) { if (lineStartY != horizontalY) return(0); if (outlineroverlapepsilon(lineStartX,lineEndX,horizontalStartX,horizontalEndX)) { intersectionPoint.y = horizontalY; if (lineStartX <= horizontalStartX && horizontalStartX <= lineEndX) intersectionPoint.x = horizontalStartX; else if (horizontalStartX <= lineStartX && lineStartX <= horizontalEndX) intersectionPoint.x = lineStartX; else assert(0); return(1); } return(0); } // Continue calculating the line equation outlinerreal equationFactor = equationTotalDifferenceX / equationTotalDifferenceY; // positive or negative outlinerreal horizontalLineDifferenceY = horizontalY - lineStartY; // positive or negative // Check if horizontal line is in the range on Y if (!outlinerbetweenepsilon(lineStartY,horizontalY,lineEndY)) return(0); // Calculate resulting X at horizontal line position outlinerreal lineX = equationBaseX + horizontalLineDifferenceY * equationFactor; // Check if the resulting position is within the horizontal line X range if (!outlinerbetweenepsilon(horizontalStartX,lineX,horizontalEndX)) return(0); // Lines intersect! Set the intersection point intersectionPoint.x = lineX; intersectionPoint.y = horizontalY; return(1); } void OutlinerMath::vectorTo(const OutlinerVector2D& from, const OutlinerVector2D& to, OutlinerVector2D& result) { result = to; result.x -= from.x; result.y -= from.y; } outlinerreal OutlinerMath::determinant2x2(const OutlinerVector2D& u, const OutlinerVector2D& v) { return(u.x * v.y - u.y * v.x); } /////////////////////////////////////////////////////////////////////////////////////////////// // Auxiliary private functions //////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void OutlinerMath::sortVectorsX2D(const OutlinerVector2D* a, const OutlinerVector2D* b, const OutlinerVector2D* c, const OutlinerVector2D** nth0, const OutlinerVector2D** nth1, const OutlinerVector2D** nth2) { // There are 6 permutations of three numbers. Simply test for each condition. if (a->x < b->x) { if (c->x < a->x) { *nth0 = c; *nth1 = a; *nth2 = b; } else if (c->x < b->x) { *nth0 = a; *nth1 = c; *nth2 = b; } else { *nth0 = a; *nth1 = b; *nth2 = c; } } else { if (c->x < b->x) { *nth0 = c; *nth1 = b; *nth2 = a; } else if (c->x < a->x) { *nth0 = b; *nth1 = c; *nth2 = a; } else { *nth0 = b; *nth1 = a; *nth2 = c; } } } void OutlinerMath::sortVectorsY2D(const OutlinerVector2D* a, const OutlinerVector2D* b, const OutlinerVector2D* c, const OutlinerVector2D** nth0, const OutlinerVector2D** nth1, const OutlinerVector2D** nth2) { // There are 6 permutations of three numbers. Simply test for each condition. if (a->y < b->y) { if (c->y < a->y) { *nth0 = c; *nth1 = a; *nth2 = b; } else if (c->y < b->y) { *nth0 = a; *nth1 = c; *nth2 = b; } else { *nth0 = a; *nth1 = b; *nth2 = c; } } else { if (c->y < b->y) { *nth0 = c; *nth1 = b; *nth2 = a; } else if (c->y < a->y) { *nth0 = b; *nth1 = c; *nth2 = a; } else { *nth0 = b; *nth1 = a; *nth2 = c; } } } void OutlinerMath::sortVectorsX3D(const OutlinerVector3D* a, const OutlinerVector3D* b, const OutlinerVector3D* c, const OutlinerVector3D** nth0, const OutlinerVector3D** nth1, const OutlinerVector3D** nth2) { // Sanity checks assert(a != 0 && b != 0 && c != 0); assert(a != b && a != c && b != c); assert(nth0 != 0 && nth1 != 0 && nth2 != 0); *nth0 = *nth1 = *nth2 = 0; // There are 6 permutations of three numbers. Simply test for each condition. if (a->x < b->x) { if (c->x < a->x) { *nth0 = c; *nth1 = a; *nth2 = b; } else if (c->x < b->x) { *nth0 = a; *nth1 = c; *nth2 = b; } else { *nth0 = a; *nth1 = b; *nth2 = c; } } else { if (c->x < b->x) { *nth0 = c; *nth1 = b; *nth2 = a; } else if (c->x < a->x) { *nth0 = b; *nth1 = c; *nth2 = a; } else { *nth0 = b; *nth1 = a; *nth2 = c; } } // More sanity checks assert(*nth0 != *nth1); assert(*nth0 != *nth2); assert(*nth1 != *nth2); assert((*nth0)->x <= (*nth1)->x); assert((*nth1)->x <= (*nth2)->x); } void OutlinerMath::sortVectorsY3D(const OutlinerVector3D* a, const OutlinerVector3D* b, const OutlinerVector3D* c, const OutlinerVector3D** nth0, const OutlinerVector3D** nth1, const OutlinerVector3D** nth2) { // Sanity checks assert(a != 0 && b != 0 && c != 0); assert(a != b && a != c && b != c); assert(nth0 != 0 && nth1 != 0 && nth2 != 0); *nth0 = *nth1 = *nth2 = 0; // There are 6 permutations of three numbers. Simply test for each condition. if (a->y < b->y) { if (c->y < a->y) { *nth0 = c; *nth1 = a; *nth2 = b; } else if (c->y < b->y) { *nth0 = a; *nth1 = c; *nth2 = b; } else { *nth0 = a; *nth1 = b; *nth2 = c; } } else { if (c->y < b->y) { *nth0 = c; *nth1 = b; *nth2 = a; } else if (c->y < a->y) { *nth0 = b; *nth1 = c; *nth2 = a; } else { *nth0 = b; *nth1 = a; *nth2 = c; } } // More sanity checks assert(*nth0 != *nth1); assert(*nth0 != *nth2); assert(*nth1 != *nth2); assert((*nth0)->y <= (*nth1)->y); assert((*nth1)->y <= (*nth2)->y); } void OutlinerMath::sortVectorsZ3D(const OutlinerVector3D* a, const OutlinerVector3D* b, const OutlinerVector3D* c, const OutlinerVector3D** nth0, const OutlinerVector3D** nth1, const OutlinerVector3D** nth2) { // Sanity checks assert(a != 0 && b != 0 && c != 0); assert(a != b && a != c && b != c); assert(nth0 != 0 && nth1 != 0 && nth2 != 0); *nth0 = *nth1 = *nth2 = 0; if (debugbbit3) debugf(" z input range in svz3 %.2f, %.2f, %.2f", a->z, b->z, c->z); // There are 6 permutations of three numbers. Simply test for each condition. if (a->z < b->z) { if (c->z < a->z) { *nth0 = c; *nth1 = a; *nth2 = b; } else if (c->z < b->z) { *nth0 = a; *nth1 = c; *nth2 = b; } else { *nth0 = a; *nth1 = b; *nth2 = c; } } else { if (c->z < b->z) { *nth0 = c; *nth1 = b; *nth2 = a; } else if (c->z < a->z) { *nth0 = b; *nth1 = c; *nth2 = a; } else { *nth0 = b; *nth1 = a; *nth2 = c; } } // More sanity checks assert(*nth0 != *nth1); assert(*nth0 != *nth2); assert(*nth1 != *nth2); assert((*nth0)->z <= (*nth1)->z); assert((*nth1)->z <= (*nth2)->z); } /////////////////////////////////////////////////////////////////////////////////////////////// // Test functions ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void OutlinerMath::mathTests(void) { infof("running math tests"); utilityTests(); vectorTests(); detTests(); lineIntersectionTests(); triangleTests(); boundingBoxTests(); triangleBoundingBoxTests(); infof("math tests ok"); } void OutlinerMath::utilityTests(void) { debugf("utility tests..."); // Between tests assert(outlinerbetweenepsilon(1,2,3)); assert(outlinerbetweenepsilon(1,2.000000001,2)); assert(!outlinerbetweenepsilon(1,3,2)); assert(!outlinerbetweenepsilon(3,2,1)); // Betweenanyorder tests assert(outlinerbetweenanyorderepsilon(1,2,3)); assert(outlinerbetweenanyorderepsilon(1,2,2)); assert(outlinerbetweenanyorderepsilon(2,2.0000000000003,1)); assert(!outlinerbetweenanyorderepsilon(1,3,2)); assert(!outlinerbetweenanyorderepsilon(2,3,1)); assert(outlinerbetweenanyorderepsilon(3,2,1)); // Overlap tests assert(outlineroverlapepsilon(1,2,2.00000000007,4)); assert(outlineroverlap(1,10,2,4)); assert(outlineroverlap(2,3,0,10)); assert(!outlineroverlap(1,2,3,4)); assert(!outlineroverlap(3,4,1,2)); // Overlapanyorder tests assert(outlineroverlapanyorder(1,2,2,4)); assert(outlineroverlapanyorder(2,1,2,4)); assert(outlineroverlapanyorder(2,1,4,2)); assert(outlineroverlapanyorder(1,2,4,2)); assert(outlineroverlapanyorder(1,10,4,2)); assert(outlineroverlapanyorder(2,3,100,1)); assert(!outlineroverlapanyorder(1,2,3,4)); assert(!outlineroverlapanyorder(4,3,2,1)); } void OutlinerMath::vectorTests(void) { debugf("vector tests..."); OutlinerVector2D a(2,2); OutlinerVector2D b(3,3); OutlinerVector2D result; vectorTo(a,b,result); deepdebugf("vector test: result: (%f,%f)", result.x, result.y); assert(result.x == 1); assert(result.y == 1); } void OutlinerMath::detTests(void) { debugf("det tests..."); OutlinerVector2D C1(4,2); OutlinerVector2D C2(1,3); outlinerreal result = determinant2x2(C1,C2); deepdebugf("determinant result = %.2f", result); assert(result == 10); } void OutlinerMath::boundingBoxTests(void) { debugf("bounding box tests..."); OutlinerVector2D a(0,0); OutlinerVector2D b(0,3); OutlinerVector2D c(2,0); OutlinerBox2D boundingBox; debugf("bounding box tests"); OutlinerTriangle2D tone(a,a,a); triangleBoundingBox2D(tone,boundingBox); debugf("a,a,a bounding box [%.2f,%.2f] to [%.2f,%.2f]", boundingBox.start.x, boundingBox.start.y, boundingBox.end.x, boundingBox.end.y); assert(boundingBox.start.x == 0 && boundingBox.start.y == 0); assert(boundingBox.end.x == 0 && boundingBox.end.y == 0); OutlinerTriangle2D t(a,b,c); triangleBoundingBox2D(t,boundingBox); debugf("a,b,c bounding box [%.2f,%.2f] to [%.2f,%.2f]", boundingBox.start.x, boundingBox.start.y, boundingBox.end.x, boundingBox.end.y); assert(boundingBox.start.x == 0 && boundingBox.start.y == 0); assert(boundingBox.end.x == 2 && boundingBox.end.y == 3); OutlinerTriangle2D trev(c,b,a); triangleBoundingBox2D(trev,boundingBox); debugf("c,b,a bounding box [%.2f,%.2f] to [%.2f,%.2f]", boundingBox.start.x, boundingBox.start.y, boundingBox.end.x, boundingBox.end.y); assert(boundingBox.start.x == 0 && boundingBox.start.y == 0); assert(boundingBox.end.x == 2 && boundingBox.end.y == 3); OutlinerVector2D x(-10,-10); OutlinerVector2D y(10,10); OutlinerVector2D z(30,9); OutlinerTriangle2D trevx(z,y,x); triangleBoundingBox2D(trevx,boundingBox); debugf("z,y,x bounding box [%.2f,%.2f] to [%.2f,%.2f]", boundingBox.start.x, boundingBox.start.y, boundingBox.end.x, boundingBox.end.y); assert(boundingBox.start.x == -10 && boundingBox.start.y == -10); assert(boundingBox.end.x == 30 && boundingBox.end.y == 10); OutlinerTriangle2D trevx2(y,z,x); triangleBoundingBox2D(trevx2,boundingBox); debugf("y,z,x bounding box [%.2f,%.2f] to [%.2f,%.2f]", boundingBox.start.x, boundingBox.start.y, boundingBox.end.x, boundingBox.end.y); assert(boundingBox.start.x == -10 && boundingBox.start.y == -10); assert(boundingBox.end.x == 30 && boundingBox.end.y == 10); OutlinerVector2D bbtest1start(10,10); OutlinerVector2D bbtest1end(20,30); OutlinerBox2D bbtest1(bbtest1start,bbtest1end); OutlinerVector2D bbtest1point1(0,25); OutlinerVector2D bbtest1point2(10,10); OutlinerVector2D bbtest1point3(20,30); OutlinerVector2D bbtest1point4(30,30); OutlinerVector2D bbtest1point5(11,15); bool ans = bbtest1.pointInside(bbtest1point1); assert(ans == 0); ans = bbtest1.pointInside(bbtest1point2); assert(ans == 1); ans = bbtest1.pointInside(bbtest1point3); assert(ans == 1); ans = bbtest1.pointInside(bbtest1point4); assert(ans == 0); ans = bbtest1.pointInside(bbtest1point5); assert(ans == 1); } void OutlinerMath::lineIntersectionTests() { debugf("line intersection tests..."); // Vertical line intersection 1 { OutlinerVector2D a(10,10); OutlinerVector2D b1(20,20); OutlinerVector2D b2(20,15); OutlinerVector2D vl1start(1,0); OutlinerVector2D vl1end(1,40); OutlinerVector2D vl2start(11,0); OutlinerVector2D vl2end(11,40); OutlinerLine2D ab1(a,b1); OutlinerLine2D ab2(a,b2); OutlinerLine2D vl1(vl1start,vl1end); OutlinerLine2D vl2(vl2start,vl2end); OutlinerVector2D inter; bool ans; ans = lineIntersectsVerticalLine2D(ab1,vl1,inter); assert(!ans); ans = lineIntersectsVerticalLine2D(ab1,vl2,inter); assert(ans); deepdebugf("vertical line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.x == 11); assert(inter.y == 11); ans = lineIntersectsVerticalLine2D(ab2,vl2,inter); assert(ans); deepdebugf("vertical line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.x == 11); assert(inter.y == 10.5); } // Vertical line intersection 2 { OutlinerVector2D a(10,10); OutlinerVector2D b(12,20); OutlinerVector2D vl1start(11,0); OutlinerVector2D vl1end(11,9); OutlinerVector2D vl2start(11,0); OutlinerVector2D vl2end(11,14); OutlinerVector2D vl3start(11,10); OutlinerVector2D vl3end(11,15); OutlinerVector2D vl4start(11,10); OutlinerVector2D vl4end(11,16); OutlinerLine2D ab(a,b); OutlinerLine2D vl1(vl1start,vl1end); OutlinerLine2D vl2(vl2start,vl2end); OutlinerLine2D vl3(vl3start,vl3end); OutlinerLine2D vl4(vl4start,vl4end); OutlinerVector2D inter; bool ans; ans = lineIntersectsVerticalLine2D(ab,vl1,inter); assert(!ans); ans = lineIntersectsVerticalLine2D(ab,vl2,inter); assert(!ans); ans = lineIntersectsVerticalLine2D(ab,vl3,inter); assert(ans); deepdebugf("vertical line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.x == 11); assert(inter.y == 15); ans = lineIntersectsVerticalLine2D(ab,vl4,inter); assert(ans); deepdebugf("vertical line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.x == 11); assert(inter.y == 15); } // Vertical line intersection 3 (parallel lines) { OutlinerVector2D a(10,10); OutlinerVector2D b(10,20); OutlinerVector2D vl1start(9,15); OutlinerVector2D vl1end(9,16); OutlinerVector2D vl2start(10,5); OutlinerVector2D vl2end(10,9); OutlinerVector2D vl3start(10,15); OutlinerVector2D vl3end(10,16); OutlinerLine2D ab(a,b); OutlinerLine2D vl1(vl1start,vl1end); OutlinerLine2D vl2(vl2start,vl2end); OutlinerLine2D vl3(vl3start,vl3end); OutlinerVector2D inter; bool ans; ans = lineIntersectsVerticalLine2D(ab,vl1,inter); assert(!ans); ans = lineIntersectsVerticalLine2D(ab,vl2,inter); assert(!ans); ans = lineIntersectsVerticalLine2D(ab,vl3,inter); assert(ans); deepdebugf("vertical parallel line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.x == 10); assert(inter.y == 15); } // Horizontal line intersection 1 { OutlinerVector2D a(10,10); OutlinerVector2D b(20,20); OutlinerVector2D hl1start(0,10); OutlinerVector2D hl1end(10,10); OutlinerVector2D hl2start(0,15); OutlinerVector2D hl2end(20,15); OutlinerVector2D hl3start(0,21); OutlinerVector2D hl3end(20,21); OutlinerLine2D ab(a,b); OutlinerLine2D hl1(hl1start,hl1end); OutlinerLine2D hl2(hl2start,hl2end); OutlinerLine2D hl3(hl3start,hl3end); OutlinerVector2D inter; bool ans; ans = lineIntersectsHorizontalLine2D(ab,hl1,inter); assert(ans); deepdebugf("horizontal line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.x == 10); assert(inter.y == 10); ans = lineIntersectsHorizontalLine2D(ab,hl2,inter); assert(ans); deepdebugf("horizontal line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.x == 15); assert(inter.y == 15); ans = lineIntersectsHorizontalLine2D(ab,hl3,inter); assert(!ans); } // Vertical line intersection 2 (parallel lines) { OutlinerVector2D a(10,10); OutlinerVector2D b(20,10); OutlinerVector2D hl1start(15,9); OutlinerVector2D hl1end(16,9); OutlinerVector2D hl2start(5,10); OutlinerVector2D hl2end(9,10); OutlinerVector2D hl3start(15,10); OutlinerVector2D hl3end(16,10); OutlinerLine2D ab(a,b); OutlinerLine2D hl1(hl1start,hl1end); OutlinerLine2D hl2(hl2start,hl2end); OutlinerLine2D hl3(hl3start,hl3end); OutlinerVector2D inter; bool ans; ans = lineIntersectsHorizontalLine2D(ab,hl1,inter); assert(!ans); ans = lineIntersectsHorizontalLine2D(ab,hl2,inter); assert(!ans); ans = lineIntersectsHorizontalLine2D(ab,hl3,inter); assert(ans); deepdebugf("horizontal parallel line intersection %.2f, %.2f", inter.x, inter.y); assert(inter.y == 10); assert(inter.x == 15); } } void OutlinerMath::triangleTests(void) { debugf("triangle tests (2D)..."); OutlinerVector2D a(0,0); OutlinerVector2D b(0,2); OutlinerVector2D c(2,0); OutlinerVector2D pointfar(2,2); OutlinerVector2D pointnear(0.5,0.5); OutlinerVector2D pointverynear(0.1,0.2); OutlinerVector2D pointata = a; OutlinerVector2D pointatb = b; OutlinerVector2D pointatc = c; OutlinerVector2D pointbeyondb = b; pointbeyondb.x += 0.01; pointbeyondb.y += 0.01; OutlinerVector2D pointbefore1(-0.001,0); OutlinerVector2D pointbefore2(0,-0.001); OutlinerVector2D pointbefore3(-0.001,-0.001); OutlinerTriangle2D t(a,b,c); bool ansfar = pointInsideTriangle2D(t,pointfar); deepdebugf("triangle test: pointfar = %u", ansfar); bool ansnear = pointInsideTriangle2D(t,pointnear); deepdebugf("triangle test: pointnear = %u", ansnear); bool ansverynear = pointInsideTriangle2D(t,pointverynear); deepdebugf("triangle test: pointverynear = %u", ansverynear); bool ansata = pointInsideTriangle2D(t,pointata); deepdebugf("triangle test: pointata = %u", ansata); bool ansatb = pointInsideTriangle2D(t,pointatb); deepdebugf("triangle test: pointatb = %u", ansatb); bool ansatc = pointInsideTriangle2D(t,pointatc); deepdebugf("triangle test: pointatc = %u", ansatc); bool ansbeyondb = pointInsideTriangle2D(t,pointbeyondb); deepdebugf("triangle test: pointbeyondb = %u", ansbeyondb); bool ansbefore1 = pointInsideTriangle2D(t,pointbefore1); deepdebugf("triangle test: pointbefore1 = %u", ansbefore1); bool ansbefore2 = pointInsideTriangle2D(t,pointbefore2); deepdebugf("triangle test: pointbefore2 = %u", ansbefore2); bool ansbefore3 = pointInsideTriangle2D(t,pointbefore3); deepdebugf("triangle test: pointbefore3 = %u", ansbefore3); assert(ansfar == 0); assert(ansnear == 1); assert(ansverynear == 1); assert(ansata == 1); assert(ansatb == 1); assert(ansatc == 1); assert(ansbeyondb == 0); assert(ansbefore1 == 0); assert(ansbefore2 == 0); assert(ansbefore3 == 0); // 3D triangle tests debugf("triangle tests (3D)..."); OutlinerVector3D a3(0,0,10); OutlinerVector3D b3(0,2,10); OutlinerVector3D c3(2,0,10); OutlinerVector3D boundingStart3a(0,0,0); OutlinerVector3D boundingEnd3a(5,5,5); OutlinerBox3D boundingBox3a(boundingStart3a,boundingEnd3a); OutlinerVector3D boundingStart3b(0,0,0); OutlinerVector3D boundingEnd3b(5,5,10); OutlinerBox3D boundingBox3b(boundingStart3b,boundingEnd3b); OutlinerTriangle3D t3(a3,b3,c3); bool ans3 = boundingBoxIntersectsTriangle3D(t3,boundingBox3a); assert(!ans3); ans3 = boundingBoxIntersectsTriangle3D(t3,boundingBox3b); assert(ans3); // Bug test for 3D triangle cases debugf("triangle tests (3D bug)..."); OutlinerVector3D bugBoxStart(0.00,-1.00,0.00); OutlinerVector3D bugBoxEnd(0.00,-0.50,0.50); OutlinerBox3D bugBox(bugBoxStart,bugBoxEnd); OutlinerVector3D buga(1.00, -1.00, -1.00); OutlinerVector3D bugb(-1.00,-1.00, 1.00); OutlinerVector3D bugc(-1.00,-1.00,-1.00); OutlinerTriangle3D bugt(buga,bugb,bugc); bool ansbug = boundingBoxIntersectsTriangle3D(bugt,bugBox); assert(ansbug); // Cross section bug tests debugf("triangle tests (cross section bug)..."); OutlinerVector3D ta( 1.000000,-1.000000,-1.000000); OutlinerVector3D tb(-1.000000,-1.000000, 1.000000); OutlinerVector3D tc(-1.000000,-1.000000,-1.000000); OutlinerTriangle3D tr(ta,tb,tc); OutlinerBox3D thisBox(0.00,-1.00,0.00,0.00,-0.90,0.10); bool crossBugAns = boundingBoxIntersectsTriangle3D(tr,thisBox); debugf("crossBugAns = %u", crossBugAns); assert(crossBugAns); debugf("triangle tests (cross section bug) ok"); } void OutlinerMath::triangleBoundingBoxTests(void) { infof("triangle bounding box tests.."); OutlinerVector2D a(0,0); OutlinerVector2D b(0,10); OutlinerVector2D c(20,0); OutlinerVector2D degenerate1a(1,1); OutlinerVector2D degenerate1b(1,1); OutlinerVector2D degenerate1c(-1,1); OutlinerVector2D degenerate2a(1,1); OutlinerVector2D degenerate2b(1,1); OutlinerVector2D degenerate2c(-1,-1); OutlinerVector2D box1Start(-10,-10); OutlinerVector2D box1End(-1,-1); OutlinerBox2D box1(box1Start,box1End); OutlinerVector2D box2Start(-10,-10); OutlinerVector2D box2End(5,5); OutlinerBox2D box2(box2Start,box2End); OutlinerVector2D box3Start(-1000,-1000); OutlinerVector2D box3End(1000,1000); OutlinerBox2D box3(box3Start,box3End); OutlinerVector2D box4Start(-10,-10); OutlinerVector2D box4End(0,0); OutlinerBox2D box4(box4Start,box4End); OutlinerVector2D box5Start(0.0,0.0); OutlinerVector2D box5End(0.0,0.50); OutlinerBox2D box5(box5Start,box5End); OutlinerTriangle2D t(a,b,c); bool ans = boundingBoxIntersectsTriangle2D(t,box1); assert(!ans); ans = boundingBoxIntersectsTriangle2D(t,box2); assert(ans); ans = boundingBoxIntersectsTriangle2D(t,box3); assert(ans); ans = boundingBoxIntersectsTriangle2D(t,box4); assert(ans); OutlinerTriangle2D degenerate1t(degenerate1a,degenerate1b,degenerate1c); ans = boundingBoxIntersectsTriangle2D(degenerate1t,box5); assert(!ans); OutlinerTriangle2D degenerate2t(degenerate2a,degenerate2b,degenerate2c); ans = boundingBoxIntersectsTriangle2D(degenerate2t,box5); assert(ans); infof("triangle bounding box tests ok"); }
36.657423
134
0.598349
jariarkko
8346580da28577cf886a6b790c76954016dbae04
502
cpp
C++
src/Game/zAnimList.cpp
stravant/bfbbdecomp
2126be355a6bb8171b850f829c1f2731c8b5de08
[ "OLDAP-2.7" ]
1
2021-01-05T11:28:55.000Z
2021-01-05T11:28:55.000Z
src/Game/zAnimList.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
null
null
null
src/Game/zAnimList.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
1
2022-03-30T15:15:08.000Z
2022-03-30T15:15:08.000Z
#include "zAnimList.h" #include <types.h> // func_8004E7E0 #pragma GLOBAL_ASM("asm/Game/zAnimList.s", "AlwaysConditional__FP15xAnimTransitionP11xAnimSinglePv") // func_8004E7E8 #pragma GLOBAL_ASM("asm/Game/zAnimList.s", "zAnimListInit__Fv") // func_8004EB44 #pragma GLOBAL_ASM("asm/Game/zAnimList.s", "zAnimListExit__Fv") // func_8004EB5C #pragma GLOBAL_ASM("asm/Game/zAnimList.s", "zAnimListGetTable__FUi") // func_8004EBA4 #pragma GLOBAL_ASM("asm/Game/zAnimList.s", "zAnimListGetNumUsed__FUi")
26.421053
100
0.784861
stravant
834f5bc52c56b23ab32e5ce48f569ce18e7ab568
98
cpp
C++
ECS/src/provided/Component/MonoBehaviourComponent.cpp
MichielCuijpers/Starfarm
560786282e105be043807820eee400db461d18f6
[ "MIT" ]
null
null
null
ECS/src/provided/Component/MonoBehaviourComponent.cpp
MichielCuijpers/Starfarm
560786282e105be043807820eee400db461d18f6
[ "MIT" ]
null
null
null
ECS/src/provided/Component/MonoBehaviourComponent.cpp
MichielCuijpers/Starfarm
560786282e105be043807820eee400db461d18f6
[ "MIT" ]
null
null
null
// // Created by TipLa on 14/04/2019. // #include "MonoBehaviourComponent.hpp" namespace ecs {}
10.888889
37
0.693878
MichielCuijpers
8354e51f173c69843a14551cf2691f141420432c
2,464
cpp
C++
graph-source-code/237-E/2433613.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/237-E/2433613.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/237-E/2433613.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: MS C++ #pragma comment(linker,"/STACK:300000000") #define _CRT_SECURE_NO_WARNINGS #pragma warning(disable:4800) #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cmath> #include <map> #include <set> #include <iomanip> #include <memory.h> #include <cstdio> #include <sstream> #include <deque> #include <bitset> #include <numeric> #include <ctime> #include <queue> #include <hash_map> using namespace std; using namespace stdext; #define show(x) cout << #x << " = " << (x) << endl; void showTime() { cerr << (double)clock()/CLOCKS_PER_SEC << endl; } #define fori(i,n) for(int i = 0; i < (n); i++) #define forab(i,a,b) for(int i = (a); i <= (b); i++) #define sz(v) int((v).size()) #define all(v) (v).begin(),(v).end() const double pi = 3.1415926535897932384626433832795; template<class T> T abs(const T &a) { return a >= 0 ? a : -a; }; template<class T> T sqr(const T &x) { return x * x; } typedef pair<int,int> ii; typedef long long ll; /////////////////////////////////////// //vector<vector<int> > g; int c[200][200]; int f[200][200]; int cf(int x, int y) { return c[x][y]-f[x][y]; } string s; int n; int last; bool visited[200]; bool dfs(int k, vector<int> &path) { visited[k] = true; path.push_back(k); if(k == last) return true; fori(to,last+1) { if(cf(k,to) > 0 && !visited[to]) { if(dfs(to,path)) return true; } } path.pop_back(); return false; } bool hasPath(vector<int> &path) { path.clear(); memset(visited,0,sizeof(visited)); return dfs(0,path); } void maxFlow() { vector<int> path; while(hasPath(path)) { int mi = int(1e9); fori(i,sz(path)-1) mi = min(mi,cf(path[i],path[i+1])); cerr << mi << endl; fori(i,sz(path)-1) { f[path[i]][path[i+1]] += mi; f[path[i+1]][path[i]] -= mi; } } } int main() { #ifdef TEDDY_BEARS freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #else //freopen(FILENAME".in","r",stdin); //freopen(FILENAME".out","w",stdout); #endif cin >> s >> n; last = n+27; fori(i,sz(s)) c[n+s[i]-'a'+1][last]++; fori(i,n) { cin >> s; cin >> c[0][i+1]; fori(j,sz(s)) c[i+1][n+s[j]-'a'+1]++; maxFlow(); } fori(i,26) if(cf(n+i+1,last) != 0) { cout << -1; exit(0); } int ans = 0; for(int i = 1; i <= n; i++) ans += i*f[0][i]; cout << ans; }
18.666667
68
0.54789
AmrARaouf
835a747f269830c3b3245f29ebb08b70fc80b85b
117
cpp
C++
cpp/backup/Thread/ThreadManager.cpp
cheukw/sample
602d5d055c3e11e1e0ba385128e64b9c0aa81305
[ "MIT" ]
null
null
null
cpp/backup/Thread/ThreadManager.cpp
cheukw/sample
602d5d055c3e11e1e0ba385128e64b9c0aa81305
[ "MIT" ]
null
null
null
cpp/backup/Thread/ThreadManager.cpp
cheukw/sample
602d5d055c3e11e1e0ba385128e64b9c0aa81305
[ "MIT" ]
null
null
null
#include "ThreadManager.h" ThreadManager::ThreadManager() { } ThreadManager::~ThreadManager() { }
8.357143
32
0.623932
cheukw
835b124c3b6021f9168b2075b5aab6c9388004f8
1,979
hpp
C++
include/common/tsqueue.hpp
AlexandruIca/NetworkMessages
07a822d046d0e593b9310536327ec614ff20601e
[ "Unlicense" ]
null
null
null
include/common/tsqueue.hpp
AlexandruIca/NetworkMessages
07a822d046d0e593b9310536327ec614ff20601e
[ "Unlicense" ]
null
null
null
include/common/tsqueue.hpp
AlexandruIca/NetworkMessages
07a822d046d0e593b9310536327ec614ff20601e
[ "Unlicense" ]
null
null
null
#ifndef NET_COMMON_TSQUEUE_HPP #define NET_COMMON_TSQUEUE_HPP #pragma once #include <cstddef> #include <deque> #include <mutex> #include <utility> namespace net { template<typename T> class tsqueue { private: mutable std::mutex m_mutex; std::deque<T> m_queue; public: tsqueue() = default; tsqueue(tsqueue const&) = delete; tsqueue(tsqueue&&) noexcept = default; ~tsqueue() noexcept = default; auto operator=(tsqueue const&) -> tsqueue& = delete; auto operator=(tsqueue&&) noexcept -> tsqueue& = default; auto front() -> T const& { std::scoped_lock<std::mutex> lock{ m_mutex }; return m_queue.front(); } auto back() -> T const& { std::scoped_lock<std::mutex> lock{ m_mutex }; return m_queue.back(); } auto push_back(T&& elem) -> void { std::scoped_lock<std::mutex> lock{ m_mutex }; m_queue.push_back(std::forward<T>(elem)); } auto push_front(T&& elem) -> void { std::scoped_lock<std::mutex> lock{ m_mutex }; m_queue.push_front(std::forward<T>(elem)); } [[nodiscard]] auto empty() const noexcept -> bool { std::scoped_lock<std::mutex> lock{ m_mutex }; return m_queue.empty(); } [[nodiscard]] auto count() const noexcept -> std::size_t { std::scoped_lock<std::mutex> lock{ m_mutex }; return m_queue.size(); } auto clear() -> void { std::scoped_lock<std::mutex> lock{ m_mutex }; m_queue.clear(); } auto pop_front() -> T { std::scoped_lock<std::mutex> lock{ m_mutex }; auto result = std::move(m_queue.front()); m_queue.pop_front(); return result; } auto pop_back() -> T { std::scoped_lock<std::mutex> lock{ m_mutex }; auto result = std::move(m_queue.back()); m_queue.pop_back(); return result; } }; } // namespace net #endif // !NET_COMMON_TSQUEUE_HPP
21.988889
61
0.586155
AlexandruIca