text
stringlengths
54
60.6k
<commit_before>/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ struct cmp{ bool operator()(const ListNode *a, const ListNode *b){ return a->val > b->val; } }; ListNode *mergeKLists(vector<ListNode*> &lists) { // write your code here ListNode *dummy = new ListNode(-1); ListNode *pre=dummy; priority_queue<ListNode*, vector<ListNode*>, cmp> pq; // insert not-null head into pq; for(auto node : lists){ if(node){ pq.push(node); } } // pop back while(!pq.empty()){ ListNode *tmp=pq.top(); pq.pop(); if(tmp->next){ pq.push(tmp->next); } pre->next=tmp; pre=pre->next; } return dummy->next; } };<commit_msg>update comment<commit_after>/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ struct cmp{ bool operator()(const ListNode *a, const ListNode *b){ return a->val > b->val; } }; ListNode *mergeKLists(vector<ListNode*> &lists) { // write your code here ListNode *dummy = new ListNode(-1); ListNode *pre=dummy; // make it a min-heap priority_queue<ListNode*, vector<ListNode*>, cmp> pq; // insert not-null head into pq; for(auto node : lists){ if(node){ pq.push(node); } } // pop the min and push its successor it exists while(!pq.empty()){ ListNode *tmp=pq.top(); pq.pop(); if(tmp->next){ pq.push(tmp->next); } pre->next=tmp; pre=pre->next; } return dummy->next; } };<|endoftext|>
<commit_before>#include <benchmark/benchmark.h> BENCHMARK_MAIN(); <commit_msg>Fix benchmarks crashing on exit (#295)<commit_after>#include <benchmark/benchmark.h> int main(int argc, char** argv) { // mostly taken from the BENCHMARK_MAIN macro ::benchmark::Initialize(&argc, argv); if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; ::benchmark::RunSpecifiedBenchmarks(); /* * Cleanup benchmarks right away so we dont get into race conditions * with the NUMA memory resources. */ ::benchmark::ClearRegisteredBenchmarks(); } <|endoftext|>
<commit_before>/* Copyright 2017 Thomas Krause <thomaskrause@posteo.de> 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 <celero/Celero.h> #include <humblelogging/api.h> #include "dynamicbenchmark.h" #include <annis/util/threadpool.h> using namespace annis; int main(int argc, char **argv) { humble::logging::Factory &fac = humble::logging::Factory::getInstance(); fac.setConfiguration(humble::logging::DefaultConfiguration::createFromString( "logger.level(*)=info\n" )); fac.setDefaultFormatter(new humble::logging::PatternFormatter("[%date]- %m (%lls, %filename:%line)\n")); fac.registerAppender(new humble::logging::FileAppender("benchmark_annis4.log", true)); if(argc > 1) { std::string benchmarkDir(argv[1]); // find all sub-directories of the "queries" folder boost::filesystem::directory_iterator fileEndIt; boost::filesystem::directory_iterator itFiles(benchmarkDir + "/queries"); while(itFiles != fileEndIt) { if(itFiles->status().type() == boost::filesystem::directory_file) { const auto subdirPath = itFiles->path(); std::string subdir = subdirPath.string(); std::string corpusName = subdirPath.filename().string(); // get the corpus path (is subfolder of "data" folder) std::string corpusPath = benchmarkDir + "/data/" + corpusName; DynamicBenchmark benchmark(subdir, corpusPath, corpusName, 6000000, true); { // default configuration and all optimizations enabled but no parallization QueryConfig config; benchmark.registerFixture("default", config); } { // No optimized graph storages QueryConfig config; config.forceFallback = true; benchmark.registerFixture("force_fallback", config); } { // no query optimization at all QueryConfig config; config.optimize = false; benchmark.registerFixture("no_optimization", config); } { // no operand order optimization QueryConfig config; config.optimize_operand_order = false; benchmark.registerFixture("no_operand_order", config); } { // no unbound regex optimization QueryConfig config; config.optimize_operand_order = false; benchmark.registerFixture("no_unbound_regex", config); } { // no node by edge annotation search QueryConfig config; config.optimize_nodeby_edgeanno = false; benchmark.registerFixture("no_nodeby_edgeanno", config); } { // no join order optimization QueryConfig config; config.optimize_join_order = false; benchmark.registerFixture("no_join_order", config); } { // not using all permutations in join order optimization QueryConfig config; config.all_permutations_threshold = 0; benchmark.registerFixture("no_join_order_permutation", config); } // add different parallel configurations for threads and SIMD (+thread) unsigned int numOfCPUs = std::thread::hardware_concurrency(); std::shared_ptr<ThreadPool> sharedThreadPool = std::make_shared<ThreadPool>(numOfCPUs); for(int i=2; i <= numOfCPUs; i += 2) { QueryConfig config; config.threadPool = i > 0 ? sharedThreadPool : nullptr; config.numOfBackgroundTasks = i; config.enableSIMDIndexJoin = false; benchmark.registerFixture("threads_" + std::to_string(i), config); } for(int i=0; i <= numOfCPUs; i += 2) { QueryConfig config; config.threadPool = i > 0 ? sharedThreadPool : nullptr; config.numOfBackgroundTasks = i; config.enableSIMDIndexJoin = true; benchmark.registerFixture("simd_" + std::to_string(i), config); } } itFiles++; } celero::Run(argc, argv); } else { std::cout << "You have to give a benchmark directy (which contains a \"queries\" and \"data\" sub-directory) as argument." << std::endl; } return 0; } <commit_msg>Add task index join to benchmark<commit_after>/* Copyright 2017 Thomas Krause <thomaskrause@posteo.de> 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 <celero/Celero.h> #include <humblelogging/api.h> #include "dynamicbenchmark.h" #include <annis/util/threadpool.h> using namespace annis; int main(int argc, char **argv) { humble::logging::Factory &fac = humble::logging::Factory::getInstance(); fac.setConfiguration(humble::logging::DefaultConfiguration::createFromString( "logger.level(*)=info\n" )); fac.setDefaultFormatter(new humble::logging::PatternFormatter("[%date]- %m (%lls, %filename:%line)\n")); fac.registerAppender(new humble::logging::FileAppender("benchmark_annis4.log", true)); if(argc > 1) { std::string benchmarkDir(argv[1]); // find all sub-directories of the "queries" folder boost::filesystem::directory_iterator fileEndIt; boost::filesystem::directory_iterator itFiles(benchmarkDir + "/queries"); while(itFiles != fileEndIt) { if(itFiles->status().type() == boost::filesystem::directory_file) { const auto subdirPath = itFiles->path(); std::string subdir = subdirPath.string(); std::string corpusName = subdirPath.filename().string(); // get the corpus path (is subfolder of "data" folder) std::string corpusPath = benchmarkDir + "/data/" + corpusName; DynamicBenchmark benchmark(subdir, corpusPath, corpusName, 6000000, true); { // default configuration and all optimizations enabled but no parallization QueryConfig config; benchmark.registerFixture("default", config); } { // No optimized graph storages QueryConfig config; config.forceFallback = true; benchmark.registerFixture("force_fallback", config); } { // no query optimization at all QueryConfig config; config.optimize = false; benchmark.registerFixture("no_optimization", config); } { // no operand order optimization QueryConfig config; config.optimize_operand_order = false; benchmark.registerFixture("no_operand_order", config); } { // no unbound regex optimization QueryConfig config; config.optimize_operand_order = false; benchmark.registerFixture("no_unbound_regex", config); } { // no node by edge annotation search QueryConfig config; config.optimize_nodeby_edgeanno = false; benchmark.registerFixture("no_nodeby_edgeanno", config); } { // no join order optimization QueryConfig config; config.optimize_join_order = false; benchmark.registerFixture("no_join_order", config); } { // not using all permutations in join order optimization QueryConfig config; config.all_permutations_threshold = 0; benchmark.registerFixture("no_join_order_permutation", config); } // add different parallel configurations for threads and SIMD (+thread) unsigned int numOfCPUs = std::thread::hardware_concurrency(); std::shared_ptr<ThreadPool> sharedThreadPool = std::make_shared<ThreadPool>(numOfCPUs); for(int i=2; i <= numOfCPUs; i += 2) { QueryConfig config; config.threadPool = i > 0 ? sharedThreadPool : nullptr; config.numOfBackgroundTasks = i; config.enableSIMDIndexJoin = false; config.enableThreadIndexJoin = true; config.enableTaskIndexJoin = false; benchmark.registerFixture("threads_" + std::to_string(i), config); } for(int i=2; i <= numOfCPUs; i += 2) { QueryConfig config; config.threadPool = i > 0 ? sharedThreadPool : nullptr; config.numOfBackgroundTasks = i; config.enableSIMDIndexJoin = false; config.enableThreadIndexJoin = false; config.enableTaskIndexJoin = true; benchmark.registerFixture("tasks_" + std::to_string(i), config); } for(int i=0; i <= numOfCPUs; i += 2) { QueryConfig config; config.threadPool = i > 0 ? sharedThreadPool : nullptr; config.numOfBackgroundTasks = i; config.enableSIMDIndexJoin = true; config.enableThreadIndexJoin = false; config.enableTaskIndexJoin = false; benchmark.registerFixture("simd_" + std::to_string(i), config); } } itFiles++; } celero::Run(argc, argv); } else { std::cout << "You have to give a benchmark directy (which contains a \"queries\" and \"data\" sub-directory) as argument." << std::endl; } return 0; } <|endoftext|>
<commit_before>#include "video.h" #include <string> #include <vector> using std::string; using std::vector; void Video::ShowVideo() const { const string& video_path = path; const vector<string>& image_files = all_frames; int annotated_frame_index = 0; // For the 0th annotation in this video, get the start and end frames. const int start_frame = annotations[0].frame_num; const int end_frame = annotations[annotations.size() - 1].frame_num; // Iterate over all frames in this video. for (size_t image_frame_num = start_frame; image_frame_num <= end_frame; ++image_frame_num) { // Load the image. const string& image_file = video_path + "/" + image_files[image_frame_num]; cv::Mat image = cv::imread(image_file); // Get the frame number for the next annotation. const int annotated_frame_num = annotations[annotated_frame_index].frame_num; bool has_bounding_box = false; // Check if the annotation frame number corresponds to the image frame number. if (annotated_frame_num == image_frame_num) { // Draw the annotation on the image. const BoundingBox& box = annotations[annotated_frame_index].bbox; box.DrawBoundingBox(&image); has_bounding_box = true; // Incremrent the annotation index. if (annotated_frame_index < annotations.size() - 1) { annotated_frame_index++; } } // Show the image with the annotation. if(!image.data ) { printf("Could not open or find image %s\n", image_file.c_str()); } else { cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. cv::imshow( "Display window", image ); // Show our image inside it. cv::waitKey(1); // Wait for a keystroke in the window } } // For all frames in video } void Video::LoadFirstAnnotation(int* first_frame, cv::Mat* image, BoundingBox* box) const { LoadAnnotation(0, first_frame, image, box); } void Video::LoadAnnotation(const int annotation_index, int* frame_num, cv::Mat* image, BoundingBox* box) const { // Get the annotation corresponding to this index. const Frame& annotated_frame = annotations[annotation_index]; // Get the frame number corresponding to this annotation. *frame_num = annotated_frame.frame_num; *box = annotated_frame.bbox; const string& video_path = path; const vector<string>& image_files = all_frames; if (image_files.empty()) { printf("Error - no image files for video at path: %s\n", path.c_str()); return; } else if (*frame_num >= image_files.size()) { printf("Cannot find frame: %d; only %zu image files were found at %s\n", *frame_num, image_files.size(), path.c_str()); return; } // Load the image corresponding to this annotation. const string& image_file = video_path + "/" + image_files[*frame_num]; *image = cv::imread(image_file); if (!image->data) { printf("Could not find file: %s\n", image_file.c_str()); } } bool Video::FindAnnotation(const int frame_num, BoundingBox* box) const { // Iterate over all annotations. for (size_t i = 0; i < annotations.size(); ++i) { const Frame& frame = annotations[i]; // Check if the annotation frame matches the desired frame. if (frame.frame_num == frame_num) { // If we found a match, return the corresponding annotation. *box = frame.bbox; return true; } } return false; } bool Video::LoadFrame(const int frame_num, const bool draw_bounding_box, const bool load_only_annotation, cv::Mat* image, BoundingBox* box) const { const string& video_path = path; const vector<string>& image_files = all_frames; // Load the image for this frame. if (!load_only_annotation) { const string& image_file = video_path + "/" + image_files[frame_num]; *image = cv::imread(image_file); } // Find the annotation (if it exists) for the desired frame_num. const bool has_annotation = FindAnnotation(frame_num, box); // Draw the annotation (if it exists) on the image. if (!load_only_annotation && has_annotation && draw_bounding_box) { box->DrawBoundingBox(image); } // Return whether we found an annotation for this frame. return has_annotation; } <commit_msg>Update video.cpp<commit_after>#define CPU_ONLY 1 #include "video.h" #include <string> #include <vector> using std::string; using std::vector; void Video::ShowVideo() const { const string& video_path = path; const vector<string>& image_files = all_frames; int annotated_frame_index = 0; // For the 0th annotation in this video, get the start and end frames. const int start_frame = annotations[0].frame_num; const int end_frame = annotations[annotations.size() - 1].frame_num; // Iterate over all frames in this video. for (size_t image_frame_num = start_frame; image_frame_num <= end_frame; ++image_frame_num) { // Load the image. const string& image_file = video_path + "/" + image_files[image_frame_num]; cv::Mat image = cv::imread(image_file); // Get the frame number for the next annotation. const int annotated_frame_num = annotations[annotated_frame_index].frame_num; bool has_bounding_box = false; // Check if the annotation frame number corresponds to the image frame number. if (annotated_frame_num == image_frame_num) { // Draw the annotation on the image. const BoundingBox& box = annotations[annotated_frame_index].bbox; box.DrawBoundingBox(&image); has_bounding_box = true; // Incremrent the annotation index. if (annotated_frame_index < annotations.size() - 1) { annotated_frame_index++; } } // Show the image with the annotation. if(!image.data ) { printf("Could not open or find image %s\n", image_file.c_str()); } else { cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. cv::imshow( "Display window", image ); // Show our image inside it. cv::waitKey(1); // Wait for a keystroke in the window } } // For all frames in video } void Video::LoadFirstAnnotation(int* first_frame, cv::Mat* image, BoundingBox* box) const { LoadAnnotation(0, first_frame, image, box); } void Video::LoadAnnotation(const int annotation_index, int* frame_num, cv::Mat* image, BoundingBox* box) const { // Get the annotation corresponding to this index. const Frame& annotated_frame = annotations[annotation_index]; // Get the frame number corresponding to this annotation. *frame_num = annotated_frame.frame_num; *box = annotated_frame.bbox; const string& video_path = path; const vector<string>& image_files = all_frames; if (image_files.empty()) { printf("Error - no image files for video at path: %s\n", path.c_str()); return; } else if (*frame_num >= image_files.size()) { printf("Cannot find frame: %d; only %zu image files were found at %s\n", *frame_num, image_files.size(), path.c_str()); return; } // Load the image corresponding to this annotation. const string& image_file = video_path + "/" + image_files[*frame_num]; *image = cv::imread(image_file); if (!image->data) { printf("Could not find file: %s\n", image_file.c_str()); } } bool Video::FindAnnotation(const int frame_num, BoundingBox* box) const { // Iterate over all annotations. for (size_t i = 0; i < annotations.size(); ++i) { const Frame& frame = annotations[i]; // Check if the annotation frame matches the desired frame. if (frame.frame_num == frame_num) { // If we found a match, return the corresponding annotation. *box = frame.bbox; return true; } } return false; } bool Video::LoadFrame(const int frame_num, const bool draw_bounding_box, const bool load_only_annotation, cv::Mat* image, BoundingBox* box) const { const string& video_path = path; const vector<string>& image_files = all_frames; // Load the image for this frame. if (!load_only_annotation) { const string& image_file = video_path + "/" + image_files[frame_num]; *image = cv::imread(image_file); } // Find the annotation (if it exists) for the desired frame_num. const bool has_annotation = FindAnnotation(frame_num, box); // Draw the annotation (if it exists) on the image. if (!load_only_annotation && has_annotation && draw_bounding_box) { box->DrawBoundingBox(image); } // Return whether we found an annotation for this frame. return has_annotation; } <|endoftext|>
<commit_before>#include "gltf.h" #include <iostream> #include <fstream> #include <string> #include <map> #include "pixels.h" #include "rgbe/rgbe.h" #include "../gl/vbo.h" #include "../tools/fs.h" #include "../tools/geom.h" #include "../tools/text.h" #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION // #define TINYGLTF_NOEXCEPTION // #define JSON_NOEXCEPTION #include "tinygltf/tiny_gltf.h" #define BUFFER_OFFSET(i) ((char *)NULL + (i)) bool loadModel(tinygltf::Model& _model, const std::string& _filename) { tinygltf::TinyGLTF loader; std::string err; std::string warn; std::string ext = getExt(_filename); bool res = false; // assume binary glTF. if (ext == "glb" || ext == "GLB") res = loader.LoadBinaryFromFile(&_model, &err, &warn, _filename.c_str()); // assume ascii glTF. else res = loader.LoadASCIIFromFile(&_model, &err, &warn, _filename.c_str()); if (!warn.empty()) std::cout << "Warn: " << warn.c_str() << std::endl; if (!err.empty()) std::cout << "ERR: " << err.c_str() << std::endl; return res; } GLenum extractMode(const tinygltf::Primitive& _primitive) { if (_primitive.mode == TINYGLTF_MODE_TRIANGLES) { return GL_TRIANGLES; } else if (_primitive.mode == TINYGLTF_MODE_TRIANGLE_STRIP) { return GL_TRIANGLE_STRIP; } else if (_primitive.mode == TINYGLTF_MODE_TRIANGLE_FAN) { return GL_TRIANGLE_FAN; } else if (_primitive.mode == TINYGLTF_MODE_POINTS) { return GL_POINTS; } else if (_primitive.mode == TINYGLTF_MODE_LINE) { return GL_LINES; } else if (_primitive.mode == TINYGLTF_MODE_LINE_LOOP) { return GL_LINE_LOOP; } else { return 0; } } void extractIndices(const tinygltf::Model& _model, const tinygltf::Accessor& _indexAccessor, Mesh& _mesh) { const tinygltf::BufferView &buffer_view = _model.bufferViews[_indexAccessor.bufferView]; const tinygltf::Buffer &buffer = _model.buffers[buffer_view.buffer]; const uint8_t* base = &buffer.data.at(buffer_view.byteOffset + _indexAccessor.byteOffset); switch (_indexAccessor.componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: { const uint32_t *p = (uint32_t*) base; for (size_t i = 0; i < _indexAccessor.count; ++i) { _mesh.addIndex( p[i] ); } }; break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { const uint16_t *p = (uint16_t*) base; for (size_t i = 0; i < _indexAccessor.count; ++i) { _mesh.addIndex( p[i] ); } }; break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { const uint8_t *p = (uint8_t*) base; for (size_t i = 0; i < _indexAccessor.count; ++i) { _mesh.addIndex( p[i] ); } }; break; } } void extractVertexData(uint32_t v_pos, const uint8_t *base, int accesor_componentType, int accesor_type, bool accesor_normalized, uint32_t byteStride, float *output, uint8_t max_num_comp) { float v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; uint32_t ncomp = 1; switch (accesor_type) { case TINYGLTF_TYPE_SCALAR: ncomp = 1; break; case TINYGLTF_TYPE_VEC2: ncomp = 2; break; case TINYGLTF_TYPE_VEC3: ncomp = 3; break; case TINYGLTF_TYPE_VEC4: ncomp = 4; break; default: assert(!"invalid type"); } switch (accesor_componentType) { case TINYGLTF_COMPONENT_TYPE_FLOAT: { const float *data = (float*)(base+byteStride*v_pos); for (uint32_t i = 0; (i < ncomp); ++i) { v[i] = data[i]; } } // TODO SUPPORT OTHER FORMATS break; default: assert(!"Conversion Type from float to -> ??? not implemented yet"); break; } for (uint32_t i = 0; i < max_num_comp; ++i) { output[i] = v[i]; } } Material extractMaterial(const tinygltf::Model& _model, int _materialIndex, Uniforms& _uniforms) { const tinygltf::Material& material = _model.materials[_materialIndex]; Material mat; mat.name = toLower( toUnderscore( purifyString( material.name ) ) ); mat.addDefine("MATERIAL_NAME_" + toUpper(mat.name) ); mat.addDefine("MATERIAL_EMISSIVE", (double*)material.emissiveFactor.data(), 3); mat.addDefine("MATERIAL_BASECOLOR", (double*)material.pbrMetallicRoughness.baseColorFactor.data(), 4); if (material.pbrMetallicRoughness.baseColorTexture.index >= 0) { const tinygltf::Texture &tex = _model.textures[material.pbrMetallicRoughness.baseColorTexture.index]; const tinygltf::Image &image = _model.images[tex.source]; std::string name = getUniformName(image.name); Texture* texture = new Texture(); texture->load(image.width, image.height, image.component, image.bits, &image.image.at(0)); if (!_uniforms.addTexture(name, texture)) { delete texture; } mat.addDefine("MATERIAL_BASECOLORMAP", name); } mat.addDefine("MATERIAL_ROUGHNESS", material.pbrMetallicRoughness.roughnessFactor); mat.addDefine("MATERIAL_METALLIC", material.pbrMetallicRoughness.metallicFactor); return mat; } void extractMesh(tinygltf::Model& _model, tinygltf::Mesh& _mesh, Uniforms& _uniforms, Models& _models, bool _verbose) { std::cout << "Mesh " << _mesh.name << std::endl; for (size_t i = 0; i < _mesh.primitives.size(); ++i) { tinygltf::Primitive primitive = _mesh.primitives[i]; Mesh mesh; extractIndices(_model, _model.accessors[primitive.indices], mesh); mesh.setDrawMode(extractMode(primitive)); // Extract Vertex Data for (auto &attrib : primitive.attributes) { tinygltf::Accessor accessor = _model.accessors[attrib.second]; const tinygltf::BufferView &bufferView = _model.bufferViews[accessor.bufferView]; const tinygltf::Buffer &buffer = _model.buffers[bufferView.buffer]; int byteStride = accessor.ByteStride(bufferView); if (attrib.first.compare("POSITION") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec3 pos; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &pos[0], 3); mesh.addVertex(pos); } } else if (attrib.first.compare("COLOR") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec4 col = glm::vec4(1.0f); extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &col[0], 4); mesh.addColor(col); } } else if (attrib.first.compare("NORMAL") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec3 nor; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &nor[0], 3); mesh.addNormal(nor); } } else if (attrib.first.compare("TEXCOORD_0") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec2 uv; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &uv[0], 2); mesh.addTexCoord(uv); } } else if (attrib.first.compare("TANGENT") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec4 tan; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &tan[0], 4); mesh.addTangent(tan); } } else { std::cout << " " << std::endl; std::cout << "Undeclared attribute: " << attrib.first << std::endl; std::cout << " type :" << accessor.type << std::endl; std::cout << " component :" << accessor.componentType << std::endl; std::cout << " normalize :" << accessor.normalized << std::endl; std::cout << " bufferView :" << accessor.bufferView << std::endl; std::cout << " byteOffset :" << accessor.byteOffset << std::endl; std::cout << " count :" << accessor.count << std::endl; std::cout << " byteStride :" << byteStride << std::endl; std::cout << " "<< std::endl; } } if (_verbose) { std::cout << " vertices = " << mesh.getVertices().size() << std::endl; std::cout << " colors = " << mesh.getColors().size() << std::endl; std::cout << " normals = " << mesh.getNormals().size() << std::endl; std::cout << " uvs = " << mesh.getTexCoords().size() << std::endl; std::cout << " indices = " << mesh.getIndices().size() << std::endl; if (mesh.getDrawMode() == GL_TRIANGLES) { std::cout << " triang. = " << mesh.getIndices().size()/3 << std::endl; } else if (mesh.getDrawMode() == GL_LINES ) { std::cout << " lines = " << mesh.getIndices().size()/2 << std::endl; } } if ( !mesh.hasNormals() ) if ( mesh.computeNormals() ) if ( _verbose ) std::cout << " . Compute normals" << std::endl; if ( mesh.computeTangents() ) if ( _verbose ) std::cout << " . Compute tangents" << std::endl; Material mat = extractMaterial( _model, primitive.material, _uniforms ); _models.push_back( new Model(_mesh.name, mesh, mat) ); } }; // bind models void extractNodes(tinygltf::Model& _model, tinygltf::Node& _node, Uniforms& _uniforms, Models& _models, bool _verbose) { std::cout << "Node " << _node.name << std::endl; extractMesh(_model, _model.meshes[ _node.mesh ], _uniforms, _models, _verbose); for (size_t i = 0; i < _node.children.size(); i++) { extractNodes(_model, _model.nodes[ _node.children[i] ], _uniforms, _models, _verbose); } }; bool loadGLTF(Uniforms& _uniforms, WatchFileList& _files, Materials& _materials, Models& _models, int _index, bool _verbose) { tinygltf::Model model; std::string filename = _files[_index].path; if (! loadModel(model, filename)) { std::cout << "Failed to load .glTF : " << filename << std::endl; return false; } std::cout << "Load Model" << std::endl; const tinygltf::Scene &scene = model.scenes[model.defaultScene]; std::cout << " tinygltf::Scene &scene" << std::endl; for (size_t i = 0; i < scene.nodes.size(); ++i) { extractNodes(model, model.nodes[scene.nodes[i]], _uniforms, _models, _verbose); } return true; } template<typename T> void flipPixelsVertically(T *_pixels, int _width, int _height, int _bytes_per_pixel) { const size_t stride = _width * _bytes_per_pixel; T *row = (T*)malloc(stride * sizeof(T)); T *low = _pixels; T *high = &_pixels[(_height - 1) * stride]; for (; low < high; low += stride, high -= stride) { memcpy(row, low, stride * sizeof(T)); memcpy(low, high, stride * sizeof(T)); memcpy(high, row, stride * sizeof(T)); } free(row); } float* loadHDRFloatPixels(const std::string& _path, int *_width, int *_height, bool _vFlip) { FILE* file = fopen(_path.c_str(), "rb"); RGBE_ReadHeader(file, _width, _height, NULL); float* pixels = new float[(*_width) * (*_height) * 3]; RGBE_ReadPixels_RLE(file, pixels, *_width, *_height); if (_vFlip) { flipPixelsVertically<float>(pixels, (*_width), (*_height), 3); } fclose(file); return pixels; } uint16_t* loadPixels16(const std::string& _path, int *_width, int *_height, Channels _channels, bool _vFlip) { stbi_set_flip_vertically_on_load(_vFlip); int comp; uint16_t *pixels = stbi_load_16(_path.c_str(), _width, _height, &comp, _channels); return pixels; } unsigned char* loadPixels(const std::string& _path, int *_width, int *_height, Channels _channels, bool _vFlip) { stbi_set_flip_vertically_on_load(_vFlip); int comp; unsigned char* pixels = stbi_load(_path.c_str(), _width, _height, &comp, (_channels == RGB)? STBI_rgb : STBI_rgb_alpha); return pixels; } bool savePixels(const std::string& _path, unsigned char* _pixels, int _width, int _height) { // Flip the image on Y int depth = 4; flipPixelsVertically<unsigned char>(_pixels, _width, _height, depth); if (0 == stbi_write_png(_path.c_str(), _width, _height, 4, _pixels, _width * 4)) { std::cout << "can't create file " << _path << std::endl; } return true; } <commit_msg>all const<commit_after>#include "gltf.h" #include <iostream> #include <fstream> #include <string> #include <map> #include "pixels.h" #include "rgbe/rgbe.h" #include "../gl/vbo.h" #include "../tools/fs.h" #include "../tools/geom.h" #include "../tools/text.h" #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION // #define TINYGLTF_NOEXCEPTION // #define JSON_NOEXCEPTION #include "tinygltf/tiny_gltf.h" #define BUFFER_OFFSET(i) ((char *)NULL + (i)) bool loadModel(tinygltf::Model& _model, const std::string& _filename) { tinygltf::TinyGLTF loader; std::string err; std::string warn; std::string ext = getExt(_filename); bool res = false; // assume binary glTF. if (ext == "glb" || ext == "GLB") res = loader.LoadBinaryFromFile(&_model, &err, &warn, _filename.c_str()); // assume ascii glTF. else res = loader.LoadASCIIFromFile(&_model, &err, &warn, _filename.c_str()); if (!warn.empty()) std::cout << "Warn: " << warn.c_str() << std::endl; if (!err.empty()) std::cout << "ERR: " << err.c_str() << std::endl; return res; } GLenum extractMode(const tinygltf::Primitive& _primitive) { if (_primitive.mode == TINYGLTF_MODE_TRIANGLES) { return GL_TRIANGLES; } else if (_primitive.mode == TINYGLTF_MODE_TRIANGLE_STRIP) { return GL_TRIANGLE_STRIP; } else if (_primitive.mode == TINYGLTF_MODE_TRIANGLE_FAN) { return GL_TRIANGLE_FAN; } else if (_primitive.mode == TINYGLTF_MODE_POINTS) { return GL_POINTS; } else if (_primitive.mode == TINYGLTF_MODE_LINE) { return GL_LINES; } else if (_primitive.mode == TINYGLTF_MODE_LINE_LOOP) { return GL_LINE_LOOP; } else { return 0; } } void extractIndices(const tinygltf::Model& _model, const tinygltf::Accessor& _indexAccessor, Mesh& _mesh) { const tinygltf::BufferView &buffer_view = _model.bufferViews[_indexAccessor.bufferView]; const tinygltf::Buffer &buffer = _model.buffers[buffer_view.buffer]; const uint8_t* base = &buffer.data.at(buffer_view.byteOffset + _indexAccessor.byteOffset); switch (_indexAccessor.componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: { const uint32_t *p = (uint32_t*) base; for (size_t i = 0; i < _indexAccessor.count; ++i) { _mesh.addIndex( p[i] ); } }; break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { const uint16_t *p = (uint16_t*) base; for (size_t i = 0; i < _indexAccessor.count; ++i) { _mesh.addIndex( p[i] ); } }; break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { const uint8_t *p = (uint8_t*) base; for (size_t i = 0; i < _indexAccessor.count; ++i) { _mesh.addIndex( p[i] ); } }; break; } } void extractVertexData(uint32_t v_pos, const uint8_t *base, int accesor_componentType, int accesor_type, bool accesor_normalized, uint32_t byteStride, float *output, uint8_t max_num_comp) { float v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; uint32_t ncomp = 1; switch (accesor_type) { case TINYGLTF_TYPE_SCALAR: ncomp = 1; break; case TINYGLTF_TYPE_VEC2: ncomp = 2; break; case TINYGLTF_TYPE_VEC3: ncomp = 3; break; case TINYGLTF_TYPE_VEC4: ncomp = 4; break; default: assert(!"invalid type"); } switch (accesor_componentType) { case TINYGLTF_COMPONENT_TYPE_FLOAT: { const float *data = (float*)(base+byteStride*v_pos); for (uint32_t i = 0; (i < ncomp); ++i) { v[i] = data[i]; } } // TODO SUPPORT OTHER FORMATS break; default: assert(!"Conversion Type from float to -> ??? not implemented yet"); break; } for (uint32_t i = 0; i < max_num_comp; ++i) { output[i] = v[i]; } } Material extractMaterial(const tinygltf::Model& _model, const tinygltf::Material& _material, Uniforms& _uniforms) { Material mat; mat.name = toLower( toUnderscore( purifyString( _material.name ) ) ); mat.addDefine("MATERIAL_NAME_" + toUpper(mat.name) ); mat.addDefine("MATERIAL_EMISSIVE", (double*)_material.emissiveFactor.data(), 3); mat.addDefine("MATERIAL_BASECOLOR", (double*)_material.pbrMetallicRoughness.baseColorFactor.data(), 4); if (_material.pbrMetallicRoughness.baseColorTexture.index >= 0) { const tinygltf::Texture &tex = _model.textures[_material.pbrMetallicRoughness.baseColorTexture.index]; const tinygltf::Image &image = _model.images[tex.source]; std::string name = getUniformName(image.name); Texture* texture = new Texture(); texture->load(image.width, image.height, image.component, image.bits, &image.image.at(0)); if (!_uniforms.addTexture(name, texture)) { delete texture; } mat.addDefine("MATERIAL_BASECOLORMAP", name); } mat.addDefine("MATERIAL_ROUGHNESS", _material.pbrMetallicRoughness.roughnessFactor); mat.addDefine("MATERIAL_METALLIC", _material.pbrMetallicRoughness.metallicFactor); return mat; } void extractMesh(const tinygltf::Model& _model, const tinygltf::Mesh& _mesh, Uniforms& _uniforms, Models& _models, bool _verbose) { std::cout << "Mesh " << _mesh.name << std::endl; for (size_t i = 0; i < _mesh.primitives.size(); ++i) { tinygltf::Primitive primitive = _mesh.primitives[i]; Mesh mesh; extractIndices(_model, _model.accessors[primitive.indices], mesh); mesh.setDrawMode(extractMode(primitive)); // Extract Vertex Data for (auto &attrib : primitive.attributes) { const tinygltf::Accessor &accessor = _model.accessors[attrib.second]; const tinygltf::BufferView &bufferView = _model.bufferViews[accessor.bufferView]; const tinygltf::Buffer &buffer = _model.buffers[bufferView.buffer]; int byteStride = accessor.ByteStride(bufferView); if (attrib.first.compare("POSITION") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec3 pos; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &pos[0], 3); mesh.addVertex(pos); } } else if (attrib.first.compare("COLOR") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec4 col = glm::vec4(1.0f); extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &col[0], 4); mesh.addColor(col); } } else if (attrib.first.compare("NORMAL") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec3 nor; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &nor[0], 3); mesh.addNormal(nor); } } else if (attrib.first.compare("TEXCOORD_0") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec2 uv; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &uv[0], 2); mesh.addTexCoord(uv); } } else if (attrib.first.compare("TANGENT") == 0) { for (size_t v = 0; v < accessor.count; v++) { glm::vec4 tan; extractVertexData(v, &buffer.data.at(bufferView.byteOffset + accessor.byteOffset), accessor.componentType, accessor.type, accessor.normalized, byteStride, &tan[0], 4); mesh.addTangent(tan); } } else { std::cout << " " << std::endl; std::cout << "Undeclared attribute: " << attrib.first << std::endl; std::cout << " type :" << accessor.type << std::endl; std::cout << " component :" << accessor.componentType << std::endl; std::cout << " normalize :" << accessor.normalized << std::endl; std::cout << " bufferView :" << accessor.bufferView << std::endl; std::cout << " byteOffset :" << accessor.byteOffset << std::endl; std::cout << " count :" << accessor.count << std::endl; std::cout << " byteStride :" << byteStride << std::endl; std::cout << " "<< std::endl; } } if (_verbose) { std::cout << " vertices = " << mesh.getVertices().size() << std::endl; std::cout << " colors = " << mesh.getColors().size() << std::endl; std::cout << " normals = " << mesh.getNormals().size() << std::endl; std::cout << " uvs = " << mesh.getTexCoords().size() << std::endl; std::cout << " indices = " << mesh.getIndices().size() << std::endl; if (mesh.getDrawMode() == GL_TRIANGLES) { std::cout << " triang. = " << mesh.getIndices().size()/3 << std::endl; } else if (mesh.getDrawMode() == GL_LINES ) { std::cout << " lines = " << mesh.getIndices().size()/2 << std::endl; } } if ( !mesh.hasNormals() ) if ( mesh.computeNormals() ) if ( _verbose ) std::cout << " . Compute normals" << std::endl; if ( mesh.computeTangents() ) if ( _verbose ) std::cout << " . Compute tangents" << std::endl; Material mat = extractMaterial( _model, _model.materials[primitive.material], _uniforms ); _models.push_back( new Model(_mesh.name, mesh, mat) ); } }; // bind models void extractNodes(const tinygltf::Model& _model, const tinygltf::Node& _node, Uniforms& _uniforms, Models& _models, bool _verbose) { std::cout << "Node " << _node.name << std::endl; extractMesh(_model, _model.meshes[ _node.mesh ], _uniforms, _models, _verbose); for (size_t i = 0; i < _node.children.size(); i++) { extractNodes(_model, _model.nodes[ _node.children[i] ], _uniforms, _models, _verbose); } }; bool loadGLTF(Uniforms& _uniforms, WatchFileList& _files, Materials& _materials, Models& _models, int _index, bool _verbose) { tinygltf::Model model; std::string filename = _files[_index].path; if (! loadModel(model, filename)) { std::cout << "Failed to load .glTF : " << filename << std::endl; return false; } std::cout << "Load Model" << std::endl; const tinygltf::Scene &scene = model.scenes[model.defaultScene]; std::cout << " tinygltf::Scene &scene" << std::endl; for (size_t i = 0; i < scene.nodes.size(); ++i) { extractNodes(model, model.nodes[scene.nodes[i]], _uniforms, _models, _verbose); } return true; } template<typename T> void flipPixelsVertically(T *_pixels, int _width, int _height, int _bytes_per_pixel) { const size_t stride = _width * _bytes_per_pixel; T *row = (T*)malloc(stride * sizeof(T)); T *low = _pixels; T *high = &_pixels[(_height - 1) * stride]; for (; low < high; low += stride, high -= stride) { memcpy(row, low, stride * sizeof(T)); memcpy(low, high, stride * sizeof(T)); memcpy(high, row, stride * sizeof(T)); } free(row); } float* loadHDRFloatPixels(const std::string& _path, int *_width, int *_height, bool _vFlip) { FILE* file = fopen(_path.c_str(), "rb"); RGBE_ReadHeader(file, _width, _height, NULL); float* pixels = new float[(*_width) * (*_height) * 3]; RGBE_ReadPixels_RLE(file, pixels, *_width, *_height); if (_vFlip) { flipPixelsVertically<float>(pixels, (*_width), (*_height), 3); } fclose(file); return pixels; } uint16_t* loadPixels16(const std::string& _path, int *_width, int *_height, Channels _channels, bool _vFlip) { stbi_set_flip_vertically_on_load(_vFlip); int comp; uint16_t *pixels = stbi_load_16(_path.c_str(), _width, _height, &comp, _channels); return pixels; } unsigned char* loadPixels(const std::string& _path, int *_width, int *_height, Channels _channels, bool _vFlip) { stbi_set_flip_vertically_on_load(_vFlip); int comp; unsigned char* pixels = stbi_load(_path.c_str(), _width, _height, &comp, (_channels == RGB)? STBI_rgb : STBI_rgb_alpha); return pixels; } bool savePixels(const std::string& _path, unsigned char* _pixels, int _width, int _height) { // Flip the image on Y int depth = 4; flipPixelsVertically<unsigned char>(_pixels, _width, _height, depth); if (0 == stbi_write_png(_path.c_str(), _width, _height, 4, _pixels, _width * 4)) { std::cout << "can't create file " << _path << std::endl; } return true; } <|endoftext|>
<commit_before>/*********************************************************************** filename: TreeView.cpp created: Fri Jun 06 2014 author: Timotei Dolean <timotei21@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/WindowRendererSets/Core/TreeView.h" #include "CEGUI/falagard/WidgetLookManager.h" #include "CEGUI/falagard/WidgetLookFeel.h" #include "CEGUI/Image.h" namespace CEGUI { //----------------------------------------------------------------------------// const String FalagardTreeView::TypeName("Core/TreeView"); const float SUBTREE_EXPANDER_MARGIN = 5.0f; //----------------------------------------------------------------------------// FalagardTreeView::FalagardTreeView(const String& type) : TreeViewWindowRenderer(type), d_subtreeExpanderImagery(0), d_subtreeCollapserImagery(0), d_subtreeExpanderImagerySize(0, 0) { } //----------------------------------------------------------------------------// void FalagardTreeView::render() { const WidgetLookFeel& wlf = getLookNFeel(); TreeView* tree_view = static_cast<TreeView*>(d_window); tree_view->prepareForRender(); const StateImagery* imagery = &wlf.getStateImagery( tree_view->isEffectiveDisabled() ? "Disabled" : "Enabled"); imagery->render(*tree_view); Rectf items_area(getViewRenderArea()); Vector2f item_pos(getItemRenderStartPosition(tree_view, items_area)); renderTreeItem(tree_view, items_area, item_pos, tree_view->getRootItemState(), 0); } //----------------------------------------------------------------------------// void FalagardTreeView::renderTreeItem(TreeView* tree_view, const Rectf& items_area, Vector2f& item_pos, const TreeViewItemRenderingState& item_to_render, size_t depth) { for (size_t i = 0; i < item_to_render.d_renderedChildren.size(); ++i) { TreeViewItemRenderingState item = item_to_render.d_renderedChildren.at(i); RenderedString& rendered_string = item.d_string; Sizef size(item.d_size); size.d_width = ceguimax(items_area.getWidth(), size.d_width); if (item.d_totalChildCount > 0) { const ImagerySection* section = item.d_subtreeIsExpanded ? d_subtreeCollapserImagery : d_subtreeExpanderImagery; Rectf button_rect; button_rect.left(item_pos.d_x + SUBTREE_EXPANDER_MARGIN); button_rect.top(item_pos.d_y + SUBTREE_EXPANDER_MARGIN); button_rect.setSize(d_subtreeExpanderImagerySize); button_rect.right(button_rect.right() - SUBTREE_EXPANDER_MARGIN); Rectf button_clipper(button_rect.getIntersection(items_area)); section->render(*tree_view, button_rect, 0, &button_clipper); } Rectf item_rect; item_rect.left(item_pos.d_x + d_subtreeExpanderImagerySize.d_width); item_rect.top(item_pos.d_y); item_rect.setSize(size); Rectf item_clipper(item_rect.getIntersection(items_area)); renderString(tree_view, rendered_string, item_rect, tree_view->getFont(), &item_clipper, item.d_isSelected); item_pos.d_y += size.d_height; if (item.d_renderedChildren.empty()) continue; item_pos.d_x += d_subtreeExpanderImagerySize.d_width; if (item.d_subtreeIsExpanded) { renderTreeItem(tree_view, items_area, item_pos, item, depth + 1); } item_pos.d_x -= d_subtreeExpanderImagerySize.d_width; } } static Sizef getImagerySize(const ImagerySection* section) { const ImageryComponent& component = section->getImageryComponentIterator().getCurrentValue(); const Image* img = component.getImage(); return img->getRenderedSize(); } //----------------------------------------------------------------------------// void FalagardTreeView::onLookNFeelAssigned() { const WidgetLookFeel& wlf = getLookNFeel(); d_subtreeExpanderImagery = &wlf.getImagerySection("SubtreeExpander"); d_subtreeCollapserImagery = &wlf.getImagerySection("SubtreeCollapser"); Sizef open_size = getImagerySize(d_subtreeExpanderImagery); Sizef close_size = getImagerySize(d_subtreeCollapserImagery); d_subtreeExpanderImagerySize = Sizef( (open_size.d_width + close_size.d_width) / 2.0f + SUBTREE_EXPANDER_MARGIN, (open_size.d_height + close_size.d_height) / 2.0f + SUBTREE_EXPANDER_MARGIN); } //----------------------------------------------------------------------------// Sizef FalagardTreeView::getSubtreeExpanderSize(void) const { return d_subtreeExpanderImagerySize; } //----------------------------------------------------------------------------// Rectf FalagardTreeView::getViewRenderArea(void) const { return ItemViewRenderer::getViewRenderArea(this); } //----------------------------------------------------------------------------// float FalagardTreeView::getSubtreeExpanderXIndent(int depth) const { return depth * d_subtreeExpanderImagerySize.d_width; } } <commit_msg>Use reference instead of pointer<commit_after>/*********************************************************************** filename: TreeView.cpp created: Fri Jun 06 2014 author: Timotei Dolean <timotei21@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/WindowRendererSets/Core/TreeView.h" #include "CEGUI/falagard/WidgetLookManager.h" #include "CEGUI/falagard/WidgetLookFeel.h" #include "CEGUI/Image.h" namespace CEGUI { //----------------------------------------------------------------------------// const String FalagardTreeView::TypeName("Core/TreeView"); const float SUBTREE_EXPANDER_MARGIN = 5.0f; //----------------------------------------------------------------------------// FalagardTreeView::FalagardTreeView(const String& type) : TreeViewWindowRenderer(type), d_subtreeExpanderImagery(0), d_subtreeCollapserImagery(0), d_subtreeExpanderImagerySize(0, 0) { } //----------------------------------------------------------------------------// void FalagardTreeView::render() { const WidgetLookFeel& wlf = getLookNFeel(); TreeView* tree_view = static_cast<TreeView*>(d_window); tree_view->prepareForRender(); const StateImagery* imagery = &wlf.getStateImagery( tree_view->isEffectiveDisabled() ? "Disabled" : "Enabled"); imagery->render(*tree_view); Rectf items_area(getViewRenderArea()); Vector2f item_pos(getItemRenderStartPosition(tree_view, items_area)); renderTreeItem(tree_view, items_area, item_pos, tree_view->getRootItemState(), 0); } //----------------------------------------------------------------------------// void FalagardTreeView::renderTreeItem(TreeView* tree_view, const Rectf& items_area, Vector2f& item_pos, const TreeViewItemRenderingState& item_to_render, size_t depth) { for (size_t i = 0; i < item_to_render.d_renderedChildren.size(); ++i) { TreeViewItemRenderingState item = item_to_render.d_renderedChildren.at(i); RenderedString& rendered_string = item.d_string; Sizef size(item.d_size); size.d_width = ceguimax(items_area.getWidth(), size.d_width); if (item.d_totalChildCount > 0) { const ImagerySection* section = item.d_subtreeIsExpanded ? d_subtreeCollapserImagery : d_subtreeExpanderImagery; Rectf button_rect; button_rect.left(item_pos.d_x + SUBTREE_EXPANDER_MARGIN); button_rect.top(item_pos.d_y + SUBTREE_EXPANDER_MARGIN); button_rect.setSize(d_subtreeExpanderImagerySize); button_rect.right(button_rect.right() - SUBTREE_EXPANDER_MARGIN); Rectf button_clipper(button_rect.getIntersection(items_area)); section->render(*tree_view, button_rect, 0, &button_clipper); } Rectf item_rect; item_rect.left(item_pos.d_x + d_subtreeExpanderImagerySize.d_width); item_rect.top(item_pos.d_y); item_rect.setSize(size); Rectf item_clipper(item_rect.getIntersection(items_area)); renderString(tree_view, rendered_string, item_rect, tree_view->getFont(), &item_clipper, item.d_isSelected); item_pos.d_y += size.d_height; if (item.d_renderedChildren.empty()) continue; item_pos.d_x += d_subtreeExpanderImagerySize.d_width; if (item.d_subtreeIsExpanded) { renderTreeItem(tree_view, items_area, item_pos, item, depth + 1); } item_pos.d_x -= d_subtreeExpanderImagerySize.d_width; } } static Sizef getImagerySize(const ImagerySection& section) { const ImageryComponent& component = section.getImageryComponentIterator().getCurrentValue(); const Image* img = component.getImage(); return img->getRenderedSize(); } //----------------------------------------------------------------------------// void FalagardTreeView::onLookNFeelAssigned() { const WidgetLookFeel& wlf = getLookNFeel(); d_subtreeExpanderImagery = &wlf.getImagerySection("SubtreeExpander"); d_subtreeCollapserImagery = &wlf.getImagerySection("SubtreeCollapser"); Sizef open_size = getImagerySize(*d_subtreeExpanderImagery); Sizef close_size = getImagerySize(*d_subtreeCollapserImagery); d_subtreeExpanderImagerySize = Sizef( (open_size.d_width + close_size.d_width) / 2.0f + SUBTREE_EXPANDER_MARGIN, (open_size.d_height + close_size.d_height) / 2.0f + SUBTREE_EXPANDER_MARGIN); } //----------------------------------------------------------------------------// Sizef FalagardTreeView::getSubtreeExpanderSize(void) const { return d_subtreeExpanderImagerySize; } //----------------------------------------------------------------------------// Rectf FalagardTreeView::getViewRenderArea(void) const { return ItemViewRenderer::getViewRenderArea(this); } //----------------------------------------------------------------------------// float FalagardTreeView::getSubtreeExpanderXIndent(int depth) const { return depth * d_subtreeExpanderImagerySize.d_width; } } <|endoftext|>
<commit_before>#include <png.h> #include <iostream> #include <cstdlib> #include <boost/thread/thread.hpp> #include <boost/progress.hpp> #include <tbb/concurrent_queue.h> #include <tbb/parallel_for.h> #include "./nbt.h" std::pair<int, int> projectCoords(std::pair<int, int> p, int phi) { if (phi == 0) return p; int cos_phi = phi % 2 - 1; if (!phi) cos_phi = 1; int sin_phi = phi % 2; if (phi == 3) sin_phi = -1; return std::make_pair(p.first * cos_phi - p.second * sin_phi, p.first * sin_phi + p.second * cos_phi); } typedef std::pair<Image<uint8_t>, std::pair<int, int> > image_coords; int startRendering(std::string filename, tbb::concurrent_bounded_queue<image_coords>& images, nbt& bf, std::pair<int, int> min_norm, std::pair<int, int> max_norm, uint16_t header_size) { image_coords img_coor; for (;;) { images.pop(img_coor); if (img_coor.first.channels == 0) { break; } std::pair<int, int> projected = projectCoords( std::make_pair(16 * img_coor.second.first, 16 * img_coor.second.second), bf.set().rotate); uint16_t width = img_coor.first.cols; uint16_t height = img_coor.first.rows; int offset_x = projected.first - min_norm.first * 16; int offset_y = projected.second - min_norm.second * 16; int g_width = (max_norm.first - min_norm.first + 1) * 16; FILE* pam = fopen(filename.c_str(), "r+b"); fseek(pam, header_size, SEEK_CUR); for (size_t i = 0; i < 1u * width * height; ++i) { size_t index = i * 4; std::swap(img_coor.first.data[index], img_coor.first.data[index + 2]); } fseek(pam, (offset_y * g_width + offset_x) * 4, SEEK_CUR); for (size_t i = 0; i < height; ++i) { for (size_t j = 0; j < width; ++j) { if (img_coor.first.data[i * width * 4 + j * 4 + 3] != 0) { fwrite(&(img_coor.first.data[i * width * 4 + j * 4]), 4, 1, pam); } else { fseek(pam, 4, SEEK_CUR); } } fseek(pam, (g_width - width) * 4, SEEK_CUR); } fclose(pam); } return 0; } uint16_t writeHeader(std::string filename, std::pair<int, int> min_norm, std::pair<int, int> max_norm, uint32_t& width, uint32_t& height, const nbt& bf) { std::stringstream ss; width = static_cast<uint32_t>(max_norm.first - min_norm.first + 1) * 16; height = static_cast<uint32_t>(max_norm.second - min_norm.second + 1) * 16; if (bf.set().oblique) height += 128; ss << "P7\n" << "WIDTH " << width << "\n" << "HEIGHT " << height << "\n" << "DEPTH " << 4 << "\n" << "MAXVAL " << 255 << "\n" << "TUPLTYPE " << "RGB_ALPHA" << "\n" << "ENDHDR" << "\n"; uint16_t header_size = static_cast<uint16_t>(ss.str().size()); FILE* pam = fopen(filename.c_str(), "wb"); fwrite(ss.str().c_str(), 1, header_size, pam); fseek(pam, static_cast<long>(width * height * 4 - 1), SEEK_CUR); fwrite("", 1, 1, pam); fclose(pam); return header_size; } class ApplyFoo { nbt* bf_; tbb::concurrent_bounded_queue<image_coords>* images_; int i_; tbb::atomic<int>* index_; public: void operator()( const tbb::blocked_range<int32_t>& r ) const { for(int32_t j=r.begin(); j!=r.end(); ++j) { bool result = false; std::pair<int, int> bp = projectCoords(std::make_pair(j, i_), (4 - bf_->set().rotate) % 4); const Image<uint8_t>& image = bf_->getImage(bp.first, bp.second, &result); if (!result) { continue; } *index_ += 1; images_->push(image_coords(image, std::make_pair(bp.first, bp.second))); } } ApplyFoo(nbt* bf, tbb::concurrent_bounded_queue<image_coords>* images, int i, tbb::atomic<int>* index) : bf_(bf), images_(images), i_(i), index_(index) {} private: ApplyFoo& operator=(const ApplyFoo&); }; Settings getSettings() { Settings set; set.topview = true; set.oblique = false; set.heightmap = false; set.color = false; set.shadow_strength = 0; set.shadow_quality = true; set.shadow_quality_ultra = false; set.relief_strength = 10; set.sun_direction = 1; set.rotate = 1; set.sun_direction = (set.sun_direction + ((set.rotate + 3) % 4) * 2) % 8; set.shadow = set.shadow_strength; set.relief = set.relief_strength; return set; } void calculateMinMaxPoint(std::pair<int, int>& min_norm, std::pair<int, int>& max_norm, const nbt& bf) { std::pair<int, int> min(bf.xPos_min(), bf.zPos_min()); std::pair<int, int> max(bf.xPos_max(), bf.zPos_max()); min = projectCoords(min, bf.set().rotate); max = projectCoords(max, bf.set().rotate); min_norm = std::make_pair(std::min(min.first, max.first), std::min(min.second, max.second)); max_norm = std::make_pair(std::max(min.first, max.first), std::max(min.second, max.second)); } void pamToPng(std::string pam_name, std::string png_name, uint16_t header_size, uint32_t width, uint32_t height) { FILE* pam = fopen(pam_name.c_str(), "rb"); FILE* out = fopen(png_name.c_str(), "wb"); fseek(pam, header_size, SEEK_CUR); png_struct* pngP; png_info* infoP; pngP = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); infoP = png_create_info_struct(pngP); png_set_IHDR(pngP, infoP, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_init_io(pngP, out); png_write_info(pngP, infoP); png_byte* pngRow = reinterpret_cast<png_byte*>(malloc(width * 4)); for (size_t i = 0; i < height; ++i) { fread(pngRow, 4, width, pam); png_write_row(pngP, pngRow); } free(pngRow); png_write_end(pngP, infoP); png_destroy_write_struct(&pngP, &infoP); fclose(pam); fclose(out); } int main(int ac, char* av[]) { if (ac != 2) { std::cerr << "Usage: ./nbtparse [filename | world number]" << std::endl; return 1; } int world = atoi(av[1]); nbt bf = world ? nbt(world) : nbt(av[1]); std::cout << bf.string(); bf.setSettings(getSettings()); tbb::concurrent_bounded_queue<image_coords> images; std::pair<int, int> min_norm, max_norm; calculateMinMaxPoint(min_norm, max_norm, bf); uint32_t width, height; uint16_t header_size = writeHeader("test.pam", min_norm, max_norm, width, height, bf); boost::thread render_thread(boost::bind(&startRendering, "test.pam", boost::ref(images), boost::ref(bf), boost::ref(min_norm), boost::ref(max_norm), header_size)); tbb::atomic<int> index; index = 0; boost::progress_display show_progress(max_norm.second - min_norm.second + 1); for (int i = min_norm.second; i <= max_norm.second; ++i) { tbb::parallel_for(tbb::blocked_range<int32_t> (min_norm.first, max_norm.first + 1), ApplyFoo(&bf, &images, i, &index)); if (index > 10000) { std::cerr << "cache cleared!" << std::endl; index = 0; bf.clearCache(); } ++show_progress; } bf.clearCache(); images.push(image_coords(Image<uint8_t>(0, 0, 0), std::make_pair(0, 0))); pamToPng("test.pam", "test.png", header_size, width, height); render_thread.join(); return 0; } <commit_msg>save image in memory when filename size is 0<commit_after>#include <png.h> #include <iostream> #include <cstdlib> #include <boost/thread/thread.hpp> #include <boost/progress.hpp> #include <tbb/concurrent_queue.h> #include <tbb/parallel_for.h> #include "./nbt.h" std::pair<int, int> projectCoords(std::pair<int, int> p, int phi) { if (phi == 0) return p; int cos_phi = phi % 2 - 1; if (!phi) cos_phi = 1; int sin_phi = phi % 2; if (phi == 3) sin_phi = -1; return std::make_pair(p.first * cos_phi - p.second * sin_phi, p.first * sin_phi + p.second * cos_phi); } typedef std::pair<Image<uint8_t>, std::pair<int, int> > image_coords; uint8_t* global_image; int startRendering(std::string filename, tbb::concurrent_bounded_queue<image_coords>& images, nbt& bf, std::pair<int, int> min_norm, std::pair<int, int> max_norm, uint16_t header_size) { image_coords img_coor; int g_width = (max_norm.first - min_norm.first + 1) * 16; int g_height = (max_norm.second - min_norm.second + 1) * 16; if (!filename.size()) { global_image = reinterpret_cast<uint8_t*> (malloc(static_cast<size_t>(g_width * g_height * 4))); } for (;;) { images.pop(img_coor); if (img_coor.first.channels == 0) { break; } std::pair<int, int> projected = projectCoords( std::make_pair(16 * img_coor.second.first, 16 * img_coor.second.second), bf.set().rotate); uint16_t width = img_coor.first.cols; uint16_t height = img_coor.first.rows; int offset_x = projected.first - min_norm.first * 16; int offset_y = projected.second - min_norm.second * 16; for (size_t i = 0; i < 1u * width * height; ++i) { size_t index = i * 4; std::swap(img_coor.first.data[index], img_coor.first.data[index + 2]); } if (filename.size()) { FILE* pam = fopen(filename.c_str(), "r+b"); fseek(pam, header_size, SEEK_CUR); fseek(pam, (offset_y * g_width + offset_x) * 4, SEEK_CUR); for (size_t i = 0; i < height; ++i) { for (size_t j = 0; j < width; ++j) { if (img_coor.first.data[i * width * 4 + j * 4 + 3] != 0) { fwrite(&(img_coor.first.data[i * width * 4 + j * 4]), 4, 1, pam); } else { fseek(pam, 4, SEEK_CUR); } } fseek(pam, (g_width - width) * 4, SEEK_CUR); } fclose(pam); } else { long pos = (offset_y * g_width + offset_x) * 4; for (size_t i = 0; i < height; ++i) { for (size_t j = 0; j < width; ++j) { if (img_coor.first.data[i * width * 4 + j * 4 + 3] != 0) { memcpy(global_image + pos, &img_coor.first.data[i * width * 4 + j * 4], 4); } pos += 4; } pos += (g_width - width) * 4; } } } return 0; } uint16_t writeHeader(std::string filename, std::pair<int, int> min_norm, std::pair<int, int> max_norm, uint32_t& width, uint32_t& height, const nbt& bf) { width = static_cast<uint32_t>(max_norm.first - min_norm.first + 1) * 16; height = static_cast<uint32_t>(max_norm.second - min_norm.second + 1) * 16; if (bf.set().oblique) height += 128; uint16_t header_size = 0; if (filename.size()) { std::stringstream ss; ss << "P7\n" << "WIDTH " << width << "\n" << "HEIGHT " << height << "\n" << "DEPTH " << 4 << "\n" << "MAXVAL " << 255 << "\n" << "TUPLTYPE " << "RGB_ALPHA" << "\n" << "ENDHDR" << "\n"; header_size = static_cast<uint16_t>(ss.str().size()); FILE* pam = fopen(filename.c_str(), "wb"); fwrite(ss.str().c_str(), 1, header_size, pam); fseek(pam, static_cast<long>(width * height * 4 - 1), SEEK_CUR); fwrite("", 1, 1, pam); fclose(pam); } return header_size; } class ApplyFoo { nbt* bf_; tbb::concurrent_bounded_queue<image_coords>* images_; int i_; tbb::atomic<int>* index_; public: void operator()( const tbb::blocked_range<int32_t>& r ) const { for(int32_t j=r.begin(); j!=r.end(); ++j) { bool result = false; std::pair<int, int> bp = projectCoords(std::make_pair(j, i_), (4 - bf_->set().rotate) % 4); const Image<uint8_t>& image = bf_->getImage(bp.first, bp.second, &result); if (!result) { continue; } *index_ += 1; images_->push(image_coords(image, std::make_pair(bp.first, bp.second))); } } ApplyFoo(nbt* bf, tbb::concurrent_bounded_queue<image_coords>* images, int i, tbb::atomic<int>* index) : bf_(bf), images_(images), i_(i), index_(index) {} private: ApplyFoo& operator=(const ApplyFoo&); }; Settings getSettings() { Settings set; set.topview = true; set.oblique = false; set.heightmap = false; set.color = false; set.shadow_strength = 0; set.shadow_quality = true; set.shadow_quality_ultra = false; set.relief_strength = 10; set.sun_direction = 1; set.rotate = 1; set.sun_direction = (set.sun_direction + ((set.rotate + 3) % 4) * 2) % 8; set.shadow = set.shadow_strength; set.relief = set.relief_strength; return set; } void calculateMinMaxPoint(std::pair<int, int>& min_norm, std::pair<int, int>& max_norm, const nbt& bf) { std::pair<int, int> min(bf.xPos_min(), bf.zPos_min()); std::pair<int, int> max(bf.xPos_max(), bf.zPos_max()); min = projectCoords(min, bf.set().rotate); max = projectCoords(max, bf.set().rotate); min_norm = std::make_pair(std::min(min.first, max.first), std::min(min.second, max.second)); max_norm = std::make_pair(std::max(min.first, max.first), std::max(min.second, max.second)); } void pamToPng(std::string pam_name, std::string png_name, uint16_t header_size, uint32_t width, uint32_t height) { FILE* pam = NULL; if (pam_name.size()) { pam = fopen(pam_name.c_str(), "rb"); fseek(pam, header_size, SEEK_CUR); } FILE* out = fopen(png_name.c_str(), "wb"); png_struct* pngP; png_info* infoP; pngP = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); infoP = png_create_info_struct(pngP); png_set_IHDR(pngP, infoP, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_init_io(pngP, out); png_write_info(pngP, infoP); png_byte* pngRow = reinterpret_cast<png_byte*>(malloc(width * 4)); for (size_t i = 0; i < height; ++i) { if (pam) { fread(pngRow, 4, width, pam); } else { memcpy(pngRow, global_image + i * width * 4, width * 4); } png_write_row(pngP, pngRow); } free(pngRow); png_write_end(pngP, infoP); png_destroy_write_struct(&pngP, &infoP); fclose(out); if (pam) { fclose(pam); } else { free(global_image); } } int main(int ac, char* av[]) { if (ac != 2) { std::cerr << "Usage: ./nbtparse [filename | world number]" << std::endl; return 1; } int world = atoi(av[1]); nbt bf = world ? nbt(world) : nbt(av[1]); std::cout << bf.string(); bf.setSettings(getSettings()); tbb::concurrent_bounded_queue<image_coords> images; std::pair<int, int> min_norm, max_norm; calculateMinMaxPoint(min_norm, max_norm, bf); uint32_t width, height; uint16_t header_size = writeHeader("", min_norm, max_norm, width, height, bf); boost::thread render_thread(boost::bind(&startRendering, "", boost::ref(images), boost::ref(bf), boost::ref(min_norm), boost::ref(max_norm), header_size)); tbb::atomic<int> index; index = 0; boost::progress_display show_progress( static_cast<size_t>(max_norm.second - min_norm.second + 1)); for (int i = min_norm.second; i <= max_norm.second; ++i) { tbb::parallel_for(tbb::blocked_range<int32_t> (min_norm.first, max_norm.first + 1), ApplyFoo(&bf, &images, i, &index)); if (index > 10000) { index = 0; bf.clearCache(); } ++show_progress; } bf.clearCache(); images.push(image_coords(Image<uint8_t>(0, 0, 0), std::make_pair(0, 0))); render_thread.join(); pamToPng("", "test.png", header_size, width, height); return 0; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/targeting/targetservicestart.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2017 */ /* [+] Google Inc. */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file targeting/targetservicestart.C * * @brief Hostboot entry point for target service */ //****************************************************************************** // Includes //****************************************************************************** // STD #include <stdio.h> #include <stdlib.h> // Other components #include <sys/misc.h> #include <sys/task.h> #include <targeting/common/trace.H> #include <targeting/adapters/assertadapter.H> #include <initservice/taskargs.H> #include <util/utilmbox_scratch.H> // This component #include <targeting/common/targetservice.H> #include <targeting/attrrp.H> // Others #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <devicefw/userif.H> #include <config.h> #include <initservice/initserviceif.H> #include <util/misc.H> #ifdef CONFIG_DRTM #include <secureboot/drtm.H> #endif using namespace INITSERVICE::SPLESS; //****************************************************************************** // targetService //****************************************************************************** namespace TARGETING { #define TARG_NAMESPACE "TARGETING::" #define TARG_LOC TARG_NAMESPACE TARG_CLASS TARG_FN ": " //****************************************************************************** // _start //****************************************************************************** #define TARG_CLASS "" /* * @brief Initialize any attributes that need to be set early on */ static void initializeAttributes(TargetService& i_targetService, bool i_isMpipl, bool i_istepMode, ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch); /** * @brief Check that at least one processor of our cpu type is being targeted */ static void checkProcessorTargeting(TargetService& i_targetService); /** * @brief Entry point for initialization service to initialize the targeting * code * * @param[in] io_pError * Error log handle; returns NULL on success, !NULL otherwise * * @note: Link register is configured to automatically invoke task_end() when * this routine returns */ static void initTargeting(errlHndl_t& io_pError) { #define TARG_FN "initTargeting(errlHndl_t& io_pError)" TARG_ENTER(); //Need to stash away the master mbox regs as they will //be overwritten bool l_isMpipl = false; bool l_isIstepMode = false; ATTR_MASTER_MBOX_SCRATCH_type l_scratch = {0,0,0,0,0,0,0,0}; for(size_t i=0; i< sizeof(l_scratch)/sizeof(l_scratch[0]); i++) { l_scratch[i] = Util::readScratchReg(MBOX_SCRATCH_REG1+i); } // Check mbox scratch reg 3 for IPL boot options // Specifically istep mode (bit 0) and MPIPL (bit 2) INITSERVICE::SPLESS::MboxScratch3_t l_scratch3; l_scratch3.data32 = l_scratch[SCRATCH_3]; if(l_scratch3.isMpipl) { TARG_INF("We are running MPIPL mode"); l_isMpipl = true; } if(l_scratch3.istepMode) { l_isIstepMode = true; } AttrRP::init(io_pError, l_isMpipl); if (io_pError == NULL) { TargetService& l_targetService = targetService(); (void)l_targetService.init(); initializeAttributes(l_targetService, l_isMpipl, l_isIstepMode, l_scratch); checkProcessorTargeting(l_targetService); // Print out top-level model value from loaded targeting values. // @TODO RTC:88056 Make the model printed more meaniful Target* l_pTopLevel = NULL; l_targetService.getTopLevelTarget(l_pTopLevel); ATTR_MODEL_type l_model = MODEL_NA; if (l_pTopLevel->tryGetAttr<ATTR_MODEL>(l_model)) { TARG_INF("Initialized targeting for model: %s", l_pTopLevel->getAttrAsString<ATTR_MODEL>()); } #ifdef CONFIG_DRTM const INITSERVICE::SPLESS::MboxScratch7_t scratch7 = {.data32 = l_scratch[SCRATCH_7] }; const INITSERVICE::SPLESS::MboxScratch8_t scratch8 = {.data32 = l_scratch[SCRATCH_8] }; errlHndl_t pError = SECUREBOOT::DRTM::discoverDrtmState( scratch7,scratch8); if(pError) { auto plid = pError->plid(); errlCommit(pError,SECURE_COMP_ID); // TODO: RTC 167205: Better GA error handling INITSERVICE::doShutdown(plid, true); } #endif // No error module loaded in VPO to save load time #ifndef CONFIG_VPO_COMPILE // call ErrlManager function - tell him that TARG is ready! ERRORLOG::ErrlManager::errlResourceReady(ERRORLOG::TARG); #endif // set global that TARG is ready Util::setIsTargetingLoaded(); } TARG_EXIT(); #undef TARG_FN } /** * @brief Create _start entry point using task entry macro and vector to * initTargeting function */ TASK_ENTRY_MACRO(initTargeting); /** * @brief Check that at least one processor of our cpu type is being targeted */ static void checkProcessorTargeting(TargetService& i_targetService) { #define TARG_FN "checkProcessorTargeting()" TARG_ENTER(); PredicateCTM l_procChip(CLASS_CHIP,TYPE_PROC); ProcessorCoreType l_coreType = cpu_core_type(); bool l_haveOneCorrectProcessor = false; TargetRangeFilter l_filter( i_targetService.begin(), i_targetService.end(), &l_procChip); for(;l_filter && (l_haveOneCorrectProcessor != true);++l_filter) { switch(l_filter->getAttr<ATTR_MODEL>()) { case MODEL_VENICE: if(l_coreType == CORE_POWER8_VENICE) { l_haveOneCorrectProcessor = true; } break; case MODEL_MURANO: if(l_coreType == CORE_POWER8_MURANO) { l_haveOneCorrectProcessor = true; } break; case MODEL_NAPLES: if(l_coreType == CORE_POWER8_NAPLES) { l_haveOneCorrectProcessor = true; } break; case MODEL_NIMBUS: if(l_coreType == CORE_POWER9_NIMBUS) { l_haveOneCorrectProcessor = true; } break; case MODEL_CUMULUS: if(l_coreType == CORE_POWER9_CUMULUS) { l_haveOneCorrectProcessor = true; } break; default: break; }; } TARG_ASSERT((l_haveOneCorrectProcessor == true), TARG_ERR_LOC "FATAL: No " "targeted processors are of the correct type"); TARG_EXIT(); #undef TARG_FN } /* * @brief Initialize any attributes that need to be set early on */ static void initializeAttributes(TargetService& i_targetService, bool i_isMpipl, bool i_istepMode, ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch) { #define TARG_FN "initializeAttributes()...)" TARG_ENTER(); Target* l_pTopLevel = NULL; i_targetService.getTopLevelTarget(l_pTopLevel); if(l_pTopLevel) { Target* l_pMasterProcChip = NULL; i_targetService.masterProcChipTargetHandle(l_pMasterProcChip); if(l_pMasterProcChip) { // Master uses xscom by default, needs to be set before // doing any other scom accesses ScomSwitches l_switches = l_pMasterProcChip->getAttr<ATTR_SCOM_SWITCHES>(); l_switches.useXscom = 1; l_switches.useFsiScom = 0; l_switches.useSbeScom = 0; l_pMasterProcChip->setAttr<ATTR_SCOM_SWITCHES>(l_switches); // Master can only use Host I2C so needs to be set before // doing any I2C accesses I2cSwitches l_i2c_switches = l_pMasterProcChip->getAttr<ATTR_I2C_SWITCHES>(); l_i2c_switches.useHostI2C = 1; l_i2c_switches.useFsiI2C = 0; l_pMasterProcChip->setAttr<ATTR_I2C_SWITCHES>(l_i2c_switches); l_pMasterProcChip->setAttr<ATTR_PROC_SBE_MASTER_CHIP>(1); // Master has SBE started l_pMasterProcChip->setAttr<ATTR_SBE_IS_STARTED>(1); l_pTopLevel->setAttr<ATTR_MASTER_MBOX_SCRATCH>(i_masterScratch); // Targeting data defaults to non istep, only turn "on" if bit // is set so we don't tromp default setting if (i_istepMode) { l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(1); } else { l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(0); } //Set the RISK_LEVEL ATTR based off of master Scratch regs INITSERVICE::SPLESS::MboxScratch5_t l_scratch5; l_scratch5.data32 = i_masterScratch[INITSERVICE::SPLESS::SCRATCH_5]; if(l_scratch5.riskLevel) { l_pTopLevel->setAttr<ATTR_RISK_LEVEL>(1); } } if(i_isMpipl) { l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(1); } else { l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(0); } } else // top level is NULL - never expected { TARG_INF("Top level target is NULL"); } TARG_EXIT(); #undef TARG_FN } #undef TARG_CLASS #undef TARG_NAMESPACE } // End namespace TARGETING <commit_msg>Clear out VIRT_ADDR_BARS in MPIPL<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/targeting/targetservicestart.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2017 */ /* [+] Google Inc. */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file targeting/targetservicestart.C * * @brief Hostboot entry point for target service */ //****************************************************************************** // Includes //****************************************************************************** // STD #include <stdio.h> #include <stdlib.h> // Other components #include <sys/misc.h> #include <sys/task.h> #include <targeting/common/trace.H> #include <targeting/adapters/assertadapter.H> #include <initservice/taskargs.H> #include <util/utilmbox_scratch.H> // This component #include <targeting/common/targetservice.H> #include <targeting/attrrp.H> // Others #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <devicefw/userif.H> #include <config.h> #include <initservice/initserviceif.H> #include <util/misc.H> #ifdef CONFIG_DRTM #include <secureboot/drtm.H> #endif using namespace INITSERVICE::SPLESS; //****************************************************************************** // targetService //****************************************************************************** namespace TARGETING { #define TARG_NAMESPACE "TARGETING::" #define TARG_LOC TARG_NAMESPACE TARG_CLASS TARG_FN ": " //****************************************************************************** // _start //****************************************************************************** #define TARG_CLASS "" /* * @brief Initialize any attributes that need to be set early on */ static void initializeAttributes(TargetService& i_targetService, bool i_isMpipl, bool i_istepMode, ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch); /** * @brief Check that at least one processor of our cpu type is being targeted */ static void checkProcessorTargeting(TargetService& i_targetService); /** * @brief Entry point for initialization service to initialize the targeting * code * * @param[in] io_pError * Error log handle; returns NULL on success, !NULL otherwise * * @note: Link register is configured to automatically invoke task_end() when * this routine returns */ static void initTargeting(errlHndl_t& io_pError) { #define TARG_FN "initTargeting(errlHndl_t& io_pError)" TARG_ENTER(); //Need to stash away the master mbox regs as they will //be overwritten bool l_isMpipl = false; bool l_isIstepMode = false; ATTR_MASTER_MBOX_SCRATCH_type l_scratch = {0,0,0,0,0,0,0,0}; for(size_t i=0; i< sizeof(l_scratch)/sizeof(l_scratch[0]); i++) { l_scratch[i] = Util::readScratchReg(MBOX_SCRATCH_REG1+i); } // Check mbox scratch reg 3 for IPL boot options // Specifically istep mode (bit 0) and MPIPL (bit 2) INITSERVICE::SPLESS::MboxScratch3_t l_scratch3; l_scratch3.data32 = l_scratch[SCRATCH_3]; if(l_scratch3.isMpipl) { TARG_INF("We are running MPIPL mode"); l_isMpipl = true; } if(l_scratch3.istepMode) { l_isIstepMode = true; } AttrRP::init(io_pError, l_isMpipl); if (io_pError == NULL) { TargetService& l_targetService = targetService(); (void)l_targetService.init(); initializeAttributes(l_targetService, l_isMpipl, l_isIstepMode, l_scratch); checkProcessorTargeting(l_targetService); // Print out top-level model value from loaded targeting values. // @TODO RTC:88056 Make the model printed more meaniful Target* l_pTopLevel = NULL; l_targetService.getTopLevelTarget(l_pTopLevel); ATTR_MODEL_type l_model = MODEL_NA; if (l_pTopLevel->tryGetAttr<ATTR_MODEL>(l_model)) { TARG_INF("Initialized targeting for model: %s", l_pTopLevel->getAttrAsString<ATTR_MODEL>()); } #ifdef CONFIG_DRTM const INITSERVICE::SPLESS::MboxScratch7_t scratch7 = {.data32 = l_scratch[SCRATCH_7] }; const INITSERVICE::SPLESS::MboxScratch8_t scratch8 = {.data32 = l_scratch[SCRATCH_8] }; errlHndl_t pError = SECUREBOOT::DRTM::discoverDrtmState( scratch7,scratch8); if(pError) { auto plid = pError->plid(); errlCommit(pError,SECURE_COMP_ID); // TODO: RTC 167205: Better GA error handling INITSERVICE::doShutdown(plid, true); } #endif // No error module loaded in VPO to save load time #ifndef CONFIG_VPO_COMPILE // call ErrlManager function - tell him that TARG is ready! ERRORLOG::ErrlManager::errlResourceReady(ERRORLOG::TARG); #endif // set global that TARG is ready Util::setIsTargetingLoaded(); } TARG_EXIT(); #undef TARG_FN } /** * @brief Create _start entry point using task entry macro and vector to * initTargeting function */ TASK_ENTRY_MACRO(initTargeting); /** * @brief Check that at least one processor of our cpu type is being targeted */ static void checkProcessorTargeting(TargetService& i_targetService) { #define TARG_FN "checkProcessorTargeting()" TARG_ENTER(); PredicateCTM l_procChip(CLASS_CHIP,TYPE_PROC); ProcessorCoreType l_coreType = cpu_core_type(); bool l_haveOneCorrectProcessor = false; TargetRangeFilter l_filter( i_targetService.begin(), i_targetService.end(), &l_procChip); for(;l_filter && (l_haveOneCorrectProcessor != true);++l_filter) { switch(l_filter->getAttr<ATTR_MODEL>()) { case MODEL_VENICE: if(l_coreType == CORE_POWER8_VENICE) { l_haveOneCorrectProcessor = true; } break; case MODEL_MURANO: if(l_coreType == CORE_POWER8_MURANO) { l_haveOneCorrectProcessor = true; } break; case MODEL_NAPLES: if(l_coreType == CORE_POWER8_NAPLES) { l_haveOneCorrectProcessor = true; } break; case MODEL_NIMBUS: if(l_coreType == CORE_POWER9_NIMBUS) { l_haveOneCorrectProcessor = true; } break; case MODEL_CUMULUS: if(l_coreType == CORE_POWER9_CUMULUS) { l_haveOneCorrectProcessor = true; } break; default: break; }; } TARG_ASSERT((l_haveOneCorrectProcessor == true), TARG_ERR_LOC "FATAL: No " "targeted processors are of the correct type"); TARG_EXIT(); #undef TARG_FN } /* * @brief Initialize any attributes that need to be set early on */ static void initializeAttributes(TargetService& i_targetService, bool i_isMpipl, bool i_istepMode, ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch) { #define TARG_FN "initializeAttributes()...)" TARG_ENTER(); Target* l_pTopLevel = NULL; TargetHandleList l_chips; i_targetService.getTopLevelTarget(l_pTopLevel); if(l_pTopLevel) { Target* l_pMasterProcChip = NULL; i_targetService.masterProcChipTargetHandle(l_pMasterProcChip); if(l_pMasterProcChip) { // Master uses xscom by default, needs to be set before // doing any other scom accesses ScomSwitches l_switches = l_pMasterProcChip->getAttr<ATTR_SCOM_SWITCHES>(); l_switches.useXscom = 1; l_switches.useFsiScom = 0; l_switches.useSbeScom = 0; l_pMasterProcChip->setAttr<ATTR_SCOM_SWITCHES>(l_switches); // Master can only use Host I2C so needs to be set before // doing any I2C accesses I2cSwitches l_i2c_switches = l_pMasterProcChip->getAttr<ATTR_I2C_SWITCHES>(); l_i2c_switches.useHostI2C = 1; l_i2c_switches.useFsiI2C = 0; l_pMasterProcChip->setAttr<ATTR_I2C_SWITCHES>(l_i2c_switches); l_pMasterProcChip->setAttr<ATTR_PROC_SBE_MASTER_CHIP>(1); // Master has SBE started l_pMasterProcChip->setAttr<ATTR_SBE_IS_STARTED>(1); l_pTopLevel->setAttr<ATTR_MASTER_MBOX_SCRATCH>(i_masterScratch); // Targeting data defaults to non istep, only turn "on" if bit // is set so we don't tromp default setting if (i_istepMode) { l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(1); } else { l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(0); } //Set the RISK_LEVEL ATTR based off of master Scratch regs INITSERVICE::SPLESS::MboxScratch5_t l_scratch5; l_scratch5.data32 = i_masterScratch[INITSERVICE::SPLESS::SCRATCH_5]; if(l_scratch5.riskLevel) { l_pTopLevel->setAttr<ATTR_RISK_LEVEL>(1); } } if(i_isMpipl) { l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(1); //Clear out some attributes that could have stale data l_pTopLevel->setAttr<ATTR_HB_RSV_MEM_NEXT_SECTION>(0); l_pTopLevel->setAttr<ATTR_ATTN_CHK_ALL_PROCS>(1); TARGETING::PredicateCTM l_chipFilter(CLASS_CHIP, TYPE_PROC); TARGETING::PredicateIsFunctional l_functional; TARGETING::PredicatePostfixExpr l_functionalChips; l_functionalChips.push(&l_chipFilter).push(&l_functional).And(); i_targetService.getAssociated( l_chips, l_pTopLevel, TargetService::CHILD_BY_AFFINITY, TARGETING::TargetService::ALL, &l_functionalChips); for (auto & l_chip : l_chips) { l_chip->setAttr<ATTR_XSCOM_VIRTUAL_ADDR>(0); l_chip->setAttr<ATTR_HOMER_VIRT_ADDR>(0); //TODO RTC:172534 Need to clear volatile attributes during MPIPL for cumulus } } else { l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(0); } } else // top level is NULL - never expected { TARG_INF("Top level target is NULL"); } TARG_EXIT(); #undef TARG_FN } #undef TARG_CLASS #undef TARG_NAMESPACE } // End namespace TARGETING <|endoftext|>
<commit_before>// $Id: mesh_smoother_laplace.C,v 1.3 2003-06-25 19:53:05 jwpeterson Exp $ // The Next Great Finite Element Library. // Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "mesh_smoother_laplace.h" #include <algorithm> // for std::copy, std::sort // Member functions for the Laplace smoother void LaplaceMeshSmoother::smooth(unsigned int n_iterations) { if (not _initialized) this->init(); // Don't smooth the nodes on the boundary... // this would change the mesh geometry which // is probably not something we want! std::vector<bool> on_boundary; _mesh.find_boundary_nodes(on_boundary); for (unsigned int n=0; n<n_iterations; n++) { for (unsigned int i=0; i<_mesh.n_nodes(); ++i) { if (not on_boundary[i]) { // Smooth! Real avg_x = 0.; Real avg_y = 0.; Real avg_z = 0.; for (unsigned int j=0; j<_graph[i].size(); ++j) { // Get a reference to the current node in // the graph const Node& node = _mesh.node(_graph[i][j]); avg_x += node(0); avg_y += node(1); avg_z += node(2); } assert (_graph[i].size() != 0); avg_x /= _graph[i].size(); avg_y /= _graph[i].size(); avg_z /= _graph[i].size(); // Update the location of node(i) Node& node = _mesh.node(i); node(0) = avg_x; node(1) = avg_y; node(2) = avg_z; } } } } void LaplaceMeshSmoother::init() { switch (_mesh.mesh_dimension()) { case 2: // Stolen directly from build_L_graph in mesh_base.C { // Initialize space in the graph. It is n_nodes // long and each node is assumed to be connected to // approximately 4 neighbors. _graph.resize(_mesh.n_nodes()); for (unsigned int i=0; i<_mesh.n_nodes(); ++i) _graph[i].reserve(4); const_active_elem_iterator el (_mesh.elements_begin()); const const_active_elem_iterator end(_mesh.elements_end()); for (; el != end; ++el) { // Shortcut notation for simplicity const Elem* elem = *el; for (unsigned int s=0; s<elem->n_neighbors(); s++) { // Only operate on sides which are on the // boundary or for which the current element's // id is greater than its neighbor's. if ((elem->neighbor(s) == NULL) || (elem->id() > elem->neighbor(s)->id())) { AutoPtr<Elem> side(elem->build_side(s)); _graph[side->node(0)].push_back(side->node(1)); _graph[side->node(1)].push_back(side->node(0)); } } } _initialized = true; break; } case 3: // Stolen blatantly from build_L_graph in mesh_base.C { // Initialize space in the graph. In 3D, I've assumed // that each node was connected to approximately 3 neighbors. _graph.resize(_mesh.n_nodes()); for (unsigned int i=0; i<_mesh.n_nodes(); ++i) _graph[i].reserve(8); const_active_elem_iterator el (_mesh.elements_begin()); const const_active_elem_iterator end(_mesh.elements_end()); for (; el != end; ++el) { // Shortcut notation for simplicity const Elem* elem = *el; for (unsigned int f=0; f<elem->n_neighbors(); f++) // Loop over faces if ((elem->neighbor(f) == NULL) || (elem->id() > elem->neighbor(f)->id())) { AutoPtr<Elem> face(elem->build_side(f)); for (unsigned int s=0; s<face->n_neighbors(); s++) // Loop over face's edges { AutoPtr<Elem> side(face->build_side(s)); // At this point, we just insert the node numbers // again. At the end we'll call sort and unique // to make sure there are no duplicates _graph[side->node(0)].push_back(side->node(1)); _graph[side->node(1)].push_back(side->node(0)); } } } // Now call sort and unique to remove duplicate entries. for (unsigned int i=0; i<_mesh.n_nodes(); ++i) { std::sort (_graph[i].begin(), _graph[i].end()); _graph[i].erase(std::unique(_graph[i].begin(), _graph[i].end()), _graph[i].end()); } _initialized = true; break; } default: { std::cerr << "At this time it is not possible " << "to smooth a dimension " << _mesh.mesh_dimension() << "mesh. Aborting..." << std::endl; error(); } } } void LaplaceMeshSmoother::print_graph() { for (unsigned int i=0; i<_graph.size(); ++i) { std::cout << i << ": "; std::copy(_graph[i].begin(), _graph[i].end(), std::ostream_iterator<unsigned int>(std::cout, " ")); std::cout << std::endl; } } <commit_msg>changed not to !. SGIs CC did not understand it... Sorry John. Maybe in the future? It may be that a command line option fixes it, but I could not find anything in the manual page. If you can find any information on the web we might be able to put it back in... Maybe you could ask Spencer?<commit_after>// $Id: mesh_smoother_laplace.C,v 1.4 2003-06-26 07:16:29 benkirk Exp $ // The Next Great Finite Element Library. // Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "mesh_smoother_laplace.h" #include <algorithm> // for std::copy, std::sort // Member functions for the Laplace smoother void LaplaceMeshSmoother::smooth(unsigned int n_iterations) { if (!_initialized) this->init(); // Don't smooth the nodes on the boundary... // this would change the mesh geometry which // is probably not something we want! std::vector<bool> on_boundary; _mesh.find_boundary_nodes(on_boundary); for (unsigned int n=0; n<n_iterations; n++) { for (unsigned int i=0; i<_mesh.n_nodes(); ++i) { if (!on_boundary[i]) { // Smooth! Real avg_x = 0.; Real avg_y = 0.; Real avg_z = 0.; for (unsigned int j=0; j<_graph[i].size(); ++j) { // Get a reference to the current node in // the graph const Node& node = _mesh.node(_graph[i][j]); avg_x += node(0); avg_y += node(1); avg_z += node(2); } assert (_graph[i].size() != 0); avg_x /= _graph[i].size(); avg_y /= _graph[i].size(); avg_z /= _graph[i].size(); // Update the location of node(i) Node& node = _mesh.node(i); node(0) = avg_x; node(1) = avg_y; node(2) = avg_z; } } } } void LaplaceMeshSmoother::init() { switch (_mesh.mesh_dimension()) { case 2: // Stolen directly from build_L_graph in mesh_base.C { // Initialize space in the graph. It is n_nodes // long and each node is assumed to be connected to // approximately 4 neighbors. _graph.resize(_mesh.n_nodes()); for (unsigned int i=0; i<_mesh.n_nodes(); ++i) _graph[i].reserve(4); const_active_elem_iterator el (_mesh.elements_begin()); const const_active_elem_iterator end(_mesh.elements_end()); for (; el != end; ++el) { // Shortcut notation for simplicity const Elem* elem = *el; for (unsigned int s=0; s<elem->n_neighbors(); s++) { // Only operate on sides which are on the // boundary or for which the current element's // id is greater than its neighbor's. if ((elem->neighbor(s) == NULL) || (elem->id() > elem->neighbor(s)->id())) { AutoPtr<Elem> side(elem->build_side(s)); _graph[side->node(0)].push_back(side->node(1)); _graph[side->node(1)].push_back(side->node(0)); } } } _initialized = true; break; } case 3: // Stolen blatantly from build_L_graph in mesh_base.C { // Initialize space in the graph. In 3D, I've assumed // that each node was connected to approximately 3 neighbors. _graph.resize(_mesh.n_nodes()); for (unsigned int i=0; i<_mesh.n_nodes(); ++i) _graph[i].reserve(8); const_active_elem_iterator el (_mesh.elements_begin()); const const_active_elem_iterator end(_mesh.elements_end()); for (; el != end; ++el) { // Shortcut notation for simplicity const Elem* elem = *el; for (unsigned int f=0; f<elem->n_neighbors(); f++) // Loop over faces if ((elem->neighbor(f) == NULL) || (elem->id() > elem->neighbor(f)->id())) { AutoPtr<Elem> face(elem->build_side(f)); for (unsigned int s=0; s<face->n_neighbors(); s++) // Loop over face's edges { AutoPtr<Elem> side(face->build_side(s)); // At this point, we just insert the node numbers // again. At the end we'll call sort and unique // to make sure there are no duplicates _graph[side->node(0)].push_back(side->node(1)); _graph[side->node(1)].push_back(side->node(0)); } } } // Now call sort and unique to remove duplicate entries. for (unsigned int i=0; i<_mesh.n_nodes(); ++i) { std::sort (_graph[i].begin(), _graph[i].end()); _graph[i].erase(std::unique(_graph[i].begin(), _graph[i].end()), _graph[i].end()); } _initialized = true; break; } default: { std::cerr << "At this time it is not possible " << "to smooth a dimension " << _mesh.mesh_dimension() << "mesh. Aborting..." << std::endl; error(); } } } void LaplaceMeshSmoother::print_graph() { for (unsigned int i=0; i<_graph.size(); ++i) { std::cout << i << ": "; std::copy(_graph[i].begin(), _graph[i].end(), std::ostream_iterator<unsigned int>(std::cout, " ")); std::cout << std::endl; } } <|endoftext|>
<commit_before>// rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // rbOOmit 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. // rbOOmit 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "rb_theta_expansion.h" #include "rb_theta.h" namespace libMesh { // ------------------------------------------------------------ // RBThetaExpansion implementation RBThetaExpansion::RBThetaExpansion() { theta_q_a_vector.clear(); theta_q_f_vector.clear(); theta_q_l_vector.clear(); } unsigned int RBThetaExpansion::get_Q_a() { return theta_q_a_vector.size(); } unsigned int RBThetaExpansion::get_Q_f() const { return theta_q_f_vector.size(); } unsigned int RBThetaExpansion::get_n_outputs() const { return theta_q_l_vector.size(); } unsigned int RBThetaExpansion::get_Q_l(unsigned int index) const { if(index >= get_n_outputs()) { libMesh::err << "Error: We must have index < n_outputs in get_Q_l." << std::endl; libmesh_error(); } return theta_q_l_vector[index].size(); } void RBThetaExpansion::attach_theta_q_a(RBTheta* theta_q_a) { libmesh_assert(theta_q_a != NULL); theta_q_a_vector.push_back(theta_q_a); } void RBThetaExpansion::attach_theta_q_f(RBTheta* theta_q_f) { libmesh_assert(theta_q_f != NULL); theta_q_f_vector.push_back(theta_q_f); } void RBThetaExpansion::attach_output_theta(std::vector<RBTheta*> theta_q_l) { theta_q_l_vector.push_back(theta_q_l); } void RBThetaExpansion::attach_output_theta(RBTheta* theta_q_l) { libmesh_assert(theta_q_l != NULL); std::vector<RBTheta*> theta_l_vector(1); theta_l_vector[0] = theta_q_l; attach_output_theta(theta_l_vector); } Number RBThetaExpansion::eval_theta_q_a(unsigned int q, const std::vector<Real>& mu) { if(q >= get_Q_a()) { libMesh::err << "Error: We must have q < Q_a in eval_theta_q_a." << std::endl; libmesh_error(); } return theta_q_a_vector[q]->evaluate( mu ); } Number RBThetaExpansion::eval_theta_q_f(unsigned int q, const std::vector<Real>& mu) { if(q >= get_Q_f()) { libMesh::err << "Error: We must have q < Q_f in eval_theta_q_f." << std::endl; libmesh_error(); } libmesh_assert(theta_q_f_vector[q] != NULL); return theta_q_f_vector[q]->evaluate( mu ); } Number RBThetaExpansion::eval_theta_q_l(unsigned int output_index, unsigned int q_l, const std::vector<Real>& mu) { if( (output_index >= get_n_outputs()) || (q_l >= get_Q_l(output_index)) ) { libMesh::err << "Error: We must have output_index < n_outputs and " << "q_l < get_Q_l(output_index) in eval_theta_q_l." << std::endl; libmesh_error(); } libmesh_assert(theta_q_l_vector[output_index][q_l] != NULL); return theta_q_l_vector[output_index][q_l]->evaluate( mu ); } }<commit_msg>Modified white space in rb_theta_expansion.C<commit_after>// rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // rbOOmit 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. // rbOOmit 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "rb_theta_expansion.h" #include "rb_theta.h" namespace libMesh { // ------------------------------------------------------------ // RBThetaExpansion implementation RBThetaExpansion::RBThetaExpansion() { theta_q_a_vector.clear(); theta_q_f_vector.clear(); theta_q_l_vector.clear(); } unsigned int RBThetaExpansion::get_Q_a() { return theta_q_a_vector.size(); } unsigned int RBThetaExpansion::get_Q_f() const { return theta_q_f_vector.size(); } unsigned int RBThetaExpansion::get_n_outputs() const { return theta_q_l_vector.size(); } unsigned int RBThetaExpansion::get_Q_l(unsigned int index) const { if(index >= get_n_outputs()) { libMesh::err << "Error: We must have index < n_outputs in get_Q_l." << std::endl; libmesh_error(); } return theta_q_l_vector[index].size(); } void RBThetaExpansion::attach_theta_q_a(RBTheta* theta_q_a) { libmesh_assert(theta_q_a != NULL); theta_q_a_vector.push_back(theta_q_a); } void RBThetaExpansion::attach_theta_q_f(RBTheta* theta_q_f) { libmesh_assert(theta_q_f != NULL); theta_q_f_vector.push_back(theta_q_f); } void RBThetaExpansion::attach_output_theta(std::vector<RBTheta*> theta_q_l) { theta_q_l_vector.push_back(theta_q_l); } void RBThetaExpansion::attach_output_theta(RBTheta* theta_q_l) { libmesh_assert(theta_q_l != NULL); std::vector<RBTheta*> theta_l_vector(1); theta_l_vector[0] = theta_q_l; attach_output_theta(theta_l_vector); } Number RBThetaExpansion::eval_theta_q_a(unsigned int q, const std::vector<Real>& mu) { if(q >= get_Q_a()) { libMesh::err << "Error: We must have q < Q_a in eval_theta_q_a." << std::endl; libmesh_error(); } return theta_q_a_vector[q]->evaluate( mu ); } Number RBThetaExpansion::eval_theta_q_f(unsigned int q, const std::vector<Real>& mu) { if(q >= get_Q_f()) { libMesh::err << "Error: We must have q < Q_f in eval_theta_q_f." << std::endl; libmesh_error(); } libmesh_assert(theta_q_f_vector[q] != NULL); return theta_q_f_vector[q]->evaluate( mu ); } Number RBThetaExpansion::eval_theta_q_l(unsigned int output_index, unsigned int q_l, const std::vector<Real>& mu) { if( (output_index >= get_n_outputs()) || (q_l >= get_Q_l(output_index)) ) { libMesh::err << "Error: We must have output_index < n_outputs and " << "q_l < get_Q_l(output_index) in eval_theta_q_l." << std::endl; libmesh_error(); } libmesh_assert(theta_q_l_vector[output_index][q_l] != NULL); return theta_q_l_vector[output_index][q_l]->evaluate( mu ); } }<|endoftext|>
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * 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. */ /*!\file BouncingBallTS.cpp \brief \ref EMBouncingBall - C++ input file, Time-Stepping version - V. Acary, F. Perignon. A Ball bouncing on the ground. Direct description of the model. Simulation with a Time-Stepping scheme. */ #include "SiconosKernel.hpp" using namespace std; int main(int argc, char* argv[]) { try { // ================= Creation of the model ======================= // User-defined main parameters unsigned int nDof = 3; // degrees of freedom for the ball double t0 = 0; // initial computation time double T = 10; // final computation time double h = 0.005; // time step double position_init = 1.0; // initial position for lowest bead. double velocity_init = 0.0; // initial velocity for lowest bead. double theta = 0.5; // theta for MoreauJeanOSI integrator double R = 0.1; // Ball radius double height = 1.0; // height to the roof double m = 1; // Ball mass double g = 9.81; // Gravity // ------------------------- // --- Dynamical systems --- // ------------------------- cout << "====> Model loading ..." << endl; SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof)); (*Mass)(0, 0) = m; (*Mass)(1, 1) = m; (*Mass)(2, 2) = 2. / 5 * m * R * R; // -- Initial positions and velocities -- SP::SiconosVector q0(new SiconosVector(nDof)); SP::SiconosVector v0(new SiconosVector(nDof)); (*q0)(0) = position_init; (*v0)(0) = velocity_init; // -- The dynamical system -- SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass)); // -- Set external forces (weight) -- SP::SiconosVector weight(new SiconosVector(nDof)); (*weight)(0) = -m * g; ball->setFExtPtr(weight); // -------------------- // --- Interactions --- // -------------------- // -- nslaw -- double e = 0.9; // Interaction ball-roof with impact // SP::SimpleMatrix H(new SimpleMatrix(1, nDof)); (*H)(0, 0) = -1.0; SP::SiconosVector b(new SiconosVector(1)); (*b)(0) = - R; SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e)); SP::Relation relation(new LagrangianLinearTIR(H,b)); SP::Interaction inter(new Interaction(1, nslaw, relation)); // -- nslaw -- double stiffness = 10.0; // Interaction ball-floor with a compliant spring SP::SimpleMatrix Hfloor(new SimpleMatrix(1, nDof)); (*Hfloor)(0, 0) = 1.0; SP::SimpleMatrix Kfloor(new SimpleMatrix(1, 1)); (*Kfloor)(0, 0) = stiffness; SP::SiconosVector bfloor(new SiconosVector(1)); (*bfloor)(0) = height - R; SP::NonSmoothLaw nslawfloor(new ComplementarityConditionNSL(1)); SP::Relation relationfloor(new LagrangianCompliantLinearTIR(Hfloor,Kfloor, bfloor)); SP::Interaction interfloor(new Interaction(1, nslawfloor, relationfloor)); // ------------- // --- Model --- // ------------- SP::Model bouncingBall(new Model(t0, T)); // add the dynamical system in the non smooth dynamical system bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(interfloor, ball); // ------------------ // --- Simulation --- // ------------------ // -- (1) OneStepIntegrators -- SP::MoreauJeanOSI OSI(new MoreauJeanOSI(theta)); // -- (2) Time discretisation -- SP::TimeDiscretisation t(new TimeDiscretisation(t0, h)); // -- (3) one step non smooth problem SP::OneStepNSProblem osnspb(new LCP()); // -- (4) Simulation setup with (1) (2) (3) SP::TimeStepping s(new TimeStepping(t, OSI, osnspb)); bouncingBall->setSimulation(s); // =========================== End of model definition =========================== // ================================= Computation ================================= // --- Simulation initialization --- cout << "====> Initialisation ..." << endl; //bouncingBall->nonSmoothDynamicalSystem()->topology()->setOSI(ball, OSI); bouncingBall->initialize(); // -- set the integrator for the ball -- int N = ceil((T - t0) / h); // Number of time steps // --- Get the values to be plotted --- // -> saved in a matrix dataPlot unsigned int outputSize = 5; SimpleMatrix dataPlot(N + 1, outputSize); SP::SiconosVector q = ball->q(); SP::SiconosVector v = ball->velocity(); SP::SiconosVector p = ball->p(1); SP::SiconosVector lambda = inter->lambda(1); dataPlot(0, 0) = bouncingBall->t0(); dataPlot(0, 1) = (*q)(0); dataPlot(0, 2) = (*v)(0); dataPlot(0, 3) = (*p)(0); dataPlot(0, 4) = (*lambda)(0); // --- Time loop --- cout << "====> Start computation ... " << endl; // ==== Simulation loop - Writing without explicit event handling ===== int k = 1; boost::progress_display show_progress(N); boost::timer time; time.restart(); while (s->hasNextEvent()) { s->computeOneStep(); // --- Get values to be plotted --- dataPlot(k, 0) = s->nextTime(); dataPlot(k, 1) = (*q)(0); dataPlot(k, 2) = (*v)(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*lambda)(0); s->nextStep(); ++show_progress; k++; } cout << "End of computation - Number of iterations done: " << k - 1 << endl; cout << "Computation Time " << time.elapsed() << endl; // // --- Output files --- // cout << "====> Output file writing ..." << endl; // dataPlot.resize(k, outputSize); // ioMatrix::write("result.dat", "ascii", dataPlot, "noDim"); // std::cout << "Comparison with a reference file" << std::endl; // SimpleMatrix dataPlotRef(dataPlot); // dataPlotRef.zero(); // ioMatrix::read("result.ref", "ascii", dataPlotRef); // double error = (dataPlot - dataPlotRef).normInf(); // std::cout << "error =" << error << std::endl; // if (error> 1e-12) // { // std::cout << "Warning. The result is rather different from the reference file." << std::endl; // return 1; // } } catch (SiconosException e) { cout << e.report() << endl; } catch (...) { cout << "Exception caught in BouncingBallTS.cpp" << endl; } } <commit_msg>[examples] a first silly simulation with compliant contact<commit_after>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * 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. */ /*!\file BouncingBallTS.cpp \brief \ref EMBouncingBall - C++ input file, Time-Stepping version - V. Acary, F. Perignon. A Ball bouncing on the ground. Direct description of the model. Simulation with a Time-Stepping scheme. */ #include "SiconosKernel.hpp" using namespace std; int main(int argc, char* argv[]) { try { // ================= Creation of the model ======================= // User-defined main parameters unsigned int nDof = 3; // degrees of freedom for the ball double t0 = 0; // initial computation time double T = 10; // final computation time double h = 0.0005; // time step double position_init = 1.0; // initial position for lowest bead. double velocity_init = 0.0; // initial velocity for lowest bead. double theta = 0.5; // theta for MoreauJeanOSI integrator double R = 0.1; // Ball radius double height = 1.0; // height to the roof double m = 1; // Ball mass double g = 9.81; // Gravity // ------------------------- // --- Dynamical systems --- // ------------------------- cout << "====> Model loading ..." << endl; SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof)); (*Mass)(0, 0) = m; (*Mass)(1, 1) = m; (*Mass)(2, 2) = 2. / 5 * m * R * R; // -- Initial positions and velocities -- SP::SiconosVector q0(new SiconosVector(nDof)); SP::SiconosVector v0(new SiconosVector(nDof)); (*q0)(0) = position_init; (*v0)(0) = velocity_init; // -- The dynamical system -- SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass)); // -- Set external forces (weight) -- SP::SiconosVector weight(new SiconosVector(nDof)); (*weight)(0) = -m * g; ball->setFExtPtr(weight); // -------------------- // --- Interactions --- // -------------------- // -- nslaw -- double e = 1.0; // Interaction ball-roof with impact // SP::SimpleMatrix H(new SimpleMatrix(1, nDof)); (*H)(0, 0) = -1.0; SP::SiconosVector b(new SiconosVector(1)); (*b)(0) = height - R- .2; SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e)); SP::Relation relation(new LagrangianLinearTIR(H,b)); SP::Interaction inter(new Interaction(1, nslaw, relation)); // -- nslaw -- double compliance = 0.01; // Interaction ball-floor with a compliant spring SP::SimpleMatrix Hfloor(new SimpleMatrix(1, nDof)); (*Hfloor)(0, 0) = 1.0; SP::SimpleMatrix Kfloor(new SimpleMatrix(1, 1)); (*Kfloor)(0, 0) = compliance; SP::SiconosVector bfloor(new SiconosVector(1)); (*bfloor)(0) = - R; SP::NonSmoothLaw nslawfloor(new ComplementarityConditionNSL(1)); SP::Relation relationfloor(new LagrangianCompliantLinearTIR(Hfloor,Kfloor, bfloor)); SP::Interaction interfloor(new Interaction(1, nslawfloor, relationfloor)); // ------------- // --- Model --- // ------------- SP::Model bouncingBall(new Model(t0, T)); // add the dynamical system in the non smooth dynamical system bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(interfloor, ball); // ------------------ // --- Simulation --- // ------------------ // -- (1) OneStepIntegrators -- SP::MoreauJeanOSI OSI(new MoreauJeanOSI(theta)); // -- (2) Time discretisation -- SP::TimeDiscretisation t(new TimeDiscretisation(t0, h)); // -- (3) one step non smooth problem SP::OneStepNSProblem osnspb(new LCP()); // -- (4) Simulation setup with (1) (2) (3) SP::TimeStepping s(new TimeStepping(t, OSI, osnspb)); bouncingBall->setSimulation(s); // =========================== End of model definition =========================== // ================================= Computation ================================= // --- Simulation initialization --- cout << "====> Initialisation ..." << endl; //bouncingBall->nonSmoothDynamicalSystem()->topology()->setOSI(ball, OSI); bouncingBall->initialize(); // -- set the integrator for the ball -- int N = ceil((T - t0) / h); // Number of time steps // --- Get the values to be plotted --- // -> saved in a matrix dataPlot unsigned int outputSize = 5; SimpleMatrix dataPlot(N + 1, outputSize); SP::SiconosVector q = ball->q(); SP::SiconosVector v = ball->velocity(); SP::SiconosVector p = ball->p(1); SP::SiconosVector lambda = inter->lambda(1); dataPlot(0, 0) = bouncingBall->t0(); dataPlot(0, 1) = (*q)(0); dataPlot(0, 2) = (*v)(0); dataPlot(0, 3) = (*p)(0); dataPlot(0, 4) = (*lambda)(0); // --- Time loop --- cout << "====> Start computation ... " << endl; // ==== Simulation loop - Writing without explicit event handling ===== int k = 1; boost::progress_display show_progress(N); boost::timer time; time.restart(); while (s->hasNextEvent()) { s->computeOneStep(); // --- Get values to be plotted --- dataPlot(k, 0) = s->nextTime(); dataPlot(k, 1) = (*q)(0); dataPlot(k, 2) = (*v)(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*lambda)(0); s->nextStep(); ++show_progress; k++; } cout << "End of computation - Number of iterations done: " << k - 1 << endl; cout << "Computation Time " << time.elapsed() << endl; // --- Output files --- cout << "====> Output file writing ..." << endl; dataPlot.resize(k, outputSize); ioMatrix::write("result.dat", "ascii", dataPlot, "noDim"); // std::cout << "Comparison with a reference file" << std::endl; // SimpleMatrix dataPlotRef(dataPlot); // dataPlotRef.zero(); // ioMatrix::read("result.ref", "ascii", dataPlotRef); // double error = (dataPlot - dataPlotRef).normInf(); // std::cout << "error =" << error << std::endl; // if (error> 1e-12) // { // std::cout << "Warning. The result is rather different from the reference file." << std::endl; // return 1; // } } catch (SiconosException e) { cout << e.report() << endl; } catch (...) { cout << "Exception caught in BouncingBallTS.cpp" << endl; } } <|endoftext|>
<commit_before><commit_msg>place date update fps below render fps<commit_after><|endoftext|>
<commit_before>/* * checked_mutex.hpp * * MIT License * * Copyright (c) 2017 yohhoy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef YAMC_CHECKED_MUTEX_HPP_ #define YAMC_CHECKED_MUTEX_HPP_ #include <cassert> #include <cstdlib> #include <chrono> #include <condition_variable> #include <mutex> #include <system_error> #include <thread> // call std::abort() when requirements violation #ifndef YAMC_CHECKED_CALL_ABORT #define YAMC_CHECKED_CALL_ABORT 0 #endif namespace yamc { /* * strict requirements checking for debug */ namespace checked { namespace detail { class mutex_base { protected: std::thread::id owner_; std::condition_variable cv_; std::mutex mtx_; void dtor_precondition(const char* emsg) { if (owner_ != std::thread::id()) { // object liveness #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } } void lock() { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "recursive lock"); #endif } while (owner_ != std::thread::id()) { cv_.wait(lk); } owner_ = tid; } bool try_lock() { const auto tid = std::this_thread::get_id(); std::lock_guard<std::mutex> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "recursive try_lock"); #endif } if (owner_ != std::thread::id()) { return false; } owner_ = tid; return true; } void unlock() { std::lock_guard<std::mutex> lk(mtx_); if (owner_ != std::this_thread::get_id()) { // owner thread #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::operation_not_permitted), "invalid unlock"); #endif } owner_ = std::thread::id(); cv_.notify_all(); } }; class recursive_mutex_base { protected: std::size_t ncount_ = 0; std::thread::id owner_; std::condition_variable cv_; std::mutex mtx_; void dtor_precondition(const char* emsg) { if (ncount_ != 0 || owner_ != std::thread::id()) { // object liveness #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } } void lock() { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { ++ncount_; return; } while (ncount_ != 0) { cv_.wait(lk); } assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; } bool try_lock() { const auto tid = std::this_thread::get_id(); std::lock_guard<std::mutex> lk(mtx_); if (owner_ == tid) { ++ncount_; return true; } if (ncount_ == 0) { assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; return true; } return false; } void unlock() { std::lock_guard<std::mutex> lk(mtx_); if (owner_ != std::this_thread::get_id()) { // owner thread #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::operation_not_permitted), "invalid unlock"); #endif } assert(0 < ncount_); if (--ncount_ == 0) { owner_ = std::thread::id(); cv_.notify_all(); } } }; } // namespace detail class mutex : private detail::mutex_base { using base = detail::mutex_base; public: mutex() = default; ~mutex() noexcept(false) { dtor_precondition("abandoned mutex"); } mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; }; class timed_mutex : private detail::mutex_base { using base = detail::mutex_base; template<typename Clock, typename Duration> bool do_try_lockwait(const std::chrono::time_point<Clock, Duration>& tp, const char* emsg) { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } while (owner_ != std::thread::id()) { if (cv_.wait_until(lk, tp) == std::cv_status::timeout) { if (owner_ == std::thread::id()) // re-check predicate break; return false; } } owner_ = tid; return true; } public: timed_mutex() = default; ~timed_mutex() noexcept(false) { dtor_precondition("abandoned timed_mutex"); } timed_mutex(const timed_mutex&) = delete; timed_mutex& operator=(const timed_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; template<typename Rep, typename Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { const auto tp = std::chrono::steady_clock::now() + duration; return do_try_lockwait(tp, "recursive try_lock_for"); } template<typename Clock, typename Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& tp) { return do_try_lockwait(tp, "recursive try_lock_until"); } }; class recursive_mutex : private detail::recursive_mutex_base { using base = detail::recursive_mutex_base; public: recursive_mutex() = default; ~recursive_mutex() noexcept(false) { dtor_precondition("abandoned recursive_mutex"); } recursive_mutex(const recursive_mutex&) = delete; recursive_mutex& operator=(const recursive_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; }; class recursive_timed_mutex : private detail::recursive_mutex_base { using base = detail::recursive_mutex_base; template<typename Clock, typename Duration> bool do_try_lockwait(const std::chrono::time_point<Clock, Duration>& tp) { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { ++ncount_; return true; } while (ncount_ != 0) { if (cv_.wait_until(lk, tp) == std::cv_status::timeout) { if (ncount_ == 0) // re-check predicate break; return false; } } assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; return true; } public: recursive_timed_mutex() = default; ~recursive_timed_mutex() noexcept(false) { dtor_precondition("abandoned recursive_timed_mutex"); } recursive_timed_mutex(const recursive_timed_mutex&) = delete; recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; template<typename Rep, typename Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { const auto tp = std::chrono::steady_clock::now() + duration; return do_try_lockwait(tp); } template<typename Clock, typename Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& tp) { return do_try_lockwait(tp); } }; } // namespace checked } // namespace yamc #endif <commit_msg>suppress unused variable warninig (checked_mutex.hpp)<commit_after>/* * checked_mutex.hpp * * MIT License * * Copyright (c) 2017 yohhoy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef YAMC_CHECKED_MUTEX_HPP_ #define YAMC_CHECKED_MUTEX_HPP_ #include <cassert> #include <cstdlib> #include <chrono> #include <condition_variable> #include <mutex> #include <system_error> #include <thread> // call std::abort() when requirements violation #ifndef YAMC_CHECKED_CALL_ABORT #define YAMC_CHECKED_CALL_ABORT 0 #endif namespace yamc { /* * strict requirements checking for debug */ namespace checked { namespace detail { class mutex_base { protected: std::thread::id owner_; std::condition_variable cv_; std::mutex mtx_; void dtor_precondition(const char* emsg) { if (owner_ != std::thread::id()) { // object liveness #if YAMC_CHECKED_CALL_ABORT std::abort(); (void)emsg; // suppress "unused variable" warning #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } } void lock() { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "recursive lock"); #endif } while (owner_ != std::thread::id()) { cv_.wait(lk); } owner_ = tid; } bool try_lock() { const auto tid = std::this_thread::get_id(); std::lock_guard<std::mutex> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "recursive try_lock"); #endif } if (owner_ != std::thread::id()) { return false; } owner_ = tid; return true; } void unlock() { std::lock_guard<std::mutex> lk(mtx_); if (owner_ != std::this_thread::get_id()) { // owner thread #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::operation_not_permitted), "invalid unlock"); #endif } owner_ = std::thread::id(); cv_.notify_all(); } }; class recursive_mutex_base { protected: std::size_t ncount_ = 0; std::thread::id owner_; std::condition_variable cv_; std::mutex mtx_; void dtor_precondition(const char* emsg) { if (ncount_ != 0 || owner_ != std::thread::id()) { // object liveness #if YAMC_CHECKED_CALL_ABORT std::abort(); (void)emsg; // suppress "unused variable" warning #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } } void lock() { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { ++ncount_; return; } while (ncount_ != 0) { cv_.wait(lk); } assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; } bool try_lock() { const auto tid = std::this_thread::get_id(); std::lock_guard<std::mutex> lk(mtx_); if (owner_ == tid) { ++ncount_; return true; } if (ncount_ == 0) { assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; return true; } return false; } void unlock() { std::lock_guard<std::mutex> lk(mtx_); if (owner_ != std::this_thread::get_id()) { // owner thread #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::operation_not_permitted), "invalid unlock"); #endif } assert(0 < ncount_); if (--ncount_ == 0) { owner_ = std::thread::id(); cv_.notify_all(); } } }; } // namespace detail class mutex : private detail::mutex_base { using base = detail::mutex_base; public: mutex() = default; ~mutex() noexcept(false) { dtor_precondition("abandoned mutex"); } mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; }; class timed_mutex : private detail::mutex_base { using base = detail::mutex_base; template<typename Clock, typename Duration> bool do_try_lockwait(const std::chrono::time_point<Clock, Duration>& tp, const char* emsg) { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); (void)emsg; // suppress "unused variable" warning #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } while (owner_ != std::thread::id()) { if (cv_.wait_until(lk, tp) == std::cv_status::timeout) { if (owner_ == std::thread::id()) // re-check predicate break; return false; } } owner_ = tid; return true; } public: timed_mutex() = default; ~timed_mutex() noexcept(false) { dtor_precondition("abandoned timed_mutex"); } timed_mutex(const timed_mutex&) = delete; timed_mutex& operator=(const timed_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; template<typename Rep, typename Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { const auto tp = std::chrono::steady_clock::now() + duration; return do_try_lockwait(tp, "recursive try_lock_for"); } template<typename Clock, typename Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& tp) { return do_try_lockwait(tp, "recursive try_lock_until"); } }; class recursive_mutex : private detail::recursive_mutex_base { using base = detail::recursive_mutex_base; public: recursive_mutex() = default; ~recursive_mutex() noexcept(false) { dtor_precondition("abandoned recursive_mutex"); } recursive_mutex(const recursive_mutex&) = delete; recursive_mutex& operator=(const recursive_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; }; class recursive_timed_mutex : private detail::recursive_mutex_base { using base = detail::recursive_mutex_base; template<typename Clock, typename Duration> bool do_try_lockwait(const std::chrono::time_point<Clock, Duration>& tp) { const auto tid = std::this_thread::get_id(); std::unique_lock<std::mutex> lk(mtx_); if (owner_ == tid) { ++ncount_; return true; } while (ncount_ != 0) { if (cv_.wait_until(lk, tp) == std::cv_status::timeout) { if (ncount_ == 0) // re-check predicate break; return false; } } assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; return true; } public: recursive_timed_mutex() = default; ~recursive_timed_mutex() noexcept(false) { dtor_precondition("abandoned recursive_timed_mutex"); } recursive_timed_mutex(const recursive_timed_mutex&) = delete; recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; template<typename Rep, typename Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { const auto tp = std::chrono::steady_clock::now() + duration; return do_try_lockwait(tp); } template<typename Clock, typename Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& tp) { return do_try_lockwait(tp); } }; } // namespace checked } // namespace yamc #endif <|endoftext|>
<commit_before>/* ** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org). ** ** This Source Code Form is subject to the terms of the Mozilla Public License ** v.2.0. If a copy of the MPL was not distributed with this file, You can ** obtain one at http://mozilla.org/MPL/2.0/. ** ** github: https://github.com/libyuni/libyuni/ ** gitlab: https://gitlab.com/libyuni/libyuni/ (mirror) */ #pragma once #include "traits.h" namespace Yuni { namespace Private { namespace CStringImpl { template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>::Data() : size(), capacity(), data(NULL) {} template<uint ChunkSizeT, bool ExpandableT> Data<ChunkSizeT,ExpandableT>::Data(const Data<ChunkSizeT,ExpandableT>& rhs) : size(rhs.size), capacity(rhs.size), data(NULL) { if (size) { if (chunkSize != 0) { capacity += static_cast<uint>(zeroTerminated); data = reinterpret_cast<C*>(::malloc(sizeof(C) * static_cast<uint>(capacity))); YUNI_MEMCPY(const_cast<void*>(static_cast<const void*>(data)), static_cast<uint>(capacity), rhs.data, sizeof(C) * size); if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } else { // this string is a string adapter data = rhs.data; } } } # ifdef YUNI_HAS_CPP_MOVE template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>::Data(Data&& rhs) : size(rhs.size), capacity(rhs.size), data(rhs.data) { rhs.size = 0; rhs.capacity = 0; rhs.data = nullptr; } # endif template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>::~Data() { // Release the internal buffer if allocated // The string is a string adapter only if the chunk size if null // When the string is an adapter, the variable is const if (chunkSize != 0) ::free(const_cast<void*>(static_cast<const void*>(data))); } # ifdef YUNI_HAS_CPP_MOVE template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>& Data<ChunkSizeT,ExpandableT>::operator = (Data&& rhs) { // Release the internal buffer if allocated // The string is a string adapter only if the chunk size if null // When the string is an adapter, the variable is const if (chunkSize != 0) ::free(const_cast<void*>(static_cast<const void*>(data))); size = rhs.size; capacity = rhs.capacity; data = rhs.data; rhs.size = 0; rhs.capacity = 0; rhs.data = nullptr; return *this; } # endif template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::adapt(const char* const cstring) { data = const_cast<char*>(cstring); capacity = size = (data ? static_cast<Size>(::strlen(data)) : 0); } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::adapt(const char* const cstring, Size length) { data = const_cast<char*>(cstring); capacity = size = length; } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::clear() { if (static_cast<uint>(zeroTerminated)) { if (size) { size = 0; *(const_cast<char*>(data)) = C(); } } else size = 0; } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::forgetContent() { capacity = 0; if (static_cast<uint>(zeroTerminated)) { if (size) { size = 0; *(const_cast<char*>(data)) = C(); } } else size = 0; data = nullptr; // forget me ! } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::shrink() { if (data) { if (size) { capacity = size + static_cast<uint>(zeroTerminated); data = reinterpret_cast<char*>(::realloc(const_cast<char*>(data), static_cast<uint>(capacity))); } else { capacity = 0; ::free(const_cast<void*>(static_cast<const void*>(data))); data = nullptr; } } } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::insert(Size offset, const C* const buffer, const Size len) { // Reserving enough space to insert the buffer reserve(len + size + static_cast<uint>(zeroTerminated)); // Move the existing block of data (void)::memmove(const_cast<char*>(data) + sizeof(C) * (offset + len), const_cast<char*>(data) + sizeof(C) * (offset), sizeof(C) * (size - offset)); // Copying the given buffer YUNI_MEMCPY(const_cast<char*>(data) + sizeof(C) * (offset), static_cast<uint>(capacity), buffer, sizeof(C) * len); // Updating the size size += len; // zero-terminated if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::put(const C rhs) { // Making sure that we have enough space reserve(size + 1 + static_cast<uint>(zeroTerminated)); // Raw copy (const_cast<char*>(data))[size] = rhs; // New size ++size; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } template<uint ChunkSizeT, bool ExpandableT> void Data<ChunkSizeT,ExpandableT>::reserve(Size mincapacity) { if (adapter) return; mincapacity += static_cast<uint>(zeroTerminated); if (static_cast<uint>(capacity) < mincapacity) { // This loop may be a little faster than the following replacement code : // static_cast<uint>(capacity) = minstatic_cast<uint>(capacity) + minstatic_cast<uint>(capacity) % chunkSize; // Especially when chunkSize is not a power of 2 Size newcapacity = static_cast<uint>(capacity); do { // Increase the static_cast<uint>(capacity) until we have enough space newcapacity += chunkSize; } while (newcapacity < mincapacity); // Realloc the internal buffer C* newdata = reinterpret_cast<C*>(::realloc(const_cast<char*>(data), (sizeof(C) * newcapacity))); // The returned value can be NULL if (!newdata) throw "Yuni::CString: Impossible to realloc"; { data = newdata; capacity = newcapacity; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } } } template<uint ChunkSizeT> typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::assignWithoutChecking(const C* const block, Size blockSize) { // We have to trunk the size if we are outer limits // This condition is a little faster than the folowing replacement code : // blockSize = Math::Min<Size>(blockSize, static_cast<uint>(capacity) - size); // // We have better performance if the two cases have their own code block // (perhaps because of the constant values) // if (blockSize > static_cast<uint>(capacity)) { // The new blocksize is actually the static_cast<uint>(capacity) itself // The static_cast<uint>(capacity) can not be null // Raw copy YUNI_MEMCPY(const_cast<char*>(data), static_cast<uint>(capacity), block, sizeof(C) * static_cast<uint>(capacity)); // New size size = static_cast<uint>(capacity); if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[static_cast<uint>(capacity)] = C(); return static_cast<uint>(capacity); } // else { // Raw copy YUNI_MEMCPY(const_cast<char*>(data), static_cast<uint>(capacity), block, sizeof(C) * blockSize); // New size size = blockSize; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); return blockSize; } } template<uint ChunkSizeT> typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::appendWithoutChecking(const C* const block, Size blockSize) { // We have to trunk the size if we are outer limits // This condition is a little faster than the folowing replacement code : // blockSize = Math::Min<Size>(blockSize, static_cast<uint>(capacity) - size); // // We have better performance if the two cases have their own code block // (perhaps because of the constant values) // if (blockSize + size > static_cast<uint>(capacity)) { // Computing the new block size to copy blockSize = static_cast<uint>(capacity) - size; // The performance are a bit better if we interupt the process sooner if (!blockSize) return 0; // Raw copy YUNI_MEMCPY(data + size * sizeof(C), static_cast<uint>(capacity), block, sizeof(C) * blockSize); // New size size = static_cast<uint>(capacity); if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[static_cast<uint>(capacity)] = C(); return blockSize; } // else { // Raw copy YUNI_MEMCPY(data + size * sizeof(C), static_cast<uint>(capacity), block, sizeof(C) * blockSize); // New size size += blockSize; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); return blockSize; } } template<uint ChunkSizeT> inline typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::assignWithoutChecking(const C c) { data[0] = c; size = 1; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[1] = C(); return 1; } template<uint ChunkSizeT> typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::appendWithoutChecking(const C c) { if (YUNI_UNLIKELY(size == static_cast<uint>(capacity))) return 0; data[size] = c; ++size; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); return 1; } template<uint ChunkSizeT> void Data<ChunkSizeT,false>::put(const C rhs) { // Making sure that we have enough space if (size != static_cast<uint>(capacity)) { // Raw copy data[size] = rhs; // New size ++size; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } } template<uint ChunkSizeT> void Data<ChunkSizeT,false>::swap(Data<ChunkSizeT,false>& rhs) { Data<ChunkSizeT,false> tmp(*this); assignWithoutChecking(rhs.data, rhs.size); rhs.assignWithoutChecking(tmp.data, tmp.size); } } // namespace CStringImpl } // namespace Private } // namespace Yuni <commit_msg>String::forgetContent: do not write a zero when forgetting a string...<commit_after>/* ** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org). ** ** This Source Code Form is subject to the terms of the Mozilla Public License ** v.2.0. If a copy of the MPL was not distributed with this file, You can ** obtain one at http://mozilla.org/MPL/2.0/. ** ** github: https://github.com/libyuni/libyuni/ ** gitlab: https://gitlab.com/libyuni/libyuni/ (mirror) */ #pragma once #include "traits.h" namespace Yuni { namespace Private { namespace CStringImpl { template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>::Data() : size(), capacity(), data(NULL) {} template<uint ChunkSizeT, bool ExpandableT> Data<ChunkSizeT,ExpandableT>::Data(const Data<ChunkSizeT,ExpandableT>& rhs) : size(rhs.size), capacity(rhs.size), data(NULL) { if (size) { if (chunkSize != 0) { capacity += static_cast<uint>(zeroTerminated); data = reinterpret_cast<C*>(::malloc(sizeof(C) * static_cast<uint>(capacity))); YUNI_MEMCPY(const_cast<void*>(static_cast<const void*>(data)), static_cast<uint>(capacity), rhs.data, sizeof(C) * size); if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } else { // this string is a string adapter data = rhs.data; } } } # ifdef YUNI_HAS_CPP_MOVE template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>::Data(Data&& rhs) : size(rhs.size), capacity(rhs.size), data(rhs.data) { rhs.size = 0; rhs.capacity = 0; rhs.data = nullptr; } # endif template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>::~Data() { // Release the internal buffer if allocated // The string is a string adapter only if the chunk size if null // When the string is an adapter, the variable is const if (chunkSize != 0) ::free(const_cast<void*>(static_cast<const void*>(data))); } # ifdef YUNI_HAS_CPP_MOVE template<uint ChunkSizeT, bool ExpandableT> inline Data<ChunkSizeT,ExpandableT>& Data<ChunkSizeT,ExpandableT>::operator = (Data&& rhs) { // Release the internal buffer if allocated // The string is a string adapter only if the chunk size if null // When the string is an adapter, the variable is const if (chunkSize != 0) ::free(const_cast<void*>(static_cast<const void*>(data))); size = rhs.size; capacity = rhs.capacity; data = rhs.data; rhs.size = 0; rhs.capacity = 0; rhs.data = nullptr; return *this; } # endif template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::adapt(const char* const cstring) { data = const_cast<char*>(cstring); capacity = size = (data ? static_cast<Size>(::strlen(data)) : 0); } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::adapt(const char* const cstring, Size length) { data = const_cast<char*>(cstring); capacity = size = length; } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::clear() { if (static_cast<uint>(zeroTerminated)) { if (size) { size = 0; *(const_cast<char*>(data)) = C(); } } else size = 0; } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::forgetContent() { capacity = 0; size = 0; data = nullptr; // forget me ! } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::shrink() { if (data) { if (size) { capacity = size + static_cast<uint>(zeroTerminated); data = reinterpret_cast<char*>(::realloc(const_cast<char*>(data), static_cast<uint>(capacity))); } else { capacity = 0; ::free(const_cast<void*>(static_cast<const void*>(data))); data = nullptr; } } } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::insert(Size offset, const C* const buffer, const Size len) { // Reserving enough space to insert the buffer reserve(len + size + static_cast<uint>(zeroTerminated)); // Move the existing block of data (void)::memmove(const_cast<char*>(data) + sizeof(C) * (offset + len), const_cast<char*>(data) + sizeof(C) * (offset), sizeof(C) * (size - offset)); // Copying the given buffer YUNI_MEMCPY(const_cast<char*>(data) + sizeof(C) * (offset), static_cast<uint>(capacity), buffer, sizeof(C) * len); // Updating the size size += len; // zero-terminated if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } template<uint ChunkSizeT, bool ExpandableT> inline void Data<ChunkSizeT,ExpandableT>::put(const C rhs) { // Making sure that we have enough space reserve(size + 1 + static_cast<uint>(zeroTerminated)); // Raw copy (const_cast<char*>(data))[size] = rhs; // New size ++size; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } template<uint ChunkSizeT, bool ExpandableT> void Data<ChunkSizeT,ExpandableT>::reserve(Size mincapacity) { if (adapter) return; mincapacity += static_cast<uint>(zeroTerminated); if (static_cast<uint>(capacity) < mincapacity) { // This loop may be a little faster than the following replacement code : // static_cast<uint>(capacity) = minstatic_cast<uint>(capacity) + minstatic_cast<uint>(capacity) % chunkSize; // Especially when chunkSize is not a power of 2 Size newcapacity = static_cast<uint>(capacity); do { // Increase the static_cast<uint>(capacity) until we have enough space newcapacity += chunkSize; } while (newcapacity < mincapacity); // Realloc the internal buffer C* newdata = reinterpret_cast<C*>(::realloc(const_cast<char*>(data), (sizeof(C) * newcapacity))); // The returned value can be NULL if (!newdata) throw "Yuni::CString: Impossible to realloc"; { data = newdata; capacity = newcapacity; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } } } template<uint ChunkSizeT> typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::assignWithoutChecking(const C* const block, Size blockSize) { // We have to trunk the size if we are outer limits // This condition is a little faster than the folowing replacement code : // blockSize = Math::Min<Size>(blockSize, static_cast<uint>(capacity) - size); // // We have better performance if the two cases have their own code block // (perhaps because of the constant values) // if (blockSize > static_cast<uint>(capacity)) { // The new blocksize is actually the static_cast<uint>(capacity) itself // The static_cast<uint>(capacity) can not be null // Raw copy YUNI_MEMCPY(const_cast<char*>(data), static_cast<uint>(capacity), block, sizeof(C) * static_cast<uint>(capacity)); // New size size = static_cast<uint>(capacity); if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[static_cast<uint>(capacity)] = C(); return static_cast<uint>(capacity); } // else { // Raw copy YUNI_MEMCPY(const_cast<char*>(data), static_cast<uint>(capacity), block, sizeof(C) * blockSize); // New size size = blockSize; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); return blockSize; } } template<uint ChunkSizeT> typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::appendWithoutChecking(const C* const block, Size blockSize) { // We have to trunk the size if we are outer limits // This condition is a little faster than the folowing replacement code : // blockSize = Math::Min<Size>(blockSize, static_cast<uint>(capacity) - size); // // We have better performance if the two cases have their own code block // (perhaps because of the constant values) // if (blockSize + size > static_cast<uint>(capacity)) { // Computing the new block size to copy blockSize = static_cast<uint>(capacity) - size; // The performance are a bit better if we interupt the process sooner if (!blockSize) return 0; // Raw copy YUNI_MEMCPY(data + size * sizeof(C), static_cast<uint>(capacity), block, sizeof(C) * blockSize); // New size size = static_cast<uint>(capacity); if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[static_cast<uint>(capacity)] = C(); return blockSize; } // else { // Raw copy YUNI_MEMCPY(data + size * sizeof(C), static_cast<uint>(capacity), block, sizeof(C) * blockSize); // New size size += blockSize; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); return blockSize; } } template<uint ChunkSizeT> inline typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::assignWithoutChecking(const C c) { data[0] = c; size = 1; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[1] = C(); return 1; } template<uint ChunkSizeT> typename Data<ChunkSizeT,false>::Size Data<ChunkSizeT,false>::appendWithoutChecking(const C c) { if (YUNI_UNLIKELY(size == static_cast<uint>(capacity))) return 0; data[size] = c; ++size; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); return 1; } template<uint ChunkSizeT> void Data<ChunkSizeT,false>::put(const C rhs) { // Making sure that we have enough space if (size != static_cast<uint>(capacity)) { // Raw copy data[size] = rhs; // New size ++size; if (static_cast<uint>(zeroTerminated)) (const_cast<char*>(data))[size] = C(); } } template<uint ChunkSizeT> void Data<ChunkSizeT,false>::swap(Data<ChunkSizeT,false>& rhs) { Data<ChunkSizeT,false> tmp(*this); assignWithoutChecking(rhs.data, rhs.size); rhs.assignWithoutChecking(tmp.data, tmp.size); } } // namespace CStringImpl } // namespace Private } // namespace Yuni <|endoftext|>
<commit_before>// // Copyright (c) 2020 INRIA // #ifndef __eigenpy_ufunc_hpp__ #define __eigenpy_ufunc_hpp__ #include "eigenpy/user-type.hpp" namespace eigenpy { namespace internal { #define EIGENPY_REGISTER_BINARY_OPERATOR(name,op) \ template<typename T1, typename T2, typename R> \ void binary_op_##name(char** args, npy_intp * dimensions, npy_intp * steps, void * /*data*/) \ { \ npy_intp is0 = steps[0], is1 = steps[1], \ os = steps[2], n = *dimensions; \ char * i0 = args[0], *i1 = args[1], *o = args[2]; \ int k; \ for (k = 0; k < n; k++) \ { \ T1 & x = *static_cast<T1*>(static_cast<void*>(i0)); \ T2 & y = *static_cast<T2*>(static_cast<void*>(i1)); \ R & res = *static_cast<R*>(static_cast<void*>(o)); \ res = x op y; \ i0 += is0; i1 += is1; o += os; \ } \ } \ \ template<typename T> \ void binary_op_##name(char** args, npy_intp * dimensions, npy_intp * steps, void * data) \ { \ binary_op_##name<T,T,T>(args,dimensions,steps,data); \ } EIGENPY_REGISTER_BINARY_OPERATOR(add,+) EIGENPY_REGISTER_BINARY_OPERATOR(subtract,-) EIGENPY_REGISTER_BINARY_OPERATOR(multiply,*) EIGENPY_REGISTER_BINARY_OPERATOR(divide,/) EIGENPY_REGISTER_BINARY_OPERATOR(equal,==) EIGENPY_REGISTER_BINARY_OPERATOR(not_equal,!=) EIGENPY_REGISTER_BINARY_OPERATOR(less,<) EIGENPY_REGISTER_BINARY_OPERATOR(greater,>) EIGENPY_REGISTER_BINARY_OPERATOR(less_equal,<=) EIGENPY_REGISTER_BINARY_OPERATOR(greater_equal,>=) } // namespace internal #define EIGENPY_REGISTER_BINARY_UFUNC(name,code,T1,T2,R) { \ PyUFuncObject* ufunc = \ (PyUFuncObject*)PyObject_GetAttrString(numpy, #name); \ int _types[3] = { Register::getTypeCode<T1>(), Register::getTypeCode<T2>(), Register::getTypeCode<R>()}; \ if (!ufunc) { \ /*goto fail; \*/ \ } \ if (sizeof(_types)/sizeof(int)!=ufunc->nargs) { \ PyErr_Format(PyExc_AssertionError, \ "ufunc %s takes %d arguments, our loop takes %lu", \ #name, ufunc->nargs, (unsigned long) \ (sizeof(_types)/sizeof(int))); \ Py_DECREF(ufunc); \ } \ if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc, code, \ internal::binary_op_##name<T1,T2,R>, _types, 0) < 0) { \ /*Py_DECREF(ufunc);*/ \ /*goto fail; \*/ \ } \ Py_DECREF(ufunc); \ } template<typename Scalar> void registerCommonUfunc() { const int code = Register::getTypeCode<Scalar>(); PyObject* numpy_str; #if PY_MAJOR_VERSION >= 3 numpy_str = PyUnicode_FromString("numpy"); #else numpy_str = PyString_FromString("numpy"); #endif PyObject* numpy; numpy = PyImport_Import(numpy_str); Py_DECREF(numpy_str); // load numpy import_ufunc(); EIGENPY_REGISTER_BINARY_UFUNC(add,code,Scalar,Scalar,Scalar); EIGENPY_REGISTER_BINARY_UFUNC(subtract,code,Scalar,Scalar,Scalar); EIGENPY_REGISTER_BINARY_UFUNC(multiply,code,Scalar,Scalar,Scalar); EIGENPY_REGISTER_BINARY_UFUNC(divide,code,Scalar,Scalar,Scalar); // Comparison operators EIGENPY_REGISTER_BINARY_UFUNC(equal,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(not_equal,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(greater,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(less,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(greater_equal,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(less_equal,code,Scalar,Scalar,bool); Py_DECREF(numpy); } } // namespace eigenpy #endif // __eigenpy_ufunc_hpp__ <commit_msg>core/ufunc: add registration of Unary operators<commit_after>// // Copyright (c) 2020 INRIA // #ifndef __eigenpy_ufunc_hpp__ #define __eigenpy_ufunc_hpp__ #include "eigenpy/user-type.hpp" namespace eigenpy { namespace internal { #define EIGENPY_REGISTER_BINARY_OPERATOR(name,op) \ template<typename T1, typename T2, typename R> \ void binary_op_##name(char** args, npy_intp * dimensions, npy_intp * steps, void * /*data*/) \ { \ npy_intp is0 = steps[0], is1 = steps[1], \ os = steps[2], n = *dimensions; \ char * i0 = args[0], *i1 = args[1], *o = args[2]; \ int k; \ for (k = 0; k < n; k++) \ { \ T1 & x = *static_cast<T1*>(static_cast<void*>(i0)); \ T2 & y = *static_cast<T2*>(static_cast<void*>(i1)); \ R & res = *static_cast<R*>(static_cast<void*>(o)); \ res = x op y; \ i0 += is0; i1 += is1; o += os; \ } \ } \ \ template<typename T> \ void binary_op_##name(char** args, npy_intp * dimensions, npy_intp * steps, void * data) \ { \ binary_op_##name<T,T,T>(args,dimensions,steps,data); \ } EIGENPY_REGISTER_BINARY_OPERATOR(add,+) EIGENPY_REGISTER_BINARY_OPERATOR(subtract,-) EIGENPY_REGISTER_BINARY_OPERATOR(multiply,*) EIGENPY_REGISTER_BINARY_OPERATOR(divide,/) EIGENPY_REGISTER_BINARY_OPERATOR(equal,==) EIGENPY_REGISTER_BINARY_OPERATOR(not_equal,!=) EIGENPY_REGISTER_BINARY_OPERATOR(less,<) EIGENPY_REGISTER_BINARY_OPERATOR(greater,>) EIGENPY_REGISTER_BINARY_OPERATOR(less_equal,<=) EIGENPY_REGISTER_BINARY_OPERATOR(greater_equal,>=) #define EIGENPY_REGISTER_UNARY_OPERATOR(name,op) \ template<typename T, typename R> \ void unary_op_##name(char** args, npy_intp * dimensions, npy_intp * steps, void * /*data*/) \ { \ npy_intp is = steps[0], \ os = steps[1], n = *dimensions; \ char * i = args[0], *o = args[1]; \ int k; \ for (k = 0; k < n; k++) \ { \ T & x = *static_cast<T*>(static_cast<void*>(i)); \ R & res = *static_cast<R*>(static_cast<void*>(o)); \ res = op x; \ i += is; o += os; \ } \ } \ \ template<typename T> \ void unary_op_##name(char** args, npy_intp * dimensions, npy_intp * steps, void * data) \ { \ unary_op_##name<T,T>(args,dimensions,steps,data); \ } EIGENPY_REGISTER_UNARY_OPERATOR(negative,-) } // namespace internal #define EIGENPY_REGISTER_BINARY_UFUNC(name,code,T1,T2,R) { \ PyUFuncObject* ufunc = \ (PyUFuncObject*)PyObject_GetAttrString(numpy, #name); \ int _types[3] = { Register::getTypeCode<T1>(), Register::getTypeCode<T2>(), Register::getTypeCode<R>()}; \ if (!ufunc) { \ /*goto fail; \*/ \ } \ if (sizeof(_types)/sizeof(int)!=ufunc->nargs) { \ PyErr_Format(PyExc_AssertionError, \ "ufunc %s takes %d arguments, our loop takes %lu", \ #name, ufunc->nargs, (unsigned long) \ (sizeof(_types)/sizeof(int))); \ Py_DECREF(ufunc); \ } \ if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc, code, \ internal::binary_op_##name<T1,T2,R>, _types, 0) < 0) { \ /*Py_DECREF(ufunc);*/ \ /*goto fail; \*/ \ } \ Py_DECREF(ufunc); \ } #define EIGENPY_REGISTER_UNARY_UFUNC(name,code,T,R) { \ PyUFuncObject* ufunc = \ (PyUFuncObject*)PyObject_GetAttrString(numpy, #name); \ int _types[2] = { Register::getTypeCode<T>(), Register::getTypeCode<R>()}; \ if (!ufunc) { \ /*goto fail; \*/ \ } \ if (sizeof(_types)/sizeof(int)!=ufunc->nargs) { \ PyErr_Format(PyExc_AssertionError, \ "ufunc %s takes %d arguments, our loop takes %lu", \ #name, ufunc->nargs, (unsigned long) \ (sizeof(_types)/sizeof(int))); \ Py_DECREF(ufunc); \ } \ if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc, code, \ internal::unary_op_##name<T,R>, _types, 0) < 0) { \ /*Py_DECREF(ufunc);*/ \ /*goto fail; \*/ \ } \ Py_DECREF(ufunc); \ } template<typename Scalar> void registerCommonUfunc() { const int code = Register::getTypeCode<Scalar>(); PyObject* numpy_str; #if PY_MAJOR_VERSION >= 3 numpy_str = PyUnicode_FromString("numpy"); #else numpy_str = PyString_FromString("numpy"); #endif PyObject* numpy; numpy = PyImport_Import(numpy_str); Py_DECREF(numpy_str); import_ufunc(); // Binary operators EIGENPY_REGISTER_BINARY_UFUNC(add,code,Scalar,Scalar,Scalar); EIGENPY_REGISTER_BINARY_UFUNC(subtract,code,Scalar,Scalar,Scalar); EIGENPY_REGISTER_BINARY_UFUNC(multiply,code,Scalar,Scalar,Scalar); EIGENPY_REGISTER_BINARY_UFUNC(divide,code,Scalar,Scalar,Scalar); // Comparison operators EIGENPY_REGISTER_BINARY_UFUNC(equal,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(not_equal,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(greater,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(less,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(greater_equal,code,Scalar,Scalar,bool); EIGENPY_REGISTER_BINARY_UFUNC(less_equal,code,Scalar,Scalar,bool); // Unary operators EIGENPY_REGISTER_UNARY_UFUNC(negative,code,Scalar,Scalar); Py_DECREF(numpy); } } // namespace eigenpy #endif // __eigenpy_ufunc_hpp__ <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_IO_HPP_INCLUDED #define TORRENT_IO_HPP_INCLUDED #include <boost/cstdint.hpp> #include <string> #include <algorithm> // for copy #include <cstring> // for memcpy namespace libtorrent { namespace detail { template <class T> struct type {}; // reads an integer from a byte stream // in big endian byte order and converts // it to native endianess template <class T, class InIt> inline T read_impl(InIt& start, type<T>) { T ret = 0; for (int i = 0; i < (int)sizeof(T); ++i) { ret <<= 8; ret |= static_cast<unsigned char>(*start); ++start; } return ret; } template <class T, class OutIt> inline void write_impl(T val, OutIt& start) { for (int i = (int)sizeof(T)-1; i >= 0; --i) { *start = static_cast<unsigned char>((val >> (i * 8)) & 0xff); ++start; } } // -- adaptors template <class InIt> boost::int64_t read_int64(InIt& start) { return read_impl(start, type<boost::int64_t>()); } template <class InIt> boost::uint64_t read_uint64(InIt& start) { return read_impl(start, type<boost::uint64_t>()); } template <class InIt> boost::uint32_t read_uint32(InIt& start) { return read_impl(start, type<boost::uint32_t>()); } template <class InIt> boost::int32_t read_int32(InIt& start) { return read_impl(start, type<boost::int32_t>()); } template <class InIt> boost::int16_t read_int16(InIt& start) { return read_impl(start, type<boost::int16_t>()); } template <class InIt> boost::uint16_t read_uint16(InIt& start) { return read_impl(start, type<boost::uint16_t>()); } template <class InIt> boost::int8_t read_int8(InIt& start) { return read_impl(start, type<boost::int8_t>()); } template <class InIt> boost::uint8_t read_uint8(InIt& start) { return read_impl(start, type<boost::uint8_t>()); } template <class OutIt> void write_uint64(boost::uint64_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int64(boost::int64_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_uint32(boost::uint32_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int32(boost::int32_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_uint16(boost::uint16_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int16(boost::int16_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_uint8(boost::uint8_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int8(boost::int8_t val, OutIt& start) { write_impl(val, start); } inline void write_string(std::string const& str, char*& start) { std::memcpy((void*)start, str.c_str(), str.size()); start += str.size(); } template <class OutIt> void write_string(std::string const& str, OutIt& start) { std::copy(str.begin(), str.end(), start); } } } #endif // TORRENT_IO_HPP_INCLUDED <commit_msg>fixed clang build warning<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_IO_HPP_INCLUDED #define TORRENT_IO_HPP_INCLUDED #include <boost/cstdint.hpp> #include <string> #include <algorithm> // for copy #include <cstring> // for memcpy namespace libtorrent { namespace detail { template <class T> struct type {}; // reads an integer from a byte stream // in big endian byte order and converts // it to native endianess template <class T, class InIt> inline T read_impl(InIt& start, type<T>) { T ret = 0; for (int i = 0; i < (int)sizeof(T); ++i) { ret <<= 8; ret |= static_cast<boost::uint8_t>(*start); ++start; } return ret; } template <class InIt> boost::uint8_t read_impl(InIt& start, type<boost::uint8_t>) { return static_cast<boost::uint8_t>(*start++); } template <class InIt> boost::int8_t read_impl(InIt& start, type<boost::int8_t>) { return static_cast<boost::int8_t>(*start++); } template <class T, class OutIt> inline void write_impl(T val, OutIt& start) { for (int i = (int)sizeof(T)-1; i >= 0; --i) { *start = static_cast<unsigned char>((val >> (i * 8)) & 0xff); ++start; } } // -- adaptors template <class InIt> boost::int64_t read_int64(InIt& start) { return read_impl(start, type<boost::int64_t>()); } template <class InIt> boost::uint64_t read_uint64(InIt& start) { return read_impl(start, type<boost::uint64_t>()); } template <class InIt> boost::uint32_t read_uint32(InIt& start) { return read_impl(start, type<boost::uint32_t>()); } template <class InIt> boost::int32_t read_int32(InIt& start) { return read_impl(start, type<boost::int32_t>()); } template <class InIt> boost::int16_t read_int16(InIt& start) { return read_impl(start, type<boost::int16_t>()); } template <class InIt> boost::uint16_t read_uint16(InIt& start) { return read_impl(start, type<boost::uint16_t>()); } template <class InIt> boost::int8_t read_int8(InIt& start) { return read_impl(start, type<boost::int8_t>()); } template <class InIt> boost::uint8_t read_uint8(InIt& start) { return read_impl(start, type<boost::uint8_t>()); } template <class OutIt> void write_uint64(boost::uint64_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int64(boost::int64_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_uint32(boost::uint32_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int32(boost::int32_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_uint16(boost::uint16_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int16(boost::int16_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_uint8(boost::uint8_t val, OutIt& start) { write_impl(val, start); } template <class OutIt> void write_int8(boost::int8_t val, OutIt& start) { write_impl(val, start); } inline void write_string(std::string const& str, char*& start) { std::memcpy((void*)start, str.c_str(), str.size()); start += str.size(); } template <class OutIt> void write_string(std::string const& str, OutIt& start) { std::copy(str.begin(), str.end(), start); } } } #endif // TORRENT_IO_HPP_INCLUDED <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // library configuration #include "libmesh/libmesh_config.h" // C++ includes #include <algorithm> // for std::min #include <map> // for std::multimap #include <sstream> // for std::ostringstream // Local includes #include "libmesh/boundary_info.h" #include "libmesh/elem.h" #include "libmesh/mesh_base.h" #include "libmesh/parallel.h" #include "libmesh/partitioner.h" #include "libmesh/point_locator_base.h" #include "libmesh/threads.h" namespace libMesh { // ------------------------------------------------------------ // MeshBase class member functions MeshBase::MeshBase (const Parallel::Communicator &comm_in, unsigned char d) : ParallelObject (comm_in), boundary_info (new BoundaryInfo(*this)), _n_parts (1), _dim (d), _is_prepared (false), _point_locator (NULL), _partitioner (NULL), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(DofObject::invalid_unique_id), #endif _skip_partitioning(false), _skip_renumber_nodes_and_elements(false) { libmesh_assert_less_equal (LIBMESH_DIM, 3); libmesh_assert_greater_equal (LIBMESH_DIM, _dim); libmesh_assert (libMesh::initialized()); } #ifndef LIBMESH_DISABLE_COMMWORLD MeshBase::MeshBase (unsigned char d) : ParallelObject (CommWorld), boundary_info (new BoundaryInfo(*this)), _n_parts (1), _dim (d), _is_prepared (false), _point_locator (NULL), _partitioner (NULL), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(DofObject::invalid_unique_id), #endif _skip_partitioning(false), _skip_renumber_nodes_and_elements(false) { libmesh_assert_less_equal (LIBMESH_DIM, 3); libmesh_assert_greater_equal (LIBMESH_DIM, _dim); libmesh_assert (libMesh::initialized()); } #endif // !LIBMESH_DISABLE_COMMWORLD MeshBase::MeshBase (const MeshBase& other_mesh) : ParallelObject (other_mesh), boundary_info (new BoundaryInfo(*this)), _n_parts (other_mesh._n_parts), _dim (other_mesh._dim), _is_prepared (other_mesh._is_prepared), _point_locator (NULL), _partitioner (NULL), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(other_mesh._next_unique_id), #endif _skip_partitioning(other_mesh._skip_partitioning), _skip_renumber_nodes_and_elements(false) { if(other_mesh._partitioner.get()) { _partitioner = other_mesh._partitioner->clone(); } } MeshBase::~MeshBase() { this->clear(); libmesh_exceptionless_assert (!libMesh::closed()); } void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors) { parallel_object_only(); // A distributed mesh may have processors with no elements (or // processors with no elements of higher dimension, if we ever // support mixed-dimension meshes), but we want consistent // mesh_dimension anyways. libmesh_assert(this->comm().verify(this->is_serial())); if (!this->is_serial()) { unsigned char dim = this->mesh_dimension(); this->comm().max(dim); this->set_mesh_dimension(dim); } // Renumber the nodes and elements so that they in contiguous // blocks. By default, _skip_renumber_nodes_and_elements is false. // // We may currently change that by passing // skip_renumber_nodes_and_elements==true to this function, but we // should use the allow_renumbering() accessor instead. // // Instances where you if prepare_for_use() should not renumber the nodes // and elements include reading in e.g. an xda/r or gmv file. In // this case, the ordering of the nodes may depend on an accompanying // solution, and the node ordering cannot be changed. if (skip_renumber_nodes_and_elements) { libmesh_deprecated(); this->allow_renumbering(false); } // Mesh modification operations might not leave us with consistent // id counts, but our partitioner might need that consistency. if(!_skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); else this->update_parallel_id_counts(); // Let all the elements find their neighbors if(!skip_find_neighbors) this->find_neighbors(); // Partition the mesh. this->partition(); // If we're using ParallelMesh, we'll want it parallelized. this->delete_remote_elements(); #ifdef LIBMESH_ENABLE_UNIQUE_ID // Assign DOF object unique ids this->assign_unique_ids(); #endif if(!_skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); // Search the mesh for all the dimensions of the elements // and cache them. this->cache_elem_dims(); // Reset our PointLocator. This needs to happen any time the elements // in the underlying elements in the mesh have changed, so we do it here. this->clear_point_locator(); // The mesh is now prepared for use. _is_prepared = true; } void MeshBase::clear () { // Reset the number of partitions _n_parts = 1; // Reset the _is_prepared flag _is_prepared = false; // Clear boundary information this->get_boundary_info().clear(); // Clear element dimensions _elem_dims.clear(); // Clear our point locator. this->clear_point_locator(); } void MeshBase::subdomain_ids (std::set<subdomain_id_type> &ids) const { // This requires an inspection on every processor parallel_object_only(); ids.clear(); const_element_iterator el = this->active_local_elements_begin(); const_element_iterator end = this->active_local_elements_end(); for (; el!=end; ++el) ids.insert((*el)->subdomain_id()); // Some subdomains may only live on other processors this->comm().set_union(ids); } subdomain_id_type MeshBase::n_subdomains() const { // This requires an inspection on every processor parallel_object_only(); std::set<subdomain_id_type> ids; this->subdomain_ids (ids); return cast_int<subdomain_id_type>(ids.size()); } dof_id_type MeshBase::n_nodes_on_proc (const processor_id_type proc_id) const { // We're either counting a processor's nodes or unpartitioned // nodes libmesh_assert (proc_id < this->n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<dof_id_type>(std::distance (this->pid_nodes_begin(proc_id), this->pid_nodes_end (proc_id))); } dof_id_type MeshBase::n_elem_on_proc (const processor_id_type proc_id) const { // We're either counting a processor's elements or unpartitioned // elements libmesh_assert (proc_id < this->n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<dof_id_type>(std::distance (this->pid_elements_begin(proc_id), this->pid_elements_end (proc_id))); } dof_id_type MeshBase::n_active_elem_on_proc (const processor_id_type proc_id) const { libmesh_assert_less (proc_id, this->n_processors()); return static_cast<dof_id_type>(std::distance (this->active_pid_elements_begin(proc_id), this->active_pid_elements_end (proc_id))); } dof_id_type MeshBase::n_sub_elem () const { dof_id_type ne=0; const_element_iterator el = this->elements_begin(); const const_element_iterator end = this->elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } dof_id_type MeshBase::n_active_sub_elem () const { dof_id_type ne=0; const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } std::string MeshBase::get_info() const { std::ostringstream oss; oss << " Mesh Information:" << '\n' << " mesh_dimension()=" << this->mesh_dimension() << '\n' << " spatial_dimension()=" << this->spatial_dimension() << '\n' << " n_nodes()=" << this->n_nodes() << '\n' << " n_local_nodes()=" << this->n_local_nodes() << '\n' << " n_elem()=" << this->n_elem() << '\n' << " n_local_elem()=" << this->n_local_elem() << '\n' #ifdef LIBMESH_ENABLE_AMR << " n_active_elem()=" << this->n_active_elem() << '\n' #endif << " n_subdomains()=" << static_cast<std::size_t>(this->n_subdomains()) << '\n' << " n_partitions()=" << static_cast<std::size_t>(this->n_partitions()) << '\n' << " n_processors()=" << static_cast<std::size_t>(this->n_processors()) << '\n' << " n_threads()=" << static_cast<std::size_t>(libMesh::n_threads()) << '\n' << " processor_id()=" << static_cast<std::size_t>(this->processor_id()) << '\n'; return oss.str(); } void MeshBase::print_info(std::ostream& os) const { os << this->get_info() << std::endl; } std::ostream& operator << (std::ostream& os, const MeshBase& m) { m.print_info(os); return os; } void MeshBase::partition (const unsigned int n_parts) { // NULL partitioner means don't partition // Non-serial meshes aren't ready for partitioning yet. if(!skip_partitioning() && partitioner().get() && this->is_serial()) { partitioner()->partition (*this, n_parts); } else { // Make sure locally cached partition count this->recalculate_n_partitions(); // Make sure any other locally cached data is correct this->update_post_partitioning(); } } unsigned int MeshBase::recalculate_n_partitions() { // This requires an inspection on every processor parallel_object_only(); const_element_iterator el = this->active_local_elements_begin(); const_element_iterator end = this->active_local_elements_end(); unsigned int max_proc_id=0; for (; el!=end; ++el) max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id())); // The number of partitions is one more than the max processor ID. _n_parts = max_proc_id+1; this->comm().max(_n_parts); return _n_parts; } const PointLocatorBase& MeshBase::point_locator () const { libmesh_deprecated(); if (_point_locator.get() == NULL) { // PointLocator construction may not be safe within threads libmesh_assert(!Threads::in_threads); _point_locator.reset (PointLocatorBase::build(TREE, *this).release()); } return *_point_locator; } AutoPtr<PointLocatorBase> MeshBase::sub_point_locator () const { if (_point_locator.get() == NULL) { // PointLocator construction may not be safe within threads libmesh_assert(!Threads::in_threads); _point_locator.reset (PointLocatorBase::build(TREE, *this).release()); } return PointLocatorBase::build(TREE, *this, _point_locator.get()); } void MeshBase::clear_point_locator () { _point_locator.reset(NULL); } std::string& MeshBase::subdomain_name(subdomain_id_type id) { return _block_id_to_name[id]; } const std::string& MeshBase::subdomain_name(subdomain_id_type id) const { // An empty string to return when no matching subdomain name is found static const std::string empty; std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.find(id); if (iter == _block_id_to_name.end()) return empty; else return iter->second; } subdomain_id_type MeshBase::get_id_by_name(const std::string& name) const { // This function is searching the *values* of the map (linear search) // We might want to make this more efficient... std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.begin(), end_iter = _block_id_to_name.end(); for ( ; iter != end_iter; ++iter) { if (iter->second == name) return iter->first; } libmesh_error_msg("Block '" << name << "' does not exist in mesh"); } void MeshBase::cache_elem_dims() { // This requires an inspection on every processor parallel_object_only(); const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) _elem_dims.insert((*el)->dim()); // Some different dimension elements may only live on other processors this->comm().set_union(_elem_dims); } } // namespace libMesh <commit_msg>Use local iterators for cache_elem_dims()<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // library configuration #include "libmesh/libmesh_config.h" // C++ includes #include <algorithm> // for std::min #include <map> // for std::multimap #include <sstream> // for std::ostringstream // Local includes #include "libmesh/boundary_info.h" #include "libmesh/elem.h" #include "libmesh/mesh_base.h" #include "libmesh/parallel.h" #include "libmesh/partitioner.h" #include "libmesh/point_locator_base.h" #include "libmesh/threads.h" namespace libMesh { // ------------------------------------------------------------ // MeshBase class member functions MeshBase::MeshBase (const Parallel::Communicator &comm_in, unsigned char d) : ParallelObject (comm_in), boundary_info (new BoundaryInfo(*this)), _n_parts (1), _dim (d), _is_prepared (false), _point_locator (NULL), _partitioner (NULL), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(DofObject::invalid_unique_id), #endif _skip_partitioning(false), _skip_renumber_nodes_and_elements(false) { libmesh_assert_less_equal (LIBMESH_DIM, 3); libmesh_assert_greater_equal (LIBMESH_DIM, _dim); libmesh_assert (libMesh::initialized()); } #ifndef LIBMESH_DISABLE_COMMWORLD MeshBase::MeshBase (unsigned char d) : ParallelObject (CommWorld), boundary_info (new BoundaryInfo(*this)), _n_parts (1), _dim (d), _is_prepared (false), _point_locator (NULL), _partitioner (NULL), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(DofObject::invalid_unique_id), #endif _skip_partitioning(false), _skip_renumber_nodes_and_elements(false) { libmesh_assert_less_equal (LIBMESH_DIM, 3); libmesh_assert_greater_equal (LIBMESH_DIM, _dim); libmesh_assert (libMesh::initialized()); } #endif // !LIBMESH_DISABLE_COMMWORLD MeshBase::MeshBase (const MeshBase& other_mesh) : ParallelObject (other_mesh), boundary_info (new BoundaryInfo(*this)), _n_parts (other_mesh._n_parts), _dim (other_mesh._dim), _is_prepared (other_mesh._is_prepared), _point_locator (NULL), _partitioner (NULL), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(other_mesh._next_unique_id), #endif _skip_partitioning(other_mesh._skip_partitioning), _skip_renumber_nodes_and_elements(false) { if(other_mesh._partitioner.get()) { _partitioner = other_mesh._partitioner->clone(); } } MeshBase::~MeshBase() { this->clear(); libmesh_exceptionless_assert (!libMesh::closed()); } void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors) { parallel_object_only(); // A distributed mesh may have processors with no elements (or // processors with no elements of higher dimension, if we ever // support mixed-dimension meshes), but we want consistent // mesh_dimension anyways. libmesh_assert(this->comm().verify(this->is_serial())); if (!this->is_serial()) { unsigned char dim = this->mesh_dimension(); this->comm().max(dim); this->set_mesh_dimension(dim); } // Renumber the nodes and elements so that they in contiguous // blocks. By default, _skip_renumber_nodes_and_elements is false. // // We may currently change that by passing // skip_renumber_nodes_and_elements==true to this function, but we // should use the allow_renumbering() accessor instead. // // Instances where you if prepare_for_use() should not renumber the nodes // and elements include reading in e.g. an xda/r or gmv file. In // this case, the ordering of the nodes may depend on an accompanying // solution, and the node ordering cannot be changed. if (skip_renumber_nodes_and_elements) { libmesh_deprecated(); this->allow_renumbering(false); } // Mesh modification operations might not leave us with consistent // id counts, but our partitioner might need that consistency. if(!_skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); else this->update_parallel_id_counts(); // Let all the elements find their neighbors if(!skip_find_neighbors) this->find_neighbors(); // Partition the mesh. this->partition(); // If we're using ParallelMesh, we'll want it parallelized. this->delete_remote_elements(); #ifdef LIBMESH_ENABLE_UNIQUE_ID // Assign DOF object unique ids this->assign_unique_ids(); #endif if(!_skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); // Search the mesh for all the dimensions of the elements // and cache them. this->cache_elem_dims(); // Reset our PointLocator. This needs to happen any time the elements // in the underlying elements in the mesh have changed, so we do it here. this->clear_point_locator(); // The mesh is now prepared for use. _is_prepared = true; } void MeshBase::clear () { // Reset the number of partitions _n_parts = 1; // Reset the _is_prepared flag _is_prepared = false; // Clear boundary information this->get_boundary_info().clear(); // Clear element dimensions _elem_dims.clear(); // Clear our point locator. this->clear_point_locator(); } void MeshBase::subdomain_ids (std::set<subdomain_id_type> &ids) const { // This requires an inspection on every processor parallel_object_only(); ids.clear(); const_element_iterator el = this->active_local_elements_begin(); const_element_iterator end = this->active_local_elements_end(); for (; el!=end; ++el) ids.insert((*el)->subdomain_id()); // Some subdomains may only live on other processors this->comm().set_union(ids); } subdomain_id_type MeshBase::n_subdomains() const { // This requires an inspection on every processor parallel_object_only(); std::set<subdomain_id_type> ids; this->subdomain_ids (ids); return cast_int<subdomain_id_type>(ids.size()); } dof_id_type MeshBase::n_nodes_on_proc (const processor_id_type proc_id) const { // We're either counting a processor's nodes or unpartitioned // nodes libmesh_assert (proc_id < this->n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<dof_id_type>(std::distance (this->pid_nodes_begin(proc_id), this->pid_nodes_end (proc_id))); } dof_id_type MeshBase::n_elem_on_proc (const processor_id_type proc_id) const { // We're either counting a processor's elements or unpartitioned // elements libmesh_assert (proc_id < this->n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<dof_id_type>(std::distance (this->pid_elements_begin(proc_id), this->pid_elements_end (proc_id))); } dof_id_type MeshBase::n_active_elem_on_proc (const processor_id_type proc_id) const { libmesh_assert_less (proc_id, this->n_processors()); return static_cast<dof_id_type>(std::distance (this->active_pid_elements_begin(proc_id), this->active_pid_elements_end (proc_id))); } dof_id_type MeshBase::n_sub_elem () const { dof_id_type ne=0; const_element_iterator el = this->elements_begin(); const const_element_iterator end = this->elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } dof_id_type MeshBase::n_active_sub_elem () const { dof_id_type ne=0; const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } std::string MeshBase::get_info() const { std::ostringstream oss; oss << " Mesh Information:" << '\n' << " mesh_dimension()=" << this->mesh_dimension() << '\n' << " spatial_dimension()=" << this->spatial_dimension() << '\n' << " n_nodes()=" << this->n_nodes() << '\n' << " n_local_nodes()=" << this->n_local_nodes() << '\n' << " n_elem()=" << this->n_elem() << '\n' << " n_local_elem()=" << this->n_local_elem() << '\n' #ifdef LIBMESH_ENABLE_AMR << " n_active_elem()=" << this->n_active_elem() << '\n' #endif << " n_subdomains()=" << static_cast<std::size_t>(this->n_subdomains()) << '\n' << " n_partitions()=" << static_cast<std::size_t>(this->n_partitions()) << '\n' << " n_processors()=" << static_cast<std::size_t>(this->n_processors()) << '\n' << " n_threads()=" << static_cast<std::size_t>(libMesh::n_threads()) << '\n' << " processor_id()=" << static_cast<std::size_t>(this->processor_id()) << '\n'; return oss.str(); } void MeshBase::print_info(std::ostream& os) const { os << this->get_info() << std::endl; } std::ostream& operator << (std::ostream& os, const MeshBase& m) { m.print_info(os); return os; } void MeshBase::partition (const unsigned int n_parts) { // NULL partitioner means don't partition // Non-serial meshes aren't ready for partitioning yet. if(!skip_partitioning() && partitioner().get() && this->is_serial()) { partitioner()->partition (*this, n_parts); } else { // Make sure locally cached partition count this->recalculate_n_partitions(); // Make sure any other locally cached data is correct this->update_post_partitioning(); } } unsigned int MeshBase::recalculate_n_partitions() { // This requires an inspection on every processor parallel_object_only(); const_element_iterator el = this->active_local_elements_begin(); const_element_iterator end = this->active_local_elements_end(); unsigned int max_proc_id=0; for (; el!=end; ++el) max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id())); // The number of partitions is one more than the max processor ID. _n_parts = max_proc_id+1; this->comm().max(_n_parts); return _n_parts; } const PointLocatorBase& MeshBase::point_locator () const { libmesh_deprecated(); if (_point_locator.get() == NULL) { // PointLocator construction may not be safe within threads libmesh_assert(!Threads::in_threads); _point_locator.reset (PointLocatorBase::build(TREE, *this).release()); } return *_point_locator; } AutoPtr<PointLocatorBase> MeshBase::sub_point_locator () const { if (_point_locator.get() == NULL) { // PointLocator construction may not be safe within threads libmesh_assert(!Threads::in_threads); _point_locator.reset (PointLocatorBase::build(TREE, *this).release()); } return PointLocatorBase::build(TREE, *this, _point_locator.get()); } void MeshBase::clear_point_locator () { _point_locator.reset(NULL); } std::string& MeshBase::subdomain_name(subdomain_id_type id) { return _block_id_to_name[id]; } const std::string& MeshBase::subdomain_name(subdomain_id_type id) const { // An empty string to return when no matching subdomain name is found static const std::string empty; std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.find(id); if (iter == _block_id_to_name.end()) return empty; else return iter->second; } subdomain_id_type MeshBase::get_id_by_name(const std::string& name) const { // This function is searching the *values* of the map (linear search) // We might want to make this more efficient... std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.begin(), end_iter = _block_id_to_name.end(); for ( ; iter != end_iter; ++iter) { if (iter->second == name) return iter->first; } libmesh_error_msg("Block '" << name << "' does not exist in mesh"); } void MeshBase::cache_elem_dims() { // This requires an inspection on every processor parallel_object_only(); const_element_iterator el = this->active_local_elements_begin(); const_element_iterator end = this->active_local_elements_end(); for (; el!=end; ++el) _elem_dims.insert((*el)->dim()); // Some different dimension elements may only live on other processors this->comm().set_union(_elem_dims); } } // namespace libMesh <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef GLOBAL_HPP #define GLOBAL_HPP // boost #include <boost/cstdint.hpp> #include <boost/detail/endian.hpp> // stl #include <cstring> namespace mapnik { #define int2net(A) (int16_t) (((boost::uint16_t) ((boost::uint8_t) (A)[1])) | \ (((boost::uint16_t) ((boost::uint8_t) (A)[0])) << 8)) #define int4net(A) (int32_t) (((boost::uint32_t) ((boost::uint8_t) (A)[3])) | \ (((boost::uint32_t) ((boost::uint8_t) (A)[2])) << 8) | \ (((boost::uint32_t) ((boost::uint8_t) (A)[1])) << 16) | \ (((boost::uint32_t) ((boost::uint8_t) (A)[0])) << 24)) typedef boost::uint8_t byte; #define float8net(V,M) do { double def_temp; \ ((byte*) &def_temp)[0]=(M)[7]; \ ((byte*) &def_temp)[1]=(M)[6]; \ ((byte*) &def_temp)[2]=(M)[5]; \ ((byte*) &def_temp)[3]=(M)[4]; \ ((byte*) &def_temp)[4]=(M)[3]; \ ((byte*) &def_temp)[5]=(M)[2]; \ ((byte*) &def_temp)[6]=(M)[1]; \ ((byte*) &def_temp)[7]=(M)[0]; \ (V) = def_temp; } while(0) #define float4net(V,M) do { float def_temp; \ ((byte*) &def_temp)[0]=(M)[3]; \ ((byte*) &def_temp)[1]=(M)[2]; \ ((byte*) &def_temp)[2]=(M)[1]; \ ((byte*) &def_temp)[3]=(M)[0]; \ (V)=def_temp; } while(0) // read int NDR (little endian) inline int& read_int_ndr(const char* data, int & val) { #ifndef BOOST_BIG_ENDIAN memcpy(&val,data,4); #else val = (data[3]&0xff) | ((data[2]&0xff)<<8) | ((data[1]&0xff)<<16) | ((data[0]&0xff)<<24); #endif return val; } // read double NDR (little endian) inline double& read_double_ndr(const char* data, double & val) { #ifndef BOOST_BIG_ENDIAN std::memcpy(&val,&data[0],8); #else boost::int64_t bits = ((boost::int64_t)data[0] & 0xff) | ((boost::int64_t)data[1] & 0xff) << 8 | ((boost::int64_t)data[2] & 0xff) << 16 | ((boost::int64_t)data[3] & 0xff) << 24 | ((boost::int64_t)data[4] & 0xff) << 32 | ((boost::int64_t)data[5] & 0xff) << 40 | ((boost::int64_t)data[6] & 0xff) << 48 | ((boost::int64_t)data[7] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #endif return val; } // read int XDR (big endian) inline int& read_int_xdr(const char* data, int & val) { #ifndef BOOST_BIG_ENDIAN val = (data[3]&0xff) | ((data[2]&0xff)<<8) | ((data[1]&0xff)<<16) | ((data[0]&0xff)<<24); #else memcpy(&val,data,4); #endif return val; } // read double XDR (big endian) inline double& read_double_xdr(const char* data, double & val) { #ifndef BOOST_BIG_ENDIAN boost::int64_t bits = ((boost::int64_t)data[0] & 0xff) | ((boost::int64_t)data[1] & 0xff) << 8 | ((boost::int64_t)data[2] & 0xff) << 16 | ((boost::int64_t)data[3] & 0xff) << 24 | ((boost::int64_t)data[4] & 0xff) << 32 | ((boost::int64_t)data[5] & 0xff) << 40 | ((boost::int64_t)data[6] & 0xff) << 48 | ((boost::int64_t)data[7] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #else std::memcpy(&val,&data[0],8); #endif return val; } } #endif //GLOBAL_HPP <commit_msg>+ fixed read_xxx_double methods <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef GLOBAL_HPP #define GLOBAL_HPP // boost #include <boost/cstdint.hpp> #include <boost/detail/endian.hpp> // stl #include <cstring> namespace mapnik { #define int2net(A) (int16_t) (((boost::uint16_t) ((boost::uint8_t) (A)[1])) | \ (((boost::uint16_t) ((boost::uint8_t) (A)[0])) << 8)) #define int4net(A) (int32_t) (((boost::uint32_t) ((boost::uint8_t) (A)[3])) | \ (((boost::uint32_t) ((boost::uint8_t) (A)[2])) << 8) | \ (((boost::uint32_t) ((boost::uint8_t) (A)[1])) << 16) | \ (((boost::uint32_t) ((boost::uint8_t) (A)[0])) << 24)) typedef boost::uint8_t byte; #define float8net(V,M) do { double def_temp; \ ((byte*) &def_temp)[0]=(M)[7]; \ ((byte*) &def_temp)[1]=(M)[6]; \ ((byte*) &def_temp)[2]=(M)[5]; \ ((byte*) &def_temp)[3]=(M)[4]; \ ((byte*) &def_temp)[4]=(M)[3]; \ ((byte*) &def_temp)[5]=(M)[2]; \ ((byte*) &def_temp)[6]=(M)[1]; \ ((byte*) &def_temp)[7]=(M)[0]; \ (V) = def_temp; } while(0) #define float4net(V,M) do { float def_temp; \ ((byte*) &def_temp)[0]=(M)[3]; \ ((byte*) &def_temp)[1]=(M)[2]; \ ((byte*) &def_temp)[2]=(M)[1]; \ ((byte*) &def_temp)[3]=(M)[0]; \ (V)=def_temp; } while(0) // read int NDR (little endian) inline int& read_int_ndr(const char* data, int & val) { #ifndef BOOST_BIG_ENDIAN memcpy(&val,data,4); #else val = (data[3]&0xff) | ((data[2]&0xff)<<8) | ((data[1]&0xff)<<16) | ((data[0]&0xff)<<24); #endif return val; } // read double NDR (little endian) inline double& read_double_ndr(const char* data, double & val) { #ifndef BOOST_BIG_ENDIAN std::memcpy(&val,&data[0],8); #else boost::int64_t bits = ((boost::int64_t)data[7] & 0xff) | ((boost::int64_t)data[6] & 0xff) << 8 | ((boost::int64_t)data[5] & 0xff) << 16 | ((boost::int64_t)data[4] & 0xff) << 24 | ((boost::int64_t)data[3] & 0xff) << 32 | ((boost::int64_t)data[2] & 0xff) << 40 | ((boost::int64_t)data[1] & 0xff) << 48 | ((boost::int64_t)data[0] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #endif return val; } // read int XDR (big endian) inline int& read_int_xdr(const char* data, int & val) { #ifndef BOOST_BIG_ENDIAN val = (data[3]&0xff) | ((data[2]&0xff)<<8) | ((data[1]&0xff)<<16) | ((data[0]&0xff)<<24); #else memcpy(&val,data,4); #endif return val; } // read double XDR (big endian) inline double& read_double_xdr(const char* data, double & val) { #ifndef BOOST_BIG_ENDIAN boost::int64_t bits = ((boost::int64_t)data[7] & 0xff) | ((boost::int64_t)data[6] & 0xff) << 8 | ((boost::int64_t)data[5] & 0xff) << 16 | ((boost::int64_t)data[4] & 0xff) << 24 | ((boost::int64_t)data[3] & 0xff) << 32 | ((boost::int64_t)data[2] & 0xff) << 40 | ((boost::int64_t)data[1] & 0xff) << 48 | ((boost::int64_t)data[0] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #else std::memcpy(&val,&data[0],8); #endif return val; } } #endif //GLOBAL_HPP <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #ifndef INCLUDED_SFX2_CHILDWIN_HXX #define INCLUDED_SFX2_CHILDWIN_HXX #include <sal/config.h> #include <sfx2/dllapi.h> #include <sal/types.h> #include <o3tl/typed_flags_set.hxx> #include <vcl/window.hxx> #include <com/sun/star/frame/XFrame.hpp> #include <sfx2/shell.hxx> #include <sfx2/chalign.hxx> #include <sfx2/bindings.hxx> // complete SfxBindings for complete SfxChildWinCtor, SfxChildWinContextCtor // under -fsanitize=function class SfxWorkWindow; class SfxModule; class SfxShell; class SfxChildWindow; class SfxChildWindowContext; enum class SfxChildWindowFlags { NONE = 0x00, ZOOMIN = 0x01, // Fully retracted Float FORCEDOCK = 0x04, // Float forbidden TASK = 0x10, // ChildWindow inside the Task CANTGETFOCUS = 0x20, // ChildWindow can not get focus ALWAYSAVAILABLE = 0x40, // ChildWindow is never disabled NEVERHIDE = 0x80 // ChildWindow is can always made // visible/is visible }; namespace o3tl { template<> struct typed_flags<SfxChildWindowFlags> : is_typed_flags<SfxChildWindowFlags, 0xf5> {}; } #define CHILDWIN_NOPOS USHRT_MAX // ChildWindow Configuration struct SAL_DLLPUBLIC_RTTI SfxChildWinInfo { bool bVisible; Point aPos; Size aSize; SfxChildWindowFlags nFlags; OUString aExtraString; OUString aModule; OString aWinState; SfxChildWinInfo() { bVisible = false; nFlags = SfxChildWindowFlags::NONE; } bool GetExtraData_Impl( SfxChildAlignment *pAlign, SfxChildAlignment *pLastAlign = 0, Size *pSize = 0, sal_uInt16 *pLine = 0, sal_uInt16 *pPos = 0 ) const; }; // ChildWindow factory methods typedef SfxChildWindow* (*SfxChildWinCtor)( vcl::Window *pParentWindow, sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo *pInfo); // ChildWindowsContexts factory methods typedef SfxChildWindowContext* (*SfxChildWinContextCtor)( vcl::Window *pParentWindow, SfxBindings *pBindings, SfxChildWinInfo *pInfo); struct SfxChildWinContextFactory { SfxChildWinContextCtor pCtor; // Factory method sal_uInt16 nContextId; // Idenifier for SfxInterface SfxChildWinInfo aInfo; // Configuration SfxChildWinContextFactory( SfxChildWinContextCtor pTheCtor, sal_uInt16 nID ) : pCtor(pTheCtor) , nContextId(nID) {} }; class SfxChildWinContextArr_Impl; struct SFX2_DLLPUBLIC SfxChildWinFactory { SfxChildWinCtor pCtor; // Factory method sal_uInt16 nId; // ChildWindow-Id ( SlotId ) SfxChildWinInfo aInfo; // Configuration sal_uInt16 nPos; // Position in UI SfxChildWinContextArr_Impl *pArr; // Array for Contexts SfxChildWinFactory( SfxChildWinCtor pTheCtor, sal_uInt16 nID, sal_uInt16 n ); ~SfxChildWinFactory(); }; class FloatingWindow; struct SfxChildWindow_Impl; class SFX2_DLLPUBLIC SfxChildWindowContext { friend class SfxChildWindow; VclPtr<vcl::Window> pWindow; sal_uInt16 nContextId; protected: SfxChildWindowContext( sal_uInt16 nId ); public: virtual ~SfxChildWindowContext(); void SetWindow( vcl::Window* pWin ) { pWindow=pWin; } vcl::Window* GetWindow() const { return pWindow; } sal_uInt16 GetContextId() const { return nContextId; } FloatingWindow* GetFloatingWindow() const; virtual void Resizing( Size& rSize ); static void RegisterChildWindowContext(SfxModule*, sal_uInt16, SfxChildWinContextFactory*); }; class SFX2_DLLPUBLIC SfxChildWindow { VclPtr<vcl::Window> pParent; // parent window ( Topwindow ) sal_uInt16 nType; // ChildWindow-Id protected: SfxChildAlignment eChildAlignment; // Current ::com::sun::star::drawing::Alignment VclPtr<vcl::Window> pWindow; // actual contents private: SfxChildWindow_Impl* pImp; // Implementation data SfxChildWindowContext* pContext; // With context-sensitive ChildWindows: // Annother window in pWindow SAL_DLLPRIVATE void ClearWorkwin(); protected: SfxChildWindow(vcl::Window *pParentWindow, sal_uInt16 nId); public: virtual ~SfxChildWindow(); void Destroy(); vcl::Window* GetWindow() const { return pWindow; } vcl::Window* GetParent() const { return pParent; } SfxChildAlignment GetAlignment() const { return eChildAlignment; } void SetAlignment(SfxChildAlignment eAlign); Size GetSizePixel() const { return pWindow->GetSizePixel(); } virtual void Hide(); virtual void Show( ShowFlags nFlags ); bool CanGetFocus() const; sal_uInt16 GetPosition(); sal_uInt16 GetType() { return nType; } void CreateContext( sal_uInt16 nContextId, SfxBindings& ); sal_uInt16 GetContextId() const { return pContext ? pContext->GetContextId(): 0; } vcl::Window* GetContextWindow() const { return pContext ? pContext->GetWindow(): 0; } vcl::Window* GetContextWindow( SfxModule *pModule ) const; virtual SfxChildWinInfo GetInfo() const; void SaveStatus(const SfxChildWinInfo& rInfo); static void RegisterChildWindow(SfxModule*, SfxChildWinFactory*); static SfxChildWindow* CreateChildWindow( sal_uInt16, vcl::Window*, SfxBindings*, SfxChildWinInfo&); void SetHideNotDelete( bool bOn ); bool IsHideNotDelete() const; bool IsHideAtToggle() const; bool IsVisible() const; void SetWantsFocus( bool ); bool WantsFocus() const; virtual bool QueryClose(); com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > GetFrame(); void SetFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > & ); SAL_DLLPRIVATE static void InitializeChildWinFactory_Impl(sal_uInt16, SfxChildWinInfo&); void SetVisible_Impl( bool bVis ); SAL_DLLPRIVATE void SetWorkWindow_Impl( SfxWorkWindow* ); SAL_DLLPRIVATE void Activate_Impl(); SAL_DLLPRIVATE void Deactivate_Impl(); SAL_DLLPRIVATE SfxChildWindowContext* GetContext_Impl() const { return pContext; } SAL_DLLPRIVATE void SetFactory_Impl( SfxChildWinFactory* ); }; //! soon obsolete ! #define SFX_DECL_CHILDWINDOW_CONTEXT(Class) \ static SfxChildWindowContext* CreateImpl(vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ); \ static void RegisterChildWindowContext(SfxModule *pMod=0); \ //! The Macro of the future ... #define SFX_DECL_CHILDWINDOWCONTEXT(Class) \ static SfxChildWindowContext* CreateImpl(vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ); \ static void RegisterChildWindowContext(sal_uInt16, SfxModule *pMod=0); \ //! soon obsolete ! #define SFX_IMPL_CHILDWINDOW_CONTEXT(Class, MyID, ShellClass) \ SfxChildWindowContext* Class::CreateImpl( vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ) \ { \ SfxChildWindowContext *pContext = new Class(pParent, \ /* cast is safe here! */static_cast< sal_uInt16 >(ShellClass::GetInterfaceId()), \ pBindings,pInfo); \ return pContext; \ } \ void Class::RegisterChildWindowContext(SfxModule* pMod) \ { \ SfxChildWinContextFactory *pFact = new SfxChildWinContextFactory( \ Class::CreateImpl, \ /* cast is safe here! */static_cast< sal_uInt16 >(ShellClass::GetInterfaceId()) ); \ SfxChildWindowContext::RegisterChildWindowContext(pMod, MyID, pFact); \ } //! The Macro of the future ... // As a parameter and because of ContextId, CreateImpl must be handed the // factory. As long as Id is set to 0 and patched in // SfxChildWindow::CreateContext #define SFX_IMPL_CHILDWINDOWCONTEXT(Class, MyID) \ SfxChildWindowContext* Class::CreateImpl( vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ) \ { \ SfxChildWindowContext *pContext = new Class(pParent,0,pBindings,pInfo);\ return pContext; \ } \ void Class::RegisterChildWindowContext(sal_uInt16 nId, SfxModule* pMod) \ { \ SfxChildWinContextFactory *pFact = new SfxChildWinContextFactory( \ Class::CreateImpl, nId ); \ SfxChildWindowContext::RegisterChildWindowContext(pMod, MyID, pFact); \ } #define SFX_DECL_CHILDWINDOW(Class) \ public : \ static SfxChildWindow* CreateImpl(vcl::Window *pParent, sal_uInt16 nId, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ); \ static void RegisterChildWindow (bool bVisible=false, SfxModule *pMod=NULL, SfxChildWindowFlags nFlags=SfxChildWindowFlags::NONE); \ virtual SfxChildWinInfo GetInfo() const SAL_OVERRIDE #define SFX_DECL_CHILDWINDOW_WITHID(Class) \ SFX_DECL_CHILDWINDOW(Class); \ static sal_uInt16 GetChildWindowId ()\ #define SFX_IMPL_CHILDWINDOW(Class, MyID) \ SFX_IMPL_POS_CHILDWINDOW(Class, MyID, CHILDWIN_NOPOS) #define SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SFX_IMPL_POS_CHILDWINDOW_WITHID(Class, MyID, CHILDWIN_NOPOS) #define SFX_IMPL_POS_CHILDWINDOW(Class, MyID, Pos) \ SfxChildWindow* Class::CreateImpl( vcl::Window *pParent, \ sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo* pInfo ) \ { \ SfxChildWindow *pWin = new Class(pParent, nId, pBindings, pInfo);\ return pWin; \ } \ void Class::RegisterChildWindow (bool bVis, SfxModule *pMod, SfxChildWindowFlags nFlags) \ { \ SfxChildWinFactory *pFact = new SfxChildWinFactory( \ Class::CreateImpl, MyID, Pos ); \ pFact->aInfo.nFlags |= nFlags; \ pFact->aInfo.bVisible = bVis; \ SfxChildWindow::RegisterChildWindow(pMod, pFact); \ } #define SFX_IMPL_POS_CHILDWINDOW_WITHID(Class, MyID, Pos) \ SFX_IMPL_POS_CHILDWINDOW(Class, MyID, Pos) \ sal_uInt16 Class::GetChildWindowId () \ { return MyID; } \ #define SFX_IMPL_FLOATINGWINDOW(Class, MyID) \ SFX_IMPL_CHILDWINDOW(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxFloatingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_FLOATINGWINDOW_WITHID(Class, MyID) \ SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxFloatingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_MODELESSDIALOG_WITHID(Class, MyID) \ SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxModelessDialog*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_DOCKINGWINDOW(Class, MyID) \ SFX_IMPL_CHILDWINDOW(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxDockingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_DOCKINGWINDOW_WITHID(Class, MyID) \ SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxDockingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } bool GetPosSizeFromString( const OUString& rStr, Point& rPos, Size& rSize ); bool GetSplitSizeFromString( const OUString& rStr, Size& rSize ); #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>clean up whitespace in childwin.hxx a little<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #ifndef INCLUDED_SFX2_CHILDWIN_HXX #define INCLUDED_SFX2_CHILDWIN_HXX #include <sal/config.h> #include <sfx2/dllapi.h> #include <sal/types.h> #include <o3tl/typed_flags_set.hxx> #include <vcl/window.hxx> #include <com/sun/star/frame/XFrame.hpp> #include <sfx2/shell.hxx> #include <sfx2/chalign.hxx> #include <sfx2/bindings.hxx> // complete SfxBindings for complete SfxChildWinCtor, SfxChildWinContextCtor // under -fsanitize=function class SfxWorkWindow; class SfxModule; class SfxShell; class SfxChildWindow; class SfxChildWindowContext; enum class SfxChildWindowFlags { NONE = 0x00, ZOOMIN = 0x01, // Fully retracted Float FORCEDOCK = 0x04, // Float forbidden TASK = 0x10, // ChildWindow inside the Task CANTGETFOCUS = 0x20, // ChildWindow can not get focus ALWAYSAVAILABLE = 0x40, // ChildWindow is never disabled NEVERHIDE = 0x80 // ChildWindow is can always made // visible/is visible }; namespace o3tl { template<> struct typed_flags<SfxChildWindowFlags> : is_typed_flags<SfxChildWindowFlags, 0xf5> {}; } #define CHILDWIN_NOPOS USHRT_MAX // ChildWindow Configuration struct SAL_DLLPUBLIC_RTTI SfxChildWinInfo { bool bVisible; Point aPos; Size aSize; SfxChildWindowFlags nFlags; OUString aExtraString; OUString aModule; OString aWinState; SfxChildWinInfo() { bVisible = false; nFlags = SfxChildWindowFlags::NONE; } bool GetExtraData_Impl( SfxChildAlignment *pAlign, SfxChildAlignment *pLastAlign = 0, Size *pSize = 0, sal_uInt16 *pLine = 0, sal_uInt16 *pPos = 0 ) const; }; // ChildWindow factory methods typedef SfxChildWindow* (*SfxChildWinCtor)( vcl::Window *pParentWindow, sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo *pInfo); // ChildWindowsContexts factory methods typedef SfxChildWindowContext* (*SfxChildWinContextCtor)( vcl::Window *pParentWindow, SfxBindings *pBindings, SfxChildWinInfo *pInfo); struct SfxChildWinContextFactory { SfxChildWinContextCtor pCtor; // Factory method sal_uInt16 nContextId; // Idenifier for SfxInterface SfxChildWinInfo aInfo; // Configuration SfxChildWinContextFactory( SfxChildWinContextCtor pTheCtor, sal_uInt16 nID ) : pCtor(pTheCtor) , nContextId(nID) {} }; class SfxChildWinContextArr_Impl; struct SFX2_DLLPUBLIC SfxChildWinFactory { SfxChildWinCtor pCtor; // Factory method sal_uInt16 nId; // ChildWindow-Id ( SlotId ) SfxChildWinInfo aInfo; // Configuration sal_uInt16 nPos; // Position in UI SfxChildWinContextArr_Impl *pArr; // Array for Contexts SfxChildWinFactory( SfxChildWinCtor pTheCtor, sal_uInt16 nID, sal_uInt16 n ); ~SfxChildWinFactory(); }; class FloatingWindow; struct SfxChildWindow_Impl; class SFX2_DLLPUBLIC SfxChildWindowContext { friend class SfxChildWindow; VclPtr<vcl::Window> pWindow; sal_uInt16 nContextId; protected: SfxChildWindowContext( sal_uInt16 nId ); public: virtual ~SfxChildWindowContext(); void SetWindow( vcl::Window* pWin ) { pWindow=pWin; } vcl::Window* GetWindow() const { return pWindow; } sal_uInt16 GetContextId() const { return nContextId; } FloatingWindow* GetFloatingWindow() const; virtual void Resizing( Size& rSize ); static void RegisterChildWindowContext(SfxModule*, sal_uInt16, SfxChildWinContextFactory*); }; class SFX2_DLLPUBLIC SfxChildWindow { VclPtr<vcl::Window> pParent; // parent window ( Topwindow ) sal_uInt16 nType; // ChildWindow-Id protected: SfxChildAlignment eChildAlignment; // Current ::com::sun::star::drawing::Alignment VclPtr<vcl::Window> pWindow; // actual contents private: SfxChildWindow_Impl* pImp; // Implementation data SfxChildWindowContext* pContext; // With context-sensitive ChildWindows: // Annother window in pWindow SAL_DLLPRIVATE void ClearWorkwin(); protected: SfxChildWindow(vcl::Window *pParentWindow, sal_uInt16 nId); public: virtual ~SfxChildWindow(); void Destroy(); vcl::Window* GetWindow() const { return pWindow; } vcl::Window* GetParent() const { return pParent; } SfxChildAlignment GetAlignment() const { return eChildAlignment; } void SetAlignment(SfxChildAlignment eAlign); Size GetSizePixel() const { return pWindow->GetSizePixel(); } virtual void Hide(); virtual void Show( ShowFlags nFlags ); bool CanGetFocus() const; sal_uInt16 GetPosition(); sal_uInt16 GetType() { return nType; } void CreateContext( sal_uInt16 nContextId, SfxBindings& ); sal_uInt16 GetContextId() const { return pContext ? pContext->GetContextId(): 0; } vcl::Window* GetContextWindow() const { return pContext ? pContext->GetWindow(): 0; } vcl::Window* GetContextWindow( SfxModule *pModule ) const; virtual SfxChildWinInfo GetInfo() const; void SaveStatus(const SfxChildWinInfo& rInfo); static void RegisterChildWindow(SfxModule*, SfxChildWinFactory*); static SfxChildWindow* CreateChildWindow( sal_uInt16, vcl::Window*, SfxBindings*, SfxChildWinInfo&); void SetHideNotDelete( bool bOn ); bool IsHideNotDelete() const; bool IsHideAtToggle() const; bool IsVisible() const; void SetWantsFocus( bool ); bool WantsFocus() const; virtual bool QueryClose(); css::uno::Reference< css::frame::XFrame > GetFrame(); void SetFrame( const css::uno::Reference< css::frame::XFrame > & ); SAL_DLLPRIVATE static void InitializeChildWinFactory_Impl(sal_uInt16, SfxChildWinInfo&); void SetVisible_Impl( bool bVis ); SAL_DLLPRIVATE void SetWorkWindow_Impl( SfxWorkWindow* ); SAL_DLLPRIVATE void Activate_Impl(); SAL_DLLPRIVATE void Deactivate_Impl(); SAL_DLLPRIVATE SfxChildWindowContext* GetContext_Impl() const { return pContext; } SAL_DLLPRIVATE void SetFactory_Impl( SfxChildWinFactory* ); }; //! soon obsolete ! #define SFX_DECL_CHILDWINDOW_CONTEXT(Class) \ static SfxChildWindowContext* CreateImpl(vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ); \ static void RegisterChildWindowContext(SfxModule *pMod=0); \ //! The Macro of the future ... #define SFX_DECL_CHILDWINDOWCONTEXT(Class) \ static SfxChildWindowContext* CreateImpl(vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ); \ static void RegisterChildWindowContext(sal_uInt16, SfxModule *pMod=0); \ //! soon obsolete ! #define SFX_IMPL_CHILDWINDOW_CONTEXT(Class, MyID, ShellClass) \ SfxChildWindowContext* Class::CreateImpl( vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ) \ { \ SfxChildWindowContext *pContext = new Class(pParent, \ /* cast is safe here! */static_cast< sal_uInt16 >(ShellClass::GetInterfaceId()), \ pBindings,pInfo); \ return pContext; \ } \ void Class::RegisterChildWindowContext(SfxModule* pMod) \ { \ SfxChildWinContextFactory *pFact = new SfxChildWinContextFactory( \ Class::CreateImpl, \ /* cast is safe here! */static_cast< sal_uInt16 >(ShellClass::GetInterfaceId()) ); \ SfxChildWindowContext::RegisterChildWindowContext(pMod, MyID, pFact); \ } //! The Macro of the future ... // As a parameter and because of ContextId, CreateImpl must be handed the // factory. As long as Id is set to 0 and patched in // SfxChildWindow::CreateContext #define SFX_IMPL_CHILDWINDOWCONTEXT(Class, MyID) \ SfxChildWindowContext* Class::CreateImpl( vcl::Window *pParent, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ) \ { \ SfxChildWindowContext *pContext = new Class(pParent,0,pBindings,pInfo);\ return pContext; \ } \ void Class::RegisterChildWindowContext(sal_uInt16 nId, SfxModule* pMod) \ { \ SfxChildWinContextFactory *pFact = new SfxChildWinContextFactory( \ Class::CreateImpl, nId ); \ SfxChildWindowContext::RegisterChildWindowContext(pMod, MyID, pFact); \ } #define SFX_DECL_CHILDWINDOW(Class) \ public : \ static SfxChildWindow* CreateImpl(vcl::Window *pParent, sal_uInt16 nId, \ SfxBindings *pBindings, SfxChildWinInfo* pInfo ); \ static void RegisterChildWindow (bool bVisible=false, SfxModule *pMod=NULL, SfxChildWindowFlags nFlags=SfxChildWindowFlags::NONE); \ virtual SfxChildWinInfo GetInfo() const SAL_OVERRIDE #define SFX_DECL_CHILDWINDOW_WITHID(Class) \ SFX_DECL_CHILDWINDOW(Class); \ static sal_uInt16 GetChildWindowId ()\ #define SFX_IMPL_CHILDWINDOW(Class, MyID) \ SFX_IMPL_POS_CHILDWINDOW(Class, MyID, CHILDWIN_NOPOS) #define SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SFX_IMPL_POS_CHILDWINDOW_WITHID(Class, MyID, CHILDWIN_NOPOS) #define SFX_IMPL_POS_CHILDWINDOW(Class, MyID, Pos) \ SfxChildWindow* Class::CreateImpl( vcl::Window *pParent, \ sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo* pInfo ) \ { \ SfxChildWindow *pWin = new Class(pParent, nId, pBindings, pInfo);\ return pWin; \ } \ void Class::RegisterChildWindow (bool bVis, SfxModule *pMod, SfxChildWindowFlags nFlags) \ { \ SfxChildWinFactory *pFact = new SfxChildWinFactory( \ Class::CreateImpl, MyID, Pos ); \ pFact->aInfo.nFlags |= nFlags; \ pFact->aInfo.bVisible = bVis; \ SfxChildWindow::RegisterChildWindow(pMod, pFact); \ } #define SFX_IMPL_POS_CHILDWINDOW_WITHID(Class, MyID, Pos) \ SFX_IMPL_POS_CHILDWINDOW(Class, MyID, Pos) \ sal_uInt16 Class::GetChildWindowId () \ { return MyID; } \ #define SFX_IMPL_FLOATINGWINDOW(Class, MyID) \ SFX_IMPL_CHILDWINDOW(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxFloatingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_FLOATINGWINDOW_WITHID(Class, MyID) \ SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxFloatingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_MODELESSDIALOG_WITHID(Class, MyID) \ SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxModelessDialog*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_DOCKINGWINDOW(Class, MyID) \ SFX_IMPL_CHILDWINDOW(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxDockingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } #define SFX_IMPL_DOCKINGWINDOW_WITHID(Class, MyID) \ SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ SfxChildWinInfo Class::GetInfo() const \ { \ SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ static_cast<SfxDockingWindow*>(GetWindow())->FillInfo( aInfo ); \ return aInfo; } bool GetPosSizeFromString( const OUString& rStr, Point& rPos, Size& rSize ); bool GetSplitSizeFromString( const OUString& rStr, Size& rSize ); #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * 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. * *******************************************************************************/ #define MIOPEN #include <miopen/config.h> #include <miopen/convolution.hpp> #include <miopen/db.hpp> #include <miopen/env.hpp> #include <miopen/gcn_asm_utils.hpp> #include <miopen/mlo_internal.hpp> #include <miopen/mlo_utils.hpp> #include <miopen/solver.hpp> #include <miopen/readonlyramdb.hpp> #include <miopen/datatype.hpp> #include <miopen/version.h> #include <miopen/stringutils.hpp> #include <miopen/hip_build_utils.hpp> #include <miopen/any_solver.hpp> #include <cmath> #include <cstring> #include <iomanip> #include <memory> #include <sstream> #include <unordered_map> #include <miopen/solver.hpp> #if MIOPEN_ENABLE_SQLITE #include <miopen/sqlite_db.hpp> #endif #include <miopen/db.hpp> #include <miopen/env.hpp> #include <miopen/gcn_asm_utils.hpp> #include <miopen/mlo_internal.hpp> #include <miopen/mlo_utils.hpp> // Only select the first applicable igemm solver due to long compilation time // (JIRA SWDEV-227826) /// \todo enable all applicable solvers of igemm after fixing slow compilation #define WORKAROUND_SWDEV_227826 1 #if WORKAROUND_SWDEV_227826 MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_IMPLICIT_GEMM_FIND_ALL_SOLUTIONS) #endif #if MIOPEN_ENABLE_SQLITE miopen::PerformanceDb mlo_construct_base::GetDb() const { auto& h = _search_params.GetStream(); return { db_path(), _search_params.GetUserPerfDbPath(), h.GetDeviceName(), h.GetMaxComputeUnits()}; } miopen::PerformanceDb miopen::GetDb(const miopen::ConvolutionContext& ctx) { auto& h = ctx.GetStream(); return { ctx.GetPerfDbPath(), ctx.GetUserPerfDbPath(), h.GetDeviceName(), h.GetMaxComputeUnits()}; } #else miopen::PerformanceDb mlo_construct_base::GetDb() const { return {db_path(), _search_params.GetUserPerfDbPath()}; } miopen::PerformanceDb miopen::GetDb(const ConvolutionContext& ctx) { return {ctx.GetPerfDbPath(), ctx.GetUserPerfDbPath()}; } #endif miopen::solver::ConvSolution mlo_construct_direct2D_fusion::FindSolution(const std::vector<miopen::solver::AnySolver>& solvers, const miopen::AnyInvokeParams& invoke_ctx) { miopen::solver::ConvSolution solution{miopenStatusUnknownError}; std::string solver_id; auto db = this->GetDb(); for(auto& solver : solvers) { solution = solver.FindSolution(_search_params, db, invoke_ctx); if(solution.Succeeded() && solver.IsApplicable(_search_params)) { solver_id = miopen::solver::SolverDbId(solver); break; } } if(solution.Succeeded() && solution.construction_params.empty()) { MIOPEN_THROW(std::string("Internal error in solver: ") + solver_id); } return solution; } static auto GetDirectSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvAsm3x3U, miopen::solver::ConvAsm1x1U, miopen::solver::ConvAsm1x1UV2, miopen::solver::ConvAsm5x10u2v2f1, miopen::solver::ConvAsm7x7c3h224w224k64u2v2p3q3f1, miopen::solver::ConvAsm5x10u2v2b1, miopen::solver::ConvOclDirectFwd11x11, miopen::solver::ConvOclDirectFwdGen, miopen::solver::ConvOclDirectFwd3x3, miopen::solver::ConvOclDirectFwd1x1, miopen::solver::ConvOclDirectFwd>{}; } static auto GetImplicitGemmSolvers() { return miopen::solver::SolverContainer< miopen::solver::ConvHipImplicitGemmForwardV4R5Xdlops, miopen::solver::ConvHipImplicitGemmForwardV4R4Xdlops, miopen::solver::ConvHipImplicitGemmBwdDataV4R1Xdlops, miopen::solver::ConvHipImplicitGemmBwdDataV1R1Xdlops, miopen::solver::ConvHipImplicitGemmV4R1Fwd, miopen::solver::ConvHipImplicitGemmV4R4Fwd, miopen::solver::ConvHipImplicitGemmBwdDataV1R1, miopen::solver::ConvHipImplicitGemmBwdDataV4R1, miopen::solver::ConvAsmImplicitGemmV4R1DynamicFwd_1x1, miopen::solver::ConvAsmImplicitGemmV4R1DynamicFwd, miopen::solver::ConvAsmImplicitGemmV4R1DynamicBwd, miopen::solver::ConvAsmImplicitGemmGTCDynamicFwdXdlops, miopen::solver::ConvAsmImplicitGemmGTCDynamicBwdXdlops>{}; } static auto GetWindogradSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvBinWinograd3x3U, miopen::solver::ConvBinWinogradRxSf3x2, miopen::solver::ConvBinWinogradRxSf2x3, miopen::solver::ConvBinWinogradRxS, miopen::solver::ConvMPBidirectWinograd<3, 3>, miopen::solver::ConvMPBidirectWinograd<4, 3>, miopen::solver::ConvMPBidirectWinograd<5, 3>, miopen::solver::ConvMPBidirectWinograd<6, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<2, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<3, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<4, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<5, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<6, 3>>{}; } static auto GetImplicitGemmWrWSolvers() { return miopen::solver::SolverContainer< miopen::solver::ConvHipImplicitGemmWrwV4R4Xdlops, miopen::solver::ConvHipImplicitGemmV4R1WrW, miopen::solver::ConvHipImplicitGemmV4R4WrW, miopen::solver::ConvAsmImplicitGemmV4R1DynamicWrw, miopen::solver::ConvAsmImplicitGemmGTCDynamicWrwXdlops>{}; } static auto GetWindogradWrWSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvBinWinogradRxS, miopen::solver::ConvBinWinogradRxSf2x3, miopen::solver::ConvWinograd3x3MultipassWrW<3, 2>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 4>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 5>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 6>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 2>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 3, 1, 1>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 2, 1, 1>, miopen::solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 2>, miopen::solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<5, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<5, 4>>{}; } static auto GetBwdWrW2DSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvAsmBwdWrW1x1, miopen::solver::ConvAsmBwdWrW3x3, miopen::solver::ConvOclBwdWrW2<1>, miopen::solver::ConvOclBwdWrW2<2>, miopen::solver::ConvOclBwdWrW2<4>, miopen::solver::ConvOclBwdWrW2<8>, miopen::solver::ConvOclBwdWrW2<16>, miopen::solver::ConvOclBwdWrW2NonTunable, miopen::solver::ConvOclBwdWrW53, miopen::solver::ConvOclBwdWrW1x1>{}; } std::vector<miopen::solver::ConvSolution> FindAllDirectSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetDirectSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } std::vector<std::pair<std::string, size_t>> AllDirectForwardBackwardDataWorkspaceSize(const miopen::ConvolutionContext& ctx) { return GetDirectSolvers().GetWorkspaceSize(ctx); } std::vector<miopen::solver::ConvSolution> FindAllImplicitGemmSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { #if WORKAROUND_SWDEV_227826 if(miopen::IsEnabled(MIOPEN_DEBUG_IMPLICIT_GEMM_FIND_ALL_SOLUTIONS{})) return GetImplicitGemmSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); else return GetImplicitGemmSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx, 1); #else return GetImplicitGemmSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); #endif } std::vector<miopen::solver::ConvSolution> FindAllWinogradSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetWindogradSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } std::vector<miopen::solver::ConvSolution> FindWinogradWrWAllSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetWindogradWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } std::vector<std::pair<std::string, size_t>> AllDirectBwdWrW2DWorkspaceSize(const miopen::ConvolutionContext& ctx) { return GetBwdWrW2DSolvers().GetWorkspaceSize(ctx); } std::vector<miopen::solver::ConvSolution> FindImplicitGemmWrWAllSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { #if WORKAROUND_SWDEV_227826 if(miopen::IsEnabled(MIOPEN_DEBUG_IMPLICIT_GEMM_FIND_ALL_SOLUTIONS{})) return GetImplicitGemmWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); else return GetImplicitGemmWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx, 1); #else return GetImplicitGemmWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); #endif } std::vector<miopen::solver::ConvSolution> FindAllBwdWrW2DSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetBwdWrW2DSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } void miopen::ConvolutionContext::SetupFloats() { if(IsFp32() || IsFp16() || IsBfp16()) { general_compile_options += GetDataTypeKernelParams(in_data_type); } else { MIOPEN_LOG_W( "Unsupported data types configuration: " << miopen::GetDataTypeName(in_data_type) << "x" << miopen::GetDataTypeName(weights_data_type) << "x" << miopen::GetDataTypeName(out_data_type)); } } void mlo_construct_activ_lrn_pooling_common::setupFloats() { if(_search_params.in_data_type == miopenFloat && _search_params.out_data_type == miopenFloat) { _search_params.general_compile_options += " -DMIOPEN_USE_FP32=1 -DMIOPEN_USE_FP16=0"; } else if(_search_params.in_data_type == miopenHalf && _search_params.out_data_type == miopenHalf) { _search_params.general_compile_options += " -DMIOPEN_USE_FP32=0 -DMIOPEN_USE_FP16=1"; } else { MIOPEN_LOG_W("Unsupported data types configuration: " << miopen::GetDataTypeName(_search_params.in_data_type) << "x" << miopen::GetDataTypeName(_search_params.out_data_type)); } } <commit_msg>add ConvHipImplicitGemmForwardV4R4Xdlops_Padded_Gemm in solver list (#497)<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * 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. * *******************************************************************************/ #define MIOPEN #include <miopen/config.h> #include <miopen/convolution.hpp> #include <miopen/db.hpp> #include <miopen/env.hpp> #include <miopen/gcn_asm_utils.hpp> #include <miopen/mlo_internal.hpp> #include <miopen/mlo_utils.hpp> #include <miopen/solver.hpp> #include <miopen/readonlyramdb.hpp> #include <miopen/datatype.hpp> #include <miopen/version.h> #include <miopen/stringutils.hpp> #include <miopen/hip_build_utils.hpp> #include <miopen/any_solver.hpp> #include <cmath> #include <cstring> #include <iomanip> #include <memory> #include <sstream> #include <unordered_map> #include <miopen/solver.hpp> #if MIOPEN_ENABLE_SQLITE #include <miopen/sqlite_db.hpp> #endif #include <miopen/db.hpp> #include <miopen/env.hpp> #include <miopen/gcn_asm_utils.hpp> #include <miopen/mlo_internal.hpp> #include <miopen/mlo_utils.hpp> // Only select the first applicable igemm solver due to long compilation time // (JIRA SWDEV-227826) /// \todo enable all applicable solvers of igemm after fixing slow compilation #define WORKAROUND_SWDEV_227826 1 #if WORKAROUND_SWDEV_227826 MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_IMPLICIT_GEMM_FIND_ALL_SOLUTIONS) #endif #if MIOPEN_ENABLE_SQLITE miopen::PerformanceDb mlo_construct_base::GetDb() const { auto& h = _search_params.GetStream(); return { db_path(), _search_params.GetUserPerfDbPath(), h.GetDeviceName(), h.GetMaxComputeUnits()}; } miopen::PerformanceDb miopen::GetDb(const miopen::ConvolutionContext& ctx) { auto& h = ctx.GetStream(); return { ctx.GetPerfDbPath(), ctx.GetUserPerfDbPath(), h.GetDeviceName(), h.GetMaxComputeUnits()}; } #else miopen::PerformanceDb mlo_construct_base::GetDb() const { return {db_path(), _search_params.GetUserPerfDbPath()}; } miopen::PerformanceDb miopen::GetDb(const ConvolutionContext& ctx) { return {ctx.GetPerfDbPath(), ctx.GetUserPerfDbPath()}; } #endif miopen::solver::ConvSolution mlo_construct_direct2D_fusion::FindSolution(const std::vector<miopen::solver::AnySolver>& solvers, const miopen::AnyInvokeParams& invoke_ctx) { miopen::solver::ConvSolution solution{miopenStatusUnknownError}; std::string solver_id; auto db = this->GetDb(); for(auto& solver : solvers) { solution = solver.FindSolution(_search_params, db, invoke_ctx); if(solution.Succeeded() && solver.IsApplicable(_search_params)) { solver_id = miopen::solver::SolverDbId(solver); break; } } if(solution.Succeeded() && solution.construction_params.empty()) { MIOPEN_THROW(std::string("Internal error in solver: ") + solver_id); } return solution; } static auto GetDirectSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvAsm3x3U, miopen::solver::ConvAsm1x1U, miopen::solver::ConvAsm1x1UV2, miopen::solver::ConvAsm5x10u2v2f1, miopen::solver::ConvAsm7x7c3h224w224k64u2v2p3q3f1, miopen::solver::ConvAsm5x10u2v2b1, miopen::solver::ConvOclDirectFwd11x11, miopen::solver::ConvOclDirectFwdGen, miopen::solver::ConvOclDirectFwd3x3, miopen::solver::ConvOclDirectFwd1x1, miopen::solver::ConvOclDirectFwd>{}; } static auto GetImplicitGemmSolvers() { return miopen::solver::SolverContainer< miopen::solver::ConvHipImplicitGemmForwardV4R5Xdlops, miopen::solver::ConvHipImplicitGemmForwardV4R4Xdlops, miopen::solver::ConvHipImplicitGemmForwardV4R4Xdlops_Padded_Gemm, miopen::solver::ConvHipImplicitGemmBwdDataV4R1Xdlops, miopen::solver::ConvHipImplicitGemmBwdDataV1R1Xdlops, miopen::solver::ConvHipImplicitGemmV4R1Fwd, miopen::solver::ConvHipImplicitGemmV4R4Fwd, miopen::solver::ConvHipImplicitGemmBwdDataV1R1, miopen::solver::ConvHipImplicitGemmBwdDataV4R1, miopen::solver::ConvAsmImplicitGemmV4R1DynamicFwd_1x1, miopen::solver::ConvAsmImplicitGemmV4R1DynamicFwd, miopen::solver::ConvAsmImplicitGemmV4R1DynamicBwd, miopen::solver::ConvAsmImplicitGemmGTCDynamicFwdXdlops, miopen::solver::ConvAsmImplicitGemmGTCDynamicBwdXdlops>{}; } static auto GetWindogradSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvBinWinograd3x3U, miopen::solver::ConvBinWinogradRxSf3x2, miopen::solver::ConvBinWinogradRxSf2x3, miopen::solver::ConvBinWinogradRxS, miopen::solver::ConvMPBidirectWinograd<3, 3>, miopen::solver::ConvMPBidirectWinograd<4, 3>, miopen::solver::ConvMPBidirectWinograd<5, 3>, miopen::solver::ConvMPBidirectWinograd<6, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<2, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<3, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<4, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<5, 3>, miopen::solver::ConvMPBidirectWinograd_xdlops<6, 3>>{}; } static auto GetImplicitGemmWrWSolvers() { return miopen::solver::SolverContainer< miopen::solver::ConvHipImplicitGemmWrwV4R4Xdlops, miopen::solver::ConvHipImplicitGemmV4R1WrW, miopen::solver::ConvHipImplicitGemmV4R4WrW, miopen::solver::ConvAsmImplicitGemmV4R1DynamicWrw, miopen::solver::ConvAsmImplicitGemmGTCDynamicWrwXdlops>{}; } static auto GetWindogradWrWSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvBinWinogradRxS, miopen::solver::ConvBinWinogradRxSf2x3, miopen::solver::ConvWinograd3x3MultipassWrW<3, 2>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 4>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 5>, miopen::solver::ConvWinograd3x3MultipassWrW<3, 6>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 2>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 3, 1, 1>, miopen::solver::ConvWinograd3x3MultipassWrW<7, 2, 1, 1>, miopen::solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 2>, miopen::solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<5, 3>, miopen::solver::ConvWinograd3x3MultipassWrW<5, 4>>{}; } static auto GetBwdWrW2DSolvers() { return miopen::solver::SolverContainer<miopen::solver::ConvAsmBwdWrW1x1, miopen::solver::ConvAsmBwdWrW3x3, miopen::solver::ConvOclBwdWrW2<1>, miopen::solver::ConvOclBwdWrW2<2>, miopen::solver::ConvOclBwdWrW2<4>, miopen::solver::ConvOclBwdWrW2<8>, miopen::solver::ConvOclBwdWrW2<16>, miopen::solver::ConvOclBwdWrW2NonTunable, miopen::solver::ConvOclBwdWrW53, miopen::solver::ConvOclBwdWrW1x1>{}; } std::vector<miopen::solver::ConvSolution> FindAllDirectSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetDirectSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } std::vector<std::pair<std::string, size_t>> AllDirectForwardBackwardDataWorkspaceSize(const miopen::ConvolutionContext& ctx) { return GetDirectSolvers().GetWorkspaceSize(ctx); } std::vector<miopen::solver::ConvSolution> FindAllImplicitGemmSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { #if WORKAROUND_SWDEV_227826 if(miopen::IsEnabled(MIOPEN_DEBUG_IMPLICIT_GEMM_FIND_ALL_SOLUTIONS{})) return GetImplicitGemmSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); else return GetImplicitGemmSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx, 1); #else return GetImplicitGemmSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); #endif } std::vector<miopen::solver::ConvSolution> FindAllWinogradSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetWindogradSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } std::vector<miopen::solver::ConvSolution> FindWinogradWrWAllSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetWindogradWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } std::vector<std::pair<std::string, size_t>> AllDirectBwdWrW2DWorkspaceSize(const miopen::ConvolutionContext& ctx) { return GetBwdWrW2DSolvers().GetWorkspaceSize(ctx); } std::vector<miopen::solver::ConvSolution> FindImplicitGemmWrWAllSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { #if WORKAROUND_SWDEV_227826 if(miopen::IsEnabled(MIOPEN_DEBUG_IMPLICIT_GEMM_FIND_ALL_SOLUTIONS{})) return GetImplicitGemmWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); else return GetImplicitGemmWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx, 1); #else return GetImplicitGemmWrWSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); #endif } std::vector<miopen::solver::ConvSolution> FindAllBwdWrW2DSolutions(const miopen::ConvolutionContext& ctx, const miopen::AnyInvokeParams& invoke_ctx) { return GetBwdWrW2DSolvers().SearchForAllSolutions(ctx, GetDb(ctx), invoke_ctx); } void miopen::ConvolutionContext::SetupFloats() { if(IsFp32() || IsFp16() || IsBfp16()) { general_compile_options += GetDataTypeKernelParams(in_data_type); } else { MIOPEN_LOG_W( "Unsupported data types configuration: " << miopen::GetDataTypeName(in_data_type) << "x" << miopen::GetDataTypeName(weights_data_type) << "x" << miopen::GetDataTypeName(out_data_type)); } } void mlo_construct_activ_lrn_pooling_common::setupFloats() { if(_search_params.in_data_type == miopenFloat && _search_params.out_data_type == miopenFloat) { _search_params.general_compile_options += " -DMIOPEN_USE_FP32=1 -DMIOPEN_USE_FP16=0"; } else if(_search_params.in_data_type == miopenHalf && _search_params.out_data_type == miopenHalf) { _search_params.general_compile_options += " -DMIOPEN_USE_FP32=0 -DMIOPEN_USE_FP16=1"; } else { MIOPEN_LOG_W("Unsupported data types configuration: " << miopen::GetDataTypeName(_search_params.in_data_type) << "x" << miopen::GetDataTypeName(_search_params.out_data_type)); } } <|endoftext|>
<commit_before>#include <memory> #include <serv.h> #define MAX_RETRY 5 int notifyFailedToRedis(RedisUpstream *redisUpstream, std::string responseCommand, std::string dataKey); void BackgroundJob::regType() { REG_BPROC(COMMAND_DATA_SAVE); REG_BPROC(COMMAND_DATA_DUMP); REG_BPROC(COMMAND_SYNC_PREPARE1); } void *BackgroundJob::thread_func(void *arg) { BackgroundJob *backgroudJob = (BackgroundJob *) arg; while (!backgroudJob->thread_quit) { backgroudJob->loop(backgroudJob->serv->bqueue); } log_debug("BackgroundJob thread quit"); backgroudJob->thread_quit = false; return nullptr; } void BackgroundJob::start() { last = time_ms(); this->regType(); thread_quit = false; int err; pthread_t tid; err = pthread_create(&tid, NULL, &BackgroundJob::thread_func, this); if (err != 0) { log_fatal("can't create thread: %s", strerror(err)); exit(0); } } void BackgroundJob::stop() { thread_quit = true; for (int i = 0; i < 100; i++) { if (!thread_quit) { break; } usleep(10 * 1000); } } void BackgroundJob::loop(const BQueue<BTask> &queue) { BTask bTask = serv->bqueue.pop(); if (bTask.type > COMMAND_MAX) { log_error("unknown command %s", bTask.dump().c_str()); } if (bTask.retry > MAX_RETRY) { free(bTask.value); bTask.value = nullptr; log_error("max retry limit reached task %s ", bTask.dump().c_str()); return; } int64_t current = time_ms(); int res = bproc_map[bTask.type](serv, bTask.data_key, bTask.value); if (res != 0) { log_error("bg_job failed %s ", bTask.dump().c_str()); // if (res == -2) { // //retry when res == -2 // bTask.retry++; // serv->bqueue.push(bTask); // return; // } } avg_wait = ((current - bTask.ts) * 1.0 - avg_wait) * 1.0 / count * 1.0 + avg_wait; avg_process = ((time_ms() - current) * 1.0 - avg_process) * 1.0 / count * 1.0 + avg_process; count++; if (count > INT16_MAX) { count = 0; //reset count. } if ((current - last) > 2000) { size_t qsize = serv->bqueue.size(); last = time_ms(); if (qsize > 500) { log_error("BackgroundJob queue size is now : %d", qsize); } else if (qsize > 218) { log_warn("BackgroundJob queue size is now : %d", qsize); } else if (qsize > 36) { log_info("BackgroundJob queue size is now : %d", qsize); } else if (qsize > 6) { log_debug("BackgroundJob queue size is now : %d", qsize); } log_info("task avg wait %f ms", avg_wait); log_info("task avg process %f ms", avg_process); if ((current - bTask.ts) > 1000) { log_warn("task %s had waited %d ms", bTask.dump().c_str(), ((current - bTask.ts))); } } if (bTask.value != nullptr) { free(bTask.value); bTask.value = nullptr; } } int bproc_COMMAND_DATA_SAVE(SSDBServer *serv, const std::string &data_key, void *value) { DumpData *dumpData = (DumpData *) value; int64_t pttl = dumpData->expire; std::string val; int ret = serv->ssdb->restore(dumpData->key, dumpData->expire, dumpData->data, dumpData->replace, &val); if (ret < 0) { //notify failed return notifyFailedToRedis(serv->redisUpstream, "customized-dump", data_key); } if (ret > 0 && pttl > 0) { Locking l(&serv->expiration->mutex); ret = serv->expiration->expire(dumpData->key, pttl, TimeUnit::Millisecond); } if (ret < 0) { //notify failed serv->ssdb->del(dumpData->key); return notifyFailedToRedis(serv->redisUpstream, "customized-dump", data_key); } log_debug("[request2redis] : customized-del %s", hexstr<std::string>(dumpData->key).c_str()); std::vector<std::string> req = {"customized-del", data_key}; RedisResponse *t_res = serv->redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("[%s %s] redis response is null", req[0].c_str(), req[1].c_str()); //redis res failed return -1; } std::string res = t_res->toString(); delete t_res; return 0; } int notifyFailedToRedis(RedisUpstream *redisUpstream, std::string responseCommand, std::string dataKey) { std::vector<std::string> req = {"customized-fail", responseCommand, dataKey}; RedisResponse *t_res = redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("[%s %s %s] redis response is null", req[0].c_str(), req[1].c_str(), req[2].c_str()); //redis res failed return -1; } delete t_res; return -1; } int bproc_COMMAND_DATA_DUMP(SSDBServer *serv, const std::string &data_key, void *value) { std::string val; int ret = serv->ssdb->dump(data_key, &val); if (ret < 0) { //notify failed return notifyFailedToRedis(serv->redisUpstream, "customized-restore", data_key); } else if (ret == 0) { //notify key not found notifyFailedToRedis(serv->redisUpstream, "customized-restore", data_key); return 0; } else { int64_t pttl = serv->expiration->pttl(data_key, TimeUnit::Millisecond); if (pttl < 0) { pttl = 0; //not sure } log_debug("[request2redis] : customized-restore %s", data_key.c_str()); std::vector<std::string> req = {"customized-restore", data_key, str(pttl), val, "replace"}; RedisResponse *t_res = serv->redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("[%s %s] redis response is null", req[0].c_str(), req[1].c_str()); //redis res failed return -1; } if (t_res->isOk()) { serv->ssdb->del(data_key); } delete t_res; } return 0; } int bproc_COMMAND_SYNC_PREPARE1(SSDBServer *serv, const std::string &data_key, void *value) { std::vector<std::string> req = {"customized-sync1", "done"}; log_debug("[request2redis] : customized-sync1"); auto t_res = serv->redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("t_res is null"); return -1; } delete t_res; return 0; }<commit_msg>add redis response log<commit_after>#include <memory> #include <serv.h> #define MAX_RETRY 5 int notifyFailedToRedis(RedisUpstream *redisUpstream, std::string responseCommand, std::string dataKey); void BackgroundJob::regType() { REG_BPROC(COMMAND_DATA_SAVE); REG_BPROC(COMMAND_DATA_DUMP); REG_BPROC(COMMAND_SYNC_PREPARE1); } void *BackgroundJob::thread_func(void *arg) { BackgroundJob *backgroudJob = (BackgroundJob *) arg; while (!backgroudJob->thread_quit) { backgroudJob->loop(backgroudJob->serv->bqueue); } log_debug("BackgroundJob thread quit"); backgroudJob->thread_quit = false; return nullptr; } void BackgroundJob::start() { last = time_ms(); this->regType(); thread_quit = false; int err; pthread_t tid; err = pthread_create(&tid, NULL, &BackgroundJob::thread_func, this); if (err != 0) { log_fatal("can't create thread: %s", strerror(err)); exit(0); } } void BackgroundJob::stop() { thread_quit = true; for (int i = 0; i < 100; i++) { if (!thread_quit) { break; } usleep(10 * 1000); } } void BackgroundJob::loop(const BQueue<BTask> &queue) { BTask bTask = serv->bqueue.pop(); if (bTask.type > COMMAND_MAX) { log_error("unknown command %s", bTask.dump().c_str()); } if (bTask.retry > MAX_RETRY) { free(bTask.value); bTask.value = nullptr; log_error("max retry limit reached task %s ", bTask.dump().c_str()); return; } int64_t current = time_ms(); int res = bproc_map[bTask.type](serv, bTask.data_key, bTask.value); if (res != 0) { log_error("bg_job failed %s ", bTask.dump().c_str()); // if (res == -2) { // //retry when res == -2 // bTask.retry++; // serv->bqueue.push(bTask); // return; // } } avg_wait = ((current - bTask.ts) * 1.0 - avg_wait) * 1.0 / count * 1.0 + avg_wait; avg_process = ((time_ms() - current) * 1.0 - avg_process) * 1.0 / count * 1.0 + avg_process; count++; if (count > INT16_MAX) { count = 0; //reset count. } if ((current - last) > 2000) { size_t qsize = serv->bqueue.size(); last = time_ms(); if (qsize > 500) { log_error("BackgroundJob queue size is now : %d", qsize); } else if (qsize > 218) { log_warn("BackgroundJob queue size is now : %d", qsize); } else if (qsize > 36) { log_info("BackgroundJob queue size is now : %d", qsize); } else if (qsize > 6) { log_debug("BackgroundJob queue size is now : %d", qsize); } log_info("task avg wait %f ms", avg_wait); log_info("task avg process %f ms", avg_process); if ((current - bTask.ts) > 1000) { log_warn("task %s had waited %d ms", bTask.dump().c_str(), ((current - bTask.ts))); } } if (bTask.value != nullptr) { free(bTask.value); bTask.value = nullptr; } } int bproc_COMMAND_DATA_SAVE(SSDBServer *serv, const std::string &data_key, void *value) { DumpData *dumpData = (DumpData *) value; int64_t pttl = dumpData->expire; std::string val; int ret = serv->ssdb->restore(dumpData->key, dumpData->expire, dumpData->data, dumpData->replace, &val); if (ret < 0) { //notify failed return notifyFailedToRedis(serv->redisUpstream, "customized-dump", data_key); } if (ret > 0 && pttl > 0) { Locking l(&serv->expiration->mutex); ret = serv->expiration->expire(dumpData->key, pttl, TimeUnit::Millisecond); } if (ret < 0) { //notify failed serv->ssdb->del(dumpData->key); return notifyFailedToRedis(serv->redisUpstream, "customized-dump", data_key); } std::vector<std::string> req = {"customized-del", data_key}; log_debug("[request->redis] : %s %s", req[0].c_str(), req[1].c_str()); RedisResponse *t_res = serv->redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("[%s %s] redis response is null", req[0].c_str(), req[1].c_str()); //redis res failed return -1; } log_debug("[response<-redis] : %s %s %s", req[0].c_str(), req[1].c_str(), t_res->toString().c_str()); delete t_res; return 0; } int notifyFailedToRedis(RedisUpstream *redisUpstream, std::string responseCommand, std::string dataKey) { std::vector<std::string> req = {"customized-fail", responseCommand, dataKey}; log_debug("[request->redis] : %s %s %s", req[0].c_str(), req[1].c_str(), req[2].c_str()); RedisResponse *t_res = redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("[%s %s %s] redis response is null", req[0].c_str(), req[1].c_str(), req[2].c_str()); //redis res failed return -1; } log_debug("[response<-redis] : %s %s %s %s", req[0].c_str(), req[1].c_str(), req[2].c_str(), t_res->toString().c_str()); delete t_res; return -1; } int bproc_COMMAND_DATA_DUMP(SSDBServer *serv, const std::string &data_key, void *value) { std::string val; int ret = serv->ssdb->dump(data_key, &val); if (ret < 0) { //notify failed return notifyFailedToRedis(serv->redisUpstream, "customized-restore", data_key); } else if (ret == 0) { //notify key not found notifyFailedToRedis(serv->redisUpstream, "customized-restore", data_key); return 0; } else { int64_t pttl = serv->expiration->pttl(data_key, TimeUnit::Millisecond); if (pttl < 0) { pttl = 0; //not sure } std::vector<std::string> req = {"customized-restore", data_key, str(pttl), val, "replace"}; log_debug("[request->redis] : %s %s", req[0].c_str(), req[1].c_str()); RedisResponse *t_res = serv->redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("[%s %s] redis response is null", req[0].c_str(), req[1].c_str()); //redis res failed return -1; } log_debug("[response<-redis] : %s %s %s", req[0].c_str(), req[1].c_str(), t_res->toString().c_str()); if (t_res->isOk()) { serv->ssdb->del(data_key); } delete t_res; } return 0; } int bproc_COMMAND_SYNC_PREPARE1(SSDBServer *serv, const std::string &data_key, void *value) { std::vector<std::string> req = {"customized-sync1", "done"}; log_debug("[request->redis] : customized-sync1"); auto t_res = serv->redisUpstream->sendCommand(req); if (t_res == nullptr) { log_error("t_res is null"); return -1; } delete t_res; return 0; }<|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../include/pyext.h" #include <omp.h> #include <cstdio> using namespace std; void makeJPEG(PyObject* _py_list_src, int idx, int _target_size, bool _crop_to_square, PyObject* _py_list_tgt); static PyMethodDef _MakeDataPyExtMethods[] = {{ "resizeJPEG", resizeJPEG, METH_VARARGS }, { NULL, NULL } }; void init_MakeDataPyExt() { (void) Py_InitModule("_MakeDataPyExt", _MakeDataPyExtMethods); } PyObject* resizeJPEG(PyObject *self, PyObject *args) { PyListObject* pyListSrc; int tgtImgSize, numThreads; int cropToSquare; if (!PyArg_ParseTuple(args, "O!iii", &PyList_Type, &pyListSrc, &tgtImgSize, &numThreads, &cropToSquare)) { return NULL; } DecoderThread* threads[numThreads]; int num_imgs = PyList_GET_SIZE(pyListSrc); //int num_imgs_per_thread = DIVUP(num_imgs, numThreads); PyObject* pyListTgt = PyList_New(0); omp_set_num_threads(numThreads); #pragma omp parallel for for (int t = 0; t < num_imgs; ++t) { //int start_img = t * num_imgs_per_thread; //int end_img = min(num_imgs, (t+1) * num_imgs_per_thread); cout << "calling makeJPEG for " << t << " on worker " << omp_get_thread_num() << endl; makeJPEG((PyObject*)pyListSrc, t, tgtImgSize, cropToSquare, pyListTgt); //threads[t] = new DecoderThread((PyObject*)pyListSrc, start_img, end_img, tgtImgSize, cropToSquare); //threads[t]->start(); } /* PyObject* pyListTgt = PyList_New(0); #pragma omp parallel for for (int t = 0; t < numThreads; ++t) { threads[t]->join(); PyList_Append(pyListTgt, threads[t]->getTargetList()); delete threads[t]; // the thread's list too } */ return pyListTgt; } /* DecoderThread::DecoderThread(PyObject* py_list_src, int start_img, int end_img, int target_size, bool crop_to_square) : Thread(true), _py_list_src(py_list_src), _start_img(start_img), _end_img(end_img), _target_size(target_size), _crop_to_square(crop_to_square) { _encode_params.push_back(CV_IMWRITE_JPEG_QUALITY); _encode_params.push_back(JPEG_QUALITY); _py_list_tgt = PyList_New(0); } DecoderThread::~DecoderThread(){ Py_DECREF(_py_list_tgt); } void* DecoderThread::run() { for (int i = _start_img; i < _end_img; ++i) { makeJPEG(i); } return NULL; } PyObject* DecoderThread::getTargetList() { return _py_list_tgt; } */ void makeJPEG(PyObject* _py_list_src, int idx, int _target_size, bool _crop_to_square, PyObject* _py_list_tgt) { cv::Mat _resized_mat_buffer; std::vector<uchar> _output_jpeg_buffer; std::vector<int> _encode_params; _encode_params.push_back(CV_IMWRITE_JPEG_QUALITY); _encode_params.push_back(JPEG_QUALITY); /* * Decompress JPEG */ PyObject* pySrc = PyList_GET_ITEM(_py_list_src, idx); uchar* src = (unsigned char*)PyString_AsString(pySrc); size_t src_len = PyString_GET_SIZE(pySrc); vector<uchar> src_vec(src, src + src_len); cv::Mat decoded_mat = cv::imdecode(cv::Mat(src_vec), CV_LOAD_IMAGE_COLOR); assert(decoded_mat.channels() == 3); /* * Resize */ double min_dim = std::min(decoded_mat.size().height, decoded_mat.size().width); double scale_factor = _target_size / min_dim; int new_height = round(scale_factor * decoded_mat.size().height); int new_width = round(scale_factor * decoded_mat.size().width); assert((new_height == _target_size && new_width >= _target_size) || (new_width == _target_size && new_height >= _target_size)); int interpolation = scale_factor == 1 ? cv::INTER_LINEAR : scale_factor > 1 ? cv::INTER_CUBIC : cv::INTER_AREA; cv::resize(decoded_mat, _resized_mat_buffer, cv::Size(new_width, new_height), 0, 0, interpolation); /* * Conditionally crop and compress JPEG */ if (_crop_to_square) { int crop_start_x = (new_width - _target_size) / 2; int crop_start_y = (new_height - _target_size) / 2; cv::Rect cropRect(crop_start_x, crop_start_y, _target_size, _target_size); cv::Mat cropped_mat_buffer = _resized_mat_buffer(cropRect); cv::imencode(".jpg", cropped_mat_buffer, _output_jpeg_buffer, _encode_params); } else { cv::imencode(".jpg", _resized_mat_buffer, _output_jpeg_buffer, _encode_params); } char* output_jpeg_buffer_ptr = reinterpret_cast<char*>(&_output_jpeg_buffer[0]); PyObject* pyStr = PyString_FromStringAndSize(output_jpeg_buffer_ptr, _output_jpeg_buffer.size()); #pragma omp critical { PyList_Append(_py_list_tgt, pyStr); } Py_DECREF(pyStr); } <commit_msg>Remove print statements<commit_after>/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../include/pyext.h" #include <omp.h> using namespace std; void makeJPEG(PyObject* _py_list_src, int idx, int _target_size, bool _crop_to_square, PyObject* _py_list_tgt); static PyMethodDef _MakeDataPyExtMethods[] = {{ "resizeJPEG", resizeJPEG, METH_VARARGS }, { NULL, NULL } }; void init_MakeDataPyExt() { (void) Py_InitModule("_MakeDataPyExt", _MakeDataPyExtMethods); } PyObject* resizeJPEG(PyObject *self, PyObject *args) { PyListObject* pyListSrc; int tgtImgSize, numThreads; int cropToSquare; if (!PyArg_ParseTuple(args, "O!iii", &PyList_Type, &pyListSrc, &tgtImgSize, &numThreads, &cropToSquare)) { return NULL; } DecoderThread* threads[numThreads]; int num_imgs = PyList_GET_SIZE(pyListSrc); //int num_imgs_per_thread = DIVUP(num_imgs, numThreads); PyObject* pyListTgt = PyList_New(0); omp_set_num_threads(numThreads); #pragma omp parallel for for (int t = 0; t < num_imgs; ++t) { //int start_img = t * num_imgs_per_thread; //int end_img = min(num_imgs, (t+1) * num_imgs_per_thread); makeJPEG((PyObject*)pyListSrc, t, tgtImgSize, cropToSquare, pyListTgt); //threads[t] = new DecoderThread((PyObject*)pyListSrc, start_img, end_img, tgtImgSize, cropToSquare); //threads[t]->start(); } /* PyObject* pyListTgt = PyList_New(0); #pragma omp parallel for for (int t = 0; t < numThreads; ++t) { threads[t]->join(); PyList_Append(pyListTgt, threads[t]->getTargetList()); delete threads[t]; // the thread's list too } */ return pyListTgt; } /* DecoderThread::DecoderThread(PyObject* py_list_src, int start_img, int end_img, int target_size, bool crop_to_square) : Thread(true), _py_list_src(py_list_src), _start_img(start_img), _end_img(end_img), _target_size(target_size), _crop_to_square(crop_to_square) { _encode_params.push_back(CV_IMWRITE_JPEG_QUALITY); _encode_params.push_back(JPEG_QUALITY); _py_list_tgt = PyList_New(0); } DecoderThread::~DecoderThread(){ Py_DECREF(_py_list_tgt); } void* DecoderThread::run() { for (int i = _start_img; i < _end_img; ++i) { makeJPEG(i); } return NULL; } PyObject* DecoderThread::getTargetList() { return _py_list_tgt; } */ void makeJPEG(PyObject* _py_list_src, int idx, int _target_size, bool _crop_to_square, PyObject* _py_list_tgt) { cv::Mat _resized_mat_buffer; std::vector<uchar> _output_jpeg_buffer; std::vector<int> _encode_params; _encode_params.push_back(CV_IMWRITE_JPEG_QUALITY); _encode_params.push_back(JPEG_QUALITY); /* * Decompress JPEG */ PyObject* pySrc = PyList_GET_ITEM(_py_list_src, idx); uchar* src = (unsigned char*)PyString_AsString(pySrc); size_t src_len = PyString_GET_SIZE(pySrc); vector<uchar> src_vec(src, src + src_len); cv::Mat decoded_mat = cv::imdecode(cv::Mat(src_vec), CV_LOAD_IMAGE_COLOR); assert(decoded_mat.channels() == 3); /* * Resize */ double min_dim = std::min(decoded_mat.size().height, decoded_mat.size().width); double scale_factor = _target_size / min_dim; int new_height = round(scale_factor * decoded_mat.size().height); int new_width = round(scale_factor * decoded_mat.size().width); assert((new_height == _target_size && new_width >= _target_size) || (new_width == _target_size && new_height >= _target_size)); int interpolation = scale_factor == 1 ? cv::INTER_LINEAR : scale_factor > 1 ? cv::INTER_CUBIC : cv::INTER_AREA; cv::resize(decoded_mat, _resized_mat_buffer, cv::Size(new_width, new_height), 0, 0, interpolation); /* * Conditionally crop and compress JPEG */ if (_crop_to_square) { int crop_start_x = (new_width - _target_size) / 2; int crop_start_y = (new_height - _target_size) / 2; cv::Rect cropRect(crop_start_x, crop_start_y, _target_size, _target_size); cv::Mat cropped_mat_buffer = _resized_mat_buffer(cropRect); cv::imencode(".jpg", cropped_mat_buffer, _output_jpeg_buffer, _encode_params); } else { cv::imencode(".jpg", _resized_mat_buffer, _output_jpeg_buffer, _encode_params); } char* output_jpeg_buffer_ptr = reinterpret_cast<char*>(&_output_jpeg_buffer[0]); PyObject* pyStr = PyString_FromStringAndSize(output_jpeg_buffer_ptr, _output_jpeg_buffer.size()); #pragma omp critical { PyList_Append(_py_list_tgt, pyStr); } Py_DECREF(pyStr); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_popup_view.h" #include "base/logging.h" #include "chrome/browser/autofill/autofill_external_delegate.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" namespace { // Used to indicate that no line is currently selected by the user. const int kNoSelection = -1; } // end namespace AutofillPopupView::AutofillPopupView( content::WebContents* web_contents, AutofillExternalDelegate* external_delegate) : external_delegate_(external_delegate), selected_line_(kNoSelection) { if (!web_contents) return; registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_HIDDEN, content::Source<content::WebContents>(web_contents)); registrar_.Add( this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<content::NavigationController>( &(web_contents->GetController()))); } AutofillPopupView::~AutofillPopupView() {} void AutofillPopupView::Hide() { HideInternal(); external_delegate_->ClearPreviewedForm(); } void AutofillPopupView::Show(const std::vector<string16>& autofill_values, const std::vector<string16>& autofill_labels, const std::vector<string16>& autofill_icons, const std::vector<int>& autofill_unique_ids, int separator_index) { autofill_values_ = autofill_values; autofill_labels_ = autofill_labels; autofill_icons_ = autofill_icons; autofill_unique_ids_ = autofill_unique_ids; separator_index_ = separator_index; ShowInternal(); } void AutofillPopupView::SetSelectedLine(int selected_line) { if (selected_line_ == selected_line) return; if (selected_line_ != kNoSelection) InvalidateRow(selected_line_); if (selected_line != kNoSelection) InvalidateRow(selected_line); selected_line_ = selected_line; if (selected_line_ != kNoSelection) { external_delegate_->SelectAutofillSuggestionAtIndex( autofill_unique_ids_[selected_line_], selected_line); } } void AutofillPopupView::SelectNextLine() { int new_selected_line = selected_line_ + 1; if (new_selected_line == static_cast<int>(autofill_values_.size())) new_selected_line = 0; SetSelectedLine(new_selected_line); } void AutofillPopupView::SelectPreviousLine() { int new_selected_line = selected_line_ - 1; if (new_selected_line <= kNoSelection) new_selected_line = autofill_values_.size() - 1; SetSelectedLine(new_selected_line); } bool AutofillPopupView::AcceptSelectedLine() { if (selected_line_ == kNoSelection) return false; DCHECK_GE(selected_line_, 0); DCHECK_LT(selected_line_, static_cast<int>(autofill_values_.size())); return external_delegate()->DidAcceptAutofillSuggestions( autofill_values_[selected_line_], autofill_unique_ids_[selected_line_], selected_line_); } bool AutofillPopupView::RemoveSelectedLine() { if (selected_line_ == kNoSelection) return false; // TODO(csharp) add removal code. return false; } void AutofillPopupView::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_WEB_CONTENTS_HIDDEN || type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) Hide(); } <commit_msg>[Coverity] Fix uninitialized member<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_popup_view.h" #include "base/logging.h" #include "chrome/browser/autofill/autofill_external_delegate.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" namespace { // Used to indicate that no line is currently selected by the user. const int kNoSelection = -1; } // end namespace AutofillPopupView::AutofillPopupView( content::WebContents* web_contents, AutofillExternalDelegate* external_delegate) : external_delegate_(external_delegate), separator_index_(0), selected_line_(kNoSelection) { if (!web_contents) return; registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_HIDDEN, content::Source<content::WebContents>(web_contents)); registrar_.Add( this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<content::NavigationController>( &(web_contents->GetController()))); } AutofillPopupView::~AutofillPopupView() {} void AutofillPopupView::Hide() { HideInternal(); external_delegate_->ClearPreviewedForm(); } void AutofillPopupView::Show(const std::vector<string16>& autofill_values, const std::vector<string16>& autofill_labels, const std::vector<string16>& autofill_icons, const std::vector<int>& autofill_unique_ids, int separator_index) { autofill_values_ = autofill_values; autofill_labels_ = autofill_labels; autofill_icons_ = autofill_icons; autofill_unique_ids_ = autofill_unique_ids; separator_index_ = separator_index; ShowInternal(); } void AutofillPopupView::SetSelectedLine(int selected_line) { if (selected_line_ == selected_line) return; if (selected_line_ != kNoSelection) InvalidateRow(selected_line_); if (selected_line != kNoSelection) InvalidateRow(selected_line); selected_line_ = selected_line; if (selected_line_ != kNoSelection) { external_delegate_->SelectAutofillSuggestionAtIndex( autofill_unique_ids_[selected_line_], selected_line); } } void AutofillPopupView::SelectNextLine() { int new_selected_line = selected_line_ + 1; if (new_selected_line == static_cast<int>(autofill_values_.size())) new_selected_line = 0; SetSelectedLine(new_selected_line); } void AutofillPopupView::SelectPreviousLine() { int new_selected_line = selected_line_ - 1; if (new_selected_line <= kNoSelection) new_selected_line = autofill_values_.size() - 1; SetSelectedLine(new_selected_line); } bool AutofillPopupView::AcceptSelectedLine() { if (selected_line_ == kNoSelection) return false; DCHECK_GE(selected_line_, 0); DCHECK_LT(selected_line_, static_cast<int>(autofill_values_.size())); return external_delegate()->DidAcceptAutofillSuggestions( autofill_values_[selected_line_], autofill_unique_ids_[selected_line_], selected_line_); } bool AutofillPopupView::RemoveSelectedLine() { if (selected_line_ == kNoSelection) return false; // TODO(csharp) add removal code. return false; } void AutofillPopupView::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_WEB_CONTENTS_HIDDEN || type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) Hide(); } <|endoftext|>
<commit_before> #include "anumber.h" /* BaseTimesInt : multiply a with one digit in the range 0..(aBase-1) */ template<class T> inline void BaseTimesInt(T& a,PlatDoubleWord aNumber, PlatDoubleWord aBase) { PlatDoubleWord carry=0; LispInt i; LispInt nr=a.size(); typename T::value_type * aptr = &a[0]; for (i=0;i<nr;i++) { PlatDoubleWord word = ((PlatDoubleWord)(*aptr))*aNumber+carry; PlatWord digit = (PlatWord)(word % aBase); PlatWord newCarry= (PlatWord)(word / aBase); *aptr = digit; aptr++; carry= newCarry; } if (carry) { a.push_back((typename T::value_type)carry); carry = 0; } assert(carry == 0); } template<class T> inline void WordBaseTimesInt(T& a,PlatDoubleWord aNumber) { PlatDoubleWord carry=0; LispInt i; LispInt nr=a.size(); typename T::value_type * aptr = &a[0]; for (i=0;i<nr;i++) { PlatDoubleWord word = ((PlatDoubleWord)(*aptr))*aNumber+carry; PlatWord digit = (PlatWord)(word); PlatWord newCarry= (PlatWord)(word >> WordBits); *aptr = digit; aptr++; carry= newCarry; } if (carry) { a.push_back((typename T::value_type)carry); carry = 0; } assert(carry == 0); } template<class T> inline void BaseDivideInt(T& a,PlatDoubleWord aNumber, PlatDoubleWord aBase, PlatDoubleWord& aCarry) { // if (a[a.size()-1] != 0) PlatDoubleWord carry=0; LispInt i; LispInt nr=a.size(); typename T::value_type * aptr = &a[0]; for (i=nr-1;i>=0;i--) { PlatDoubleWord word = ((carry*aBase)+((PlatDoubleWord)(aptr[i]))); PlatWord digit = (PlatWord)(word / aNumber); PlatWord newCarry= (PlatWord)(word % aNumber); aptr[i] = digit; carry= newCarry; } //carry now is the remainder aCarry = carry; } /* GrowDigits : add digits to a until it has aDigits digits */ template<class T> inline void GrowDigits(T& a,LispInt aDigits) { LispInt i; if (aDigits <= a.size()) return; /* LispInt nrToAdd = aDigits-a.size(); for (i=0;i<nrToAdd;i++) a.push_back(0); */ LispInt origSize = a.size(); a.resize(aDigits); //a.resize(aDigits); if (aDigits<=origSize) return; typename T::value_type* ptr = &a[origSize]; for (i=origSize;i<aDigits;i++) *ptr++ = 0; } /* BaseAdd : destructively add aSource to aTarget, in base aBase. */ template<class T> inline void BaseAdd(T& aTarget, const T& aSource, PlatDoubleWord aBase) { // Initialize result GrowDigits(aTarget,aSource.size()); aTarget.push_back(0); LispInt nr1 = aTarget.size(); LispInt nr2 = aSource.size(); LispInt nr; // nr represents min(nr1,nr2), the number of digits to add if (nr1>nr2) nr=nr2; else nr=nr1; PlatDoubleWord carry=0; LispInt digit; const typename T::value_type * sourcePtr = &aSource[0]; typename T::value_type * targetPtr = &aTarget[0]; for (digit=0;digit<nr;digit++) { PlatDoubleWord word; word = (PlatDoubleWord)targetPtr[digit] + (PlatDoubleWord)sourcePtr[digit] + carry; PlatDoubleWord newDigit = (word%aBase); PlatDoubleWord newCarry = (word/aBase); targetPtr[digit] = (typename T::value_type)newDigit; carry = newCarry; } while (carry != 0) { PlatSignedDoubleWord ww = targetPtr[nr]; ww+=carry; targetPtr[nr] = (typename T::value_type)(ww%aBase); // PDG - cast to avoid compile-time warning carry = ww/aBase; nr++; } } template<class T> inline void WordBaseAdd(T& aTarget, const T& aSource) { // Initialize result GrowDigits(aTarget,aSource.size()); aTarget.push_back(0); LispInt nr1 = aTarget.size(); LispInt nr2 = aSource.size(); LispInt nr; // nr represents min(nr1,nr2), the number of digits to add if (nr1>nr2) nr=nr2; else nr=nr1; PlatDoubleWord carry=0; LispInt digit; const typename T::value_type * sourcePtr = &aSource[0]; typename T::value_type * targetPtr = &aTarget[0]; for (digit=0;digit<nr;digit++) { PlatDoubleWord word; word = (PlatDoubleWord)targetPtr[digit] + (PlatDoubleWord)sourcePtr[digit] + carry; PlatWord newDigit = (PlatWord)(word); PlatWord newCarry = (PlatWord)(word >> WordBits); targetPtr[digit] = (typename T::value_type)newDigit; carry = newCarry; } while (carry != 0) { PlatSignedDoubleWord ww = targetPtr[nr]; ww+=carry; targetPtr[nr] = (typename T::value_type)ww; // PDG - cast to avoid compile-time warning carry = ww >> WordBits; nr++; } } template<class T> inline void BaseSubtract(T& aResult, T& a2, LispInt offset) { if (a2.IsZero()) return; // Initialize result LispInt nr = a2.size(); typename T::value_type * resultPtr = &aResult[0]; typename T::value_type * a2ptr = &a2[0]; while (a2ptr[nr-1] == 0) nr--; // Subtract on a per-digit basis PlatSignedDoubleWord carry=0; LispInt digit; for (digit=0;digit<nr;digit++) { PlatSignedDoubleWord word; word = ((PlatSignedDoubleWord)resultPtr[digit+offset]) - ((PlatSignedDoubleWord)a2ptr[digit]) + (PlatSignedDoubleWord)carry; carry=0; while (word<0) { word+=WordBase; carry--; } resultPtr[digit+offset] = ((PlatWord)(word)); } while (carry != 0) { assert(nr+offset<aResult.size()); LispInt newCarry = 0; PlatSignedDoubleWord ww = resultPtr[nr+offset]+carry; while (ww<0) { ww = ww + WordBase; newCarry = newCarry - 1; } resultPtr[nr+offset]=(typename T::value_type)ww; carry = newCarry; offset++; } } /* BaseIntNumber : convert a number into a different base, */ inline void BaseIntNumber(std::string& aTarget, PlatSignedDoubleWord aNumber, PlatWord aBase) { // Assume aBase is an integer > 0. // Assume aNumber is an integer > 0. // Assume PlatDoubleWord is an integer type. // Will maximum digit (i.e., aBase-1) convert to T::value_type right? //LISPASSERT( (typename T::value_type)(aBase) == (aBase) ); // use aBase instead, to help CTCE aTarget.resize(0); while (aNumber != 0) { PlatDoubleWord digit = aNumber%aBase; aTarget.push_back((LispString::value_type)(digit)); aNumber/=aBase; } if (aTarget.size() == 0) aTarget.push_back(0); } // BaseAddMultiply : multiply x and y, and add result to aTarget // inline void BaseAddMultiply(std::string& aTarget, std::string& x, std::string& y, PlatDoubleWord aBase) { LispInt nrx=x.size(); LispInt nry=y.size(); GrowDigits(aTarget,nrx+nry+1); LispInt ix,iy; std::string::value_type *targetPtr = &aTarget[0]; std::string::value_type *xPtr = &x[0]; std::string::value_type *yPtr = &y[0]; for (ix=0;ix<nrx;ix++) { PlatDoubleWord carry = 0; for (iy=0;iy<nry;iy++) { PlatDoubleWord word = static_cast<PlatDoubleWord>(targetPtr[ix+iy])+ static_cast<PlatDoubleWord>(xPtr[ix])* static_cast<PlatDoubleWord>(yPtr[iy])+carry; // This calculates aTarget[ix+iy]+x[ix]*y[iy]+carry; targetPtr[ix+iy] = (LispString::value_type)(word % aBase); carry = word / aBase; } targetPtr[ix+nry] += (LispString::value_type)(carry); } } template<class T> inline void WordBaseAddMultiply(T& aTarget, T& x, T& y) { LispInt nrx=x.size(); LispInt nry=y.size(); GrowDigits(aTarget,nrx+nry+1); LispInt ix,iy; typename T::value_type *targetPtr = &aTarget[0]; typename T::value_type *xPtr = &x[0]; typename T::value_type *yPtr = &y[0]; for (ix=0;ix<nrx;ix++) { PlatDoubleWord carry = 0; for (iy=0;iy<nry;iy++) { PlatDoubleWord word = static_cast<PlatDoubleWord>(targetPtr[ix+iy])+ static_cast<PlatDoubleWord>(xPtr[ix])* static_cast<PlatDoubleWord>(yPtr[iy])+carry; // This calculates aTarget[ix+iy]+x[ix]*y[iy]+carry; targetPtr[ix+iy] = (typename T::value_type)(word); carry = word >> WordBits; } { PlatDoubleWord word = static_cast<PlatDoubleWord>(targetPtr[ix+nry])+carry; targetPtr[ix+nry] = (typename T::value_type)(word); carry = word >> WordBits; assert(carry == 0); // targetPtr[ix+nry] += (typename T::value_type)(carry); } } } /* BaseMultiply : multiply x and y, and put result in aTarget */ template<class T> inline void BaseMultiply(T& aTarget, T& x, T& y, PlatDoubleWord aBase) { aTarget.resize(1); aTarget[0] = 0; BaseAddMultiply(aTarget, x, y, aBase); } template<class T> inline void WordBaseMultiply(T& aTarget, T& x, T& y) { aTarget.resize(1); aTarget[0] = 0; WordBaseAddMultiply(aTarget, x, y); } template<class T> inline bool IsZero(T& a) { register typename T::value_type *ptr = &a[0]; register typename T::value_type *endptr = ptr+a.size(); while (ptr != endptr) { if (*ptr++ != 0) return false; } return true; } template<class T> inline void WordBaseDivide(T& aQuotient, T& aRemainder, T& a1, T& a2) { // Find the values n and m as described in Knuth II: LispInt n,m; n=a2.size(); assert(n>0); assert(a2[n-1] != 0); //a1.size() = m+n => m = a1.size()-n m = a1.size()-n; assert(m>=0); aQuotient.resize(m+1); //D1: //this calculates d = base/(a2[n-1]+1); PlatDoubleWord d = WordBase/(static_cast<PlatDoubleWord>(a2[n-1])+1); WordBaseTimesInt(a1, d); WordBaseTimesInt(a2, d); a1.push_back(0); a2.push_back(0); //D2: LispInt j = m; while (j>=0) { //D3: PlatDoubleWord q = (a1[j+n]*WordBase+a1[j+n-1])/a2[n-1]; PlatDoubleWord r = (a1[j+n]*WordBase+a1[j+n-1])%a2[n-1]; REDO: if (q == WordBase || q*a2[n-2] > WordBase*r+a1[j+n-2]) { q = q - 1; r = r + a2[n-1]; if (r < WordBase) goto REDO; } //D4: ANumber sub(aQuotient.Precision()); sub.CopyFrom(a2); WordBaseTimesInt(sub, q); sub.push_back(0); PlatSignedDoubleWord carry; LispInt digit; {//Subtract the two //TODO this can be generalized!!!! // // Beware though: this is not a normal subtraction. Only a // certain set of digits ends up being subtracted. // First check if qv isn't too big... carry = 0; for (digit=0;digit<=n;digit++) { PlatSignedDoubleWord word; word = ((PlatSignedDoubleWord)a1[digit+j]) - ((PlatSignedDoubleWord)sub[digit]) + (PlatSignedDoubleWord)carry; carry=0; while (word<0) { word+=WordBase; carry--; } } if (carry) { q--; sub.CopyFrom(a2); WordBaseTimesInt(sub, q); sub.push_back(0); } carry = 0; for (digit=0;digit<=n;digit++) { PlatSignedDoubleWord word; word = ((PlatSignedDoubleWord)a1[digit+j]) - ((PlatSignedDoubleWord)sub[digit]) + (PlatSignedDoubleWord)carry; carry=0; while (word<0) { word+=WordBase; carry--; } a1[digit+j] = ((PlatWord)(word)); } } assert(carry == 0); //D5: aQuotient[j] = (typename T::value_type)q; //D7: j--; } //D8: a1.resize(n); PlatDoubleWord carry; BaseDivideInt(a1, d, WordBase,carry); aRemainder.CopyFrom(a1); } inline void ANumber::Expand() { while (iExp+1>LispInt(size())) push_back(0); }<commit_msg>minor cleanup<commit_after> #include "anumber.h" /* BaseTimesInt : multiply a with one digit in the range 0..(aBase-1) */ template<class T> inline void BaseTimesInt(T& a,PlatDoubleWord aNumber, PlatDoubleWord aBase) { PlatDoubleWord carry=0; LispInt i; LispInt nr=a.size(); typename T::value_type * aptr = &a[0]; for (i=0;i<nr;i++) { PlatDoubleWord word = ((PlatDoubleWord)(*aptr))*aNumber+carry; PlatWord digit = (PlatWord)(word % aBase); PlatWord newCarry= (PlatWord)(word / aBase); *aptr = digit; aptr++; carry= newCarry; } if (carry) { a.push_back((typename T::value_type)carry); carry = 0; } assert(carry == 0); } template<class T> inline void WordBaseTimesInt(T& a,PlatDoubleWord aNumber) { PlatDoubleWord carry=0; LispInt i; LispInt nr=a.size(); typename T::value_type * aptr = &a[0]; for (i=0;i<nr;i++) { PlatDoubleWord word = ((PlatDoubleWord)(*aptr))*aNumber+carry; PlatWord digit = (PlatWord)(word); PlatWord newCarry= (PlatWord)(word >> WordBits); *aptr = digit; aptr++; carry= newCarry; } if (carry) { a.push_back((typename T::value_type)carry); carry = 0; } assert(carry == 0); } template<class T> inline void BaseDivideInt(T& a,PlatDoubleWord aNumber, PlatDoubleWord aBase, PlatDoubleWord& aCarry) { // if (a[a.size()-1] != 0) PlatDoubleWord carry=0; LispInt i; LispInt nr=a.size(); typename T::value_type * aptr = &a[0]; for (i=nr-1;i>=0;i--) { PlatDoubleWord word = ((carry*aBase)+((PlatDoubleWord)(aptr[i]))); PlatWord digit = (PlatWord)(word / aNumber); PlatWord newCarry= (PlatWord)(word % aNumber); aptr[i] = digit; carry= newCarry; } //carry now is the remainder aCarry = carry; } /* GrowDigits : add digits to a until it has aDigits digits */ template<class T> inline void GrowDigits(T& a, std::size_t aDigits) { if (aDigits <= a.size()) return; a.resize(aDigits, 0); } /* BaseAdd : destructively add aSource to aTarget, in base aBase. */ template<class T> inline void BaseAdd(T& aTarget, const T& aSource, PlatDoubleWord aBase) { // Initialize result GrowDigits(aTarget,aSource.size()); aTarget.push_back(0); LispInt nr1 = aTarget.size(); LispInt nr2 = aSource.size(); LispInt nr; // nr represents min(nr1,nr2), the number of digits to add if (nr1>nr2) nr=nr2; else nr=nr1; PlatDoubleWord carry=0; LispInt digit; const typename T::value_type * sourcePtr = &aSource[0]; typename T::value_type * targetPtr = &aTarget[0]; for (digit=0;digit<nr;digit++) { PlatDoubleWord word; word = (PlatDoubleWord)targetPtr[digit] + (PlatDoubleWord)sourcePtr[digit] + carry; PlatDoubleWord newDigit = (word%aBase); PlatDoubleWord newCarry = (word/aBase); targetPtr[digit] = (typename T::value_type)newDigit; carry = newCarry; } while (carry != 0) { PlatSignedDoubleWord ww = targetPtr[nr]; ww+=carry; targetPtr[nr] = (typename T::value_type)(ww%aBase); // PDG - cast to avoid compile-time warning carry = ww/aBase; nr++; } } template<class T> inline void WordBaseAdd(T& aTarget, const T& aSource) { // Initialize result GrowDigits(aTarget,aSource.size()); aTarget.push_back(0); LispInt nr1 = aTarget.size(); LispInt nr2 = aSource.size(); LispInt nr; // nr represents min(nr1,nr2), the number of digits to add if (nr1>nr2) nr=nr2; else nr=nr1; PlatDoubleWord carry=0; LispInt digit; const typename T::value_type * sourcePtr = &aSource[0]; typename T::value_type * targetPtr = &aTarget[0]; for (digit=0;digit<nr;digit++) { PlatDoubleWord word; word = (PlatDoubleWord)targetPtr[digit] + (PlatDoubleWord)sourcePtr[digit] + carry; PlatWord newDigit = (PlatWord)(word); PlatWord newCarry = (PlatWord)(word >> WordBits); targetPtr[digit] = (typename T::value_type)newDigit; carry = newCarry; } while (carry != 0) { PlatSignedDoubleWord ww = targetPtr[nr]; ww+=carry; targetPtr[nr] = (typename T::value_type)ww; // PDG - cast to avoid compile-time warning carry = ww >> WordBits; nr++; } } template<class T> inline void BaseSubtract(T& aResult, T& a2, LispInt offset) { if (a2.IsZero()) return; // Initialize result LispInt nr = a2.size(); typename T::value_type * resultPtr = &aResult[0]; typename T::value_type * a2ptr = &a2[0]; while (a2ptr[nr-1] == 0) nr--; // Subtract on a per-digit basis PlatSignedDoubleWord carry=0; LispInt digit; for (digit=0;digit<nr;digit++) { PlatSignedDoubleWord word; word = ((PlatSignedDoubleWord)resultPtr[digit+offset]) - ((PlatSignedDoubleWord)a2ptr[digit]) + (PlatSignedDoubleWord)carry; carry=0; while (word<0) { word+=WordBase; carry--; } resultPtr[digit+offset] = ((PlatWord)(word)); } while (carry != 0) { assert(nr+offset<aResult.size()); LispInt newCarry = 0; PlatSignedDoubleWord ww = resultPtr[nr+offset]+carry; while (ww<0) { ww = ww + WordBase; newCarry = newCarry - 1; } resultPtr[nr+offset]=(typename T::value_type)ww; carry = newCarry; offset++; } } /* BaseIntNumber : convert a number into a different base, */ inline void BaseIntNumber(std::string& aTarget, PlatSignedDoubleWord aNumber, PlatWord aBase) { // Assume aBase is an integer > 0. // Assume aNumber is an integer > 0. // Assume PlatDoubleWord is an integer type. // Will maximum digit (i.e., aBase-1) convert to T::value_type right? //LISPASSERT( (typename T::value_type)(aBase) == (aBase) ); // use aBase instead, to help CTCE aTarget.resize(0); while (aNumber != 0) { PlatDoubleWord digit = aNumber%aBase; aTarget.push_back((LispString::value_type)(digit)); aNumber/=aBase; } if (aTarget.size() == 0) aTarget.push_back(0); } // BaseAddMultiply : multiply x and y, and add result to aTarget // inline void BaseAddMultiply(std::string& aTarget, std::string& x, std::string& y, PlatDoubleWord aBase) { LispInt nrx=x.size(); LispInt nry=y.size(); GrowDigits(aTarget,nrx+nry+1); LispInt ix,iy; std::string::value_type *targetPtr = &aTarget[0]; std::string::value_type *xPtr = &x[0]; std::string::value_type *yPtr = &y[0]; for (ix=0;ix<nrx;ix++) { PlatDoubleWord carry = 0; for (iy=0;iy<nry;iy++) { PlatDoubleWord word = static_cast<PlatDoubleWord>(targetPtr[ix+iy])+ static_cast<PlatDoubleWord>(xPtr[ix])* static_cast<PlatDoubleWord>(yPtr[iy])+carry; // This calculates aTarget[ix+iy]+x[ix]*y[iy]+carry; targetPtr[ix+iy] = (LispString::value_type)(word % aBase); carry = word / aBase; } targetPtr[ix+nry] += (LispString::value_type)(carry); } } template<class T> inline void WordBaseAddMultiply(T& aTarget, T& x, T& y) { LispInt nrx=x.size(); LispInt nry=y.size(); GrowDigits(aTarget,nrx+nry+1); LispInt ix,iy; typename T::value_type *targetPtr = &aTarget[0]; typename T::value_type *xPtr = &x[0]; typename T::value_type *yPtr = &y[0]; for (ix=0;ix<nrx;ix++) { PlatDoubleWord carry = 0; for (iy=0;iy<nry;iy++) { PlatDoubleWord word = static_cast<PlatDoubleWord>(targetPtr[ix+iy])+ static_cast<PlatDoubleWord>(xPtr[ix])* static_cast<PlatDoubleWord>(yPtr[iy])+carry; // This calculates aTarget[ix+iy]+x[ix]*y[iy]+carry; targetPtr[ix+iy] = (typename T::value_type)(word); carry = word >> WordBits; } { PlatDoubleWord word = static_cast<PlatDoubleWord>(targetPtr[ix+nry])+carry; targetPtr[ix+nry] = (typename T::value_type)(word); carry = word >> WordBits; assert(carry == 0); // targetPtr[ix+nry] += (typename T::value_type)(carry); } } } /* BaseMultiply : multiply x and y, and put result in aTarget */ template<class T> inline void BaseMultiply(T& aTarget, T& x, T& y, PlatDoubleWord aBase) { aTarget.resize(1); aTarget[0] = 0; BaseAddMultiply(aTarget, x, y, aBase); } template<class T> inline void WordBaseMultiply(T& aTarget, T& x, T& y) { aTarget.resize(1); aTarget[0] = 0; WordBaseAddMultiply(aTarget, x, y); } template<class T> inline bool IsZero(T& a) { register typename T::value_type *ptr = &a[0]; register typename T::value_type *endptr = ptr+a.size(); while (ptr != endptr) { if (*ptr++ != 0) return false; } return true; } template<class T> inline void WordBaseDivide(T& aQuotient, T& aRemainder, T& a1, T& a2) { // Find the values n and m as described in Knuth II: LispInt n,m; n=a2.size(); assert(n>0); assert(a2[n-1] != 0); //a1.size() = m+n => m = a1.size()-n m = a1.size()-n; assert(m>=0); aQuotient.resize(m+1); //D1: //this calculates d = base/(a2[n-1]+1); PlatDoubleWord d = WordBase/(static_cast<PlatDoubleWord>(a2[n-1])+1); WordBaseTimesInt(a1, d); WordBaseTimesInt(a2, d); a1.push_back(0); a2.push_back(0); //D2: LispInt j = m; while (j>=0) { //D3: PlatDoubleWord q = (a1[j+n]*WordBase+a1[j+n-1])/a2[n-1]; PlatDoubleWord r = (a1[j+n]*WordBase+a1[j+n-1])%a2[n-1]; REDO: if (q == WordBase || q*a2[n-2] > WordBase*r+a1[j+n-2]) { q = q - 1; r = r + a2[n-1]; if (r < WordBase) goto REDO; } //D4: ANumber sub(aQuotient.Precision()); sub.CopyFrom(a2); WordBaseTimesInt(sub, q); sub.push_back(0); PlatSignedDoubleWord carry; LispInt digit; {//Subtract the two //TODO this can be generalized!!!! // // Beware though: this is not a normal subtraction. Only a // certain set of digits ends up being subtracted. // First check if qv isn't too big... carry = 0; for (digit=0;digit<=n;digit++) { PlatSignedDoubleWord word; word = ((PlatSignedDoubleWord)a1[digit+j]) - ((PlatSignedDoubleWord)sub[digit]) + (PlatSignedDoubleWord)carry; carry=0; while (word<0) { word+=WordBase; carry--; } } if (carry) { q--; sub.CopyFrom(a2); WordBaseTimesInt(sub, q); sub.push_back(0); } carry = 0; for (digit=0;digit<=n;digit++) { PlatSignedDoubleWord word; word = ((PlatSignedDoubleWord)a1[digit+j]) - ((PlatSignedDoubleWord)sub[digit]) + (PlatSignedDoubleWord)carry; carry=0; while (word<0) { word+=WordBase; carry--; } a1[digit+j] = ((PlatWord)(word)); } } assert(carry == 0); //D5: aQuotient[j] = (typename T::value_type)q; //D7: j--; } //D8: a1.resize(n); PlatDoubleWord carry; BaseDivideInt(a1, d, WordBase,carry); aRemainder.CopyFrom(a1); } inline void ANumber::Expand() { while (iExp+1>LispInt(size())) push_back(0); }<|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/update_screen.h" #include "base/file_util.h" #include "base/logging.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "content/browser/browser_thread.h" namespace { // Progress bar stages. Each represents progress bar value // at the beginning of each stage. // TODO(nkostylev): Base stage progress values on approximate time. // TODO(nkostylev): Animate progress during each state. const int kBeforeUpdateCheckProgress = 7; const int kBeforeDownloadProgress = 14; const int kBeforeVerifyingProgress = 74; const int kBeforeFinalizingProgress = 81; const int kProgressComplete = 100; // Defines what part of update progress does download part takes. const int kDownloadProgressIncrement = 60; // Considering 10px shadow from each side. const int kUpdateScreenWidth = 580; const int kUpdateScreenHeight = 305; const char kUpdateDeadlineFile[] = "/tmp/update-check-response-deadline"; } // anonymous namespace namespace chromeos { // static UpdateScreen::InstanceSet& UpdateScreen::GetInstanceSet() { static std::set<UpdateScreen*> instance_set; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // not threadsafe. return instance_set; } // static bool UpdateScreen::HasInstance(UpdateScreen* inst) { InstanceSet& instance_set = GetInstanceSet(); InstanceSet::iterator found = instance_set.find(inst); return (found != instance_set.end()); } UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : DefaultViewScreen<chromeos::UpdateView>(delegate, kUpdateScreenWidth, kUpdateScreenHeight), checking_for_update_(true), reboot_check_delay_(0), is_downloading_update_(false), is_all_updates_critical_(false) { GetInstanceSet().insert(this); } UpdateScreen::~UpdateScreen() { // Remove pointer to this object from view. if (view()) view()->set_controller(NULL); CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); GetInstanceSet().erase(this); } void UpdateScreen::UpdateStatusChanged(UpdateLibrary* library) { UpdateStatusOperation status = library->status().status; if (checking_for_update_ && status > UPDATE_STATUS_CHECKING_FOR_UPDATE) { checking_for_update_ = false; } switch (status) { case UPDATE_STATUS_CHECKING_FOR_UPDATE: // Do nothing in these cases, we don't want to notify the user of the // check unless there is an update. break; case UPDATE_STATUS_UPDATE_AVAILABLE: MakeSureScreenIsShown(); view()->SetProgress(kBeforeDownloadProgress); if (!HasCriticalUpdate()) { LOG(INFO) << "Noncritical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } break; case UPDATE_STATUS_DOWNLOADING: { MakeSureScreenIsShown(); if (!is_downloading_update_) { // Because update engine doesn't send UPDATE_STATUS_UPDATE_AVAILABLE // we need to is update critical on first downloading notification. is_downloading_update_ = true; if (!HasCriticalUpdate()) { LOG(INFO) << "Non-critical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } } view()->ShowCurtain(false); int download_progress = static_cast<int>( library->status().download_progress * kDownloadProgressIncrement); view()->SetProgress(kBeforeDownloadProgress + download_progress); } break; case UPDATE_STATUS_VERIFYING: MakeSureScreenIsShown(); view()->SetProgress(kBeforeVerifyingProgress); break; case UPDATE_STATUS_FINALIZING: MakeSureScreenIsShown(); view()->SetProgress(kBeforeFinalizingProgress); break; case UPDATE_STATUS_UPDATED_NEED_REBOOT: MakeSureScreenIsShown(); // Make sure that first OOBE stage won't be shown after reboot. WizardController::MarkOobeCompleted(); view()->SetProgress(kProgressComplete); if (HasCriticalUpdate()) { view()->ShowCurtain(false); VLOG(1) << "Initiate reboot after update"; CrosLibrary::Get()->GetUpdateLibrary()->RebootAfterUpdate(); reboot_timer_.Start(base::TimeDelta::FromSeconds(reboot_check_delay_), this, &UpdateScreen::OnWaitForRebootTimeElapsed); } else { ExitUpdate(REASON_UPDATE_NON_CRITICAL); } break; case UPDATE_STATUS_IDLE: case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: ExitUpdate(REASON_UPDATE_ENDED); break; default: NOTREACHED(); break; } } namespace { // Invoked from call to RequestUpdateCheck upon completion of the DBus call. void StartUpdateCallback(void* user_data, UpdateResult result, const char* msg) { if (result != UPDATE_RESULT_SUCCESS) { DCHECK(user_data); UpdateScreen* screen = static_cast<UpdateScreen*>(user_data); if (UpdateScreen::HasInstance(screen)) screen->ExitUpdate(UpdateScreen::REASON_UPDATE_INIT_FAILED); } } } // namespace void UpdateScreen::StartUpdate() { // Reset view if view was created. if (view()) { view()->Reset(); view()->set_controller(this); is_downloading_update_ = false; view()->SetProgress(kBeforeUpdateCheckProgress); } if (!CrosLibrary::Get()->EnsureLoaded()) { LOG(ERROR) << "Error loading CrosLibrary"; ExitUpdate(REASON_UPDATE_INIT_FAILED); } else { CrosLibrary::Get()->GetUpdateLibrary()->AddObserver(this); VLOG(1) << "Initiate update check"; CrosLibrary::Get()->GetUpdateLibrary()->RequestUpdateCheck( StartUpdateCallback, this); } } void UpdateScreen::CancelUpdate() { // Screen has longer lifetime than it's view. // View is deleted after wizard proceeds to the next screen. if (view()) ExitUpdate(REASON_UPDATE_CANCELED); } void UpdateScreen::Show() { DefaultViewScreen<UpdateView>::Show(); view()->set_controller(this); is_downloading_update_ = false; view()->SetProgress(kBeforeUpdateCheckProgress); } void UpdateScreen::ExitUpdate(UpdateScreen::ExitReason reason) { ScreenObserver* observer = delegate()->GetObserver(this); if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); switch(reason) { case REASON_UPDATE_CANCELED: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case REASON_UPDATE_INIT_FAILED: observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); break; case REASON_UPDATE_NON_CRITICAL: case REASON_UPDATE_ENDED: { UpdateLibrary* update_library = CrosLibrary::Get()->GetUpdateLibrary(); switch (update_library->status().status) { case UPDATE_STATUS_UPDATE_AVAILABLE: case UPDATE_STATUS_UPDATED_NEED_REBOOT: case UPDATE_STATUS_DOWNLOADING: case UPDATE_STATUS_FINALIZING: case UPDATE_STATUS_VERIFYING: DCHECK(!HasCriticalUpdate()); // Noncritical update, just exit screen as if there is no update. // no break case UPDATE_STATUS_IDLE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: observer->OnExit(checking_for_update_ ? ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE : ScreenObserver::UPDATE_ERROR_UPDATING); break; default: NOTREACHED(); } } break; default: NOTREACHED(); } } void UpdateScreen::OnWaitForRebootTimeElapsed() { LOG(ERROR) << "Unable to reboot - asking user for a manual reboot."; MakeSureScreenIsShown(); view()->ShowManualRebootInfo(); } void UpdateScreen::MakeSureScreenIsShown() { if (!view()) { delegate()->ShowCurrentScreen(); } } void UpdateScreen::SetRebootCheckDelay(int seconds) { if (seconds <= 0) reboot_timer_.Stop(); DCHECK(!reboot_timer_.IsRunning()); reboot_check_delay_ = seconds; } bool UpdateScreen::HasCriticalUpdate() { if (is_all_updates_critical_) return true; std::string deadline; // Checking for update flag file causes us to do blocking IO on UI thread. // Temporarily allow it until we fix http://crosbug.com/11106 base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath update_deadline_file_path(kUpdateDeadlineFile); if (!file_util::ReadFileToString(update_deadline_file_path, &deadline) || deadline.empty()) { return false; } // TODO(dpolukhin): Analyze file content. Now we can just assume that // if the file exists and not empty, there is critical update. return true; } void UpdateScreen::SetAllUpdatesCritical(bool is_critical) { is_all_updates_critical_ = is_critical; } } // namespace chromeos <commit_msg>[cros] Mark all OOBE updates as critical.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/update_screen.h" #include "base/file_util.h" #include "base/logging.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "content/browser/browser_thread.h" namespace { // Progress bar stages. Each represents progress bar value // at the beginning of each stage. // TODO(nkostylev): Base stage progress values on approximate time. // TODO(nkostylev): Animate progress during each state. const int kBeforeUpdateCheckProgress = 7; const int kBeforeDownloadProgress = 14; const int kBeforeVerifyingProgress = 74; const int kBeforeFinalizingProgress = 81; const int kProgressComplete = 100; // Defines what part of update progress does download part takes. const int kDownloadProgressIncrement = 60; // Considering 10px shadow from each side. const int kUpdateScreenWidth = 580; const int kUpdateScreenHeight = 305; const char kUpdateDeadlineFile[] = "/tmp/update-check-response-deadline"; } // anonymous namespace namespace chromeos { // static UpdateScreen::InstanceSet& UpdateScreen::GetInstanceSet() { static std::set<UpdateScreen*> instance_set; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // not threadsafe. return instance_set; } // static bool UpdateScreen::HasInstance(UpdateScreen* inst) { InstanceSet& instance_set = GetInstanceSet(); InstanceSet::iterator found = instance_set.find(inst); return (found != instance_set.end()); } UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : DefaultViewScreen<chromeos::UpdateView>(delegate, kUpdateScreenWidth, kUpdateScreenHeight), checking_for_update_(true), reboot_check_delay_(0), is_downloading_update_(false), is_all_updates_critical_(true) { // See http://crosbug.com/10068 GetInstanceSet().insert(this); } UpdateScreen::~UpdateScreen() { // Remove pointer to this object from view. if (view()) view()->set_controller(NULL); CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); GetInstanceSet().erase(this); } void UpdateScreen::UpdateStatusChanged(UpdateLibrary* library) { UpdateStatusOperation status = library->status().status; if (checking_for_update_ && status > UPDATE_STATUS_CHECKING_FOR_UPDATE) { checking_for_update_ = false; } switch (status) { case UPDATE_STATUS_CHECKING_FOR_UPDATE: // Do nothing in these cases, we don't want to notify the user of the // check unless there is an update. break; case UPDATE_STATUS_UPDATE_AVAILABLE: MakeSureScreenIsShown(); view()->SetProgress(kBeforeDownloadProgress); if (!HasCriticalUpdate()) { LOG(INFO) << "Noncritical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } break; case UPDATE_STATUS_DOWNLOADING: { MakeSureScreenIsShown(); if (!is_downloading_update_) { // Because update engine doesn't send UPDATE_STATUS_UPDATE_AVAILABLE // we need to is update critical on first downloading notification. is_downloading_update_ = true; if (!HasCriticalUpdate()) { LOG(INFO) << "Non-critical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } } view()->ShowCurtain(false); int download_progress = static_cast<int>( library->status().download_progress * kDownloadProgressIncrement); view()->SetProgress(kBeforeDownloadProgress + download_progress); } break; case UPDATE_STATUS_VERIFYING: MakeSureScreenIsShown(); view()->SetProgress(kBeforeVerifyingProgress); break; case UPDATE_STATUS_FINALIZING: MakeSureScreenIsShown(); view()->SetProgress(kBeforeFinalizingProgress); break; case UPDATE_STATUS_UPDATED_NEED_REBOOT: MakeSureScreenIsShown(); // Make sure that first OOBE stage won't be shown after reboot. WizardController::MarkOobeCompleted(); view()->SetProgress(kProgressComplete); if (HasCriticalUpdate()) { view()->ShowCurtain(false); VLOG(1) << "Initiate reboot after update"; CrosLibrary::Get()->GetUpdateLibrary()->RebootAfterUpdate(); reboot_timer_.Start(base::TimeDelta::FromSeconds(reboot_check_delay_), this, &UpdateScreen::OnWaitForRebootTimeElapsed); } else { ExitUpdate(REASON_UPDATE_NON_CRITICAL); } break; case UPDATE_STATUS_IDLE: case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: ExitUpdate(REASON_UPDATE_ENDED); break; default: NOTREACHED(); break; } } namespace { // Invoked from call to RequestUpdateCheck upon completion of the DBus call. void StartUpdateCallback(void* user_data, UpdateResult result, const char* msg) { if (result != UPDATE_RESULT_SUCCESS) { DCHECK(user_data); UpdateScreen* screen = static_cast<UpdateScreen*>(user_data); if (UpdateScreen::HasInstance(screen)) screen->ExitUpdate(UpdateScreen::REASON_UPDATE_INIT_FAILED); } } } // namespace void UpdateScreen::StartUpdate() { // Reset view if view was created. if (view()) { view()->Reset(); view()->set_controller(this); is_downloading_update_ = false; view()->SetProgress(kBeforeUpdateCheckProgress); } if (!CrosLibrary::Get()->EnsureLoaded()) { LOG(ERROR) << "Error loading CrosLibrary"; ExitUpdate(REASON_UPDATE_INIT_FAILED); } else { CrosLibrary::Get()->GetUpdateLibrary()->AddObserver(this); VLOG(1) << "Initiate update check"; CrosLibrary::Get()->GetUpdateLibrary()->RequestUpdateCheck( StartUpdateCallback, this); } } void UpdateScreen::CancelUpdate() { // Screen has longer lifetime than it's view. // View is deleted after wizard proceeds to the next screen. if (view()) ExitUpdate(REASON_UPDATE_CANCELED); } void UpdateScreen::Show() { DefaultViewScreen<UpdateView>::Show(); view()->set_controller(this); is_downloading_update_ = false; view()->SetProgress(kBeforeUpdateCheckProgress); } void UpdateScreen::ExitUpdate(UpdateScreen::ExitReason reason) { ScreenObserver* observer = delegate()->GetObserver(this); if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); switch(reason) { case REASON_UPDATE_CANCELED: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case REASON_UPDATE_INIT_FAILED: observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); break; case REASON_UPDATE_NON_CRITICAL: case REASON_UPDATE_ENDED: { UpdateLibrary* update_library = CrosLibrary::Get()->GetUpdateLibrary(); switch (update_library->status().status) { case UPDATE_STATUS_UPDATE_AVAILABLE: case UPDATE_STATUS_UPDATED_NEED_REBOOT: case UPDATE_STATUS_DOWNLOADING: case UPDATE_STATUS_FINALIZING: case UPDATE_STATUS_VERIFYING: DCHECK(!HasCriticalUpdate()); // Noncritical update, just exit screen as if there is no update. // no break case UPDATE_STATUS_IDLE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: observer->OnExit(checking_for_update_ ? ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE : ScreenObserver::UPDATE_ERROR_UPDATING); break; default: NOTREACHED(); } } break; default: NOTREACHED(); } } void UpdateScreen::OnWaitForRebootTimeElapsed() { LOG(ERROR) << "Unable to reboot - asking user for a manual reboot."; MakeSureScreenIsShown(); view()->ShowManualRebootInfo(); } void UpdateScreen::MakeSureScreenIsShown() { if (!view()) { delegate()->ShowCurrentScreen(); } } void UpdateScreen::SetRebootCheckDelay(int seconds) { if (seconds <= 0) reboot_timer_.Stop(); DCHECK(!reboot_timer_.IsRunning()); reboot_check_delay_ = seconds; } bool UpdateScreen::HasCriticalUpdate() { if (is_all_updates_critical_) return true; std::string deadline; // Checking for update flag file causes us to do blocking IO on UI thread. // Temporarily allow it until we fix http://crosbug.com/11106 base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath update_deadline_file_path(kUpdateDeadlineFile); if (!file_util::ReadFileToString(update_deadline_file_path, &deadline) || deadline.empty()) { return false; } // TODO(dpolukhin): Analyze file content. Now we can just assume that // if the file exists and not empty, there is critical update. return true; } void UpdateScreen::SetAllUpdatesCritical(bool is_critical) { is_all_updates_critical_ = is_critical; } } // namespace chromeos <|endoftext|>
<commit_before><commit_msg>Posix: implement diagnostics mode console output.<commit_after><|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_integrate_1d_HPP #define STAN_MATH_REV_FUNCTOR_integrate_1d_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/fun/is_nan.hpp> #include <stan/math/rev/fun/value_of.hpp> #include <stan/math/rev/core/precomputed_gradients.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/functor/integrate_1d.hpp> #include <cmath> #include <functional> #include <ostream> #include <string> #include <type_traits> #include <vector> namespace stan { namespace math { /** * Calculate first derivative of f(x, xc, msgs, args...) * with respect to the nth parameter in args. Uses nested reverse mode autodiff * * Gradients that evaluate to NaN are set to zero if the function itself * evaluates to zero. If the function is not zero and the gradient evaluates to * NaN, a std::domain_error is thrown * * @tparam F type of f * @tparam Args types of arguments to f * @param f function to compute gradients of * @param x location at which to evaluate gradients * @param xc complement of location (if bounded domain of integration) * @param n compute gradient with respect to nth parameter * @param msgs stream for messages * @param args other arguments to pass to f */ template <typename F, typename... Args> inline double gradient_of_f(const F &f, const double &x, const double &xc, size_t n, std::ostream *msgs, const Args &... args) { double gradient = 0.0; // Run nested autodiff in this scope nested_rev_autodiff nested; auto args_tuple_local_copy = std::make_tuple(deep_copy_vars(args)...); Eigen::VectorXd adjoints = Eigen::VectorXd::Zero(count_vars(args...)); var fx = apply( [&f, &x, &xc, msgs](auto &&... args) { return f(x, xc, msgs, args...); }, args_tuple_local_copy); fx.grad(); apply( [&](auto &&... args) { accumulate_adjoints(adjoints.data(), std::forward<decltype(args)>(args)...); }, std::move(args_tuple_local_copy)); gradient = adjoints.coeff(n); if (is_nan(gradient)) { if (fx.val() == 0) { gradient = 0; } else { throw_domain_error("gradient_of_f", "The gradient of f", n, "is nan for parameter ", ""); } } return gradient; } /** * Return the integral of f from a to b to the given relative tolerance * * @tparam F Type of f * @tparam T_a type of first limit * @tparam T_b type of second limit * @tparam Args types of parameter pack arguments * * @param f the functor to integrate * @param a lower limit of integration * @param b upper limit of integration * @param relative_tolerance relative tolerance passed to Boost quadrature * @param[in, out] msgs the print stream for warning messages * @param args additional arguments to pass to f * @return numeric integral of function f */ template <typename F, typename T_a, typename T_b, typename... Args, require_any_st_var<T_a, T_b, Args...> * = nullptr> inline return_type_t<T_a, T_b, Args...> integrate_1d_impl( const F &f, const T_a &a, const T_b &b, double relative_tolerance, std::ostream *msgs, const Args &... args) { static constexpr const char *function = "integrate_1d"; check_less_or_equal(function, "lower limit", a, b); double a_val = value_of(a); double b_val = value_of(b); if (a_val == b_val) { if (is_inf(a_val)) { throw_domain_error(function, "Integration endpoints are both", a_val, "", ""); } return var(0.0); } else { std::tuple<decltype(value_of(args))...> args_val_tuple(value_of(args)...); double integral = integrate( [&](const auto &x, const auto &xc) { return apply([&](auto &&... args) { return f(x, xc, msgs, args...); }, args_val_tuple); }, a_val, b_val, relative_tolerance); size_t num_vars_ab = count_vars(a, b); size_t num_vars_args = count_vars(args...); vari **varis = ChainableStack::instance_->memalloc_.alloc_array<vari *>( num_vars_ab + num_vars_args); double *partials = ChainableStack::instance_->memalloc_.alloc_array<double>( num_vars_ab + num_vars_args); double *partials_ptr = partials; save_varis(varis, a, b, args...); for (size_t i = 0; i < num_vars_ab + num_vars_args; ++i) { partials[i] = 0.0; } if (!is_inf(a) && is_var<T_a>::value) { *partials_ptr = apply( [&f, a_val, msgs](auto &&... args) { return -f(a_val, 0.0, msgs, args...); }, args_val_tuple); partials_ptr++; } if (!is_inf(b) && is_var<T_b>::value) { *partials_ptr = apply([&f, b_val, msgs]( auto &&... args) { return f(b_val, 0.0, msgs, args...); }, args_val_tuple); partials_ptr++; } for (size_t n = 0; n < num_vars_args; ++n) { *partials_ptr = integrate( [&](const auto &x, const auto &xc) { return gradient_of_f<F, Args...>(f, x, xc, n, msgs, args...); }, a_val, b_val, relative_tolerance); partials_ptr++; } return var(new precomputed_gradients_vari( integral, num_vars_ab + num_vars_args, varis, partials)); } } /** * Compute the integral of the single variable function f from a to b to within * a specified relative tolerance. a and b can be finite or infinite. * * f should be compatible with reverse mode autodiff and have the signature: * var f(double x, double xc, const std::vector<var>& theta, * const std::vector<double>& x_r, const std::vector<int> &x_i, * std::ostream* msgs) * * It should return the value of the function evaluated at x. Any errors * should be printed to the msgs stream. * * Integrals that cross zero are broken into two, and the separate integrals are * each integrated to the given relative tolerance. * * For integrals with finite limits, the xc argument is the distance to the * nearest boundary. So for a > 0, b > 0, it will be a - x for x closer to a, * and b - x for x closer to b. xc is computed in a way that avoids the * precision loss of computing a - x or b - x manually. For integrals that cross * zero, xc can take values a - x, -x, or b - x depending on which integration * limit it is nearest. * * If either limit is infinite, xc is set to NaN * * The integration algorithm terminates when * \f[ * \frac{{|I_{n + 1} - I_n|}}{{|I|_{n + 1}}} < \text{relative tolerance} * \f] * where \f$I_{n}\f$ is the nth estimate of the integral and \f$|I|_{n}\f$ is * the nth estimate of the norm of the integral. * * Integrals that cross zero are * split into two. In this case, each integral is separately integrated to the * given relative_tolerance. * * Gradients of f that evaluate to NaN when the function evaluates to zero are * set to zero themselves. This is due to the autodiff easily overflowing to NaN * when evaluating gradients near the maximum and minimum floating point values * (where the function should be zero anyway for the integral to exist) * * @tparam T_a type of first limit * @tparam T_b type of second limit * @tparam T_theta type of parameters * @tparam T Type of f * * @param f the functor to integrate * @param a lower limit of integration * @param b upper limit of integration * @param theta additional parameters to be passed to f * @param x_r additional data to be passed to f * @param x_i additional integer data to be passed to f * @param[in, out] msgs the print stream for warning messages * @param relative_tolerance relative tolerance passed to Boost quadrature * @return numeric integral of function f */ template <typename F, typename T_a, typename T_b, typename T_theta, typename = require_any_var_t<T_a, T_b, T_theta>> inline return_type_t<T_a, T_b, T_theta> integrate_1d( const F &f, const T_a &a, const T_b &b, const std::vector<T_theta> &theta, const std::vector<double> &x_r, const std::vector<int> &x_i, std::ostream *msgs, const double relative_tolerance = std::sqrt(EPSILON)) { return integrate_1d_impl(integrate_1d_adapter<F>(f), a, b, relative_tolerance, msgs, theta, x_r, x_i); } } // namespace math } // namespace stan #endif <commit_msg>Reordered if<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_integrate_1d_HPP #define STAN_MATH_REV_FUNCTOR_integrate_1d_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/fun/is_nan.hpp> #include <stan/math/rev/fun/value_of.hpp> #include <stan/math/rev/core/precomputed_gradients.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/functor/integrate_1d.hpp> #include <cmath> #include <functional> #include <ostream> #include <string> #include <type_traits> #include <vector> namespace stan { namespace math { /** * Calculate first derivative of f(x, xc, msgs, args...) * with respect to the nth parameter in args. Uses nested reverse mode autodiff * * Gradients that evaluate to NaN are set to zero if the function itself * evaluates to zero. If the function is not zero and the gradient evaluates to * NaN, a std::domain_error is thrown * * @tparam F type of f * @tparam Args types of arguments to f * @param f function to compute gradients of * @param x location at which to evaluate gradients * @param xc complement of location (if bounded domain of integration) * @param n compute gradient with respect to nth parameter * @param msgs stream for messages * @param args other arguments to pass to f */ template <typename F, typename... Args> inline double gradient_of_f(const F &f, const double &x, const double &xc, size_t n, std::ostream *msgs, const Args &... args) { double gradient = 0.0; // Run nested autodiff in this scope nested_rev_autodiff nested; auto args_tuple_local_copy = std::make_tuple(deep_copy_vars(args)...); Eigen::VectorXd adjoints = Eigen::VectorXd::Zero(count_vars(args...)); var fx = apply( [&f, &x, &xc, msgs](auto &&... args) { return f(x, xc, msgs, args...); }, args_tuple_local_copy); fx.grad(); apply( [&](auto &&... args) { accumulate_adjoints(adjoints.data(), std::forward<decltype(args)>(args)...); }, std::move(args_tuple_local_copy)); gradient = adjoints.coeff(n); if (is_nan(gradient)) { if (fx.val() == 0) { gradient = 0; } else { throw_domain_error("gradient_of_f", "The gradient of f", n, "is nan for parameter ", ""); } } return gradient; } /** * Return the integral of f from a to b to the given relative tolerance * * @tparam F Type of f * @tparam T_a type of first limit * @tparam T_b type of second limit * @tparam Args types of parameter pack arguments * * @param f the functor to integrate * @param a lower limit of integration * @param b upper limit of integration * @param relative_tolerance relative tolerance passed to Boost quadrature * @param[in, out] msgs the print stream for warning messages * @param args additional arguments to pass to f * @return numeric integral of function f */ template <typename F, typename T_a, typename T_b, typename... Args, require_any_st_var<T_a, T_b, Args...> * = nullptr> inline return_type_t<T_a, T_b, Args...> integrate_1d_impl( const F &f, const T_a &a, const T_b &b, double relative_tolerance, std::ostream *msgs, const Args &... args) { static constexpr const char *function = "integrate_1d"; check_less_or_equal(function, "lower limit", a, b); double a_val = value_of(a); double b_val = value_of(b); if (a_val == b_val) { if (is_inf(a_val)) { throw_domain_error(function, "Integration endpoints are both", a_val, "", ""); } return var(0.0); } else { std::tuple<decltype(value_of(args))...> args_val_tuple(value_of(args)...); double integral = integrate( [&](const auto &x, const auto &xc) { return apply([&](auto &&... args) { return f(x, xc, msgs, args...); }, args_val_tuple); }, a_val, b_val, relative_tolerance); size_t num_vars_ab = count_vars(a, b); size_t num_vars_args = count_vars(args...); vari **varis = ChainableStack::instance_->memalloc_.alloc_array<vari *>( num_vars_ab + num_vars_args); double *partials = ChainableStack::instance_->memalloc_.alloc_array<double>( num_vars_ab + num_vars_args); double *partials_ptr = partials; save_varis(varis, a, b, args...); for (size_t i = 0; i < num_vars_ab + num_vars_args; ++i) { partials[i] = 0.0; } if (is_var<T_a>::value && !is_inf(a)) { *partials_ptr = apply( [&f, a_val, msgs](auto &&... args) { return -f(a_val, 0.0, msgs, args...); }, args_val_tuple); partials_ptr++; } if (!is_inf(b) && is_var<T_b>::value) { *partials_ptr = apply([&f, b_val, msgs]( auto &&... args) { return f(b_val, 0.0, msgs, args...); }, args_val_tuple); partials_ptr++; } for (size_t n = 0; n < num_vars_args; ++n) { *partials_ptr = integrate( [&](const auto &x, const auto &xc) { return gradient_of_f<F, Args...>(f, x, xc, n, msgs, args...); }, a_val, b_val, relative_tolerance); partials_ptr++; } return var(new precomputed_gradients_vari( integral, num_vars_ab + num_vars_args, varis, partials)); } } /** * Compute the integral of the single variable function f from a to b to within * a specified relative tolerance. a and b can be finite or infinite. * * f should be compatible with reverse mode autodiff and have the signature: * var f(double x, double xc, const std::vector<var>& theta, * const std::vector<double>& x_r, const std::vector<int> &x_i, * std::ostream* msgs) * * It should return the value of the function evaluated at x. Any errors * should be printed to the msgs stream. * * Integrals that cross zero are broken into two, and the separate integrals are * each integrated to the given relative tolerance. * * For integrals with finite limits, the xc argument is the distance to the * nearest boundary. So for a > 0, b > 0, it will be a - x for x closer to a, * and b - x for x closer to b. xc is computed in a way that avoids the * precision loss of computing a - x or b - x manually. For integrals that cross * zero, xc can take values a - x, -x, or b - x depending on which integration * limit it is nearest. * * If either limit is infinite, xc is set to NaN * * The integration algorithm terminates when * \f[ * \frac{{|I_{n + 1} - I_n|}}{{|I|_{n + 1}}} < \text{relative tolerance} * \f] * where \f$I_{n}\f$ is the nth estimate of the integral and \f$|I|_{n}\f$ is * the nth estimate of the norm of the integral. * * Integrals that cross zero are * split into two. In this case, each integral is separately integrated to the * given relative_tolerance. * * Gradients of f that evaluate to NaN when the function evaluates to zero are * set to zero themselves. This is due to the autodiff easily overflowing to NaN * when evaluating gradients near the maximum and minimum floating point values * (where the function should be zero anyway for the integral to exist) * * @tparam T_a type of first limit * @tparam T_b type of second limit * @tparam T_theta type of parameters * @tparam T Type of f * * @param f the functor to integrate * @param a lower limit of integration * @param b upper limit of integration * @param theta additional parameters to be passed to f * @param x_r additional data to be passed to f * @param x_i additional integer data to be passed to f * @param[in, out] msgs the print stream for warning messages * @param relative_tolerance relative tolerance passed to Boost quadrature * @return numeric integral of function f */ template <typename F, typename T_a, typename T_b, typename T_theta, typename = require_any_var_t<T_a, T_b, T_theta>> inline return_type_t<T_a, T_b, T_theta> integrate_1d( const F &f, const T_a &a, const T_b &b, const std::vector<T_theta> &theta, const std::vector<double> &x_r, const std::vector<int> &x_i, std::ostream *msgs, const double relative_tolerance = std::sqrt(EPSILON)) { return integrate_1d_impl(integrate_1d_adapter<F>(f), a, b, relative_tolerance, msgs, theta, x_r, x_i); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s template<class X> class B { public: explicit B(X* p = 0); }; class A { public: A(int value) : m_a_value(value) {}; A(int value, A* client_A) : m_a_value (value), m_client_A (client_A) {} virtual ~A() {} private: int m_a_value; B<A> m_client_A; }; int main(int argc, char **argv) { A reallyA (500); } // FIXME: The numbers are truly awful. // CHECK: !18 = metadata !{i32 786447, i32 0, metadata !"", i32 0, i32 0, i64 64, i64 64, i64 0, i32 64, metadata !19} ; [ DW_TAG_pointer_type ] // CHECK: !19 = metadata !{i32 786434, null, metadata !"A", metadata !6, i32 8, i64 128, i64 64, i32 0, i32 0, null, metadata !20, i32 0, metadata !19, null} ; [ DW_TAG_class_type ] // CHECK: metadata !19, metadata !"A", metadata !"A", metadata !"", metadata !6, i32 12, metadata !45, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !47} ; [ DW_TAG_subprogram ] // CHECK: metadata !"", i32 0, i32 0, i64 0, i64 0, i64 0, i32 0, null, metadata !46, i32 0, i32 0} ; [ DW_TAG_subroutine_type ] // CHECK: !46 = metadata !{null, metadata !18, metadata !9, metadata !34} <commit_msg>Make this test a bit more robust for debug info changes.<commit_after>// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s template<class X> class B { public: explicit B(X* p = 0); }; class A { public: A(int value) : m_a_value(value) {}; A(int value, A* client_A) : m_a_value (value), m_client_A (client_A) {} virtual ~A() {} private: int m_a_value; B<A> m_client_A; }; int main(int argc, char **argv) { A reallyA (500); } // FIXME: The numbers are truly awful. // CHECK: !18 = metadata !{i32 {{.*}}, i32 0, metadata !"", i32 0, i32 0, i64 64, i64 64, i64 0, i32 64, metadata !19} ; [ DW_TAG_pointer_type ] // CHECK: !19 = metadata !{i32 {{.*}}, null, metadata !"A", metadata !6, i32 8, i64 128, i64 64, i32 0, i32 0, null, metadata !20, i32 0, metadata !19, null} ; [ DW_TAG_class_type ] // CHECK: metadata !19, metadata !"A", metadata !"A", metadata !"", metadata !6, i32 12, metadata !45, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !47} ; [ DW_TAG_subprogram ] // CHECK: metadata !"", i32 0, i32 0, i64 0, i64 0, i64 0, i32 0, null, metadata !46, i32 0, i32 0} ; [ DW_TAG_subroutine_type ] // CHECK: !46 = metadata !{null, metadata !18, metadata !9, metadata !34} <|endoftext|>
<commit_before>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ #include <sstream> #include <algorithm> #include "Log.h" #include "LossFunctionLayer.h" #include "TrainingLayer.h" #include "GradientAccumulationLayer.h" #include "StatLayer.h" #include "NetGraph.h" namespace Conv { void NetGraph::AddNode(NetGraphNode* node) { // Validate node if (node == nullptr) FATAL("Tried to add null-pointer node!"); if (node->layer == nullptr) FATAL("Tried to add layerless node!"); // We don't check the node's connections at this time because we can't expect // the user to sort the nodes before adding. NetGraph::IsComplete() contains // all necessary checks. // Assign the node a new unique ID if it doesn't have one already if (node->unique_id == -1) node->unique_id = ++last_uid; // Add node to list nodes_.push_back(node); // Add node to registries if (node->is_input) input_nodes_.push_back(node); if (node->is_output) output_nodes_.push_back(node); if (dynamic_cast<StatLayer*>(node->layer) != NULL) stat_nodes_.push_back(node); if (dynamic_cast<LossFunctionLayer*>(node->layer) != NULL) loss_nodes_.push_back(node); if (dynamic_cast<TrainingLayer*>(node->layer) != NULL) training_nodes_.push_back(node); // Add backprop connection where appropiate for(NetGraphConnection connection : node->input_connections) { if (connection.backprop && !connection.node->is_input) { NetGraphBackpropConnection backprop_connection(node, connection.buffer); connection.node->backprop_connections.push_back(backprop_connection); } else if (connection.backprop && connection.node->is_input) { connection.backprop = false; } } } bool NetGraph::IsComplete() const { unsigned int inputs = 0, outputs = 0; bool is_complete = true; for (NetGraphNode* node : nodes_) { bool node_okay = true; if (node != nullptr) { if (node->layer != nullptr) { for (NetGraphConnection connection : node->input_connections) { if (connection.node != nullptr) { if (std::find(nodes_.begin(), nodes_.end(), node) == nodes_.end()) { LOGWARN << "Node has out-of-network connection: " << node->layer->GetLayerDescription(); } else { if (connection.buffer >= connection.node->output_buffers.size()) { LOGWARN << "Node's connection points to invalid buffer: " << node->layer->GetLayerDescription(); node_okay = false; } } } else { LOGWARN << "Node has null-pointer connection: " << node->layer->GetLayerDescription(); node_okay = false; } } } else { LOGWARN << "Node has null-pointer for layer!"; node_okay = false; } if (node->unique_id == -1) { LOGWARN << "Node has no unique identifier!"; node_okay = false; } if (node->is_input && node->is_output) { LOGWARN << "Node is both input and output!"; node_okay = false; } if (node->is_input) inputs++; if (node->is_output) outputs++; } else { LOGWARN << "Null-pointer node encountered!"; node_okay = false; } if (node_okay) { LOGINFO << "Node is okay: " << node->layer->GetLayerDescription(); } else { LOGINFO << "Node is not okay: " << node->layer->GetLayerDescription(); is_complete = false; } } if (inputs == 0) { LOGWARN << "Net has no inputs!"; is_complete = false; } if (outputs == 0) { LOGWARN << "Net has no outputs!"; is_complete = false; } LOGINFO << "Graph check complete."; return is_complete; } void NetGraph::PrintGraph(std::ostream& graph_output) { if (nodes_.size() == 0) return; std::ostringstream node_output; std::ostringstream edge_output; node_output << "graph [ranksep=.75, esep=1];"; for (NetGraphNode* node : nodes_) { // 1. Print node details node_output << "node" << node->unique_id << " [shape=record,"; if (node->is_input) { node_output << "color=red,"; } if (node->is_output) { node_output << "color=blue,"; } node_output << " label=\"" << "{ <i>" << node->layer->GetLayerDescription(); if (node->output_buffers.size() > 1) { node_output << "| {"; for (unsigned int i = 0; i < node->output_buffers.size(); i++) { if (i > 0) node_output << "|"; node_output << "<o" << i << ">" << node->output_buffers[i].description; } node_output << "}"; } else if (node->output_buffers.size() == 1) { node_output << "| <o0> " << node->output_buffers[0].description; } node_output << "}\"];\n"; // 2. Print edges for (NetGraphConnection connection : node->input_connections) { edge_output << "node" << connection.node->unique_id << ":o" << connection.buffer << " -> node" << node->unique_id << ":i" << "[penwidth=2];\n"; } for (NetGraphBackpropConnection backprop_connection : node->backprop_connections) { edge_output << "node" << backprop_connection.node->unique_id << ":i -> node" << node->unique_id << ":o" << backprop_connection.buffer << "[penwidth=5,style=dotted,arrowsize=.6];\n"; } } graph_output << node_output.str(); graph_output << edge_output.str(); } void NetGraph::Initialize() { // check for nodes with multiple backprop connections bool no_multiple_connections = true; do { no_multiple_connections = true; std::vector<NetGraphNode*> nodes(nodes_); for (NetGraphNode* node : nodes) { if(node->backprop_connections.size() > 1 && dynamic_cast<GradientAccumulationLayer*>(node->layer) == NULL) { no_multiple_connections = false; LOGINFO << "Node has multiple backprop connections: " << node->layer->GetLayerDescription(); // Insert gradient accumulation layer GradientAccumulationLayer* ga = new GradientAccumulationLayer(node->backprop_connections.size()); NetGraphNode* ga_node = new NetGraphNode(ga, NetGraphConnection(node)); AddNode(ga_node); // Redirect input connections using backprop connections int b = 0; for(NetGraphBackpropConnection& backprop_connection : node->backprop_connections) { if(backprop_connection.node != ga_node) { for(NetGraphConnection& target_connection : backprop_connection.node->input_connections) { if(target_connection.node == node && target_connection.buffer == backprop_connection.buffer && target_connection.backprop) { target_connection.node = ga_node; backprop_connection.buffer = b; target_connection.buffer = b++; } } ga_node->backprop_connections.push_back(backprop_connection); } } // Remove backprop connections from node auto predicate = [&](NetGraphBackpropConnection backprop_connection){ return backprop_connection.node != ga_node; }; node->backprop_connections.erase(std::remove_if(node->backprop_connections.begin(), node->backprop_connections.end(), predicate), node->backprop_connections.end()); } } } while(!no_multiple_connections); for (NetGraphNode* node : nodes_){ InitializeNode(node); } } void NetGraph::InitializeNode(NetGraphNode* node) { if (!node->initialized) { // Collect input tensors through DFS std::vector<CombinedTensor*> input_tensors; for (NetGraphConnection connection : node->input_connections) { InitializeNode(connection.node); input_tensors.push_back(connection.node->output_buffers[connection.buffer].combined_tensor); } // Ask layer to create output buffers std::vector<CombinedTensor*> output_tensors; bool success_outputs = node->layer->CreateOutputs(input_tensors, output_tensors); // Verify output buffer creation if (!success_outputs) FATAL("Layer will not create outputs: " << node->layer->GetLayerDescription()); // Verify output buffer count if (output_tensors.size() != node->output_buffers.size()) FATAL("Node created wrong number of output buffers!"); // Update node output buffer info for (unsigned int b = 0; b < output_tensors.size(); b++) { node->output_buffers[b].combined_tensor = output_tensors[b]; } // Connect layer bool success_connect = node->layer->Connect(input_tensors, output_tensors, this); if (!success_connect) FATAL("Layer will not connect: " << node->layer->GetLayerDescription()); // Save to flag node->initialized = true; } } void NetGraph::FeedForward() { FeedForward(nodes_, true); } void NetGraph::FeedForward(std::vector<NetGraphNode*>& nodes, bool clear_flag) { if (clear_flag) for (NetGraphNode* node : nodes) node->flag_ff_visited = false; for (NetGraphNode* node : nodes) FeedForward(node); } void NetGraph::FeedForward(NetGraphNode* node) { if (!node->flag_ff_visited) { // Make sure all input nodes have valid outputs for (NetGraphConnection connection : node->input_connections) FeedForward(connection.node); PrepareNode(node); // Call the Layer::FeedForward method and set the visited flag node->layer->FeedForward(); node->flag_ff_visited = true; } } void NetGraph::BackPropagate() { BackPropagate(nodes_, true); } void NetGraph::BackPropagate(std::vector<NetGraphNode*>& nodes, bool clear_flag) { if (clear_flag) for (NetGraphNode* node : nodes) node->flag_bp_visited = false; for (NetGraphNode* node : nodes) BackPropagate(node); } void NetGraph::BackPropagate(NetGraphNode* node) { if (!node->flag_bp_visited) { // Make sure all source nodes have valid gradients for (NetGraphBackpropConnection backprop_connection : node->backprop_connections) BackPropagate(backprop_connection.node); bool do_backprop = false; for (NetGraphConnection connection : node->input_connections) do_backprop |= connection.backprop; PrepareNode(node); node->layer->SetBackpropagationEnabled(do_backprop); // Call the Layer::FeedForward method and set the visited flag node->layer->BackPropagate(); node->flag_bp_visited = true; } } void NetGraph::GetParameters (std::vector< CombinedTensor* >& parameters) { for (NetGraphNode* node : nodes_) { Layer* layer = node->layer; for (unsigned int p = 0; p < layer->parameters().size(); p++) { parameters.push_back (layer->parameters() [p]); } } } void NetGraph::SerializeParameters(std::ostream& output) { // TODO use unique layer ids for (unsigned int l = 0; l < nodes_.size(); l++) { Layer* layer = nodes_[l]->layer; for (unsigned int p = 0; p < layer->parameters().size(); p++) { layer->parameters()[p]->data.Serialize(output); } } } void NetGraph::DeserializeParameters(std::istream& input, unsigned int last_layer) { // TODO use unique layer ids if (last_layer == 0 || last_layer >= nodes_.size()) last_layer = nodes_.size() - 1; for (unsigned int l = 0; l <= last_layer; l++) { Layer* layer = nodes_[l]->layer; for (unsigned int p = 0; p < layer->parameters().size(); p++) { if (!input.good() || input.eof()) break; layer->parameters() [p]->data.Deserialize (input); LOGINFO << "Loaded parameters for layer " << l << " parameter set " << p << ": " << layer->parameters()[p]->data; input.peek(); } } } void NetGraph::InitializeWeights() { for (NetGraphNode* node : nodes_) node->flag_bp_visited = false; for (NetGraphNode* node : nodes_) InitializeWeights(node); for (NetGraphNode* node : nodes_) node->flag_bp_visited = false; } void NetGraph::InitializeWeights(NetGraphNode* node) { if (!node->flag_bp_visited) { for (NetGraphBackpropConnection backprop_connection : node->backprop_connections) { InitializeWeights(backprop_connection.node); node->layer->OnLayerConnect(backprop_connection.node->layer); } node->flag_bp_visited = true; } } void NetGraph::PrepareNode(NetGraphNode* node) { #ifdef BUILD_OPENCL if (!node->layer->IsOpenCLAware()) { for (NetGraphConnection connection : node->input_connections) { connection.node->output_buffers[connection.buffer].combined_tensor->data.MoveToCPU(); connection.node->output_buffers[connection.buffer].combined_tensor->delta.MoveToCPU(); } for (NetGraphBuffer& buffer : node->output_buffers) { buffer.combined_tensor->data.MoveToCPU(); buffer.combined_tensor->delta.MoveToCPU(); } } #endif } datum NetGraph::AggregateLoss() { datum loss = 0; for (NetGraphNode* loss_node : GetLossNodes()) { LossFunctionLayer* loss_layer = dynamic_cast<LossFunctionLayer*>(loss_node->layer); if (loss_layer != NULL) { loss += loss_layer->CalculateLossFunction(); } else { FATAL("Null pointer in loss node encountered!"); } } return loss; } }<commit_msg>NetGraph: Cleared up graph output<commit_after>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ #include <sstream> #include <algorithm> #include "Log.h" #include "LossFunctionLayer.h" #include "TrainingLayer.h" #include "GradientAccumulationLayer.h" #include "StatLayer.h" #include "NetGraph.h" namespace Conv { void NetGraph::AddNode(NetGraphNode* node) { // Validate node if (node == nullptr) FATAL("Tried to add null-pointer node!"); if (node->layer == nullptr) FATAL("Tried to add layerless node!"); // We don't check the node's connections at this time because we can't expect // the user to sort the nodes before adding. NetGraph::IsComplete() contains // all necessary checks. // Assign the node a new unique ID if it doesn't have one already if (node->unique_id == -1) node->unique_id = ++last_uid; // Add node to list nodes_.push_back(node); // Add node to registries if (node->is_input) input_nodes_.push_back(node); if (node->is_output) output_nodes_.push_back(node); if (dynamic_cast<StatLayer*>(node->layer) != NULL) stat_nodes_.push_back(node); if (dynamic_cast<LossFunctionLayer*>(node->layer) != NULL) loss_nodes_.push_back(node); if (dynamic_cast<TrainingLayer*>(node->layer) != NULL) training_nodes_.push_back(node); // Add backprop connection where appropiate for(NetGraphConnection& connection : node->input_connections) { if (connection.backprop && !connection.node->is_input) { NetGraphBackpropConnection backprop_connection(node, connection.buffer); connection.node->backprop_connections.push_back(backprop_connection); } else if (connection.backprop && connection.node->is_input) { connection.backprop = false; } } } bool NetGraph::IsComplete() const { unsigned int inputs = 0, outputs = 0; bool is_complete = true; for (NetGraphNode* node : nodes_) { bool node_okay = true; if (node != nullptr) { if (node->layer != nullptr) { for (NetGraphConnection connection : node->input_connections) { if (connection.node != nullptr) { if (std::find(nodes_.begin(), nodes_.end(), node) == nodes_.end()) { LOGWARN << "Node has out-of-network connection: " << node->layer->GetLayerDescription(); } else { if (connection.buffer >= connection.node->output_buffers.size()) { LOGWARN << "Node's connection points to invalid buffer: " << node->layer->GetLayerDescription(); node_okay = false; } } } else { LOGWARN << "Node has null-pointer connection: " << node->layer->GetLayerDescription(); node_okay = false; } } } else { LOGWARN << "Node has null-pointer for layer!"; node_okay = false; } if (node->unique_id == -1) { LOGWARN << "Node has no unique identifier!"; node_okay = false; } if (node->is_input && node->is_output) { LOGWARN << "Node is both input and output!"; node_okay = false; } if (node->is_input) inputs++; if (node->is_output) outputs++; } else { LOGWARN << "Null-pointer node encountered!"; node_okay = false; } if (node_okay) { LOGINFO << "Node is okay: " << node->layer->GetLayerDescription(); } else { LOGINFO << "Node is not okay: " << node->layer->GetLayerDescription(); is_complete = false; } } if (inputs == 0) { LOGWARN << "Net has no inputs!"; is_complete = false; } if (outputs == 0) { LOGWARN << "Net has no outputs!"; is_complete = false; } LOGINFO << "Graph check complete."; return is_complete; } void NetGraph::PrintGraph(std::ostream& graph_output) { if (nodes_.size() == 0) return; std::ostringstream node_output; std::ostringstream edge_output; node_output << "graph [ranksep=.75, esep=1];"; for (NetGraphNode* node : nodes_) { // 1. Print node details node_output << "node" << node->unique_id << " [shape=record,"; if (node->is_input) { node_output << "color=red,"; } if (node->is_output) { node_output << "color=blue,"; } node_output << " label=\"" << "{ <i>" << node->layer->GetLayerDescription(); if (node->output_buffers.size() > 1) { node_output << "| {"; for (unsigned int i = 0; i < node->output_buffers.size(); i++) { if (i > 0) node_output << "|"; node_output << "<o" << i << ">" << node->output_buffers[i].description; } node_output << "}"; } else if (node->output_buffers.size() == 1) { node_output << "| <o0> " << node->output_buffers[0].description; } node_output << "}\"];\n"; // 2. Print edges for (NetGraphConnection connection : node->input_connections) { edge_output << "node" << connection.node->unique_id << ":o" << connection.buffer << " -> node" << node->unique_id << ":i" << "[penwidth=2"; if (!connection.backprop) edge_output << ",style=dotted"; edge_output << "];\n"; } /*for (NetGraphBackpropConnection backprop_connection : node->backprop_connections) { edge_output << "node" << backprop_connection.node->unique_id << ":i -> node" << node->unique_id << ":o" << backprop_connection.buffer << "[penwidth=5,style=dotted,arrowsize=.6];\n"; }*/ } graph_output << node_output.str(); graph_output << edge_output.str(); } void NetGraph::Initialize() { // check for nodes with multiple backprop connections bool no_multiple_connections = true; do { no_multiple_connections = true; std::vector<NetGraphNode*> nodes(nodes_); for (NetGraphNode* node : nodes) { if(node->backprop_connections.size() > 1 && dynamic_cast<GradientAccumulationLayer*>(node->layer) == NULL) { no_multiple_connections = false; LOGINFO << "Node has multiple backprop connections: " << node->layer->GetLayerDescription(); // Insert gradient accumulation layer GradientAccumulationLayer* ga = new GradientAccumulationLayer(node->backprop_connections.size()); NetGraphNode* ga_node = new NetGraphNode(ga, NetGraphConnection(node)); AddNode(ga_node); // Redirect input connections using backprop connections int b = 0; for(NetGraphBackpropConnection& backprop_connection : node->backprop_connections) { if(backprop_connection.node != ga_node) { for(NetGraphConnection& target_connection : backprop_connection.node->input_connections) { if(target_connection.node == node && target_connection.buffer == backprop_connection.buffer && target_connection.backprop) { target_connection.node = ga_node; backprop_connection.buffer = b; target_connection.buffer = b++; } } ga_node->backprop_connections.push_back(backprop_connection); } } // Remove backprop connections from node auto predicate = [&](NetGraphBackpropConnection backprop_connection){ return backprop_connection.node != ga_node; }; node->backprop_connections.erase(std::remove_if(node->backprop_connections.begin(), node->backprop_connections.end(), predicate), node->backprop_connections.end()); } } } while(!no_multiple_connections); for (NetGraphNode* node : nodes_){ InitializeNode(node); } } void NetGraph::InitializeNode(NetGraphNode* node) { if (!node->initialized) { // Collect input tensors through DFS std::vector<CombinedTensor*> input_tensors; for (NetGraphConnection connection : node->input_connections) { InitializeNode(connection.node); input_tensors.push_back(connection.node->output_buffers[connection.buffer].combined_tensor); } // Ask layer to create output buffers std::vector<CombinedTensor*> output_tensors; bool success_outputs = node->layer->CreateOutputs(input_tensors, output_tensors); // Verify output buffer creation if (!success_outputs) FATAL("Layer will not create outputs: " << node->layer->GetLayerDescription()); // Verify output buffer count if (output_tensors.size() != node->output_buffers.size()) FATAL("Node created wrong number of output buffers!"); // Update node output buffer info for (unsigned int b = 0; b < output_tensors.size(); b++) { node->output_buffers[b].combined_tensor = output_tensors[b]; } // Connect layer bool success_connect = node->layer->Connect(input_tensors, output_tensors, this); if (!success_connect) FATAL("Layer will not connect: " << node->layer->GetLayerDescription()); // Save to flag node->initialized = true; } } void NetGraph::FeedForward() { FeedForward(nodes_, true); } void NetGraph::FeedForward(std::vector<NetGraphNode*>& nodes, bool clear_flag) { if (clear_flag) for (NetGraphNode* node : nodes) node->flag_ff_visited = false; for (NetGraphNode* node : nodes) FeedForward(node); } void NetGraph::FeedForward(NetGraphNode* node) { if (!node->flag_ff_visited) { // Make sure all input nodes have valid outputs for (NetGraphConnection connection : node->input_connections) FeedForward(connection.node); PrepareNode(node); // Call the Layer::FeedForward method and set the visited flag node->layer->FeedForward(); node->flag_ff_visited = true; } } void NetGraph::BackPropagate() { BackPropagate(nodes_, true); } void NetGraph::BackPropagate(std::vector<NetGraphNode*>& nodes, bool clear_flag) { if (clear_flag) for (NetGraphNode* node : nodes) node->flag_bp_visited = false; for (NetGraphNode* node : nodes) BackPropagate(node); } void NetGraph::BackPropagate(NetGraphNode* node) { if (!node->flag_bp_visited) { // Make sure all source nodes have valid gradients for (NetGraphBackpropConnection backprop_connection : node->backprop_connections) BackPropagate(backprop_connection.node); bool do_backprop = false; for (NetGraphConnection connection : node->input_connections) do_backprop |= connection.backprop; PrepareNode(node); node->layer->SetBackpropagationEnabled(do_backprop); // Call the Layer::FeedForward method and set the visited flag node->layer->BackPropagate(); node->flag_bp_visited = true; } } void NetGraph::GetParameters (std::vector< CombinedTensor* >& parameters) { for (NetGraphNode* node : nodes_) { Layer* layer = node->layer; for (unsigned int p = 0; p < layer->parameters().size(); p++) { parameters.push_back (layer->parameters() [p]); } } } void NetGraph::SerializeParameters(std::ostream& output) { // TODO use unique layer ids for (unsigned int l = 0; l < nodes_.size(); l++) { Layer* layer = nodes_[l]->layer; for (unsigned int p = 0; p < layer->parameters().size(); p++) { layer->parameters()[p]->data.Serialize(output); } } } void NetGraph::DeserializeParameters(std::istream& input, unsigned int last_layer) { // TODO use unique layer ids if (last_layer == 0 || last_layer >= nodes_.size()) last_layer = nodes_.size() - 1; for (unsigned int l = 0; l <= last_layer; l++) { Layer* layer = nodes_[l]->layer; for (unsigned int p = 0; p < layer->parameters().size(); p++) { if (!input.good() || input.eof()) break; layer->parameters() [p]->data.Deserialize (input); LOGINFO << "Loaded parameters for layer " << l << " parameter set " << p << ": " << layer->parameters()[p]->data; input.peek(); } } } void NetGraph::InitializeWeights() { for (NetGraphNode* node : nodes_) node->flag_bp_visited = false; for (NetGraphNode* node : nodes_) InitializeWeights(node); for (NetGraphNode* node : nodes_) node->flag_bp_visited = false; } void NetGraph::InitializeWeights(NetGraphNode* node) { if (!node->flag_bp_visited) { for (NetGraphBackpropConnection backprop_connection : node->backprop_connections) { InitializeWeights(backprop_connection.node); node->layer->OnLayerConnect(backprop_connection.node->layer); } node->flag_bp_visited = true; } } void NetGraph::PrepareNode(NetGraphNode* node) { #ifdef BUILD_OPENCL if (!node->layer->IsOpenCLAware()) { for (NetGraphConnection connection : node->input_connections) { connection.node->output_buffers[connection.buffer].combined_tensor->data.MoveToCPU(); connection.node->output_buffers[connection.buffer].combined_tensor->delta.MoveToCPU(); } for (NetGraphBuffer& buffer : node->output_buffers) { buffer.combined_tensor->data.MoveToCPU(); buffer.combined_tensor->delta.MoveToCPU(); } } #endif } datum NetGraph::AggregateLoss() { datum loss = 0; for (NetGraphNode* loss_node : GetLossNodes()) { LossFunctionLayer* loss_layer = dynamic_cast<LossFunctionLayer*>(loss_node->layer); if (loss_layer != NULL) { loss += loss_layer->CalculateLossFunction(); } else { FATAL("Null pointer in loss node encountered!"); } } return loss; } }<|endoftext|>
<commit_before>/** ** \file object/object.hh ** \brief Definition of object::Object. */ #ifndef OBJECT_OBJECT_HH # define OBJECT_OBJECT_HH # include <deque> # include <iosfwd> # include <set> # include <boost/function.hpp> # include <boost/optional.hpp> # include <libport/shared-ptr.hh> # include <object/fwd.hh> # include <object/object-kind.hh> # include <object/hash-slots.hh> # include <object/sorted-vector-slots.hh> # include <runner/fwd.hh> namespace object { /// Run time values for Urbi. class Object: public libport::RefCounted { /// \name Ctor & dtor. /// \{ public: /// Create a new Object. Object (); /// Destroy a Object. virtual ~Object (); /// \} /// Type of the keys. typedef Slots::key_type key_type; /// Ref-couting. typedef libport::shared_ptr<Object> shared_type; /// \name Kind /// \{ /// The kinds of primitive objects. typedef object_kind_type kind_type; /// Return the kind of this Object. virtual kind_type kind_get () const; /// Whether kind == \a k. bool kind_is(Object::kind_type k) const; /// Whether \a Type has the same kind as \a this. /// Very similar to testing via dynamic_cast, might not be faster. template <typename Type> bool type_is() const; /// \} /// \name The protos. /// \{ /// The protos. typedef std::deque<rObject> protos_type; /// Add proto. Object& proto_add (const rObject& p); /// Remove proto. Object& proto_remove (const rObject& p); /// Read only access to protos. const protos_type& protos_get () const; /// Change the whole set of protos. void protos_set (rObject); // Urbi access to protos. rObject urbi_protos_get (); /// \} /// \name The slots. /// \{ /// The slots implementation typedef HashSlots slots_implem; /// One slot. typedef std::set<const Object*> objects_set_type; /// Abstract lookup traversal /// /// Traverse the inheritance hierarchy, calling \a action on each /// encountered object. If the lookup is successful, \a action /// should return the result. Otherwise, it should return an empty /// boost::optional, so as the lookup continues. This enables to /// perform different kind of searches without duplicating the /// traversal algorithm. /// /// \param action The search to apply on each encountered object. /// \return The result returned by \a action, or an empty /// boost::optional if the lookup failed. template <typename R> boost::optional<R> lookup(boost::function1<boost::optional<R>, rObject> action) const; /// Lookup helper, with a mark table template <typename R> boost::optional<R> lookup(boost::function1<boost::optional<R>, rObject> action, objects_set_type& marks) const; /// Lookup field in object hierarchy. /// \param value Whether to return the owner of the slot or its value /// \return the Object containing slot \a k if \a value is false, /// the slot value if \a value is true, 0 if not found. rObject slot_locate(const key_type& k, bool fallback = true, bool value = false) const; /// Same as slot_locate, but raise LookupError if not found. /// \throw LookupError if the lookup fails. rObject safe_slot_locate(const key_type& k, bool value = false) const; /// Lookup field in object hierarchy. /// \param name The name of the slot to search /// \param def The optional default value /// \throw LookupError if \a def isn't given and the slot isn't found. rObject slot_get(const key_type& k, boost::optional<rObject> def = boost::optional<rObject>()) const; /// Implement copy-on-write if the owner of the scope is not this. /// Otherwise, falls-thru to own_slot_update(). /// \param r Runner to run the updateHook. /// \param k The slot to update /// \param o The new value /// \param hook Whether to trigger the potential updateHook void slot_update(runner::Runner& r, const key_type& k, rObject o, bool hook = true); /// Update slot \c k to \a o. void own_slot_update(const key_type& k, rObject o); /// \brief Update value in slot. /// /// Set slot value in local slot. /// \precondition the slot does not exist in this. Object& slot_set(const key_type& k, rObject o); /// \brief Copy another object's slot. /// /// \precondition the slot does not exist in this. /// \precondition the slot exists in \a from. /// \postcondition the slot exists in \a this. /// \param name The name of the slot to copy /// \param from The object to copy the slot from /// \return this Object& slot_copy(const key_type& name, rObject from); /// Get the object pointed to by the *local* slot. /// An error if the slot does not exist in this object (not its /// protos). rObject own_slot_get(const key_type& k) const; /// Remove slot. Object& slot_remove(const key_type& k); /// Read only access to slots. const slots_implem::content_type& slots_get () const; /// Copy another object local slots, if not already present. void all_slots_copy(const rObject& other); /// \} /// \name Properties. /// \{ /// \} /// \name Printing. /// \{ /// Dump the list of protos. /// FIXME: Should become useless when protos become Urbi lists. std::ostream& protos_dump (std::ostream& o, runner::Runner& r) const; /// Report a short string describing the identity. std::ostream& id_dump (std::ostream& o, runner::Runner& r) const; /// Dump the special slots if there are. virtual std::ostream& special_slots_dump (std::ostream& o, runner::Runner&) const; // Print out the value. Suitable for user interaction. std::ostream& print(std::ostream&, runner::Runner&) const; /// Report the content on \p o. For debugging purpose. std::ostream& dump(std::ostream&, runner::Runner&, int depth_max) const; /// \} /// Clone, i.e., create a fresh object with this class as sole proto. // It is tempting to make it const, but then the list of protos // must be const too. virtual rObject clone () const; /// Comparison methods. virtual bool operator< (const Object& rhs) const; /// Create a fresh scope /** ** \param parent The parent scope (optional, in which case lobby ** becomes the parent) ** \return The new scope */ static rObject make_scope(const rObject& parent = 0); /// Make a method outer scope /** ** Similar to \see make_scope, but make the scope forward ** messages to this object when relevant. ** \return The new scope. **/ rObject make_method_scope(const rObject& parent = 0); /// Return the value of \a atom as an Atom<T>. template <class T> typename T::value_type value(); private: typedef std::pair<bool, rObject> locate_type; /// Lookup field in object hierarchy. /// \param k the key looked up for /// \param os the objects already looked up for, to break infinite /// recursions /// \return (false,0) if k does not exist, (true,0) if k is in this, /// (true, ptr) if k is in ptr. locate_type slot_locate(const key_type& k, objects_set_type& os) const; private: /// The protos. protos_type* protos_; /// The protos cache at the Urbi level. rObject protos_cache_; /// The slots. slots_implem slots_; }; /// Helpers to call Urbi functions from C++. // self.'msg'(args) rObject urbi_call(runner::Runner& r, rObject self, libport::Symbol msg, objects_type args); // self.'msg'(args) for up to five arguments rObject urbi_call(runner::Runner& r, rObject self, libport::Symbol msg, rObject arg1 = 0, rObject arg2 = 0, rObject arg3 = 0, rObject arg4 = 0, rObject arg5 = 0); // owner.getSlot(msg).apply([self]) rObject urbi_call_function(runner::Runner& r, rObject self, rObject function_owner, libport::Symbol msg); // owner.getSlot(msg).apply([self, args]) rObject urbi_call_function(runner::Runner& r, rObject self, rObject function_owner, libport::Symbol msg, objects_type args); /// Call f(robj) on r and all its protos hierarchy, stop if it returns true. template<class F> bool for_all_protos(rObject& r, F& f); /// Whether \b p is present in \b c's proto hierarchy. bool is_a(const rObject& c, const rObject& p); /// Whether \a o represents a true value. bool is_true(const rObject& o); /// Return an Urbi boolean object corresponding to \a b. rObject to_boolean(bool b); } // namespace object # include <object/object.hxx> #endif // !OBJECT_OBJECT_HH <commit_msg>Remove dead declaration.<commit_after>/** ** \file object/object.hh ** \brief Definition of object::Object. */ #ifndef OBJECT_OBJECT_HH # define OBJECT_OBJECT_HH # include <deque> # include <iosfwd> # include <set> # include <boost/function.hpp> # include <boost/optional.hpp> # include <libport/shared-ptr.hh> # include <object/fwd.hh> # include <object/object-kind.hh> # include <object/hash-slots.hh> # include <object/sorted-vector-slots.hh> # include <runner/fwd.hh> namespace object { /// Run time values for Urbi. class Object: public libport::RefCounted { /// \name Ctor & dtor. /// \{ public: /// Create a new Object. Object (); /// Destroy a Object. virtual ~Object (); /// \} /// Type of the keys. typedef Slots::key_type key_type; /// Ref-couting. typedef libport::shared_ptr<Object> shared_type; /// \name Kind /// \{ /// The kinds of primitive objects. typedef object_kind_type kind_type; /// Return the kind of this Object. virtual kind_type kind_get () const; /// Whether kind == \a k. bool kind_is(Object::kind_type k) const; /// Whether \a Type has the same kind as \a this. /// Very similar to testing via dynamic_cast, might not be faster. template <typename Type> bool type_is() const; /// \} /// \name The protos. /// \{ /// The protos. typedef std::deque<rObject> protos_type; /// Add proto. Object& proto_add (const rObject& p); /// Remove proto. Object& proto_remove (const rObject& p); /// Read only access to protos. const protos_type& protos_get () const; /// Change the whole set of protos. void protos_set (rObject); // Urbi access to protos. rObject urbi_protos_get (); /// \} /// \name The slots. /// \{ /// The slots implementation typedef HashSlots slots_implem; /// One slot. typedef std::set<const Object*> objects_set_type; /// Abstract lookup traversal /// /// Traverse the inheritance hierarchy, calling \a action on each /// encountered object. If the lookup is successful, \a action /// should return the result. Otherwise, it should return an empty /// boost::optional, so as the lookup continues. This enables to /// perform different kind of searches without duplicating the /// traversal algorithm. /// /// \param action The search to apply on each encountered object. /// \return The result returned by \a action, or an empty /// boost::optional if the lookup failed. template <typename R> boost::optional<R> lookup(boost::function1<boost::optional<R>, rObject> action) const; /// Lookup helper, with a mark table template <typename R> boost::optional<R> lookup(boost::function1<boost::optional<R>, rObject> action, objects_set_type& marks) const; /// Lookup field in object hierarchy. /// \param value Whether to return the owner of the slot or its value /// \return the Object containing slot \a k if \a value is false, /// the slot value if \a value is true, 0 if not found. rObject slot_locate(const key_type& k, bool fallback = true, bool value = false) const; /// Same as slot_locate, but raise LookupError if not found. /// \throw LookupError if the lookup fails. rObject safe_slot_locate(const key_type& k, bool value = false) const; /// Lookup field in object hierarchy. /// \param name The name of the slot to search /// \param def The optional default value /// \throw LookupError if \a def isn't given and the slot isn't found. rObject slot_get(const key_type& k, boost::optional<rObject> def = boost::optional<rObject>()) const; /// Implement copy-on-write if the owner of the scope is not this. /// Otherwise, falls-thru to own_slot_update(). /// \param r Runner to run the updateHook. /// \param k The slot to update /// \param o The new value /// \param hook Whether to trigger the potential updateHook void slot_update(runner::Runner& r, const key_type& k, rObject o, bool hook = true); /// Update slot \c k to \a o. void own_slot_update(const key_type& k, rObject o); /// \brief Update value in slot. /// /// Set slot value in local slot. /// \precondition the slot does not exist in this. Object& slot_set(const key_type& k, rObject o); /// \brief Copy another object's slot. /// /// \precondition the slot does not exist in this. /// \precondition the slot exists in \a from. /// \postcondition the slot exists in \a this. /// \param name The name of the slot to copy /// \param from The object to copy the slot from /// \return this Object& slot_copy(const key_type& name, rObject from); /// Get the object pointed to by the *local* slot. /// An error if the slot does not exist in this object (not its /// protos). rObject own_slot_get(const key_type& k) const; /// Remove slot. Object& slot_remove(const key_type& k); /// Read only access to slots. const slots_implem::content_type& slots_get () const; /// Copy another object local slots, if not already present. void all_slots_copy(const rObject& other); /// \} /// \name Properties. /// \{ /// \} /// \name Printing. /// \{ /// Dump the list of protos. /// FIXME: Should become useless when protos become Urbi lists. std::ostream& protos_dump (std::ostream& o, runner::Runner& r) const; /// Report a short string describing the identity. std::ostream& id_dump (std::ostream& o, runner::Runner& r) const; /// Dump the special slots if there are. virtual std::ostream& special_slots_dump (std::ostream& o, runner::Runner&) const; // Print out the value. Suitable for user interaction. std::ostream& print(std::ostream&, runner::Runner&) const; /// Report the content on \p o. For debugging purpose. std::ostream& dump(std::ostream&, runner::Runner&, int depth_max) const; /// \} /// Clone, i.e., create a fresh object with this class as sole proto. // It is tempting to make it const, but then the list of protos // must be const too. virtual rObject clone () const; /// Comparison methods. virtual bool operator< (const Object& rhs) const; /// Create a fresh scope /** ** \param parent The parent scope (optional, in which case lobby ** becomes the parent) ** \return The new scope */ static rObject make_scope(const rObject& parent = 0); /// Make a method outer scope /** ** Similar to \see make_scope, but make the scope forward ** messages to this object when relevant. ** \return The new scope. **/ rObject make_method_scope(const rObject& parent = 0); /// Return the value of \a atom as an Atom<T>. template <class T> typename T::value_type value(); private: /// The protos. protos_type* protos_; /// The protos cache at the Urbi level. rObject protos_cache_; /// The slots. slots_implem slots_; }; /// Helpers to call Urbi functions from C++. // self.'msg'(args) rObject urbi_call(runner::Runner& r, rObject self, libport::Symbol msg, objects_type args); // self.'msg'(args) for up to five arguments rObject urbi_call(runner::Runner& r, rObject self, libport::Symbol msg, rObject arg1 = 0, rObject arg2 = 0, rObject arg3 = 0, rObject arg4 = 0, rObject arg5 = 0); // owner.getSlot(msg).apply([self]) rObject urbi_call_function(runner::Runner& r, rObject self, rObject function_owner, libport::Symbol msg); // owner.getSlot(msg).apply([self, args]) rObject urbi_call_function(runner::Runner& r, rObject self, rObject function_owner, libport::Symbol msg, objects_type args); /// Call f(robj) on r and all its protos hierarchy, stop if it returns true. template<class F> bool for_all_protos(rObject& r, F& f); /// Whether \b p is present in \b c's proto hierarchy. bool is_a(const rObject& c, const rObject& p); /// Whether \a o represents a true value. bool is_true(const rObject& o); /// Return an Urbi boolean object corresponding to \a b. rObject to_boolean(bool b); } // namespace object # include <object/object.hxx> #endif // !OBJECT_OBJECT_HH <|endoftext|>
<commit_before>#include <cstring> #include <vector> #include <string> #include <fstream> #include <cstdio> #include <miopen/gcn_asm_utils.h> #include <miopen/clhelper.hpp> #include <miopen/kernel.hpp> #include <miopen/errors.hpp> #include <miopen/stringutils.hpp> #ifndef _WIN32 //Linux or APPLE #include <unistd.h> #include <paths.h> #include <sys/types.h> #include <sys/wait.h> #endif //WIN32 #ifndef _WIN32 //Linux or APPLE class TempFile { public: TempFile(const std::string& path_template) : _path(GetTempDirectoryPath() + "/" + path_template + "-XXXXXX") { _fd = mkstemp(&_path[0]); if (_fd == -1) { MIOPEN_THROW("Error: TempFile: mkstemp()"); } } ~TempFile() { const int remove_rc = std::remove(_path.c_str()); const int close_rc = close(_fd); if (remove_rc != 0 || close_rc != 0) { #ifndef NDEBUG // Be quiet in release versions. std::fprintf(stderr, "Error: TempFile: On removal of '%s', remove_rc = %d, close_rc = %d.\n", _path.c_str(), remove_rc, close_rc); #endif } } inline operator const std::string&() { return _path; } private: std::string _path; int _fd; static const std::string GetTempDirectoryPath() { const auto path = getenv("TMPDIR"); if (path != nullptr) { return path; } #if defined(P_tmpdir) return P_tmpdir; // a string literal, if defined. #elif defined(_PATH_TMP) return _PATH_TMP; // a string literal, if defined. #else return "/tmp"; #endif } }; #endif namespace miopen { static cl_program CreateProgram(cl_context ctx, const char* char_source, size_t size) { cl_int status; auto result = clCreateProgramWithSource(ctx, 1, &char_source, &size, &status); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error Creating OpenCL Program (cl_program) in LoadProgram()"); } return result; } /* * Temporary function which emulates online assembly feature of OpenCL-on-ROCm being developed. * Not intended to be used in production code, so error handling is very straghtforward, * just catch whatever possible and throw an exception. */ static void ExperimentalAmdgcnAssemble(cl_device_id device, std::string& source, const std::string& params) { #ifndef _WIN32 //Linux or APPLE TempFile outfile("amdgcn-asm-out-XXXXXX"); std::vector<std::string> args ({ "-x", "assembler", "-target", "amdgcn--amdhsa", }); { // Add -mcpu=name as reported by OpenCL-on-ROCm runtime. char name[64] = {0}; if (CL_SUCCESS != clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(name), name, nullptr)) { MIOPEN_THROW("Error: X-AMDGCN-ASM: clGetDeviceInfo()"); } args.push_back("-mcpu=" + std::string(name)); } { std::istringstream iss(params); std::string param; while (iss >> param) { args.push_back(param); }; } args.push_back("-"); args.push_back("-o"); args.push_back(outfile); std::istringstream clang_stdin(source); const auto clang_rc = ExecuteGcnAssembler(args, &clang_stdin, nullptr); if (clang_rc != 0) MIOPEN_THROW("Assembly error(" + std::to_string(clang_rc) + ")"); std::ifstream file(outfile, std::ios::binary | std::ios::ate); bool outfile_read_failed = false; do { const auto size = file.tellg(); if (size == -1) { outfile_read_failed = true; break; } source.resize(size, '\0'); file.seekg(std::ios::beg); if (file.fail()) { outfile_read_failed = true; break; } if (file.rdbuf()->sgetn(&source[0], size) != size) { outfile_read_failed = true; break; } } while (false); file.close(); if (outfile_read_failed) { MIOPEN_THROW("Error: X-AMDGCN-ASM: outfile_read_failed"); } #else (void)device; // -warning (void)source; // -warning (void)params; // -warning MIOPEN_THROW("Error: X-AMDGCN-ASM: online assembly under Windows is not supported"); #endif //WIN32 } static cl_program CreateProgramWithBinary(cl_context ctx, cl_device_id device, const char* char_source, size_t size) { cl_int status, binaryStatus; auto result = clCreateProgramWithBinary(ctx, 1, &device, reinterpret_cast<const size_t*>(&size), reinterpret_cast<const unsigned char**>(&char_source), &status, &binaryStatus); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error creating code object program (cl_program) in LoadProgramFromBinary()"); } return result; } static void BuildProgram(cl_program program, cl_device_id device, const std::string& params = "") { auto status = clBuildProgram(program, 1, &device, params.c_str(), nullptr, nullptr); if (status != CL_SUCCESS) { std::string msg = "Error Building OpenCL Program in BuildProgram()\n"; std::vector<char> errorbuf(1024 * 1024); size_t psize; clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 1024 * 1024, errorbuf.data(), &psize); msg += errorbuf.data(); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, msg); } } } ClProgramPtr LoadProgram(cl_context ctx, cl_device_id device, const std::string &program_name, std::string params, bool is_kernel_str) { bool is_binary = false; std::string source; if (is_kernel_str) { source = program_name; } else { source = miopen::GetKernelSrc(program_name); auto is_asm = miopen::EndsWith(program_name, ".s"); if (is_asm) { // Overwrites source (asm text) by binary results of assembly: ExperimentalAmdgcnAssemble(device, source, params); is_binary = true; } else { is_binary = miopen::EndsWith(program_name, ".so"); } } cl_program result = nullptr; if (is_binary) { result = CreateProgramWithBinary(ctx, device, source.data(), source.size()); BuildProgram(result, device); } else { result = CreateProgram(ctx, source.data(), source.size()); #if MIOPEN_BUILD_DEV params += " -Werror"; #endif params += " -cl-std=CL1.2"; std::cout << "BuildProgram: " << params << std::endl; BuildProgram(result, device, params); } return ClProgramPtr{ result }; } ClKernelPtr CreateKernel(cl_program program, const std::string& kernel_name) { cl_int status; ClKernelPtr result{clCreateKernel(program, kernel_name.c_str(), &status)}; if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status); } return result; } cl_device_id GetDevice(cl_command_queue q) { cl_device_id device; cl_int status = clGetCommandQueueInfo(q, CL_QUEUE_DEVICE, sizeof(cl_device_id), &device, nullptr); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error Getting Device Info from Queue in GetDevice()"); } return device; } cl_context GetContext(cl_command_queue q) { cl_context context; cl_int status = clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &context, nullptr); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error Getting Device Info from Queue in GetDevice()"); } return context; } ClAqPtr CreateQueueWithProfiling(cl_context ctx, cl_device_id dev) { cl_int status; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif ClAqPtr q{clCreateCommandQueue(ctx, dev, CL_QUEUE_PROFILING_ENABLE, &status)}; #ifdef __clang__ #pragma clang diagnostic pop #endif if(status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status); } return q; } } // namespace miopen <commit_msg>Add warnings to opencl<commit_after>#include <cstring> #include <vector> #include <string> #include <fstream> #include <cstdio> #include <miopen/gcn_asm_utils.h> #include <miopen/clhelper.hpp> #include <miopen/kernel.hpp> #include <miopen/errors.hpp> #include <miopen/stringutils.hpp> #ifndef _WIN32 //Linux or APPLE #include <unistd.h> #include <paths.h> #include <sys/types.h> #include <sys/wait.h> #endif //WIN32 #ifndef _WIN32 //Linux or APPLE class TempFile { public: TempFile(const std::string& path_template) : _path(GetTempDirectoryPath() + "/" + path_template + "-XXXXXX") { _fd = mkstemp(&_path[0]); if (_fd == -1) { MIOPEN_THROW("Error: TempFile: mkstemp()"); } } ~TempFile() { const int remove_rc = std::remove(_path.c_str()); const int close_rc = close(_fd); if (remove_rc != 0 || close_rc != 0) { #ifndef NDEBUG // Be quiet in release versions. std::fprintf(stderr, "Error: TempFile: On removal of '%s', remove_rc = %d, close_rc = %d.\n", _path.c_str(), remove_rc, close_rc); #endif } } inline operator const std::string&() { return _path; } private: std::string _path; int _fd; static const std::string GetTempDirectoryPath() { const auto path = getenv("TMPDIR"); if (path != nullptr) { return path; } #if defined(P_tmpdir) return P_tmpdir; // a string literal, if defined. #elif defined(_PATH_TMP) return _PATH_TMP; // a string literal, if defined. #else return "/tmp"; #endif } }; #endif namespace miopen { static cl_program CreateProgram(cl_context ctx, const char* char_source, size_t size) { cl_int status; auto result = clCreateProgramWithSource(ctx, 1, &char_source, &size, &status); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error Creating OpenCL Program (cl_program) in LoadProgram()"); } return result; } /* * Temporary function which emulates online assembly feature of OpenCL-on-ROCm being developed. * Not intended to be used in production code, so error handling is very straghtforward, * just catch whatever possible and throw an exception. */ static void ExperimentalAmdgcnAssemble(cl_device_id device, std::string& source, const std::string& params) { #ifndef _WIN32 //Linux or APPLE TempFile outfile("amdgcn-asm-out-XXXXXX"); std::vector<std::string> args ({ "-x", "assembler", "-target", "amdgcn--amdhsa", }); { // Add -mcpu=name as reported by OpenCL-on-ROCm runtime. char name[64] = {0}; if (CL_SUCCESS != clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(name), name, nullptr)) { MIOPEN_THROW("Error: X-AMDGCN-ASM: clGetDeviceInfo()"); } args.push_back("-mcpu=" + std::string(name)); } { std::istringstream iss(params); std::string param; while (iss >> param) { args.push_back(param); }; } args.push_back("-"); args.push_back("-o"); args.push_back(outfile); std::istringstream clang_stdin(source); const auto clang_rc = ExecuteGcnAssembler(args, &clang_stdin, nullptr); if (clang_rc != 0) MIOPEN_THROW("Assembly error(" + std::to_string(clang_rc) + ")"); std::ifstream file(outfile, std::ios::binary | std::ios::ate); bool outfile_read_failed = false; do { const auto size = file.tellg(); if (size == -1) { outfile_read_failed = true; break; } source.resize(size, '\0'); file.seekg(std::ios::beg); if (file.fail()) { outfile_read_failed = true; break; } if (file.rdbuf()->sgetn(&source[0], size) != size) { outfile_read_failed = true; break; } } while (false); file.close(); if (outfile_read_failed) { MIOPEN_THROW("Error: X-AMDGCN-ASM: outfile_read_failed"); } #else (void)device; // -warning (void)source; // -warning (void)params; // -warning MIOPEN_THROW("Error: X-AMDGCN-ASM: online assembly under Windows is not supported"); #endif //WIN32 } static cl_program CreateProgramWithBinary(cl_context ctx, cl_device_id device, const char* char_source, size_t size) { cl_int status, binaryStatus; auto result = clCreateProgramWithBinary(ctx, 1, &device, reinterpret_cast<const size_t*>(&size), reinterpret_cast<const unsigned char**>(&char_source), &status, &binaryStatus); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error creating code object program (cl_program) in LoadProgramFromBinary()"); } return result; } static void BuildProgram(cl_program program, cl_device_id device, const std::string& params = "") { auto status = clBuildProgram(program, 1, &device, params.c_str(), nullptr, nullptr); if (status != CL_SUCCESS) { std::string msg = "Error Building OpenCL Program in BuildProgram()\n"; std::vector<char> errorbuf(1024 * 1024); size_t psize; clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 1024 * 1024, errorbuf.data(), &psize); msg += errorbuf.data(); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, msg); } } } ClProgramPtr LoadProgram(cl_context ctx, cl_device_id device, const std::string &program_name, std::string params, bool is_kernel_str) { bool is_binary = false; std::string source; if (is_kernel_str) { source = program_name; } else { source = miopen::GetKernelSrc(program_name); auto is_asm = miopen::EndsWith(program_name, ".s"); if (is_asm) { // Overwrites source (asm text) by binary results of assembly: ExperimentalAmdgcnAssemble(device, source, params); is_binary = true; } else { is_binary = miopen::EndsWith(program_name, ".so"); } } cl_program result = nullptr; if (is_binary) { result = CreateProgramWithBinary(ctx, device, source.data(), source.size()); BuildProgram(result, device); } else { result = CreateProgram(ctx, source.data(), source.size()); #if MIOPEN_BUILD_DEV params += " -Werror"; #ifdef __linux__ params += " -Wf,-Weverything -Wf,-Wno-shorten-64-to-32 -Wf,-Wno-unused-macros -Wf,-Wno-unused-function -Wf,-Wno-sign-compare -Wf,-Wno-reserved-id-macro -Wf,-Wno-sign-conversion -Wf,-Wno-missing-prototypes -Wf,-Wno-cast-qual"; #endif #endif params += " -cl-std=CL1.2"; std::cout << "BuildProgram: " << params << std::endl; BuildProgram(result, device, params); } return ClProgramPtr{ result }; } ClKernelPtr CreateKernel(cl_program program, const std::string& kernel_name) { cl_int status; ClKernelPtr result{clCreateKernel(program, kernel_name.c_str(), &status)}; if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status); } return result; } cl_device_id GetDevice(cl_command_queue q) { cl_device_id device; cl_int status = clGetCommandQueueInfo(q, CL_QUEUE_DEVICE, sizeof(cl_device_id), &device, nullptr); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error Getting Device Info from Queue in GetDevice()"); } return device; } cl_context GetContext(cl_command_queue q) { cl_context context; cl_int status = clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &context, nullptr); if (status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status, "Error Getting Device Info from Queue in GetDevice()"); } return context; } ClAqPtr CreateQueueWithProfiling(cl_context ctx, cl_device_id dev) { cl_int status; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif ClAqPtr q{clCreateCommandQueue(ctx, dev, CL_QUEUE_PROFILING_ENABLE, &status)}; #ifdef __clang__ #pragma clang diagnostic pop #endif if(status != CL_SUCCESS) { MIOPEN_THROW_CL_STATUS(status); } return q; } } // namespace miopen <|endoftext|>
<commit_before>#include "ofxShadersFX.h" namespace ofxShadersFX { Shader::Shader(ShaderType p_type) { setShaderType(p_type); } void Shader::begin() { // The shader needs reload if not loaded // or if modifications in attributes occurred since last frame if (!m_shader.isLoaded() || m_needsReload) { reload(); m_needsReload = false; } m_shader.begin(); } void Shader::end() { m_shader.end(); } ShaderType Shader::shaderType() const { return m_type; } void Shader::setShaderType(ShaderType p_type) { m_type = p_type; } void Shader::reload() { this->m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER)); this->m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER)); if(ofIsGLProgrammableRenderer()) { this->m_shader.bindDefaults(); } this->m_shader.linkProgram(); } } <commit_msg>Remove unnecessary "this->" (style issue)<commit_after>// The MIT License (MIT) // Copyright (c) 2016 Alexandre Baron (Scylardor) // 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 "ofxShadersFX.h" namespace ofxShadersFX { Shader::Shader(ShaderType p_type) { setShaderType(p_type); } void Shader::begin() { // The shader needs reload if not loaded // or if modifications in attributes occurred since last frame if (!m_shader.isLoaded() || m_needsReload) { reload(); m_needsReload = false; } m_shader.begin(); } void Shader::end() { m_shader.end(); } ShaderType Shader::shaderType() const { return m_type; } void Shader::setShaderType(ShaderType p_type) { m_type = p_type; } void Shader::reload() { m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER)); m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER)); if(ofIsGLProgrammableRenderer()) { m_shader.bindDefaults(); } m_shader.linkProgram(); } } <|endoftext|>
<commit_before>// -!- c++ -!- ////////////////////////////////////////////////////////////// // // System : // Module : // Object Name : $RCSfile$ // Revision : $Revision$ // Date : $Date$ // Author : $Author$ // Created By : Robert Heller // Created : Tue Oct 9 21:19:14 2018 // Last Modified : <181014.2046> // // Description // // Notes // // History // /** \copyright * * Copyright (C) 2018 Robert Heller D/B/A Deepwoods Software * 51 Locke Hill Road * Wendell, MA 01379-9728 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * * * \file LinuxGpio.hxx * * Defines GPIO pins using the Linux sysfs ABI. * * \section HOWTOUSE How to use * * You need to use the GPIO_PIN macro at the bottom, like this: * * GPIO_PIN(LED1, GpioOutputSafeLow, 27); // Defines LED1_Pin, for GPIO 27, initialized low. * GPIO_PIN(CSLow, GpioOutputSafeHighInvert, 5); // Defines CSLow_Pin, for GPIO 5, initialized high, with the set logic inverted. * GPIO_PIN(Button1, GpioInputActiveLow, 20); // Defines Button1_Pin, for GPIO 20, avtive low -- return true when shorted to ground. * * Classes available for the second macro parameter are: * * - GpioOutputSafeLow Output initialized low, true = high * - GpioOutputSafeLowInvert Output initialized low, true = low * - GpioOutputSafeHigh Output initialized high, true = high * - GpioOutputSafeHighInvert Output initialized high, true = high * - GpioInputActiveHigh Input, high = true * - GpioInputActiveLow Input, low = true * * Be sure to use GpioInitializer to create an Initializer class: * * typedef GpioInitializer<LED1_Pin, CSLow_Pin, Button1_Pin> GpioInit; * * somewhere in main.cxx, and then in appl_main(): * * GpioInit::hw_init(); * * This makes sure the GPIO pins are properly set up (eg exported to /sys/class/gpio/). * Also, the process running the node needs to be in group gpio. * * @author Robert Heller * @date 10 October 2018 */ #ifndef __LINUXGPIO_HXX #define __LINUXGPIO_HXX #include "freertos_drivers/common/GpioWrapper.hxx" #include "os/Gpio.hxx" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> /// Defines a GPIO output pin. Writes to this structure will change the output /// level of the pin. Reads will return the pin's current level. /// Uses Linux sysfs ABI /// /// The pin is set to output at initialization time, with the level defined by /// `SAFE_VALUE'. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <int PIN_NUM> class LinuxGpio { public: /// Number of the pin static constexpr const uint32_t PIN = PIN_NUM; /// Export pin static void export_pin() { FILE *fp = fopen("/sys/class/gpio/export","w"); fprintf(fp,"%d\n",PIN); fclose(fp); // 50ms delay IS needed while kernel changes ownership of created GPIO directory usleep(50000); } /// Sets pin to output. static void set_output() { char dirname[40]; snprintf(dirname,sizeof(dirname),"/sys/class/gpio/gpio%d/direction",PIN); int dfd = open(dirname,O_WRONLY); write(dfd,"out\n",4); close(dfd); } /// Sets pin to input. static void set_input() { char dirname[40]; snprintf(dirname,sizeof(dirname),"/sys/class/gpio/gpio%d/direction",PIN); int dfd = open(dirname,O_WRONLY); write(dfd,"in\n",3); close(dfd); } /// Sets output to HIGH. static void set_on() { char valname[40]; snprintf(valname,sizeof(valname),"/sys/class/gpio/gpio%d/value",PIN); int vfd = open(valname,O_WRONLY); write(vfd,"1\n",2); close(vfd); } /// Sets output to LOW. static void set_off() { char valname[40]; snprintf(valname,sizeof(valname),"/sys/class/gpio/gpio%d/value",PIN); int vfd = open(valname,O_WRONLY); write(vfd,"0\n",2); close(vfd); } /// @return input pin level. static bool get() { char valname[40], c; snprintf(valname,sizeof(valname),"/sys/class/gpio/gpio%d/value",PIN); int vfd = open(valname,O_RDONLY); read(vfd,&c,1); close(vfd); return (c != '0'); } /// Set output pin level. @param value is the level to set to. static void set(bool value) { if (value) { set_on(); } else { set_off(); } } /// Toggles output pin value. static void toggle() { set(!get()); } /// @return true if pin is configured as an output pin. static bool is_output() { char dirname[40], c; snprintf(dirname,sizeof(dirname),"/sys/class/gpio/gpio%d/direction",PIN); int dfd = open(dirname,O_RDONLY); read(dfd,&c,1); close(dfd); return (c == 'o'); } }; /// Generic output pin template <class Base, bool SAFE_VALUE, bool INVERT = false> struct GpioOutputPin : public Base { public: /// Initializes the hardware pin. static void hw_init() { Base::export_pin(); Base::set_output(); Base::set(SAFE_VALUE); } /// Sets the hardware pin to a safe value. static void hw_set_to_safe() { Base::set(SAFE_VALUE); } /// Sets the output pinm @param value if true, output is set to HIGH, if /// false, output is set to LOW. static void set(bool value) { if (INVERT) { Base::set(!value); } else { Base::set(value); } } /// @return the static Gpio instance. static const Gpio *instance() { return GpioWrapper<GpioOutputPin<Base,SAFE_VALUE,INVERT>>::instance(); } }; /// Defines a GPIO output pin, initialized to be an output pin with low level. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeLow : public GpioOutputPin<Defs, false> { }; /// Defines a GPIO output pin, initialized to be an output pin with low /// level. All set() commands are acted upon by inverting the value. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeLowInvert : public GpioOutputPin<Defs, false, true> { }; /// Defines a GPIO output pin, initialized to be an output pin with high level. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeHigh : public GpioOutputPin<Defs, true> { }; /// Defines a GPIO output pin, initialized to be an output pin with high /// level. All set() commands are acted upon by inverting the value. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeHighInvert : public GpioOutputPin<Defs, true, true> { }; /// Generic input pin template <class Base, bool ACTIVE_HIGH = true> struct GpioInputPin : public Base { public: /// Initializes the hardware pin. static void hw_init() { Base::export_pin(); Base::set_input(); } /// Sets the hardware pin to a safe state. static void hw_set_to_safe() { hw_init(); } /// @return the static Gpio instance. static const Gpio *instance() { return GpioWrapper<GpioInputPin<Base>>::instance(); } static bool get() { if (ACTIVE_HIGH) { return Base::get(); } else { return !Base::get(); } } }; /// Defines a GPIO input pin, Active High (High == true). /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioInputActiveHigh : public GpioInputPin<Defs, true> { }; /// Defines a GPIO input pin, Active Low (Low == true). /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioInputActiveLow : public GpioInputPin<Defs, false> { }; /// Helper macro for defining GPIO pins on Linux-based microcontrollers (like the Raspberry Pi or Bagle Bone. /// /// @param NAME is the basename of the declaration. For NAME==FOO the macro /// declared FOO_Pin as a structure on which the read-write functions will be /// available. /// /// @param BaseClass is the initialization structure, such as @ref LedPin, or /// @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow. /// /// @param NUM is the pin number, such as 3 /// /// Example: /// GPIO_PIN(FOO, GpioOutputSafeLow, 3); /// ... /// FOO_Pin::set(true); #define GPIO_PIN(NAME, BaseClass, NUM) \ typedef BaseClass<LinuxGpio<NUM>> NAME##_Pin #endif // __LINUXGPIO_HXX <commit_msg>Updated copyright in LinuxGpio.hxx<commit_after>// -!- c++ -!- ////////////////////////////////////////////////////////////// // // System : // Module : // Object Name : $RCSfile$ // Revision : $Revision$ // Date : $Date$ // Author : $Author$ // Created By : Robert Heller // Created : Tue Oct 9 21:19:14 2018 // Last Modified : <181031.2137> // // Description // // Notes // // History // /** \copyright * * Copyright (C) 2018 Robert Heller D/B/A Deepwoods Software * 51 Locke Hill Road * Wendell, MA 01379-9728 * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * \file LinuxGpio.hxx * * Defines GPIO pins using the Linux sysfs ABI. * * \section HOWTOUSE How to use * * You need to use the GPIO_PIN macro at the bottom, like this: * * GPIO_PIN(LED1, GpioOutputSafeLow, 27); // Defines LED1_Pin, for GPIO 27, initialized low. * GPIO_PIN(CSLow, GpioOutputSafeHighInvert, 5); // Defines CSLow_Pin, for GPIO 5, initialized high, with the set logic inverted. * GPIO_PIN(Button1, GpioInputActiveLow, 20); // Defines Button1_Pin, for GPIO 20, avtive low -- return true when shorted to ground. * * Classes available for the second macro parameter are: * * - GpioOutputSafeLow Output initialized low, true = high * - GpioOutputSafeLowInvert Output initialized low, true = low * - GpioOutputSafeHigh Output initialized high, true = high * - GpioOutputSafeHighInvert Output initialized high, true = high * - GpioInputActiveHigh Input, high = true * - GpioInputActiveLow Input, low = true * * Be sure to use GpioInitializer to create an Initializer class: * * typedef GpioInitializer<LED1_Pin, CSLow_Pin, Button1_Pin> GpioInit; * * somewhere in main.cxx, and then in appl_main(): * * GpioInit::hw_init(); * * This makes sure the GPIO pins are properly set up (eg exported to /sys/class/gpio/). * Also, the process running the node needs to be in group gpio. * * @author Robert Heller * @date 10 October 2018 */ #ifndef __LINUXGPIO_HXX #define __LINUXGPIO_HXX #include "freertos_drivers/common/GpioWrapper.hxx" #include "os/Gpio.hxx" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> /// Defines a GPIO output pin. Writes to this structure will change the output /// level of the pin. Reads will return the pin's current level. /// Uses Linux sysfs ABI /// /// The pin is set to output at initialization time, with the level defined by /// `SAFE_VALUE'. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <int PIN_NUM> class LinuxGpio { public: /// Number of the pin static constexpr const uint32_t PIN = PIN_NUM; /// Export pin static void export_pin() { FILE *fp = fopen("/sys/class/gpio/export","w"); fprintf(fp,"%d\n",PIN); fclose(fp); // 50ms delay IS needed while kernel changes ownership of created GPIO directory usleep(50000); } /// Sets pin to output. static void set_output() { char dirname[40]; snprintf(dirname,sizeof(dirname),"/sys/class/gpio/gpio%d/direction",PIN); int dfd = open(dirname,O_WRONLY); write(dfd,"out\n",4); close(dfd); } /// Sets pin to input. static void set_input() { char dirname[40]; snprintf(dirname,sizeof(dirname),"/sys/class/gpio/gpio%d/direction",PIN); int dfd = open(dirname,O_WRONLY); write(dfd,"in\n",3); close(dfd); } /// Sets output to HIGH. static void set_on() { char valname[40]; snprintf(valname,sizeof(valname),"/sys/class/gpio/gpio%d/value",PIN); int vfd = open(valname,O_WRONLY); write(vfd,"1\n",2); close(vfd); } /// Sets output to LOW. static void set_off() { char valname[40]; snprintf(valname,sizeof(valname),"/sys/class/gpio/gpio%d/value",PIN); int vfd = open(valname,O_WRONLY); write(vfd,"0\n",2); close(vfd); } /// @return input pin level. static bool get() { char valname[40], c; snprintf(valname,sizeof(valname),"/sys/class/gpio/gpio%d/value",PIN); int vfd = open(valname,O_RDONLY); read(vfd,&c,1); close(vfd); return (c != '0'); } /// Set output pin level. @param value is the level to set to. static void set(bool value) { if (value) { set_on(); } else { set_off(); } } /// Toggles output pin value. static void toggle() { set(!get()); } /// @return true if pin is configured as an output pin. static bool is_output() { char dirname[40], c; snprintf(dirname,sizeof(dirname),"/sys/class/gpio/gpio%d/direction",PIN); int dfd = open(dirname,O_RDONLY); read(dfd,&c,1); close(dfd); return (c == 'o'); } }; /// Generic output pin template <class Base, bool SAFE_VALUE, bool INVERT = false> struct GpioOutputPin : public Base { public: /// Initializes the hardware pin. static void hw_init() { Base::export_pin(); Base::set_output(); Base::set(SAFE_VALUE); } /// Sets the hardware pin to a safe value. static void hw_set_to_safe() { Base::set(SAFE_VALUE); } /// Sets the output pinm @param value if true, output is set to HIGH, if /// false, output is set to LOW. static void set(bool value) { if (INVERT) { Base::set(!value); } else { Base::set(value); } } /// @return the static Gpio instance. static const Gpio *instance() { return GpioWrapper<GpioOutputPin<Base,SAFE_VALUE,INVERT>>::instance(); } }; /// Defines a GPIO output pin, initialized to be an output pin with low level. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeLow : public GpioOutputPin<Defs, false> { }; /// Defines a GPIO output pin, initialized to be an output pin with low /// level. All set() commands are acted upon by inverting the value. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeLowInvert : public GpioOutputPin<Defs, false, true> { }; /// Defines a GPIO output pin, initialized to be an output pin with high level. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeHigh : public GpioOutputPin<Defs, true> { }; /// Defines a GPIO output pin, initialized to be an output pin with high /// level. All set() commands are acted upon by inverting the value. /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioOutputSafeHighInvert : public GpioOutputPin<Defs, true, true> { }; /// Generic input pin template <class Base, bool ACTIVE_HIGH = true> struct GpioInputPin : public Base { public: /// Initializes the hardware pin. static void hw_init() { Base::export_pin(); Base::set_input(); } /// Sets the hardware pin to a safe state. static void hw_set_to_safe() { hw_init(); } /// @return the static Gpio instance. static const Gpio *instance() { return GpioWrapper<GpioInputPin<Base>>::instance(); } static bool get() { if (ACTIVE_HIGH) { return Base::get(); } else { return !Base::get(); } } }; /// Defines a GPIO input pin, Active High (High == true). /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioInputActiveHigh : public GpioInputPin<Defs, true> { }; /// Defines a GPIO input pin, Active Low (Low == true). /// /// Do not use this class directly. Use @ref GPIO_PIN instead. template <class Defs> struct GpioInputActiveLow : public GpioInputPin<Defs, false> { }; /// Helper macro for defining GPIO pins on Linux-based microcontrollers (like the Raspberry Pi or Bagle Bone. /// /// @param NAME is the basename of the declaration. For NAME==FOO the macro /// declared FOO_Pin as a structure on which the read-write functions will be /// available. /// /// @param BaseClass is the initialization structure, such as @ref LedPin, or /// @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow. /// /// @param NUM is the pin number, such as 3 /// /// Example: /// GPIO_PIN(FOO, GpioOutputSafeLow, 3); /// ... /// FOO_Pin::set(true); #define GPIO_PIN(NAME, BaseClass, NUM) \ typedef BaseClass<LinuxGpio<NUM>> NAME##_Pin #endif // __LINUXGPIO_HXX <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/save_restore_tensor.h" #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/tensor_bundle/tensor_bundle.h" #include "tensorflow/core/util/tensor_slice_reader.h" #include "tensorflow/core/util/tensor_slice_reader_cache.h" #include "tensorflow/core/util/tensor_slice_writer.h" namespace tensorflow { void SaveTensors( OpKernelContext* context, checkpoint::TensorSliceWriter::CreateBuilderFunction builder_func, bool save_slices) { const Tensor& filename_t = context->input(0); { const int64 size = filename_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (filename) must be a string scalar; got a tensor of ", size, "elements")); } // Path, names, and slices if save_slices is true. const int kFixedInputs = save_slices ? 3 : 2; const Tensor& tensor_names_t = context->input(1); OP_REQUIRES(context, FastBoundsCheck(tensor_names_t.NumElements() + kFixedInputs, std::numeric_limits<int>::max()), errors::InvalidArgument("Too many inputs to SaveTensors")); const int N = static_cast<int>(tensor_names_t.NumElements()); const string* tensor_shapes_and_slices_ptr = nullptr; if (save_slices) { const Tensor& tensor_shapes_and_slices_t = context->input(2); OP_REQUIRES( context, tensor_shapes_and_slices_t.NumElements() == static_cast<int64>(N), errors::InvalidArgument("Expected ", N, " elements for the tensor " "shapes and slices but got ", tensor_shapes_and_slices_t.NumElements())); tensor_shapes_and_slices_ptr = tensor_shapes_and_slices_t.flat<string>().data(); } OP_REQUIRES(context, context->num_inputs() == N + kFixedInputs, errors::InvalidArgument("Expected totally ", N + kFixedInputs, " inputs as input #1 (which is a string " "tensor of saved names) contains ", N, " names, but received ", context->num_inputs(), " inputs")); VLOG(1) << "About to save tensors to file " << filename_t.flat<string>()(0) << "..."; checkpoint::TensorSliceWriter writer(filename_t.flat<string>()(0), std::move(builder_func)); Status s; auto tensor_names_flat = tensor_names_t.flat<string>(); // Process tensors in sorted name order. This allows us to avoid seeking // during restoration in the common case where we are restoring a full // checkpoint. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); for (size_t i : sorted_name_idx) { const string& name = tensor_names_flat(i); const Tensor& input = context->input(i + kFixedInputs); TensorShape shape(input.shape()); TensorSlice slice(input.dims()); if (save_slices && !tensor_shapes_and_slices_ptr[i].empty()) { const string& shape_spec = tensor_shapes_and_slices_ptr[i]; TensorShape slice_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &shape, &slice, &slice_shape)); OP_REQUIRES(context, slice_shape.IsSameSize(input.shape()), errors::InvalidArgument( "Slice in shape_and_slice " "specification does not match the " "shape of the tensor to save: ", shape_spec, ", tensor: ", input.shape().DebugString())); } #define WRITER_ADD(T) \ case DataTypeToEnum<T>::value: \ s = writer.Add(name, shape, slice, input.flat<T>().data()); \ break; switch (input.dtype()) { TF_CALL_SAVE_RESTORE_TYPES(WRITER_ADD) default: context->SetStatus(errors::Unimplemented("Saving data type ", DataTypeString(input.dtype()), " not yet supported")); return; } #undef WRITER_ADD if (!s.ok()) { context->SetStatus(s); return; } } s = writer.Finish(); if (!s.ok()) { context->SetStatus(s); } } void RestoreTensor(OpKernelContext* context, checkpoint::TensorSliceReader::OpenTableFunction open_func, int preferred_shard, bool restore_slice, int restore_index) { const Tensor& file_pattern_t = context->input(0); { const int64 size = file_pattern_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (file_pattern) must be a string scalar; got a tensor of ", size, "elements")); } const string& file_pattern = file_pattern_t.flat<string>()(0); const Tensor& tensor_name_t = context->input(1); const string& tensor_name = tensor_name_t.flat<string>()(restore_index); // If we cannot find a cached reader we will allocate our own. std::unique_ptr<checkpoint::TensorSliceReader> allocated_reader; const checkpoint::TensorSliceReader* reader = context->slice_reader_cache()->GetReader(file_pattern, open_func, preferred_shard); if (!reader) { allocated_reader.reset(new checkpoint::TensorSliceReader( file_pattern, open_func, preferred_shard)); reader = allocated_reader.get(); } OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status()); // Get the shape and type from the save file. DataType type; TensorShape saved_shape; OP_REQUIRES( context, reader->HasTensor(tensor_name, &saved_shape, &type), errors::NotFound("Tensor name \"", tensor_name, "\" not found in checkpoint files ", file_pattern)); OP_REQUIRES( context, type == context->expected_output_dtype(restore_index), errors::InvalidArgument("Expected to restore a tensor of type ", DataTypeString(context->expected_output_dtype(0)), ", got a tensor of type ", DataTypeString(type), " instead: tensor_name = ", tensor_name)); // Shape of the output and slice to load. TensorShape output_shape(saved_shape); TensorSlice slice_to_load(saved_shape.dims()); if (restore_slice) { const string& shape_spec = context->input(2).flat<string>()(restore_index); if (!shape_spec.empty()) { TensorShape parsed_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &parsed_shape, &slice_to_load, &output_shape)); OP_REQUIRES( context, parsed_shape.IsSameSize(saved_shape), errors::InvalidArgument( "Shape in shape_and_slice spec does not match the shape in the " "save file: ", parsed_shape.DebugString(), ", save file shape: ", saved_shape.DebugString())); } } Tensor* t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(restore_index, output_shape, &t)); if (output_shape.num_elements() == 0) return; #define READER_COPY(T) \ case DataTypeToEnum<T>::value: \ OP_REQUIRES(context, \ reader->CopySliceData(tensor_name, slice_to_load, \ t->flat<T>().data()), \ errors::InvalidArgument("Error copying slice data")); \ break; switch (type) { TF_CALL_SAVE_RESTORE_TYPES(READER_COPY) default: context->SetStatus(errors::Unimplemented( "Restoring data type ", DataTypeString(type), " not yet supported")); } #undef READER_COPY } Status RestoreTensorsV2(OpKernelContext* context, const Tensor& prefix, const Tensor& tensor_names, const Tensor& shape_and_slices, gtl::ArraySlice<DataType> dtypes) { const string& prefix_string = prefix.scalar<string>()(); const auto& tensor_names_flat = tensor_names.flat<string>(); const auto& shape_and_slices_flat = shape_and_slices.flat<string>(); // Sort lookup keys to improve locality when reading multiple tensors. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); BundleReader reader(Env::Default(), prefix_string); TF_RETURN_IF_ERROR(reader.status()); // TODO(zongheng): potential optimization: one Seek() in first lookup. // TODO(zongheng): consider measuring speed and issuing concurrent lookups // within a fixed memory budget. TensorShape restored_full_shape; std::vector<string> mismatched_errors; for (size_t i : sorted_name_idx) { DataType original_dtype; const string& tensor_name = tensor_names_flat(i); TF_RETURN_IF_ERROR( reader.LookupDtypeAndShape(tensor_name, &original_dtype, &restored_full_shape)); if (dtypes[i] != original_dtype) { string error_msg = strings::StrCat( "tensor_name = ", tensor_name, "; expected dtype ", DataTypeString(dtypes[i]), " does not equal original dtype ", DataTypeString(original_dtype)); mismatched_errors.emplace_back(error_msg); } } if (!mismatched_errors.empty()) { const string error_msg = str_util::Join(mismatched_errors, "\n"); return errors::InvalidArgument(error_msg); } Tensor* restored_tensor = nullptr; for (auto i : sorted_name_idx) { const string& tensor_name = tensor_names_flat(i); const string& shape_and_slice = shape_and_slices_flat(i); TF_RETURN_IF_ERROR( reader.LookupTensorShape(tensor_name, &restored_full_shape)); if (shape_and_slice.empty()) { // Lookup the full tensor. TF_RETURN_IF_ERROR( context->allocate_output(i, restored_full_shape, &restored_tensor)); TF_RETURN_IF_ERROR(reader.Lookup(tensor_name, restored_tensor)); } else { // Lookup the slice. TensorShape parsed_full_shape; TensorSlice parsed_slice; TensorShape parsed_slice_shape; TF_RETURN_IF_ERROR( checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape, &parsed_slice, &parsed_slice_shape)); if (!restored_full_shape.IsSameSize(parsed_full_shape)) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; shape in shape_and_slice spec ", parsed_full_shape.DebugString(), " does not match the shape stored in checkpoint: ", restored_full_shape.DebugString()); } TF_RETURN_IF_ERROR( context->allocate_output(i, parsed_slice_shape, &restored_tensor)); TF_RETURN_IF_ERROR( reader.LookupSlice(tensor_name, parsed_slice, restored_tensor)); } if (dtypes[i] != restored_tensor->dtype()) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; expected dtype ", DataTypeString(dtypes[i]), " does not equal restored dtype ", DataTypeString(restored_tensor->dtype())); } } return Status::OK(); } } // namespace tensorflow <commit_msg>Const correct.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/save_restore_tensor.h" #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/tensor_bundle/tensor_bundle.h" #include "tensorflow/core/util/tensor_slice_reader.h" #include "tensorflow/core/util/tensor_slice_reader_cache.h" #include "tensorflow/core/util/tensor_slice_writer.h" namespace tensorflow { void SaveTensors( OpKernelContext* context, checkpoint::TensorSliceWriter::CreateBuilderFunction builder_func, bool save_slices) { const Tensor& filename_t = context->input(0); { const int64 size = filename_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (filename) must be a string scalar; got a tensor of ", size, "elements")); } // Path, names, and slices if save_slices is true. const int kFixedInputs = save_slices ? 3 : 2; const Tensor& tensor_names_t = context->input(1); OP_REQUIRES(context, FastBoundsCheck(tensor_names_t.NumElements() + kFixedInputs, std::numeric_limits<int>::max()), errors::InvalidArgument("Too many inputs to SaveTensors")); const int N = static_cast<int>(tensor_names_t.NumElements()); const string* tensor_shapes_and_slices_ptr = nullptr; if (save_slices) { const Tensor& tensor_shapes_and_slices_t = context->input(2); OP_REQUIRES( context, tensor_shapes_and_slices_t.NumElements() == static_cast<int64>(N), errors::InvalidArgument("Expected ", N, " elements for the tensor " "shapes and slices but got ", tensor_shapes_and_slices_t.NumElements())); tensor_shapes_and_slices_ptr = tensor_shapes_and_slices_t.flat<string>().data(); } OP_REQUIRES(context, context->num_inputs() == N + kFixedInputs, errors::InvalidArgument("Expected totally ", N + kFixedInputs, " inputs as input #1 (which is a string " "tensor of saved names) contains ", N, " names, but received ", context->num_inputs(), " inputs")); VLOG(1) << "About to save tensors to file " << filename_t.flat<string>()(0) << "..."; checkpoint::TensorSliceWriter writer(filename_t.flat<string>()(0), std::move(builder_func)); Status s; auto tensor_names_flat = tensor_names_t.flat<string>(); // Process tensors in sorted name order. This allows us to avoid seeking // during restoration in the common case where we are restoring a full // checkpoint. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); for (const size_t i : sorted_name_idx) { const string& name = tensor_names_flat(i); const Tensor& input = context->input(i + kFixedInputs); TensorShape shape(input.shape()); TensorSlice slice(input.dims()); if (save_slices && !tensor_shapes_and_slices_ptr[i].empty()) { const string& shape_spec = tensor_shapes_and_slices_ptr[i]; TensorShape slice_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &shape, &slice, &slice_shape)); OP_REQUIRES(context, slice_shape.IsSameSize(input.shape()), errors::InvalidArgument( "Slice in shape_and_slice " "specification does not match the " "shape of the tensor to save: ", shape_spec, ", tensor: ", input.shape().DebugString())); } #define WRITER_ADD(T) \ case DataTypeToEnum<T>::value: \ s = writer.Add(name, shape, slice, input.flat<T>().data()); \ break; switch (input.dtype()) { TF_CALL_SAVE_RESTORE_TYPES(WRITER_ADD) default: context->SetStatus(errors::Unimplemented("Saving data type ", DataTypeString(input.dtype()), " not yet supported")); return; } #undef WRITER_ADD if (!s.ok()) { context->SetStatus(s); return; } } s = writer.Finish(); if (!s.ok()) { context->SetStatus(s); } } void RestoreTensor(OpKernelContext* context, checkpoint::TensorSliceReader::OpenTableFunction open_func, int preferred_shard, bool restore_slice, int restore_index) { const Tensor& file_pattern_t = context->input(0); { const int64 size = file_pattern_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (file_pattern) must be a string scalar; got a tensor of ", size, "elements")); } const string& file_pattern = file_pattern_t.flat<string>()(0); const Tensor& tensor_name_t = context->input(1); const string& tensor_name = tensor_name_t.flat<string>()(restore_index); // If we cannot find a cached reader we will allocate our own. std::unique_ptr<checkpoint::TensorSliceReader> allocated_reader; const checkpoint::TensorSliceReader* reader = context->slice_reader_cache()->GetReader(file_pattern, open_func, preferred_shard); if (!reader) { allocated_reader.reset(new checkpoint::TensorSliceReader( file_pattern, open_func, preferred_shard)); reader = allocated_reader.get(); } OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status()); // Get the shape and type from the save file. DataType type; TensorShape saved_shape; OP_REQUIRES( context, reader->HasTensor(tensor_name, &saved_shape, &type), errors::NotFound("Tensor name \"", tensor_name, "\" not found in checkpoint files ", file_pattern)); OP_REQUIRES( context, type == context->expected_output_dtype(restore_index), errors::InvalidArgument("Expected to restore a tensor of type ", DataTypeString(context->expected_output_dtype(0)), ", got a tensor of type ", DataTypeString(type), " instead: tensor_name = ", tensor_name)); // Shape of the output and slice to load. TensorShape output_shape(saved_shape); TensorSlice slice_to_load(saved_shape.dims()); if (restore_slice) { const string& shape_spec = context->input(2).flat<string>()(restore_index); if (!shape_spec.empty()) { TensorShape parsed_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &parsed_shape, &slice_to_load, &output_shape)); OP_REQUIRES( context, parsed_shape.IsSameSize(saved_shape), errors::InvalidArgument( "Shape in shape_and_slice spec does not match the shape in the " "save file: ", parsed_shape.DebugString(), ", save file shape: ", saved_shape.DebugString())); } } Tensor* t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(restore_index, output_shape, &t)); if (output_shape.num_elements() == 0) return; #define READER_COPY(T) \ case DataTypeToEnum<T>::value: \ OP_REQUIRES(context, \ reader->CopySliceData(tensor_name, slice_to_load, \ t->flat<T>().data()), \ errors::InvalidArgument("Error copying slice data")); \ break; switch (type) { TF_CALL_SAVE_RESTORE_TYPES(READER_COPY) default: context->SetStatus(errors::Unimplemented( "Restoring data type ", DataTypeString(type), " not yet supported")); } #undef READER_COPY } Status RestoreTensorsV2(OpKernelContext* context, const Tensor& prefix, const Tensor& tensor_names, const Tensor& shape_and_slices, gtl::ArraySlice<DataType> dtypes) { const string& prefix_string = prefix.scalar<string>()(); const auto& tensor_names_flat = tensor_names.flat<string>(); const auto& shape_and_slices_flat = shape_and_slices.flat<string>(); // Sort lookup keys to improve locality when reading multiple tensors. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); BundleReader reader(Env::Default(), prefix_string); TF_RETURN_IF_ERROR(reader.status()); // TODO(zongheng): potential optimization: one Seek() in first lookup. // TODO(zongheng): consider measuring speed and issuing concurrent lookups // within a fixed memory budget. TensorShape restored_full_shape; std::vector<string> mismatched_errors; for (size_t i : sorted_name_idx) { DataType original_dtype; const string& tensor_name = tensor_names_flat(i); TF_RETURN_IF_ERROR( reader.LookupDtypeAndShape(tensor_name, &original_dtype, &restored_full_shape)); if (dtypes[i] != original_dtype) { string error_msg = strings::StrCat( "tensor_name = ", tensor_name, "; expected dtype ", DataTypeString(dtypes[i]), " does not equal original dtype ", DataTypeString(original_dtype)); mismatched_errors.emplace_back(error_msg); } } if (!mismatched_errors.empty()) { const string error_msg = str_util::Join(mismatched_errors, "\n"); return errors::InvalidArgument(error_msg); } Tensor* restored_tensor = nullptr; for (auto i : sorted_name_idx) { const string& tensor_name = tensor_names_flat(i); const string& shape_and_slice = shape_and_slices_flat(i); TF_RETURN_IF_ERROR( reader.LookupTensorShape(tensor_name, &restored_full_shape)); if (shape_and_slice.empty()) { // Lookup the full tensor. TF_RETURN_IF_ERROR( context->allocate_output(i, restored_full_shape, &restored_tensor)); TF_RETURN_IF_ERROR(reader.Lookup(tensor_name, restored_tensor)); } else { // Lookup the slice. TensorShape parsed_full_shape; TensorSlice parsed_slice; TensorShape parsed_slice_shape; TF_RETURN_IF_ERROR( checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape, &parsed_slice, &parsed_slice_shape)); if (!restored_full_shape.IsSameSize(parsed_full_shape)) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; shape in shape_and_slice spec ", parsed_full_shape.DebugString(), " does not match the shape stored in checkpoint: ", restored_full_shape.DebugString()); } TF_RETURN_IF_ERROR( context->allocate_output(i, parsed_slice_shape, &restored_tensor)); TF_RETURN_IF_ERROR( reader.LookupSlice(tensor_name, parsed_slice, restored_tensor)); } if (dtypes[i] != restored_tensor->dtype()) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; expected dtype ", DataTypeString(dtypes[i]), " does not equal restored dtype ", DataTypeString(restored_tensor->dtype())); } } return Status::OK(); } } // namespace tensorflow <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/save_restore_tensor.h" #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/tensor_bundle/tensor_bundle.h" #include "tensorflow/core/util/tensor_slice_reader.h" #include "tensorflow/core/util/tensor_slice_reader_cache.h" #include "tensorflow/core/util/tensor_slice_writer.h" namespace tensorflow { void SaveTensors( OpKernelContext* context, checkpoint::TensorSliceWriter::CreateBuilderFunction builder_func, bool save_slices) { const Tensor& filename_t = context->input(0); { const int64 size = filename_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (filename) must be a string scalar; got a tensor of ", size, "elements")); } // Path, names, and slices if save_slices is true. const int kFixedInputs = save_slices ? 3 : 2; const Tensor& tensor_names_t = context->input(1); OP_REQUIRES(context, FastBoundsCheck(tensor_names_t.NumElements() + kFixedInputs, std::numeric_limits<int>::max()), errors::InvalidArgument("Too many inputs to SaveTensors")); const int N = static_cast<int>(tensor_names_t.NumElements()); const string* tensor_shapes_and_slices_ptr = nullptr; if (save_slices) { const Tensor& tensor_shapes_and_slices_t = context->input(2); OP_REQUIRES( context, tensor_shapes_and_slices_t.NumElements() == static_cast<int64>(N), errors::InvalidArgument("Expected ", N, " elements for the tensor " "shapes and slices but got ", tensor_shapes_and_slices_t.NumElements())); tensor_shapes_and_slices_ptr = tensor_shapes_and_slices_t.flat<string>().data(); } OP_REQUIRES(context, context->num_inputs() == N + kFixedInputs, errors::InvalidArgument("Expected totally ", N + kFixedInputs, " inputs as input #1 (which is a string " "tensor of saved names) contains ", N, " names, but received ", context->num_inputs(), " inputs")); VLOG(1) << "About to save tensors to file " << filename_t.flat<string>()(0) << "..."; checkpoint::TensorSliceWriter writer(filename_t.flat<string>()(0), std::move(builder_func)); Status s; auto tensor_names_flat = tensor_names_t.flat<string>(); // Process tensors in sorted name order. This allows us to avoid seeking // during restoration in the common case where we are restoring a full // checkpoint. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); for (size_t i : sorted_name_idx) { const string& name = tensor_names_flat(i); const Tensor& input = context->input(i + kFixedInputs); TensorShape shape(input.shape()); TensorSlice slice(input.dims()); if (save_slices && !tensor_shapes_and_slices_ptr[i].empty()) { const string& shape_spec = tensor_shapes_and_slices_ptr[i]; TensorShape slice_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &shape, &slice, &slice_shape)); OP_REQUIRES(context, slice_shape.IsSameSize(input.shape()), errors::InvalidArgument( "Slice in shape_and_slice " "specification does not match the " "shape of the tensor to save: ", shape_spec, ", tensor: ", input.shape().DebugString())); } #define WRITER_ADD(T) \ case DataTypeToEnum<T>::value: \ s = writer.Add(name, shape, slice, input.flat<T>().data()); \ break; switch (input.dtype()) { TF_CALL_SAVE_RESTORE_TYPES(WRITER_ADD) default: context->SetStatus(errors::Unimplemented("Saving data type ", DataTypeString(input.dtype()), " not yet supported")); return; } #undef WRITER_ADD if (!s.ok()) { context->SetStatus(s); return; } } s = writer.Finish(); if (!s.ok()) { context->SetStatus(s); } } void RestoreTensor(OpKernelContext* context, checkpoint::TensorSliceReader::OpenTableFunction open_func, int preferred_shard, bool restore_slice, int restore_index) { const Tensor& file_pattern_t = context->input(0); { const int64 size = file_pattern_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (file_pattern) must be a string scalar; got a tensor of ", size, "elements")); } const string& file_pattern = file_pattern_t.flat<string>()(0); const Tensor& tensor_name_t = context->input(1); const string& tensor_name = tensor_name_t.flat<string>()(restore_index); // If we cannot find a cached reader we will allocate our own. std::unique_ptr<checkpoint::TensorSliceReader> allocated_reader; const checkpoint::TensorSliceReader* reader = context->slice_reader_cache()->GetReader(file_pattern, open_func, preferred_shard); if (!reader) { allocated_reader.reset(new checkpoint::TensorSliceReader( file_pattern, open_func, preferred_shard)); reader = allocated_reader.get(); } OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status()); // Get the shape and type from the save file. DataType type; TensorShape saved_shape; OP_REQUIRES( context, reader->HasTensor(tensor_name, &saved_shape, &type), errors::NotFound("Tensor name \"", tensor_name, "\" not found in checkpoint files ", file_pattern)); OP_REQUIRES( context, type == context->expected_output_dtype(restore_index), errors::InvalidArgument("Expected to restore a tensor of type ", DataTypeString(context->expected_output_dtype(0)), ", got a tensor of type ", DataTypeString(type), " instead: tensor_name = ", tensor_name)); // Shape of the output and slice to load. TensorShape output_shape(saved_shape); TensorSlice slice_to_load(saved_shape.dims()); if (restore_slice) { const string& shape_spec = context->input(2).flat<string>()(restore_index); if (!shape_spec.empty()) { TensorShape parsed_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &parsed_shape, &slice_to_load, &output_shape)); OP_REQUIRES( context, parsed_shape.IsSameSize(saved_shape), errors::InvalidArgument( "Shape in shape_and_slice spec does not match the shape in the " "save file: ", parsed_shape.DebugString(), ", save file shape: ", saved_shape.DebugString())); } } Tensor* t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(restore_index, output_shape, &t)); if (output_shape.num_elements() == 0) return; #define READER_COPY(T) \ case DataTypeToEnum<T>::value: \ OP_REQUIRES(context, \ reader->CopySliceData(tensor_name, slice_to_load, \ t->flat<T>().data()), \ errors::InvalidArgument("Error copying slice data")); \ break; switch (type) { TF_CALL_SAVE_RESTORE_TYPES(READER_COPY) default: context->SetStatus(errors::Unimplemented( "Restoring data type ", DataTypeString(type), " not yet supported")); } #undef READER_COPY } Status RestoreTensorsV2(OpKernelContext* context, const Tensor& prefix, const Tensor& tensor_names, const Tensor& shape_and_slices, gtl::ArraySlice<DataType> dtypes) { const string& prefix_string = prefix.scalar<string>()(); const auto& tensor_names_flat = tensor_names.flat<string>(); const auto& shape_and_slices_flat = shape_and_slices.flat<string>(); // Sort lookup keys to improve locality when reading multiple tensors. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); BundleReader reader(Env::Default(), prefix_string); TF_RETURN_IF_ERROR(reader.status()); // TODO(zongheng): potential optimization: one Seek() in first lookup. // TODO(zongheng): consider measuring speed and issuing concurrent lookups // within a fixed memory budget. TensorShape restored_full_shape; Tensor* restored_tensor = nullptr; for (auto i : sorted_name_idx) { const string& tensor_name = tensor_names_flat(i); const string& shape_and_slice = shape_and_slices_flat(i); TF_RETURN_IF_ERROR( reader.LookupTensorShape(tensor_name, &restored_full_shape)); if (shape_and_slice.empty()) { // Lookup the full tensor. TF_RETURN_IF_ERROR( context->allocate_output(i, restored_full_shape, &restored_tensor)); TF_RETURN_IF_ERROR(reader.Lookup(tensor_name, restored_tensor)); } else { // Lookup the slice. TensorShape parsed_full_shape; TensorSlice parsed_slice; TensorShape parsed_slice_shape; TF_RETURN_IF_ERROR( checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape, &parsed_slice, &parsed_slice_shape)); if (!restored_full_shape.IsSameSize(parsed_full_shape)) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; shape in shape_and_slice spec ", parsed_full_shape.DebugString(), " does not match the shape stored in checkpoint: ", restored_full_shape.DebugString()); } TF_RETURN_IF_ERROR( context->allocate_output(i, parsed_slice_shape, &restored_tensor)); TF_RETURN_IF_ERROR( reader.LookupSlice(tensor_name, parsed_slice, restored_tensor)); } if (dtypes[i] != restored_tensor->dtype()) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; expected dtype ", DataTypeString(dtypes[i]), " does not equal restored dtype ", DataTypeString(restored_tensor->dtype())); } } return Status::OK(); } } // namespace tensorflow <commit_msg>BUG: check original dtype with restore dtype<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/save_restore_tensor.h" #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/tensor_bundle/tensor_bundle.h" #include "tensorflow/core/util/tensor_slice_reader.h" #include "tensorflow/core/util/tensor_slice_reader_cache.h" #include "tensorflow/core/util/tensor_slice_writer.h" namespace tensorflow { void SaveTensors( OpKernelContext* context, checkpoint::TensorSliceWriter::CreateBuilderFunction builder_func, bool save_slices) { const Tensor& filename_t = context->input(0); { const int64 size = filename_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (filename) must be a string scalar; got a tensor of ", size, "elements")); } // Path, names, and slices if save_slices is true. const int kFixedInputs = save_slices ? 3 : 2; const Tensor& tensor_names_t = context->input(1); OP_REQUIRES(context, FastBoundsCheck(tensor_names_t.NumElements() + kFixedInputs, std::numeric_limits<int>::max()), errors::InvalidArgument("Too many inputs to SaveTensors")); const int N = static_cast<int>(tensor_names_t.NumElements()); const string* tensor_shapes_and_slices_ptr = nullptr; if (save_slices) { const Tensor& tensor_shapes_and_slices_t = context->input(2); OP_REQUIRES( context, tensor_shapes_and_slices_t.NumElements() == static_cast<int64>(N), errors::InvalidArgument("Expected ", N, " elements for the tensor " "shapes and slices but got ", tensor_shapes_and_slices_t.NumElements())); tensor_shapes_and_slices_ptr = tensor_shapes_and_slices_t.flat<string>().data(); } OP_REQUIRES(context, context->num_inputs() == N + kFixedInputs, errors::InvalidArgument("Expected totally ", N + kFixedInputs, " inputs as input #1 (which is a string " "tensor of saved names) contains ", N, " names, but received ", context->num_inputs(), " inputs")); VLOG(1) << "About to save tensors to file " << filename_t.flat<string>()(0) << "..."; checkpoint::TensorSliceWriter writer(filename_t.flat<string>()(0), std::move(builder_func)); Status s; auto tensor_names_flat = tensor_names_t.flat<string>(); // Process tensors in sorted name order. This allows us to avoid seeking // during restoration in the common case where we are restoring a full // checkpoint. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); for (size_t i : sorted_name_idx) { const string& name = tensor_names_flat(i); const Tensor& input = context->input(i + kFixedInputs); TensorShape shape(input.shape()); TensorSlice slice(input.dims()); if (save_slices && !tensor_shapes_and_slices_ptr[i].empty()) { const string& shape_spec = tensor_shapes_and_slices_ptr[i]; TensorShape slice_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &shape, &slice, &slice_shape)); OP_REQUIRES(context, slice_shape.IsSameSize(input.shape()), errors::InvalidArgument( "Slice in shape_and_slice " "specification does not match the " "shape of the tensor to save: ", shape_spec, ", tensor: ", input.shape().DebugString())); } #define WRITER_ADD(T) \ case DataTypeToEnum<T>::value: \ s = writer.Add(name, shape, slice, input.flat<T>().data()); \ break; switch (input.dtype()) { TF_CALL_SAVE_RESTORE_TYPES(WRITER_ADD) default: context->SetStatus(errors::Unimplemented("Saving data type ", DataTypeString(input.dtype()), " not yet supported")); return; } #undef WRITER_ADD if (!s.ok()) { context->SetStatus(s); return; } } s = writer.Finish(); if (!s.ok()) { context->SetStatus(s); } } void RestoreTensor(OpKernelContext* context, checkpoint::TensorSliceReader::OpenTableFunction open_func, int preferred_shard, bool restore_slice, int restore_index) { const Tensor& file_pattern_t = context->input(0); { const int64 size = file_pattern_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (file_pattern) must be a string scalar; got a tensor of ", size, "elements")); } const string& file_pattern = file_pattern_t.flat<string>()(0); const Tensor& tensor_name_t = context->input(1); const string& tensor_name = tensor_name_t.flat<string>()(restore_index); // If we cannot find a cached reader we will allocate our own. std::unique_ptr<checkpoint::TensorSliceReader> allocated_reader; const checkpoint::TensorSliceReader* reader = context->slice_reader_cache()->GetReader(file_pattern, open_func, preferred_shard); if (!reader) { allocated_reader.reset(new checkpoint::TensorSliceReader( file_pattern, open_func, preferred_shard)); reader = allocated_reader.get(); } OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status()); // Get the shape and type from the save file. DataType type; TensorShape saved_shape; OP_REQUIRES( context, reader->HasTensor(tensor_name, &saved_shape, &type), errors::NotFound("Tensor name \"", tensor_name, "\" not found in checkpoint files ", file_pattern)); OP_REQUIRES( context, type == context->expected_output_dtype(restore_index), errors::InvalidArgument("Expected to restore a tensor of type ", DataTypeString(context->expected_output_dtype(0)), ", got a tensor of type ", DataTypeString(type), " instead: tensor_name = ", tensor_name)); // Shape of the output and slice to load. TensorShape output_shape(saved_shape); TensorSlice slice_to_load(saved_shape.dims()); if (restore_slice) { const string& shape_spec = context->input(2).flat<string>()(restore_index); if (!shape_spec.empty()) { TensorShape parsed_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &parsed_shape, &slice_to_load, &output_shape)); OP_REQUIRES( context, parsed_shape.IsSameSize(saved_shape), errors::InvalidArgument( "Shape in shape_and_slice spec does not match the shape in the " "save file: ", parsed_shape.DebugString(), ", save file shape: ", saved_shape.DebugString())); } } Tensor* t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(restore_index, output_shape, &t)); if (output_shape.num_elements() == 0) return; #define READER_COPY(T) \ case DataTypeToEnum<T>::value: \ OP_REQUIRES(context, \ reader->CopySliceData(tensor_name, slice_to_load, \ t->flat<T>().data()), \ errors::InvalidArgument("Error copying slice data")); \ break; switch (type) { TF_CALL_SAVE_RESTORE_TYPES(READER_COPY) default: context->SetStatus(errors::Unimplemented( "Restoring data type ", DataTypeString(type), " not yet supported")); } #undef READER_COPY } Status RestoreTensorsV2(OpKernelContext* context, const Tensor& prefix, const Tensor& tensor_names, const Tensor& shape_and_slices, gtl::ArraySlice<DataType> dtypes) { const string& prefix_string = prefix.scalar<string>()(); const auto& tensor_names_flat = tensor_names.flat<string>(); const auto& shape_and_slices_flat = shape_and_slices.flat<string>(); // Sort lookup keys to improve locality when reading multiple tensors. std::vector<size_t> sorted_name_idx(tensor_names_flat.size()); std::iota(sorted_name_idx.begin(), sorted_name_idx.end(), 0); std::sort(sorted_name_idx.begin(), sorted_name_idx.end(), [&tensor_names_flat](size_t a, size_t b) { return tensor_names_flat(a) < tensor_names_flat(b); }); BundleReader reader(Env::Default(), prefix_string); TF_RETURN_IF_ERROR(reader.status()); // TODO(zongheng): potential optimization: one Seek() in first lookup. // TODO(zongheng): consider measuring speed and issuing concurrent lookups // within a fixed memory budget. TensorShape restored_full_shape; DataType restored_dtype; Tensor* restored_tensor = nullptr; for (auto i : sorted_name_idx) { const string& tensor_name = tensor_names_flat(i); const string& shape_and_slice = shape_and_slices_flat(i); TF_RETURN_IF_ERROR( reader.LookupDtypeAndShape(tensor_name, &restored_dtype, &restored_full_shape)); if (shape_and_slice.empty()) { // Lookup the full tensor. TF_RETURN_IF_ERROR( context->allocate_output(i, restored_full_shape, &restored_tensor)); TF_RETURN_IF_ERROR(reader.Lookup(tensor_name, restored_tensor)); } else { // Lookup the slice. TensorShape parsed_full_shape; TensorSlice parsed_slice; TensorShape parsed_slice_shape; TF_RETURN_IF_ERROR( checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape, &parsed_slice, &parsed_slice_shape)); if (!restored_full_shape.IsSameSize(parsed_full_shape)) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; shape in shape_and_slice spec ", parsed_full_shape.DebugString(), " does not match the shape stored in checkpoint: ", restored_full_shape.DebugString()); } TF_RETURN_IF_ERROR( context->allocate_output(i, parsed_slice_shape, &restored_tensor)); TF_RETURN_IF_ERROR( reader.LookupSlice(tensor_name, parsed_slice, restored_tensor)); } if (restored_dtype != restored_tensor->dtype()) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; expected dtype ", DataTypeString(restored_dtype), " does not equal restored dtype ", DataTypeString(restored_tensor->dtype())); } } return Status::OK(); } } // namespace tensorflow <|endoftext|>
<commit_before>// RUN: %clang_cc1 -triple %itanium_abi_triple -fms-extensions -emit-llvm %s -o- | FileCheck %s struct A { void foo() __unaligned; void foo() const __unaligned; void foo() volatile __unaligned; void foo() const volatile __unaligned; }; void A::foo() __unaligned {} // CHECK: define void @_ZNU11__unaligned1A3fooEv( void A::foo() const __unaligned {} // CHECK: define void @_ZNU11__unalignedK1A3fooEv( void A::foo() volatile __unaligned {} // CHECK: define void @_ZNU11__unalignedV1A3fooEv( void A::foo() const volatile __unaligned {} // CHECK: define void @_ZNU11__unalignedVK1A3fooEv( <commit_msg>clang/test/CodeGenCXX/unaligned-member-qualifier.cpp: Satisfy x86_thiscallcc.<commit_after>// RUN: %clang_cc1 -triple %itanium_abi_triple -fms-extensions -emit-llvm %s -o- | FileCheck %s struct A { void foo() __unaligned; void foo() const __unaligned; void foo() volatile __unaligned; void foo() const volatile __unaligned; }; void A::foo() __unaligned {} // CHECK: define [[THISCALL:(x86_thiscallcc )?]]void @_ZNU11__unaligned1A3fooEv( void A::foo() const __unaligned {} // CHECK: define [[THISCALL]]void @_ZNU11__unalignedK1A3fooEv( void A::foo() volatile __unaligned {} // CHECK: define [[THISCALL]]void @_ZNU11__unalignedV1A3fooEv( void A::foo() const volatile __unaligned {} // CHECK: define [[THISCALL]]void @_ZNU11__unalignedVK1A3fooEv( <|endoftext|>
<commit_before><commit_msg>pdn: more clang fixes<commit_after><|endoftext|>
<commit_before>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2017 Liviu Ionescu. * * 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 <micro-os-plus/board.h> #include <micro-os-plus/startup/initialize-hooks.h> // ---------------------------------------------------------------------------- {% if content == 'blinky' %} extern plic_instance_t g_plic; {% endif %} // Called early, before copying .data and clearing .bss. // Should initialise the clocks and possible other RAM areas. void os_startup_initialize_hardware_early (void) { // Disable all interrupts. {% if language == 'cpp' %} riscv::csr::clear_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_clear_mstatus (MSTATUS_MIE); {% endif %} // Disable all individual interrupts. {% if language == 'cpp' %} riscv::csr::mie (0); {% elsif language == 'c' %} riscv_csr_write_mie (0); {% endif %} // Set the trap assembly handler. {% if language == 'cpp' %} riscv::csr::mtvec ((riscv::arch::register_t) riscv_trap_entry); {% elsif language == 'c' %} riscv_csr_write_mtvec ((riscv_arch_register_t) riscv_trap_entry); {% endif %} // TODO: add support for the PRCI peripheral and use it. {% if deviceName == 'fe310' %} // TODO: add to C/C++ API // Make sure the HFROSC is on before the next line: PRCI_REG(PRCI_HFROSCCFG) |= ROSC_EN(1); // Run off 16 MHz Crystal for accuracy. PRCI_REG(PRCI_PLLCFG) = (PLL_REFSEL(1) | PLL_BYPASS(1)); PRCI_REG(PRCI_PLLCFG) |= (PLL_SEL(1)); // Turn off HFROSC to save power PRCI_REG(PRCI_HFROSCCFG) &= ~((uint32_t)ROSC_EN(1)); {% endif %} {% if boardName == 'e31arty' or boardName == 'e51arty' %} // For the Arty board, be sure LED1 is off, since it is very bright. PWM0_REG(PWM_CMP1) = 0xFF; PWM0_REG(PWM_CMP2) = 0xFF; PWM0_REG(PWM_CMP3) = 0xFF; {% endif %} // TODO: check Arduino main.cpp for more/better initialisations. } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" // Called before running the static constructors. void os_startup_initialize_hardware (void) { // Measure the CPU frequency in cycles, with the RTC as reference. {% if language == 'cpp' %} riscv::core::update_running_frequency (); {% elsif language == 'c' %} riscv_core_update_running_frequency (); {% endif %} {% if content == 'blinky' %} // TODO: make PLIC static inline. PLIC_init (&g_plic, PLIC_CTRL_ADDR, PLIC_NUM_INTERRUPTS, PLIC_NUM_PRIORITIES); {% endif %} // Disable M timer interrupt. {% if language == 'cpp' %} riscv::csr::clear_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_clear_mie (MIP_MTIP); {% endif %} // Clear both mtime and mtimecmp to start afresh. // Should trigger an interrupt as soon as enabled. {% if language == 'cpp' %} riscv::device::mtime (0); riscv::device::mtimecmp (0); {% elsif language == 'c' %} riscv_device_write_mtime (0); riscv_device_write_mtimecmp (0); {% endif %} {% if content == 'blinky' %} // ------------------------------------------------------------------- // Configure Button 0 as a global GPIO irq. // Disable output. GPIO_REG(GPIO_OUTPUT_EN) &= ~((0x1 << BUTTON_0_OFFSET)); // Disable hw io function GPIO_REG(GPIO_IOF_EN) &= ~(1 << BUTTON_0_OFFSET); // Configure as input GPIO_REG(GPIO_INPUT_EN) |= (1 << BUTTON_0_OFFSET); GPIO_REG(GPIO_PULLUP_EN) |= (1 << BUTTON_0_OFFSET); // Configure to interrupt on both falling and rising edges. GPIO_REG(GPIO_FALL_IE) |= (1 << BUTTON_0_OFFSET); GPIO_REG(GPIO_RISE_IE) |= (1 << BUTTON_0_OFFSET); // Enable the BUTTON interrupt in PLIC. PLIC_enable_interrupt (&g_plic, INT_DEVICE_BUTTON_0); // Configure the BUTTON priority in PLIC. 2 out of 7. PLIC_set_priority (&g_plic, INT_DEVICE_BUTTON_0, 2); // Enable Global (PLIC) interrupt. {% if language == 'cpp' %} riscv::csr::set_mie (MIP_MEIP); {% elsif language == 'c' %} riscv_csr_set_mie (MIP_MEIP); {% endif %} {% endif %} // ------------------------------------------------------------------- // When everything else is ready... // Enable M timer interrupt. {% if language == 'cpp' %} riscv::csr::set_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_set_mie (MIP_MTIP); {% endif %} // Enable interrupts. {% if language == 'cpp' %} riscv::csr::set_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_set_mstatus (MSTATUS_MIE); {% endif %} } #pragma GCC diagnostic pop // ---------------------------------------------------------------------------- <commit_msg>templates.sifive: init hard use new plic api<commit_after>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2017 Liviu Ionescu. * * 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 <micro-os-plus/board.h> #include <micro-os-plus/startup/initialize-hooks.h> // ---------------------------------------------------------------------------- // Called early, before copying .data and clearing .bss. // Should initialise the clocks and possible other RAM areas. void os_startup_initialize_hardware_early (void) { // Disable all interrupts. {% if language == 'cpp' %} riscv::csr::clear_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_clear_mstatus (MSTATUS_MIE); {% endif %} // Disable all individual interrupts. {% if language == 'cpp' %} riscv::csr::mie (0); {% elsif language == 'c' %} riscv_csr_write_mie (0); {% endif %} // Set the trap assembly handler. {% if language == 'cpp' %} riscv::csr::mtvec ((riscv::arch::register_t) riscv_trap_entry); {% elsif language == 'c' %} riscv_csr_write_mtvec ((riscv_arch_register_t) riscv_trap_entry); {% endif %} // TODO: add support for the PRCI peripheral and use it. {% if deviceName == 'fe310' %} // TODO: add to C/C++ API // Make sure the HFROSC is on before the next line: PRCI_REG(PRCI_HFROSCCFG) |= ROSC_EN(1); // Run off 16 MHz Crystal for accuracy. PRCI_REG(PRCI_PLLCFG) = (PLL_REFSEL(1) | PLL_BYPASS(1)); PRCI_REG(PRCI_PLLCFG) |= (PLL_SEL(1)); // Turn off HFROSC to save power PRCI_REG(PRCI_HFROSCCFG) &= ~((uint32_t)ROSC_EN(1)); {% endif %} {% if boardName == 'e31arty' or boardName == 'e51arty' %} // For the Arty board, be sure LED1 is off, since it is very bright. PWM0_REG(PWM_CMP1) = 0xFF; PWM0_REG(PWM_CMP2) = 0xFF; PWM0_REG(PWM_CMP3) = 0xFF; {% endif %} // TODO: check Arduino main.cpp for more/better initialisations. } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" // Called before running the static constructors. void os_startup_initialize_hardware (void) { // Measure the CPU frequency in cycles, with the RTC as reference. {% if language == 'cpp' %} riscv::core::update_running_frequency (); {% elsif language == 'c' %} riscv_core_update_running_frequency (); {% endif %} {% if content == 'blinky' %} {% if language == 'cpp' %} riscv::plic::clear_priorities (); {% elsif language == 'c' %} riscv_plic_clear_priorities (); {% endif %} // Hart specific initializations. {% if language == 'cpp' %} riscv::plic::initialize (); {% elsif language == 'c' %} riscv_plic_initialize (); {% endif %} {% endif %} // Disable M timer interrupt. {% if language == 'cpp' %} riscv::csr::clear_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_clear_mie (MIP_MTIP); {% endif %} // Clear both mtime and mtimecmp to start afresh. // Should trigger an interrupt as soon as enabled. {% if language == 'cpp' %} riscv::device::mtime (0); riscv::device::mtimecmp (0); {% elsif language == 'c' %} riscv_device_write_mtime (0); riscv_device_write_mtimecmp (0); {% endif %} {% if content == 'blinky' %} // ------------------------------------------------------------------- // Configure Button 0 as a global GPIO irq. // Disable output. GPIO_REG(GPIO_OUTPUT_EN) &= ~((0x1 << BUTTON_0_OFFSET)); // Disable hw io function GPIO_REG(GPIO_IOF_EN) &= ~(1 << BUTTON_0_OFFSET); // Configure as input GPIO_REG(GPIO_INPUT_EN) |= (1 << BUTTON_0_OFFSET); GPIO_REG(GPIO_PULLUP_EN) |= (1 << BUTTON_0_OFFSET); // Configure to interrupt on both falling and rising edges. GPIO_REG(GPIO_FALL_IE) |= (1 << BUTTON_0_OFFSET); GPIO_REG(GPIO_RISE_IE) |= (1 << BUTTON_0_OFFSET); // Enable the BUTTON interrupt in PLIC. {% if language == 'cpp' %} riscv::plic::enable_interrupt (INT_DEVICE_BUTTON_0); {% elsif language == 'c' %} riscv_plic_enable_interrupt (INT_DEVICE_BUTTON_0); {% endif %} // Configure the BUTTON priority in PLIC. 2 out of 7. {% if language == 'cpp' %} riscv::plic::priority (INT_DEVICE_BUTTON_0, 2); {% elsif language == 'c' %} riscv_plic_write_priority (INT_DEVICE_BUTTON_0, 2); {% endif %} // Enable Global (PLIC) interrupt. {% if language == 'cpp' %} riscv::core::enable_machine_external_interrupts (); {% elsif language == 'c' %} riscv_core_enable_machine_external_interrupts (MIP_MEIP); {% endif %} {% endif %} // ------------------------------------------------------------------- // When everything else is ready... // Enable M timer interrupt. {% if language == 'cpp' %} riscv::csr::set_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_set_mie (MIP_MTIP); {% endif %} // Enable interrupts. {% if language == 'cpp' %} riscv::csr::set_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_set_mstatus (MSTATUS_MIE); {% endif %} } #pragma GCC diagnostic pop // ---------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2017 Liviu Ionescu. * * 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 <micro-os-plus/board.h> #include <micro-os-plus/startup/initialize-hooks.h> // ---------------------------------------------------------------------------- // Called early, before copying .data and clearing .bss. // Should initialise the clocks and possible other RAM areas. void os_startup_initialize_hardware_early (void) { // Disable all interrupts. {% if language == 'cpp' %} riscv::csr::clear_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_clear_mstatus (MSTATUS_MIE); {% endif %} // Disable all individual interrupts. {% if language == 'cpp' %} riscv::csr::mie (0); {% elsif language == 'c' %} riscv_csr_write_mie (0); {% endif %} // Set the trap assembly handler. {% if language == 'cpp' %} riscv::csr::mtvec ((riscv::arch::register_t) riscv_trap_entry); {% elsif language == 'c' %} riscv_csr_write_mtvec ((riscv_arch_register_t) riscv_trap_entry); {% endif %} // TODO: add support for the PRCI peripheral and use it. #if defined(SIFIVE_FREEDOM_E310) // TODO: add to C/C++ API // Make sure the HFROSC is on before the next line: PRCI_REG(PRCI_HFROSCCFG) |= ROSC_EN(1); // Run off 16 MHz Crystal for accuracy. PRCI_REG(PRCI_PLLCFG) = (PLL_REFSEL(1) | PLL_BYPASS(1)); PRCI_REG(PRCI_PLLCFG) |= (PLL_SEL(1)); // Turn off HFROSC to save power PRCI_REG(PRCI_HFROSCCFG) &= ~((uint32_t)ROSC_EN(1)); #endif /* defined(SIFIVE_FREEDOM_E310) */ // TODO: check Arduino main.cpp for more/better initialisations. } // Called before running the static constructors. void os_startup_initialize_hardware (void) { // Measure the CPU frequency in cycles, with the RTC as reference. {% if language == 'cpp' %} riscv::core::update_cpu_frequency (); {% elsif language == 'c' %} riscv_core_update_cpu_frequency (); {% endif %} // Disable M timer interrupt. {% if language == 'cpp' %} riscv::csr::clear_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_clear_mie (MIP_MTIP); {% endif %} // Clear both mtime and mtimecmp to start afresh. // Should trigger an interrupt as soon as enabled. {% if language == 'cpp' %} riscv::device::mtime (0); riscv::device::mtimecmp (0); {% elsif language == 'c' %} riscv_device_write_mtime (0); riscv_device_write_mtimecmp (0); {% endif %} // Enable M timer interrupt. {% if language == 'cpp' %} riscv::csr::set_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_set_mie (MIP_MTIP); {% endif %} // Enable interrupts. {% if language == 'cpp' %} riscv::csr::set_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_set_mstatus (MSTATUS_MIE); {% endif %} } // ---------------------------------------------------------------------------- <commit_msg>templates.sifive: initialize-hardware LED1 off<commit_after>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2017 Liviu Ionescu. * * 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 <micro-os-plus/board.h> #include <micro-os-plus/startup/initialize-hooks.h> // ---------------------------------------------------------------------------- // Called early, before copying .data and clearing .bss. // Should initialise the clocks and possible other RAM areas. void os_startup_initialize_hardware_early (void) { // Disable all interrupts. {% if language == 'cpp' %} riscv::csr::clear_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_clear_mstatus (MSTATUS_MIE); {% endif %} // Disable all individual interrupts. {% if language == 'cpp' %} riscv::csr::mie (0); {% elsif language == 'c' %} riscv_csr_write_mie (0); {% endif %} // Set the trap assembly handler. {% if language == 'cpp' %} riscv::csr::mtvec ((riscv::arch::register_t) riscv_trap_entry); {% elsif language == 'c' %} riscv_csr_write_mtvec ((riscv_arch_register_t) riscv_trap_entry); {% endif %} // TODO: add support for the PRCI peripheral and use it. #if defined(SIFIVE_FREEDOM_E310) // TODO: add to C/C++ API // Make sure the HFROSC is on before the next line: PRCI_REG(PRCI_HFROSCCFG) |= ROSC_EN(1); // Run off 16 MHz Crystal for accuracy. PRCI_REG(PRCI_PLLCFG) = (PLL_REFSEL(1) | PLL_BYPASS(1)); PRCI_REG(PRCI_PLLCFG) |= (PLL_SEL(1)); // Turn off HFROSC to save power PRCI_REG(PRCI_HFROSCCFG) &= ~((uint32_t)ROSC_EN(1)); #endif /* defined(SIFIVE_FREEDOM_E310) */ #if defined(SIFIVE_COREPLEX_IP_31_ARTY_BOARD) || defined(SIFIVE_COREPLEX_IP_51_ARTY_BOARD) // For the Arty board, be sure LED1 is off, since it is very bright. PWM0_REG(PWM_CMP1) = 0xFF; PWM0_REG(PWM_CMP2) = 0xFF; PWM0_REG(PWM_CMP3) = 0xFF; #endif /* SIFIVE_COREPLEX_IP_[35]1_ARTY_BOARD */ // TODO: check Arduino main.cpp for more/better initialisations. } // Called before running the static constructors. void os_startup_initialize_hardware (void) { // Measure the CPU frequency in cycles, with the RTC as reference. {% if language == 'cpp' %} riscv::core::update_cpu_frequency (); {% elsif language == 'c' %} riscv_core_update_cpu_frequency (); {% endif %} // Disable M timer interrupt. {% if language == 'cpp' %} riscv::csr::clear_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_clear_mie (MIP_MTIP); {% endif %} // Clear both mtime and mtimecmp to start afresh. // Should trigger an interrupt as soon as enabled. {% if language == 'cpp' %} riscv::device::mtime (0); riscv::device::mtimecmp (0); {% elsif language == 'c' %} riscv_device_write_mtime (0); riscv_device_write_mtimecmp (0); {% endif %} // Enable M timer interrupt. {% if language == 'cpp' %} riscv::csr::set_mie (MIP_MTIP); {% elsif language == 'c' %} riscv_csr_set_mie (MIP_MTIP); {% endif %} // Enable interrupts. {% if language == 'cpp' %} riscv::csr::set_mstatus (MSTATUS_MIE); {% elsif language == 'c' %} riscv_csr_set_mstatus (MSTATUS_MIE); {% endif %} } // ---------------------------------------------------------------------------- <|endoftext|>
<commit_before><commit_msg>added collision reponse demo. TAB now creates an object that will bounce off walls and floors.<commit_after><|endoftext|>
<commit_before>#define DEBUG 1 /** * File : C2.cpp * Author : Kazune Takahashi * Created : 2019-6-3 00:42:00 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; /* void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } */ /* const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; */ // const ll MOD = 1000000007; ll N, X; ll b[100010], l[100010], u[100010]; ll base = 0; typedef tuple<ll, ll, ll, ll> test; vector<test> V; ll sum[100010]; bool solve(ll T) { ll cnt = T / X; ll x = T % X; ll ans = -1000000000000000; for (auto i = 0; i < cnt; i++) { ll t, b, l, u; tie(t, b, l, u) = V[i]; ll tmp = 0; if (x >= b) { tmp = l * b + u * (x - b); } else { tmp = l * x; } ans = max(ans, sum[cnt + 1] - t + tmp); } for (auto i = cnt; i < N; i++) { ll t, b, l, u; tie(t, b, l, u) = V[i]; ll tmp = 0; if (x >= b) { tmp = l * b + u * (x - b); } else { tmp = l * x; } ans = max(ans, sum[cnt] + tmp); } return (ans >= 0); } int main() { cin >> N >> X; for (auto i = 0; i < N; i++) { cin >> b[i] >> l[i] >> u[i]; } for (auto i = 0; i < N; i++) { base -= l[i] * b[i]; } for (auto i = 0; i < N; i++) { ll t = l[i] * b[i] + u[i] * (X - b[i]); V.emplace_back(t, b[i], l[i], u[i]); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); sum[0] = base; for (auto i = 0; i < N; i++) { sum[i + 1] = sum[i] + get<0>(V[i]); } ll ok = N * X + 1; ll ng = -1; while (abs(ok - ng) > 1) { ll t = (ok + ng) / 2; if (solve(t)) { ok = t; } else { ng = t; } } cout << ok << endl; }<commit_msg>submit C2.cpp to 'C - Tests' (agc034) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : C2.cpp * Author : Kazune Takahashi * Created : 2019-6-3 00:42:00 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; /* void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } */ /* const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; */ // const ll MOD = 1000000007; ll N, X; ll b[100010], l[100010], u[100010]; ll base = 0; typedef tuple<ll, ll, ll, ll> test; vector<test> V; ll sum[100010]; bool solve(ll T) { ll cnt = T / X; ll x = T % X; ll ans = -1000000000000000; for (auto i = 0; i < N; i++) { ll t, b, l, u; tie(t, b, l, u) = V[i]; ll tmp = 0; if (x >= b) { tmp = l * b + u * (x - b); } else { tmp = l * x; } if (i < cnt) { ans = max(ans, sum[cnt + 1] - t + tmp); } else { ans = max(ans, sum[cnt] + tmp); } } return (ans >= 0); } int main() { cin >> N >> X; for (auto i = 0; i < N; i++) { cin >> b[i] >> l[i] >> u[i]; } for (auto i = 0; i < N; i++) { base -= l[i] * b[i]; } for (auto i = 0; i < N; i++) { ll t = l[i] * b[i] + u[i] * (X - b[i]); V.emplace_back(t, b[i], l[i], u[i]); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); sum[0] = base; for (auto i = 0; i < N; i++) { sum[i + 1] = sum[i] + get<0>(V[i]); } sum[N + 1] = sum[N]; ll ok = N * X + 1; ll ng = -1; while (abs(ok - ng) > 1) { ll t = (ok + ng) / 2; if (solve(t)) { ok = t; } else { ng = t; } } cout << ok << endl; }<|endoftext|>
<commit_before>/** * @file NetworkPipeTestTest.cpp * @brief NetworkPipeTest class tester. * @author zer0 * @date 2017-05-09 */ #include <gtest/gtest.h> #include <libtbag/network/details/PipeServer.hpp> #include <libtbag/network/details/PipeClient.hpp> using namespace libtbag; using namespace libtbag::network; using namespace libtbag::network::details; TEST(NetworkPipeTestTest, Default) { } <commit_msg>Implement NetworkPipeTest.MultiEcho<commit_after>/** * @file NetworkPipeTestTest.cpp * @brief NetworkPipeTest class tester. * @author zer0 * @date 2017-05-09 */ #include <gtest/gtest.h> #include <tester/DemoAsset.hpp> #include <libtbag/log/Log.hpp> #include <libtbag/network/details/NetCommon.hpp> #include <libtbag/network/details/PipeServer.hpp> #include <libtbag/network/details/PipeClient.hpp> #include <thread> #include <memory> #include <vector> #include <iostream> using namespace libtbag; using namespace libtbag::network; using namespace libtbag::network::details; TEST(NetworkPipeTest, MultiEcho) { tttDir(true, true); auto path = tttDirGet() / "temp.pipe"; log::SeverityGuard guard; using namespace uvpp; std::size_t const CLIENT_SIZE = 100; std::string const ECHO_MESSAGE = "ECHO MESSAGE"; // --------------- // SERVER PROCESS. // --------------- Loop loop_server; FunctionalPipeServer server(loop_server); int server_connection = 0; int server_client_read = 0; int server_client_write = 0; int server_client_close = 0; int server_close = 0; uerr server_result = uerr::UVPP_UNKNOWN; server.setOnConnection([&](uerr code){ if (auto shared = server.accept().lock()) { if (shared->start()) { server_connection++; } } }); server.setOnClientRead([&](FunctionalPipeServer::WeakClient node, uerr code, char const * buffer, FunctionalPipeServer::Size size){ if (code == uerr::UVPP_SUCCESS) { if (auto shared = node.lock()) { if (shared->stop()) { server_client_read++; shared->write(buffer, size); } } } }); server.setOnClientWrite([&](FunctionalPipeServer::WeakClient node, uerr code){ if (code == uerr::UVPP_SUCCESS) { if (auto shared = node.lock()) { server_client_write++; shared->close(); } } }); server.setOnClientClose([&](FunctionalPipeServer::WeakClient node){ if (auto shared = node.lock()) { server_client_close++; } if (server_client_close >= CLIENT_SIZE) { server.close(); } }); server.setOnServerClose([&](){ server_close++; }); server.init(path, 0); std::thread thread_server([&](){ server_result = loop_server.run(); }); // --------------- // CLIENT PROCESS. // --------------- using SharedLoop = std::shared_ptr<Loop>; using LoopVector = std::vector<SharedLoop>; using SharedFuncClient = std::shared_ptr<FunctionalPipeClient>; using ClientVector = std::vector<SharedFuncClient>; using ThreadVector = std::vector<std::thread>; std::vector<uerr> connect_result(CLIENT_SIZE, uerr::UVPP_UNKNOWN); std::vector<uerr> write_result(CLIENT_SIZE, uerr::UVPP_UNKNOWN); std::vector<uerr> read_result(CLIENT_SIZE, uerr::UVPP_UNKNOWN); std::vector<uerr> close_result(CLIENT_SIZE, uerr::UVPP_UNKNOWN); std::vector<uerr> loop_result(CLIENT_SIZE, uerr::UVPP_UNKNOWN); ThreadVector cthreads(CLIENT_SIZE); LoopVector cloops(CLIENT_SIZE); ClientVector clients(CLIENT_SIZE); std::size_t i = 0; for (i = 0; i < CLIENT_SIZE; ++i) { cloops.at(i).reset(new Loop()); clients.at(i).reset(new FunctionalPipeClient(*(cloops.at(i)))); clients.at(i)->setOnConnect([&, i](uerr code){ if (clients.at(i)->write(ECHO_MESSAGE.data(), ECHO_MESSAGE.size())) { connect_result.at(i) = code; } }); clients.at(i)->setOnWrite([&, i](uerr code){ if (clients.at(i)->start()) { write_result.at(i) = code; } }); clients.at(i)->setOnRead([&, i](uerr code, char const * buffer, PipeClient::Size size){ if (clients.at(i)->stop()) { read_result.at(i) = code; clients.at(i)->close(); } }); clients.at(i)->setOnClose([&, i](){ close_result.at(i) = uerr::UVPP_SUCCESS; }); clients.at(i)->init(path); cthreads.at(i) = std::thread([&, i](){ loop_result.at(i) = cloops.at(i)->run(); }); } for (i = 0; i < CLIENT_SIZE; ++i) { cthreads.at(i).join(); } thread_server.join(); for (i = 0; i < CLIENT_SIZE; ++i) { ASSERT_EQ(uerr::UVPP_SUCCESS, connect_result.at(i)); ASSERT_EQ(uerr::UVPP_SUCCESS, write_result.at(i)); ASSERT_EQ(uerr::UVPP_SUCCESS, read_result.at(i)); ASSERT_EQ(uerr::UVPP_SUCCESS, close_result.at(i)); ASSERT_EQ(uerr::UVPP_SUCCESS, loop_result.at(i)); } ASSERT_EQ(uerr::UVPP_SUCCESS, server_result); ASSERT_EQ(CLIENT_SIZE, server_connection ); ASSERT_EQ(CLIENT_SIZE, server_client_read ); ASSERT_EQ(CLIENT_SIZE, server_client_write); ASSERT_EQ(CLIENT_SIZE, server_client_close); ASSERT_EQ(1, server_close); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: msfiltertracer.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-12-13 12:19:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _MS_FILTERTRACER_HXX #include "msfiltertracer.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #ifndef _COM_SUN_STAR_UTIL_LOGGING_LOGLEVEL_HPP_ #include <com/sun/star/util/logging/LogLevel.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHALGORITHMS_HPP_ #include <com/sun/star/util/SearchAlgorithms.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_ #include <com/sun/star/util/SearchFlags.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _FILTER_CONFIG_ITEM_HXX_ #include <svtools/FilterConfigItem.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UTL_STREAM_WRAPPER_HXX_ #include <unotools/streamwrap.hxx> #endif #ifndef _UNTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif // -------------- // - Namespaces - // -------------- using namespace ::com::sun::star; MSFilterTracer::MSFilterTracer( const ::rtl::OUString& rConfigPath, uno::Sequence< beans::PropertyValue >* pConfigData ) : mpCfgItem( new FilterConfigItem( rConfigPath, pConfigData ) ), mpAttributeList( new SvXMLAttributeList() ), mpStream( NULL ), mbEnabled( sal_False ) // will be set to true in StartTracing() { if ( mpCfgItem->ReadBool( rtl::OUString::createFromAscii( "On" ), sal_False ) ) { uno::Reference< lang::XMultiServiceFactory > xMgr( ::comphelper::getProcessServiceFactory() ); if ( xMgr.is() ) { /* the following methods try to read a property, if it is not available it will put the second parameter as default into the property sequence of the FilterConfigItem. It means we ensure that the property is available by trying to read it (the return value of the method is ignored) */ ::rtl::OUString aEmptyString; mpCfgItem->ReadInt32( rtl::OUString::createFromAscii( "LogLevel" ), util::logging::LogLevel::ALL ); mpCfgItem->ReadString( rtl::OUString::createFromAscii( "ClassFilter" ), aEmptyString ); mpCfgItem->ReadString( rtl::OUString::createFromAscii( "MethodFilter" ), aEmptyString ); mpCfgItem->ReadString( rtl::OUString::createFromAscii( "MessageFilter" ), aEmptyString ); util::SearchAlgorithms eSearchAlgorithm = (util::SearchAlgorithms) mpCfgItem->ReadInt32( rtl::OUString::createFromAscii( "SearchAlgorithm" ), util::SearchAlgorithms_ABSOLUTE ); // creating the name of the log file rtl::OUString aPath( mpCfgItem->ReadString( rtl::OUString::createFromAscii( "Path" ), aEmptyString ) ); rtl::OUString aName( mpCfgItem->ReadString( rtl::OUString::createFromAscii( "Name" ), aEmptyString ) ); rtl::OUString aDocumentURL( mpCfgItem->ReadString( rtl::OUString::createFromAscii( "DocumentURL" ), aEmptyString ) ); INetURLObject aLogFile( aDocumentURL ); if ( aLogFile.GetMainURL( INetURLObject::NO_DECODE ).getLength() ) { if ( aPath.getLength() ) { String aOldName( aLogFile.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::NO_DECODE ) ); aLogFile = INetURLObject( aPath ); aLogFile.insertName( aOldName ); } if ( aName.getLength() ) aLogFile.setName( aName ); } else { if ( aPath.getLength() ) aLogFile = INetURLObject( aPath ); else { String aURLStr; if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( Application::GetAppFileName(), aURLStr ) ) { aLogFile = INetURLObject(aURLStr); aLogFile .removeSegment(); aLogFile .removeFinalSlash(); } } if ( !aName.getLength() ) aName = rtl::OUString::createFromAscii( "tracer" ); aLogFile.insertName( aName ); } aLogFile.setExtension( rtl::OUString::createFromAscii( "log" ) ); // creating the file stream mpStream = ::utl::UcbStreamHelper::CreateStream( aLogFile.GetMainURL( INetURLObject::NO_DECODE ), STREAM_WRITE | STREAM_TRUNC | STREAM_SHARE_DENYNONE ); if ( mpStream && !mpStream->GetError() ) { // creating a wrapper for our stream utl::OOutputStreamWrapper* pHelper = new ::utl::OOutputStreamWrapper( *mpStream ); uno::Reference< io::XOutputStream > xOutputStream( pHelper ); // instanciating the DocumentHandler, then setting the OutputStream mxHandler = uno::Reference< xml::sax::XDocumentHandler >( xMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" ) ), uno::UNO_QUERY ); uno::Reference< io::XActiveDataSource > xDocSrc( mxHandler, uno::UNO_QUERY ); xDocSrc->setOutputStream( xOutputStream ); mxHandler->startDocument(); mxHandler->ignorableWhitespace ( rtl::OUString::createFromAscii( " " ) ); // writing the "DocumentHandler" property, so the FilterTracer component // will use it for the output uno::Any aAny; aAny <<= xDocSrc; mpCfgItem->WriteAny( rtl::OUString::createFromAscii( "DocumentHandler" ), aAny ); SvXMLAttributeList* pAttrList = new SvXMLAttributeList; pAttrList->AddAttribute( rtl::OUString::createFromAscii( "DocumentURL" ), aDocumentURL ); uno::Reference < xml::sax::XAttributeList > xAttributeList(pAttrList); mxHandler->startElement( rtl::OUString::createFromAscii( "Document" ), xAttributeList ); } uno::Sequence< uno::Any > aArgument( 1 ); uno::Sequence< beans::PropertyValue > aPropValues( mpCfgItem->GetFilterData() ); aArgument[ 0 ] <<= aPropValues; mxFilterTracer = xMgr->createInstanceWithArguments( rtl::OUString::createFromAscii( "com.sun.star.util.FilterTracer" ), aArgument ); if ( mxFilterTracer.is() ) { mxTextSearch = uno::Reference< util::XTextSearch >( mxFilterTracer, uno::UNO_QUERY ); mxLogger = uno::Reference< util::logging::XLogger >( mxFilterTracer, uno::UNO_QUERY ); if ( mxTextSearch.is() ) { maSearchOptions.algorithmType = eSearchAlgorithm; mxTextSearch->setOptions( maSearchOptions ); } } } } } MSFilterTracer::~MSFilterTracer() { mxLogger = NULL; mxFilterTracer = NULL; if ( mxHandler.is() ) { mxHandler->ignorableWhitespace ( rtl::OUString::createFromAscii( " " ) ); mxHandler->endElement( rtl::OUString::createFromAscii( "Document" ) ); mxHandler->ignorableWhitespace ( rtl::OUString::createFromAscii( " " ) ); mxHandler->endDocument(); mxHandler = NULL; } delete mpAttributeList; delete mpCfgItem; delete mpStream; } void MSFilterTracer::StartTracing() { mbEnabled = mpCfgItem->ReadBool( rtl::OUString::createFromAscii( "On" ), sal_False ); } void MSFilterTracer::EndTracing() { mbEnabled = sal_False; } void MSFilterTracer::StartElement( const rtl::OUString& rName, uno::Reference< xml::sax::XAttributeList > xAttribs ) { if ( mxHandler.is() ) mxHandler->startElement( rName, xAttribs ); } void MSFilterTracer::EndElement( const rtl::OUString& rName ) { if ( mxHandler.is() ) mxHandler->endElement( rName ); } void MSFilterTracer::Trace( const rtl::OUString& rElement, const rtl::OUString& rMessage ) { if ( mbEnabled && mxLogger.is() ) { sal_Bool bFilter = sal_False; if ( rMessage.getLength() && mxTextSearch.is() ) { maSearchOptions.searchString = rMessage; mxTextSearch->setOptions( maSearchOptions ); util::SearchResult aSearchResult = mxTextSearch->searchForward( rMessage, 0, rMessage.getLength() ); bFilter = aSearchResult.subRegExpressions != 0; } if ( !bFilter ) { uno::Reference < xml::sax::XAttributeList > xAttrList( new SvXMLAttributeList( *mpAttributeList ) ); if ( mxHandler.is() ) mxHandler->startElement( rElement, xAttrList ); if ( rMessage.getLength() ) { rtl::OUString aEmpty; mxLogger->logp( 0, aEmpty, aEmpty, rMessage ); } if ( mxHandler.is() ) mxHandler->endElement( rElement ); } } } void MSFilterTracer::AddAttribute( const ::rtl::OUString& sName , const ::rtl::OUString& sValue ) { if ( mbEnabled ) mpAttributeList->AddAttribute( sName, sValue ); } void MSFilterTracer::ClearAttributes() { if ( mbEnabled ) mpAttributeList->Clear(); } void MSFilterTracer::RemoveAttribute( const ::rtl::OUString& sName ) { if ( mbEnabled ) mpAttributeList->RemoveAttribute( sName ); } uno::Any MSFilterTracer::GetProperty( const rtl::OUString& rPropName, const uno::Any* pDefault ) const { uno::Any aDefault; if ( pDefault ) aDefault = *pDefault; return mpCfgItem->ReadAny( rPropName, aDefault ); } void MSFilterTracer::SetProperty( const ::rtl::OUString& rPropName, const uno::Any& rProperty ) { mpCfgItem->WriteAny( rPropName, rProperty ); } <commit_msg>INTEGRATION: CWS ooo19126 (1.6.516); FILE MERGED 2005/09/05 14:25:59 rt 1.6.516.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: msfiltertracer.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 23:46:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _MS_FILTERTRACER_HXX #include "msfiltertracer.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #ifndef _COM_SUN_STAR_UTIL_LOGGING_LOGLEVEL_HPP_ #include <com/sun/star/util/logging/LogLevel.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHALGORITHMS_HPP_ #include <com/sun/star/util/SearchAlgorithms.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_ #include <com/sun/star/util/SearchFlags.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _FILTER_CONFIG_ITEM_HXX_ #include <svtools/FilterConfigItem.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UTL_STREAM_WRAPPER_HXX_ #include <unotools/streamwrap.hxx> #endif #ifndef _UNTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif // -------------- // - Namespaces - // -------------- using namespace ::com::sun::star; MSFilterTracer::MSFilterTracer( const ::rtl::OUString& rConfigPath, uno::Sequence< beans::PropertyValue >* pConfigData ) : mpCfgItem( new FilterConfigItem( rConfigPath, pConfigData ) ), mpAttributeList( new SvXMLAttributeList() ), mpStream( NULL ), mbEnabled( sal_False ) // will be set to true in StartTracing() { if ( mpCfgItem->ReadBool( rtl::OUString::createFromAscii( "On" ), sal_False ) ) { uno::Reference< lang::XMultiServiceFactory > xMgr( ::comphelper::getProcessServiceFactory() ); if ( xMgr.is() ) { /* the following methods try to read a property, if it is not available it will put the second parameter as default into the property sequence of the FilterConfigItem. It means we ensure that the property is available by trying to read it (the return value of the method is ignored) */ ::rtl::OUString aEmptyString; mpCfgItem->ReadInt32( rtl::OUString::createFromAscii( "LogLevel" ), util::logging::LogLevel::ALL ); mpCfgItem->ReadString( rtl::OUString::createFromAscii( "ClassFilter" ), aEmptyString ); mpCfgItem->ReadString( rtl::OUString::createFromAscii( "MethodFilter" ), aEmptyString ); mpCfgItem->ReadString( rtl::OUString::createFromAscii( "MessageFilter" ), aEmptyString ); util::SearchAlgorithms eSearchAlgorithm = (util::SearchAlgorithms) mpCfgItem->ReadInt32( rtl::OUString::createFromAscii( "SearchAlgorithm" ), util::SearchAlgorithms_ABSOLUTE ); // creating the name of the log file rtl::OUString aPath( mpCfgItem->ReadString( rtl::OUString::createFromAscii( "Path" ), aEmptyString ) ); rtl::OUString aName( mpCfgItem->ReadString( rtl::OUString::createFromAscii( "Name" ), aEmptyString ) ); rtl::OUString aDocumentURL( mpCfgItem->ReadString( rtl::OUString::createFromAscii( "DocumentURL" ), aEmptyString ) ); INetURLObject aLogFile( aDocumentURL ); if ( aLogFile.GetMainURL( INetURLObject::NO_DECODE ).getLength() ) { if ( aPath.getLength() ) { String aOldName( aLogFile.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::NO_DECODE ) ); aLogFile = INetURLObject( aPath ); aLogFile.insertName( aOldName ); } if ( aName.getLength() ) aLogFile.setName( aName ); } else { if ( aPath.getLength() ) aLogFile = INetURLObject( aPath ); else { String aURLStr; if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( Application::GetAppFileName(), aURLStr ) ) { aLogFile = INetURLObject(aURLStr); aLogFile .removeSegment(); aLogFile .removeFinalSlash(); } } if ( !aName.getLength() ) aName = rtl::OUString::createFromAscii( "tracer" ); aLogFile.insertName( aName ); } aLogFile.setExtension( rtl::OUString::createFromAscii( "log" ) ); // creating the file stream mpStream = ::utl::UcbStreamHelper::CreateStream( aLogFile.GetMainURL( INetURLObject::NO_DECODE ), STREAM_WRITE | STREAM_TRUNC | STREAM_SHARE_DENYNONE ); if ( mpStream && !mpStream->GetError() ) { // creating a wrapper for our stream utl::OOutputStreamWrapper* pHelper = new ::utl::OOutputStreamWrapper( *mpStream ); uno::Reference< io::XOutputStream > xOutputStream( pHelper ); // instanciating the DocumentHandler, then setting the OutputStream mxHandler = uno::Reference< xml::sax::XDocumentHandler >( xMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" ) ), uno::UNO_QUERY ); uno::Reference< io::XActiveDataSource > xDocSrc( mxHandler, uno::UNO_QUERY ); xDocSrc->setOutputStream( xOutputStream ); mxHandler->startDocument(); mxHandler->ignorableWhitespace ( rtl::OUString::createFromAscii( " " ) ); // writing the "DocumentHandler" property, so the FilterTracer component // will use it for the output uno::Any aAny; aAny <<= xDocSrc; mpCfgItem->WriteAny( rtl::OUString::createFromAscii( "DocumentHandler" ), aAny ); SvXMLAttributeList* pAttrList = new SvXMLAttributeList; pAttrList->AddAttribute( rtl::OUString::createFromAscii( "DocumentURL" ), aDocumentURL ); uno::Reference < xml::sax::XAttributeList > xAttributeList(pAttrList); mxHandler->startElement( rtl::OUString::createFromAscii( "Document" ), xAttributeList ); } uno::Sequence< uno::Any > aArgument( 1 ); uno::Sequence< beans::PropertyValue > aPropValues( mpCfgItem->GetFilterData() ); aArgument[ 0 ] <<= aPropValues; mxFilterTracer = xMgr->createInstanceWithArguments( rtl::OUString::createFromAscii( "com.sun.star.util.FilterTracer" ), aArgument ); if ( mxFilterTracer.is() ) { mxTextSearch = uno::Reference< util::XTextSearch >( mxFilterTracer, uno::UNO_QUERY ); mxLogger = uno::Reference< util::logging::XLogger >( mxFilterTracer, uno::UNO_QUERY ); if ( mxTextSearch.is() ) { maSearchOptions.algorithmType = eSearchAlgorithm; mxTextSearch->setOptions( maSearchOptions ); } } } } } MSFilterTracer::~MSFilterTracer() { mxLogger = NULL; mxFilterTracer = NULL; if ( mxHandler.is() ) { mxHandler->ignorableWhitespace ( rtl::OUString::createFromAscii( " " ) ); mxHandler->endElement( rtl::OUString::createFromAscii( "Document" ) ); mxHandler->ignorableWhitespace ( rtl::OUString::createFromAscii( " " ) ); mxHandler->endDocument(); mxHandler = NULL; } delete mpAttributeList; delete mpCfgItem; delete mpStream; } void MSFilterTracer::StartTracing() { mbEnabled = mpCfgItem->ReadBool( rtl::OUString::createFromAscii( "On" ), sal_False ); } void MSFilterTracer::EndTracing() { mbEnabled = sal_False; } void MSFilterTracer::StartElement( const rtl::OUString& rName, uno::Reference< xml::sax::XAttributeList > xAttribs ) { if ( mxHandler.is() ) mxHandler->startElement( rName, xAttribs ); } void MSFilterTracer::EndElement( const rtl::OUString& rName ) { if ( mxHandler.is() ) mxHandler->endElement( rName ); } void MSFilterTracer::Trace( const rtl::OUString& rElement, const rtl::OUString& rMessage ) { if ( mbEnabled && mxLogger.is() ) { sal_Bool bFilter = sal_False; if ( rMessage.getLength() && mxTextSearch.is() ) { maSearchOptions.searchString = rMessage; mxTextSearch->setOptions( maSearchOptions ); util::SearchResult aSearchResult = mxTextSearch->searchForward( rMessage, 0, rMessage.getLength() ); bFilter = aSearchResult.subRegExpressions != 0; } if ( !bFilter ) { uno::Reference < xml::sax::XAttributeList > xAttrList( new SvXMLAttributeList( *mpAttributeList ) ); if ( mxHandler.is() ) mxHandler->startElement( rElement, xAttrList ); if ( rMessage.getLength() ) { rtl::OUString aEmpty; mxLogger->logp( 0, aEmpty, aEmpty, rMessage ); } if ( mxHandler.is() ) mxHandler->endElement( rElement ); } } } void MSFilterTracer::AddAttribute( const ::rtl::OUString& sName , const ::rtl::OUString& sValue ) { if ( mbEnabled ) mpAttributeList->AddAttribute( sName, sValue ); } void MSFilterTracer::ClearAttributes() { if ( mbEnabled ) mpAttributeList->Clear(); } void MSFilterTracer::RemoveAttribute( const ::rtl::OUString& sName ) { if ( mbEnabled ) mpAttributeList->RemoveAttribute( sName ); } uno::Any MSFilterTracer::GetProperty( const rtl::OUString& rPropName, const uno::Any* pDefault ) const { uno::Any aDefault; if ( pDefault ) aDefault = *pDefault; return mpCfgItem->ReadAny( rPropName, aDefault ); } void MSFilterTracer::SetProperty( const ::rtl::OUString& rPropName, const uno::Any& rProperty ) { mpCfgItem->WriteAny( rPropName, rProperty ); } <|endoftext|>
<commit_before><commit_msg>coverity#1202787 Unchecked dynamic_cast<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2010-2018, Mark Final All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of BuildAMation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "renderer/renderer.h" #include "log.h" #include "appwindow.h" #ifdef D_BAM_PLATFORM_WINDOWS #include <Windows.h> #else #endif #include <memory> namespace { int event_loop() { #if defined(D_BAM_PLATFORM_WINDOWS) ::MSG msg; // loop until WM_QUIT(0) received while (::GetMessage(&msg, 0, 0, 0) > 0) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } return static_cast<int>(msg.wParam); #endif } } // anonymous namespace #ifdef D_BAM_PLATFORM_WINDOWS int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) #else int main() #endif { Log().get() << "Vulkan cube test starting up..." << std::endl; try { std::unique_ptr<AppWindow> window(new AppWindow); #ifdef D_BAM_PLATFORM_WINDOWS (void)nCmdShow; (void)lpCmdLine; (void)hPrevInstance; window->win32SetInstanceHandle(hInstance); #endif window->init(256, 256, "Vulkan Cube"); std::unique_ptr<Renderer> renderer(new Renderer(window.get())); renderer->init(); window->show(); Log().get() << "Vulkan cube test finished successfully" << std::endl; return event_loop(); } catch (const std::exception &inEx) { Log().get() << "ERROR: " << inEx.what() << std::endl; return -1; } catch (...) { Log().get() << "ERROR: Unhandled exception" << std::endl; return -2; } } <commit_msg>Render a frame<commit_after>/* Copyright (c) 2010-2018, Mark Final All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of BuildAMation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "renderer/renderer.h" #include "log.h" #include "appwindow.h" #ifdef D_BAM_PLATFORM_WINDOWS #include <Windows.h> #else #endif #include <memory> namespace { int event_loop( Renderer *inRenderer) { #if defined(D_BAM_PLATFORM_WINDOWS) ::MSG msg; // loop until WM_QUIT(0) received while (::GetMessage(&msg, 0, 0, 0) > 0) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); inRenderer->draw_frame(); } return static_cast<int>(msg.wParam); #endif } } // anonymous namespace #ifdef D_BAM_PLATFORM_WINDOWS int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) #else int main() #endif { Log().get() << "Vulkan cube test starting up..." << std::endl; try { std::unique_ptr<AppWindow> window(new AppWindow); #ifdef D_BAM_PLATFORM_WINDOWS (void)nCmdShow; (void)lpCmdLine; (void)hPrevInstance; window->win32SetInstanceHandle(hInstance); #endif window->init(256, 256, "Vulkan Cube"); std::unique_ptr<Renderer> renderer(new Renderer(window.get())); renderer->init(); window->show(); Log().get() << "Vulkan cube test finished successfully" << std::endl; return event_loop(renderer.get()); } catch (const std::exception &inEx) { Log().get() << "ERROR: " << inEx.what() << std::endl; return -1; } catch (...) { Log().get() << "ERROR: Unhandled exception" << std::endl; return -2; } } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <cstring> #include "string.h" #define DEBUG false using namespace std; double f1 (double x, double y) { return log(1 + log(x) * log(x) + log(y) * log(y)); } double f2 (double x, double y) { return log(1 + x * x + (x * x - y) * (x * x - y)); } void df1(double x, double y, double* out) { // x (2 log(x))/(x (log^2(x) + log^2(y) + 1)) out[0] = (2 * log (x)) / (x * (1 + log(x) * log (x) + log(y) * log(y))); // y (2 log(y))/(y (log^2(x) + log^2(y) + 1)) out[1] = (2 * log (y)) / (y * (1 + log(y) * log (y) + log(x) * log(x))); } void df2(double x, double y, double* out) { // x (2 (2 x^3 - 2 x y + x))/((x^2 - y)^2 + x^2 + 1) out[0] = (2*(2*x*x*x - 2*x*y + x))/(pow(x*x - y, 2) + x*x + 1); // y -(2 (x^2 - y))/((x^2 - y)^2 + x^2 + 1) out[1] = -1 * (2*(x*x - y))/(pow(x*x - y, 2) + x*x + 1); } void Hf1 (double x, double y, double* out) { //xx -(2 (log(x) (log^2(y) + 1) + log^3(x) + log^2(x) - log^2(y) - 1))/(x^2 (log^2(x) + log^2(y) + 1)^2) out[0] = -1*(2*(log(x)*(pow(log(y),2) + 1) + pow(log(x),3) + pow(log(x),2) - pow(log(y),2) - 1))/(x*x*pow(pow(log(x),2) + pow(log(y),2) + 1, 2)); //xy -(4 log(x) log(y))/(x y (log^2(x) + log^2(y) + 1)^2) out[1] = -1*(4*log(x)*log(y))/(x*y*pow(pow(log(x),2) + pow(log(y),2) + 1, 2)); //yx -(4 log(x) log(y))/(x y (log^2(x) + log^2(y) + 1)^2) out[2] = -1*(4*log(x)*log(y))/(x*y*pow(pow(log(x),2) + pow(log(y),2) + 1, 2)); //yy -(2 (log^2(x) (log(y) - 1) + log^3(y) + log^2(y) + log(y) - 1))/(y^2 (log^2(x) + log^2(y) + 1)^2) out[3] = -1*(2*(pow(log(x),2)*(log(y) - 1) + pow(log(y),3) + pow(log(y),2) + log(y) - 1))/(y*y*pow(pow(log(x),2) + pow(log(y),2) + 1, 2)); } void Hf2 (double x, double y, double* out) { //xx (2 (-2 x^6 + x^4 (2 y - 1) + x^2 (2 y^2 + 4 y + 5) - 2 y^3 + y^2 - 2 y + 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[0] = (2*(-2*pow(x,6) + pow(x,4)*(2*y - 1) + x*x*(2*y*y + 4*y + 5) - 2*y*y*y + y*y - 2*y + 1))/pow(pow(x,4) + x*x*(1 - 2*y) + y*y + 1, 2); //xy (4 x (x^4 - 2 x^2 y + y^2 - y - 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[1] = (4*x*(pow(x,4) - 2*x*x*y + y*y - y - 1))/pow(pow(x,4) + x*x*(1 - 2*y) + y*y + 1, 2); //yx (4 x (x^4 - 2 x^2 y + y^2 - y - 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[2] = (4*x*(pow(x,4) - 2*x*x*y + y*y - y - 1))/pow(pow(x,4) + x*x*(1 - 2*y) + y*y + 1, 2); //yy -(2 (x^4 - x^2 (2 y + 1) + y^2 - 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[3] = -1 * (2*(pow(x,4) + x*x*(2*y - 1) + y*y - 1))/pow(pow(x,4) + x*x*(2*y + 1) + y*y + 1, 2); } void invert2dmatrix (double* original, double* inverted) { double idet = 1 / (original[0]*original[3]-original[1]*original[2]); inverted[0] = original[3] * idet; inverted[1] = original[1] * idet * -1; inverted[2] = original[2] * idet * -1; inverted[3] = original[0] * idet; } double goldenSectionSearch(double precision, double in_a, double in_b, double *x, double *dx, double(*f) (double, double)) { const double theta1 = ((3-sqrt(5)) / 2); const double theta2 = 1 - theta1; // initialize bounds double a = in_a; double c = (in_a + in_b) / 2; //center double b = in_b; while (f(x[0] + c*dx[0], x[1] + c*dx[1]) < f(x[0] + c*dx[0], x[1] + c*dx[1])) { a = c; c = b; b = 2*b; } double u = a + theta1 * (b - a); double v = a + theta2 * (b - a); while (b - a > precision) { if (f(x[0] + u*dx[0], x[1] + u*dx[1]) < f(x[0] + v*dx[0], x[1] + v*dx[1])) { b = v; v = u; u = a + theta1 * (b - a); } else { a = u; u = v; v = a + theta1 * (b - a); } } return (u + v) / 2; } void quasiNewton (string name, double precision, int max_iterations, double *out, double (*function) (double, double), void (*d_function)(double, double, double*), void (*h_function)(double, double, double*)) { int current_iteration = 0; double grad [2] = {0, 0}; double est_inv_hess [4] = {0, 0, 0, 0}; double dk [2] = {0, 0}; double tmp [2] = {0, 0}; double p [2] = {0, 0}; double q [2] = {0, 0}; out[0] = out[1] = 1.3; cout << "Starting Quasi-Newtonn method.\nParameters:" << endl; cout << "Precision: " << precision << endl; cout << "Max number of iterations: " << max_iterations << endl; cout << "Starting..." << endl; //initialize H h_function(out[0], out[1], est_inv_hess); //main loop while (current_iteration < max_iterations) { //tmp = x[k-1] // p = x[k] - x[k-1] p[0] = out[0] - tmp[0]; p[1] = out[1] - tmp[1]; d_function(tmp[0], tmp[1], grad); // q = grad(x[k]) - grad(x[k-1]) q[0] = -1 * grad[0]; q[1] = -1 * grad[1]; memcpy(&tmp, out, 2 * sizeof(double)); //tmp = x[k]; d_function(tmp[0], tmp[1], grad); q[0] += grad[0]; q[1] += grad[1]; //BFGS? //h[k] = h[k-1] + (1+(qk^T*Hk*qk)*(pk^T*qk)^-1)*((pk*pk^-T)*(pk^T*qk)^-1) - ((pk*qk^T*Hk + Hk*qk*pk^T)*(pk^T*qk)^-1) // update est_inv_hess if (grad[0] == 0 && grad[1] == 0) { cout << "Grad exit " << grad[0] << " " << grad[1] << endl; break; } if (current_iteration%100 == 0 || DEBUG) { cout << "i_HESS: "<< est_inv_hess[0]<<", "<<est_inv_hess[1]<<", "<<est_inv_hess[2]<<", "<<est_inv_hess[3]<<endl; cout << "GRAD: "<< grad[0]<<", "<<grad[1]<<endl; } dk[0] = -1 * (est_inv_hess[0]*grad[0] + est_inv_hess[1]*grad[1]); dk[1] = -1 * (est_inv_hess[2]*grad[0] + est_inv_hess[3]*grad[1]); double t = 1;//goldenSectionSearch(precision, 0, 10, out, dk, function); if (current_iteration%100 == 0 || DEBUG) { cout << "Dk: "<<dk[0]<<" "<<dk[1]<< " t: "<<t<<endl; } out[0] += t * dk[0]; out[1] += t * dk[1]; if (current_iteration%100 == 0 || DEBUG) { cout <<"Iteration: " << current_iteration <<" Result: (" << out[0] << ", " << out[1] << ")" << endl; } current_iteration += 1; if ((abs(out[0] - tmp[0]) < precision) && (abs(out[1] - tmp[1]) < precision)) { cout << "Precision Exit" << endl; break; } } cout << "Proccess finalized for " << name <<". Result: (" << out[0] << ", " << out[1] << ")" << endl; cout << "Total iterations: " << current_iteration << endl; } int main() { // starting point double new_arr [2] = {10, 10}; // step size double gamma = 0.01; // precision neede for stop double precision = 0.00001; // max iterations int max_iterations = 100; quasiNewton("F1",precision, max_iterations, new_arr, f1, df1, Hf1); quasiNewton("F2",precision, max_iterations, new_arr, f2, df2, Hf2); cout << "Exiting..." << endl; //cin.ignore(); return 0; } <commit_msg>Quasi Newton BFGS working<commit_after>#include <iostream> #include <cmath> #include <cstring> #include "stdlib.h" #include "string.h" #define DEBUG true using namespace std; double f1 (double x, double y) { return log(1 + log(x) * log(x) + log(y) * log(y)); } double f2 (double x, double y) { return log(1 + x * x + (x * x - y) * (x * x - y)); } void df1(double x, double y, double* out) { // x (2 log(x))/(x (log^2(x) + log^2(y) + 1)) out[0] = (2 * log (x)) / (x * (1 + log(x) * log (x) + log(y) * log(y))); // y (2 log(y))/(y (log^2(x) + log^2(y) + 1)) out[1] = (2 * log (y)) / (y * (1 + log(y) * log (y) + log(x) * log(x))); } void df2(double x, double y, double* out) { // x (2 (2 x^3 - 2 x y + x))/((x^2 - y)^2 + x^2 + 1) out[0] = (2*(2*x*x*x - 2*x*y + x))/(pow(x*x - y, 2) + x*x + 1); // y -(2 (x^2 - y))/((x^2 - y)^2 + x^2 + 1) out[1] = -1 * (2*(x*x - y))/(pow(x*x - y, 2) + x*x + 1); } void Hf1 (double x, double y, double* out) { // xx (-(4 log^2(x))/(x^2 (log^2(x) + log^2(y) + 1)^2) - (2 log(x))/(x^2 (log^2(x) + log^2(y) + 1)) + 2/(x^2 (log^2(x) + log^2(y) + 1)) out[0] = (-(4*pow(log(x),2))/(x*x*pow((pow(log(x), 2) + pow(log(y), 2) + 1), 2)) - (2*log(x))/(x*x*(pow(log(x), 2) + pow(log(y), 2) + 1)) + 2/(x*x*(pow(log(x), 2) + pow(log(y), 2) + 1))); //xy -(4 log(x) log(y))/(x y (log^2(x) + log^2(y) + 1)^2) out[1] = -1*(4*log(x)*log(y))/(x*y*pow(pow(log(x),2) + pow(log(y),2) + 1, 2)); //yx -(4 log(x) log(y))/(x y (log^2(x) + log^2(y) + 1)^2) out[2] = -1*(4*log(x)*log(y))/(x*y*pow(pow(log(x),2) + pow(log(y),2) + 1, 2)); //yy -(4 log^2(y))/(y^2 (log^2(x) + log^2(y) + 1)^2) - (2 log(y))/(y^2 (log^2(x) + log^2(y) + 1)) + 2/(y^2 (log^2(x) + log^2(y) + 1))) out[3] = (-(4*pow(log(y),2))/(y*y*pow((pow(log(x), 2) + pow(log(y), 2) + 1), 2)) - (2*log(y))/(y*y*(pow(log(x), 2) + pow(log(y), 2) + 1)) + 2/(y*y*(pow(log(x), 2) + pow(log(y), 2) + 1))); } void Hf2 (double x, double y, double* out) { //xx (2 (-2 x^6 + x^4 (2 y - 1) + x^2 (2 y^2 + 4 y + 5) - 2 y^3 + y^2 - 2 y + 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[0] = (2*(-2*pow(x,6) + pow(x,4)*(2*y - 1) + x*x*(2*y*y + 4*y + 5) - 2*y*y*y + y*y - 2*y + 1))/pow(pow(x,4) + x*x*(1 - 2*y) + y*y + 1, 2); //xy (4 x (x^4 - 2 x^2 y + y^2 - y - 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[1] = (4*x*(pow(x,4) - 2*x*x*y + y*y - y - 1))/pow(pow(x,4) + x*x*(1 - 2*y) + y*y + 1, 2); //yx (4 x (x^4 - 2 x^2 y + y^2 - y - 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[2] = (4*x*(pow(x,4) - 2*x*x*y + y*y - y - 1))/pow(pow(x,4) + x*x*(1 - 2*y) + y*y + 1, 2); //yy -(2 (x^4 - x^2 (2 y + 1) + y^2 - 1))/(x^4 + x^2 (1 - 2 y) + y^2 + 1)^2 out[3] = -1 * (2*(pow(x,4) + x*x*(2*y - 1) + y*y - 1))/pow(pow(x,4) + x*x*(2*y + 1) + y*y + 1, 2); } void invert2dmatrix (double* original, double* inverted) { double idet = 1 / (original[0]*original[3]-original[1]*original[2]); inverted[0] = original[3] * idet; inverted[1] = original[1] * idet * -1; inverted[2] = original[2] * idet * -1; inverted[3] = original[0] * idet; } double goldenSectionSearch(double precision, double in_a, double in_b, double *x, double *dx, double(*f) (double, double)) { const double theta1 = ((3-sqrt(5)) / 2); const double theta2 = 1 - theta1; // initialize bounds double a = in_a; double c = (in_a + in_b) / 2; //center double b = in_b; while (f(x[0] + c*dx[0], x[1] + c*dx[1]) < f(x[0] + c*dx[0], x[1] + c*dx[1])) { a = c; c = b; b = 2*b; } double u = a + theta1 * (b - a); double v = a + theta2 * (b - a); while (b - a > precision) { if (f(x[0] + u*dx[0], x[1] + u*dx[1]) < f(x[0] + v*dx[0], x[1] + v*dx[1])) { b = v; v = u; u = a + theta1 * (b - a); } else { a = u; u = v; v = a + theta1 * (b - a); } } return (u + v) / 2; } void update_est_inv_hess(double *hess, double *p, double *q) { double old_hess[4]; for (int i = 0; i < 4; i++) { cout << "OLDHESS: " << hess[i] << endl; old_hess[i] = hess[i]; } double common_divider = p[0]*q[0] + p[1]*q[1]; double first_factor = 1; double first_ratio = q[0] * (q[0]*old_hess[0] + q[1]*old_hess[2]); first_ratio += q[1] * (q[0]*old_hess[1] + q[1]*old_hess[3]); first_ratio /= common_divider; first_factor += first_ratio; double first_matrix[4]; first_matrix[0] = p[0]*p[0]; first_matrix[1] = p[0]*p[1]; first_matrix[2] = p[1]*p[0]; first_matrix[3] = p[1]*p[1]; for (int i = 0; i < 4; i++) { first_matrix[i] *= first_ratio; first_matrix[i] /= common_divider; } double aux_matrix_a[4]; aux_matrix_a[0] = old_hess[0]*p[0]*q[0] + old_hess[2]*p[0]*q[1]; aux_matrix_a[1] = old_hess[1]*p[0]*q[0] + old_hess[3]*p[0]*q[1]; aux_matrix_a[2] = old_hess[0]*p[1]*q[0] + old_hess[2]*p[1]*q[1]; aux_matrix_a[3] = old_hess[1]*p[1]*q[0] + old_hess[3]*p[1]*q[1]; double aux_matrix_b[4]; aux_matrix_b[0] = old_hess[0]*q[0]*p[0] + old_hess[1]*q[1]*p[0]; aux_matrix_b[1] = old_hess[0]*q[0]*p[1] + old_hess[1]*q[1]*p[1]; aux_matrix_b[2] = old_hess[2]*q[0]*p[0] + old_hess[3]*q[1]*p[0]; aux_matrix_b[3] = old_hess[2]*q[0]*p[1] + old_hess[3]*q[1]*p[1]; for (int i = 0; i < 4; i++) { aux_matrix_a[i] += aux_matrix_b[i]; aux_matrix_a[i] /= common_divider; } for (int i = 0; i < 4; i++) { hess[i] = old_hess[i] + first_matrix[i] - aux_matrix_a[i]; cout << "HESS: " << hess[i] << endl; } // exit(0); } void quasiNewton (string name, double precision, int max_iterations, double *out, double (*function) (double, double), void (*d_function)(double, double, double*), void (*h_function)(double, double, double*)) { int current_iteration = 0; double grad [2] = {0, 0}; double est_hess [4] = {0, 0, 0, 0}; double est_inv_hess [4] = {0, 0, 0, 0}; double dk [2] = {0, 0}; double tmp [2] = {1.1, 1.8}; double p [2] = {0, 0}; double q [2] = {0, 0}; cout << "Starting Quasi-Newtonn method.\nParameters:" << endl; cout << "Precision: " << precision << endl; cout << "Max number of iterations: " << max_iterations << endl; cout << "Starting..." << endl; //initialize H h_function(out[0], out[1], est_hess); //main loop while (current_iteration < max_iterations) { //tmp = x[k-1] // p = x[k] - x[k-1] p[0] = out[0] - tmp[0]; p[1] = out[1] - tmp[1]; d_function(tmp[0], tmp[1], grad); // q = grad(x[k]) - grad(x[k-1]) q[0] = -1 * grad[0]; q[1] = -1 * grad[1]; memcpy(&tmp, out, 2 * sizeof(double)); //tmp = x[k]; d_function(tmp[0], tmp[1], grad); q[0] += grad[0]; q[1] += grad[1]; update_est_inv_hess(est_hess, p, q); invert2dmatrix(est_hess, est_inv_hess); //BFGS? //h[k] = h[k-1] + (1+(qk^T*Hk*qk)*(pk^T*qk)^-1)*((pk*pk^-T)*(pk^T*qk)^-1) - ((pk*qk^T*Hk + Hk*qk*pk^T)*(pk^T*qk)^-1) // update est_inv_hess if (grad[0] == 0 && grad[1] == 0) { cout << "Grad exit " << grad[0] << " " << grad[1] << endl; break; } if (current_iteration%100 == 0 || DEBUG) { cout << "i_HESS: "<< est_inv_hess[0]<<", "<<est_inv_hess[1]<<", "<<est_inv_hess[2]<<", "<<est_inv_hess[3]<<endl; cout << "GRAD: "<< grad[0]<<", "<<grad[1]<<endl; } dk[0] = -1 * (est_inv_hess[0]*grad[0] + est_inv_hess[1]*grad[1]); dk[1] = -1 * (est_inv_hess[2]*grad[0] + est_inv_hess[3]*grad[1]); // double t = goldenSectionSearch(precision, 0, 10, out, dk, function); double t = 1; if (current_iteration%100 == 0 || DEBUG) { cout << "Dk: "<<dk[0]<<" "<<dk[1]<< " t: "<<t<<endl; } out[0] += t * dk[0]; out[1] += t * dk[1]; if (current_iteration%100 == 0 || DEBUG) { cout <<"Iteration: " << current_iteration <<" Result: (" << out[0] << ", " << out[1] << ")" << endl; } current_iteration += 1; if ((abs(out[0] - tmp[0]) < precision) && (abs(out[1] - tmp[1]) < precision)) { cout << "Precision Exit" << endl; break; } } cout << "Proccess finalized for " << name <<". Result: (" << out[0] << ", " << out[1] << ")" << endl; cout << "Total iterations: " << current_iteration << endl; } int main() { // starting point double new_arr [2] = {0.1, 0.1}; // step size double gamma = 0.01; // precision neede for stop double precision = 0.00001; // max iterations int max_iterations = 100; quasiNewton("F1",precision, max_iterations, new_arr, f1, df1, Hf1); // cout << "\n===========\n" << endl; // quasiNewton("F2",precision, max_iterations, new_arr, f2, df2, Hf2); cout << "Exiting..." << endl; //cin.ignore(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/source/thread_posix.h" #include <algorithm> #include <errno.h> #include <unistd.h> #ifdef WEBRTC_LINUX #include <linux/unistd.h> #include <sched.h> #include <sys/prctl.h> #include <sys/syscall.h> #include <sys/types.h> #endif #include "webrtc/base/checks.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/sleep.h" #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { namespace { struct ThreadAttributes { ThreadAttributes() { pthread_attr_init(&attr); } ~ThreadAttributes() { pthread_attr_destroy(&attr); } pthread_attr_t* operator&() { return &attr; } pthread_attr_t attr; }; } // namespace int ConvertToSystemPriority(ThreadPriority priority, int min_prio, int max_prio) { DCHECK(max_prio - min_prio > 2); const int top_prio = max_prio - 1; const int low_prio = min_prio + 1; switch (priority) { case kLowPriority: return low_prio; case kNormalPriority: // The -1 ensures that the kHighPriority is always greater or equal to // kNormalPriority. return (low_prio + top_prio - 1) / 2; case kHighPriority: return std::max(top_prio - 2, low_prio); case kHighestPriority: return std::max(top_prio - 1, low_prio); case kRealtimePriority: return top_prio; } DCHECK(false); return low_prio; } // static void* ThreadPosix::StartThread(void* param) { static_cast<ThreadPosix*>(param)->Run(); return 0; } ThreadPosix::ThreadPosix(ThreadRunFunction func, void* obj, const char* thread_name) : run_function_(func), obj_(obj), stop_event_(false, false), name_(thread_name ? thread_name : "webrtc"), thread_(0) { DCHECK(name_.length() < 64); } uint32_t ThreadWrapper::GetThreadId() { return rtc::CurrentThreadId(); } ThreadPosix::~ThreadPosix() { DCHECK(thread_checker_.CalledOnValidThread()); } // TODO(pbos): Make Start void, calling code really doesn't support failures // here. bool ThreadPosix::Start() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!thread_) << "Thread already started?"; ThreadAttributes attr; // Set the stack stack size to 1M. pthread_attr_setstacksize(&attr, 1024 * 1024); CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this)); return true; } bool ThreadPosix::Stop() { DCHECK(thread_checker_.CalledOnValidThread()); if (!thread_) return true; stop_event_.Set(); CHECK_EQ(0, pthread_join(thread_, nullptr)); thread_ = 0; return true; } bool ThreadPosix::SetPriority(ThreadPriority priority) { DCHECK(thread_checker_.CalledOnValidThread()); if (!thread_) return false; #ifdef WEBRTC_THREAD_RR const int policy = SCHED_RR; #else const int policy = SCHED_FIFO; #endif const int min_prio = sched_get_priority_min(policy); const int max_prio = sched_get_priority_max(policy); if (min_prio == -1 || max_prio == -1) { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "unable to retreive min or max priority for threads"); return false; } if (max_prio - min_prio <= 2) return false; sched_param param; param.sched_priority = ConvertToSystemPriority(priority, min_prio, max_prio); if (pthread_setschedparam(thread_, policy, &param) != 0) { WEBRTC_TRACE( kTraceError, kTraceUtility, -1, "unable to set thread priority"); return false; } return true; } void ThreadPosix::Run() { if (!name_.empty()) { // Setting the thread name may fail (harmlessly) if running inside a // sandbox. Ignore failures if they happen. #if defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID) prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name_.c_str())); #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) pthread_setname_np(name_.substr(0, 63).c_str()); #endif } // It's a requirement that for successful thread creation that the run // function be called at least once (see RunFunctionIsCalled unit test), // so to fullfill that requirement, we use a |do| loop and not |while|. do { if (!run_function_(obj_)) break; } while (!stop_event_.Wait(0)); } } // namespace webrtc <commit_msg>Temporarily disable SetPriority when building with Chromium. This is due to errors we were hitting with Chromium's sandbox policy for pthread_setschedparam.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/source/thread_posix.h" #include <algorithm> #include <errno.h> #include <unistd.h> #ifdef WEBRTC_LINUX #include <linux/unistd.h> #include <sched.h> #include <sys/prctl.h> #include <sys/syscall.h> #include <sys/types.h> #endif #include "webrtc/base/checks.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/sleep.h" #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { namespace { struct ThreadAttributes { ThreadAttributes() { pthread_attr_init(&attr); } ~ThreadAttributes() { pthread_attr_destroy(&attr); } pthread_attr_t* operator&() { return &attr; } pthread_attr_t attr; }; } // namespace int ConvertToSystemPriority(ThreadPriority priority, int min_prio, int max_prio) { DCHECK(max_prio - min_prio > 2); const int top_prio = max_prio - 1; const int low_prio = min_prio + 1; switch (priority) { case kLowPriority: return low_prio; case kNormalPriority: // The -1 ensures that the kHighPriority is always greater or equal to // kNormalPriority. return (low_prio + top_prio - 1) / 2; case kHighPriority: return std::max(top_prio - 2, low_prio); case kHighestPriority: return std::max(top_prio - 1, low_prio); case kRealtimePriority: return top_prio; } DCHECK(false); return low_prio; } // static void* ThreadPosix::StartThread(void* param) { static_cast<ThreadPosix*>(param)->Run(); return 0; } ThreadPosix::ThreadPosix(ThreadRunFunction func, void* obj, const char* thread_name) : run_function_(func), obj_(obj), stop_event_(false, false), name_(thread_name ? thread_name : "webrtc"), thread_(0) { DCHECK(name_.length() < 64); } uint32_t ThreadWrapper::GetThreadId() { return rtc::CurrentThreadId(); } ThreadPosix::~ThreadPosix() { DCHECK(thread_checker_.CalledOnValidThread()); } // TODO(pbos): Make Start void, calling code really doesn't support failures // here. bool ThreadPosix::Start() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!thread_) << "Thread already started?"; ThreadAttributes attr; // Set the stack stack size to 1M. pthread_attr_setstacksize(&attr, 1024 * 1024); CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this)); return true; } bool ThreadPosix::Stop() { DCHECK(thread_checker_.CalledOnValidThread()); if (!thread_) return true; stop_event_.Set(); CHECK_EQ(0, pthread_join(thread_, nullptr)); thread_ = 0; return true; } bool ThreadPosix::SetPriority(ThreadPriority priority) { DCHECK(thread_checker_.CalledOnValidThread()); if (!thread_) return false; #if defined(WEBRTC_CHROMIUM_BUILD) // TODO(tommi): Switch to the same mechanism as Chromium uses for // changing thread priorities. return true; #else #ifdef WEBRTC_THREAD_RR const int policy = SCHED_RR; #else const int policy = SCHED_FIFO; #endif const int min_prio = sched_get_priority_min(policy); const int max_prio = sched_get_priority_max(policy); if (min_prio == -1 || max_prio == -1) { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "unable to retreive min or max priority for threads"); return false; } if (max_prio - min_prio <= 2) return false; sched_param param; param.sched_priority = ConvertToSystemPriority(priority, min_prio, max_prio); if (pthread_setschedparam(thread_, policy, &param) != 0) { WEBRTC_TRACE( kTraceError, kTraceUtility, -1, "unable to set thread priority"); return false; } return true; #endif // defined(WEBRTC_CHROMIUM_BUILD) } void ThreadPosix::Run() { if (!name_.empty()) { // Setting the thread name may fail (harmlessly) if running inside a // sandbox. Ignore failures if they happen. #if defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID) prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name_.c_str())); #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) pthread_setname_np(name_.substr(0, 63).c_str()); #endif } // It's a requirement that for successful thread creation that the run // function be called at least once (see RunFunctionIsCalled unit test), // so to fullfill that requirement, we use a |do| loop and not |while|. do { if (!run_function_(obj_)) break; } while (!stop_event_.Wait(0)); } } // namespace webrtc <|endoftext|>
<commit_before>#include <shogun/io/SerializableAsciiFile.h> #include <shogun/lib/SGMatrix.h> #include <shogun/features/SparseFeatures.h> #include <gtest/gtest.h> using namespace shogun; TEST(SparseFeaturesTest,serialization) { /* create feature data matrix */ SGMatrix<int32_t> data(3, 20); /* fill matrix with random data */ for (index_t i=0; i<20*3; ++i) { if(i%2==0) data.matrix[i]=0; else data.matrix[i]=i; } //data.display_matrix(); /* create sparse features */ CSparseFeatures<int32_t>* sparse_features=new CSparseFeatures<int32_t>(data); CSerializableAsciiFile* outfile = new CSerializableAsciiFile("sparseFeatures.txt", 'w'); sparse_features->save_serializable(outfile); SG_UNREF(outfile); CSparseFeatures<int32_t>* sparse_features_loaded = new CSparseFeatures<int32_t>(); CSerializableAsciiFile* infile= new CSerializableAsciiFile("sparseFeatures.txt", 'r'); sparse_features_loaded->load_serializable(infile); SG_UNREF(infile); SGMatrix<int32_t> data_loaded = sparse_features_loaded->get_full_feature_matrix(); //data_loaded.display_matrix(); EXPECT_TRUE(data_loaded.equals(data)); SG_UNREF(sparse_features); SG_UNREF(sparse_features_loaded); } <commit_msg>added a massive bunch of tests for subsets on sparse features<commit_after>#include <shogun/io/SerializableAsciiFile.h> #include <shogun/lib/SGMatrix.h> #include <shogun/features/SparseFeatures.h> #include <gtest/gtest.h> using namespace shogun; TEST(SparseFeaturesTest,serialization) { /* create feature data matrix */ SGMatrix<int32_t> data(3, 20); /* fill matrix with random data */ for (index_t i=0; i<20*3; ++i) { if(i%2==0) data.matrix[i]=0; else data.matrix[i]=i; } //data.display_matrix(); /* create sparse features */ CSparseFeatures<int32_t>* sparse_features=new CSparseFeatures<int32_t>(data); CSerializableAsciiFile* outfile = new CSerializableAsciiFile("sparseFeatures.txt", 'w'); sparse_features->save_serializable(outfile); SG_UNREF(outfile); CSparseFeatures<int32_t>* sparse_features_loaded = new CSparseFeatures<int32_t>(); CSerializableAsciiFile* infile= new CSerializableAsciiFile("sparseFeatures.txt", 'r'); sparse_features_loaded->load_serializable(infile); SG_UNREF(infile); SGMatrix<int32_t> data_loaded = sparse_features_loaded->get_full_feature_matrix(); //data_loaded.display_matrix(); EXPECT_TRUE(data_loaded.equals(data)); SG_UNREF(sparse_features); SG_UNREF(sparse_features_loaded); } TEST(SparseFeaturesTest,constructor_from_dense) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), data.num_cols); EXPECT_EQ(features->get_sparse_feature_vector(0).num_feat_entries, 1); EXPECT_EQ(features->get_sparse_feature_vector(1).num_feat_entries, 2); EXPECT_EQ(features->get_sparse_feature_vector(2).num_feat_entries, 2); EXPECT_EQ(features->get_sparse_feature_vector(0).features[0].entry, data(1,0)); EXPECT_EQ(features->get_sparse_feature_vector(1).features[0].entry, data(0,1)); EXPECT_EQ(features->get_sparse_feature_vector(2).features[0].entry, data(0,2)); SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_feature_vector_identity) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=0; subset_idx[1]=1; subset_idx[2]=2; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), data.num_cols); EXPECT_EQ(features->get_sparse_feature_vector(0).features[0].entry, data(1,0)); EXPECT_EQ(features->get_sparse_feature_vector(1).features[0].entry, data(0,1)); EXPECT_EQ(features->get_sparse_feature_vector(1).features[1].entry, data(1,1)); EXPECT_EQ(features->get_sparse_feature_vector(2).features[0].entry, data(0,2)); EXPECT_EQ(features->get_sparse_feature_vector(2).features[1].entry, data(1,2)); SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_feature_vector_permutation) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=2; subset_idx[1]=0; subset_idx[2]=1; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), data.num_cols); EXPECT_EQ(features->get_sparse_feature_vector(0).features[0].entry, data(0,2)); EXPECT_EQ(features->get_sparse_feature_vector(0).features[1].entry, data(1,2)); EXPECT_EQ(features->get_sparse_feature_vector(1).features[0].entry, data(1,0)); EXPECT_EQ(features->get_sparse_feature_vector(2).features[0].entry, data(0,1)); EXPECT_EQ(features->get_sparse_feature_vector(2).features[1].entry, data(1,1)); SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_feature_vector_smaller) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(2); subset_idx[0]=2; subset_idx[1]=0; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); EXPECT_EQ(features->get_sparse_feature_vector(0).features[0].entry, data(0,2)); EXPECT_EQ(features->get_sparse_feature_vector(0).features[1].entry, data(1,2)); EXPECT_EQ(features->get_sparse_feature_vector(1).features[0].entry, data(1,0)); SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_full_feature_matrix_identity) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=0; subset_idx[1]=1; subset_idx[2]=2; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); SGMatrix<int32_t> mat=features->get_full_feature_matrix(); EXPECT_TRUE(mat.equals(data)); SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_full_feature_matrix_permutation) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=2; subset_idx[1]=0; subset_idx[2]=1; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); SGMatrix<int32_t> mat=features->get_full_feature_matrix(); EXPECT_EQ(mat.num_rows, data.num_rows); EXPECT_EQ(mat.num_cols, subset_idx.vlen); for (index_t i=0; i<data.num_rows; ++i) { for (index_t j=0; j<data.num_cols; ++j) EXPECT_EQ(mat(i,j), data(i,subset_idx[j])); } SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_full_feature_matrix_repetition1) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=0; subset_idx[1]=1; subset_idx[2]=1; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); SGMatrix<int32_t> mat=features->get_full_feature_matrix(); EXPECT_EQ(mat.num_rows, data.num_rows); EXPECT_EQ(mat.num_cols, subset_idx.vlen); for (index_t i=0; i<data.num_rows; ++i) { for (index_t j=0; j<data.num_cols; ++j) EXPECT_EQ(mat(i,j), data(i,subset_idx[j])); } SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_full_feature_matrix_smaller) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=2; subset_idx[1]=1; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); SGMatrix<int32_t> mat=features->get_full_feature_matrix(); EXPECT_EQ(mat.num_rows, data.num_rows); EXPECT_EQ(mat.num_cols, subset_idx.vlen); for (index_t i=0; i<data.num_rows; ++i) { for (index_t j=0; j<data.num_cols; ++j) EXPECT_EQ(mat(i,j), data(i,subset_idx[j])); } SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_full_feature_vector_identity) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=0; subset_idx[1]=1; subset_idx[2]=2; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); for (index_t i=0; i<features->get_num_vectors(); ++i) { SGVector<int32_t> vec=features->get_full_feature_vector(i); EXPECT_EQ(vec.vlen, data.num_rows); for (index_t j=0; j<vec.vlen; ++j) EXPECT_EQ(vec[j], data(j,subset_idx[i])); } SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_full_feature_vector_permutation) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=0; subset_idx[1]=2; subset_idx[2]=1; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); for (index_t i=0; i<features->get_num_vectors(); ++i) { SGVector<int32_t> vec=features->get_full_feature_vector(i); EXPECT_EQ(vec.vlen, data.num_rows); for (index_t j=0; j<vec.vlen; ++j) EXPECT_EQ(vec[j], data(j,subset_idx[i])); } SG_UNREF(features); } TEST(SparseFeaturesTest,subset_get_full_feature_vector_smaller) { SGMatrix<int32_t> data(2, 3); data(0, 0)=0; data(0, 1)=1; data(0, 2)=2; data(1, 0)=3; data(1, 1)=4; data(1, 2)=5; CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); SGVector<index_t> subset_idx(3); subset_idx[0]=0; subset_idx[1]=2; features->add_subset(subset_idx); EXPECT_EQ(features->get_num_features(), data.num_rows); EXPECT_EQ(features->get_num_vectors(), subset_idx.vlen); for (index_t i=0; i<features->get_num_vectors(); ++i) { SGVector<int32_t> vec=features->get_full_feature_vector(i); EXPECT_EQ(vec.vlen, data.num_rows); for (index_t j=0; j<vec.vlen; ++j) EXPECT_EQ(vec[j], data(j,subset_idx[i])); } SG_UNREF(features); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: TSortIndex.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: oj $ $Date: 2002-07-04 06:32:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_TSORTINDEX_HXX #include "TSortIndex.hxx" #endif #include <algorithm> #include <functional> using namespace connectivity; //------------------------------------------------------------------ /// binary_function Functor object for class OSortIndex::TIntValuePairVector::value_type returntype is bool struct TKeyValueFunc : ::std::binary_function<OSortIndex::TIntValuePairVector::value_type,OSortIndex::TIntValuePairVector::value_type,bool> { OSortIndex* pIndex; TKeyValueFunc(OSortIndex* _pIndex) : pIndex(_pIndex) { } // return false if compared values are equal otherwise true inline bool operator()(const OSortIndex::TIntValuePairVector::value_type& lhs,const OSortIndex::TIntValuePairVector::value_type& rhs) const { const ::std::vector<OKeyType>& aKeyType = pIndex->getKeyType(); ::std::vector<OKeyType>::const_iterator aIter = aKeyType.begin(); for (::std::vector<sal_Int16>::size_type i=0;aIter != aKeyType.end(); ++aIter,++i) { const bool nGreater = (pIndex->getAscending(i) == SQL_ASC) ? false : true; const bool nLess = !nGreater; // compare depending for type switch (*aIter) { case SQL_ORDERBYKEY_STRING: { sal_Int32 nRes = lhs.second->getKeyString(i).compareTo(rhs.second->getKeyString(i)); if (nRes < 0) return nLess; else if (nRes > 0) return nGreater; } break; case SQL_ORDERBYKEY_DOUBLE: { double d1 = lhs.second->getKeyDouble(i); double d2 = rhs.second->getKeyDouble(i); if (d1 < d2) return nLess; else if (d1 > d2) return nGreater; } break; } } // know we know that the values are equal return false; } }; // ----------------------------------------------------------------------------- ::vos::ORef<OKeySet> OSortIndex::CreateKeySet() { Freeze(); ::vos::ORef<OKeySet> pKeySet = new OKeySet(); pKeySet->reserve(m_aKeyValues.size()); ::std::transform(m_aKeyValues.begin() ,m_aKeyValues.end() ,::std::back_inserter(*pKeySet) ,::std::select1st<TIntValuePairVector::value_type>()); pKeySet->setFrozen(); return pKeySet; } // ----------------------------------------------------------------------------- OSortIndex::OSortIndex( const ::std::vector<OKeyType>& _aKeyType, const ::std::vector<sal_Int16>& _aAscending) : m_bFrozen(sal_False) ,m_aAscending(_aAscending) ,m_aKeyType(_aKeyType) { } //------------------------------------------------------------------ OSortIndex::~OSortIndex() { } //------------------------------------------------------------------ void OSortIndex::AddKeyValue(OKeyValue * pKeyValue) { OSL_ENSURE(pKeyValue,"Can not be null here!"); if(m_bFrozen) { m_aKeyValues.push_back(TIntValuePairVector::value_type(pKeyValue->getValue(),NULL)); delete pKeyValue; } else m_aKeyValues.push_back(TIntValuePairVector::value_type(pKeyValue->getValue(),pKeyValue)); } //------------------------------------------------------------------ void OSortIndex::Freeze() { OSL_ENSURE(! m_bFrozen,"OSortIndex::Freeze: already frozen!"); // Sortierung: if (m_aKeyType[0] != SQL_ORDERBYKEY_NONE) // we will sort ourself when the first keyType say so ::std::sort(m_aKeyValues.begin(),m_aKeyValues.end(),TKeyValueFunc(this)); TIntValuePairVector::iterator aIter = m_aKeyValues.begin(); for(;aIter != m_aKeyValues.end();++aIter) { delete aIter->second; aIter->second = NULL; } m_bFrozen = sal_True; } //------------------------------------------------------------------ sal_Int32 OSortIndex::GetValue(sal_Int32 nPos) const { OSL_ENSURE(nPos > 0,"OSortIndex::GetValue: nPos == 0"); OSL_ENSURE(nPos <= m_aKeyValues.size(),"OSortIndex::GetValue: Zugriff ausserhalb der Array-Grenzen"); if (!m_bFrozen && m_aKeyType[0] != SQL_ORDERBYKEY_NONE) { OSL_ASSERT("OSortIndex::GetValue: Invalid use of index!"); return 0; } return m_aKeyValues[nPos-1].first; } // ----------------------------------------------------------------------------- OKeyValue::OKeyValue() { } // ----------------------------------------------------------------------------- OKeyValue::OKeyValue(sal_Int32 nVal) : m_nValue(nVal) { } // ----------------------------------------------------------------------------- OKeyValue::~OKeyValue() { } // ----------------------------------------------------------------------------- OKeyValue* OKeyValue::createKeyValue(sal_Int32 _nVal) { return new OKeyValue(_nVal); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS ooo19126 (1.5.326); FILE MERGED 2005/09/05 17:22:52 rt 1.5.326.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TSortIndex.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 05:13:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONNECTIVITY_TSORTINDEX_HXX #include "TSortIndex.hxx" #endif #include <algorithm> #include <functional> using namespace connectivity; //------------------------------------------------------------------ /// binary_function Functor object for class OSortIndex::TIntValuePairVector::value_type returntype is bool struct TKeyValueFunc : ::std::binary_function<OSortIndex::TIntValuePairVector::value_type,OSortIndex::TIntValuePairVector::value_type,bool> { OSortIndex* pIndex; TKeyValueFunc(OSortIndex* _pIndex) : pIndex(_pIndex) { } // return false if compared values are equal otherwise true inline bool operator()(const OSortIndex::TIntValuePairVector::value_type& lhs,const OSortIndex::TIntValuePairVector::value_type& rhs) const { const ::std::vector<OKeyType>& aKeyType = pIndex->getKeyType(); ::std::vector<OKeyType>::const_iterator aIter = aKeyType.begin(); for (::std::vector<sal_Int16>::size_type i=0;aIter != aKeyType.end(); ++aIter,++i) { const bool nGreater = (pIndex->getAscending(i) == SQL_ASC) ? false : true; const bool nLess = !nGreater; // compare depending for type switch (*aIter) { case SQL_ORDERBYKEY_STRING: { sal_Int32 nRes = lhs.second->getKeyString(i).compareTo(rhs.second->getKeyString(i)); if (nRes < 0) return nLess; else if (nRes > 0) return nGreater; } break; case SQL_ORDERBYKEY_DOUBLE: { double d1 = lhs.second->getKeyDouble(i); double d2 = rhs.second->getKeyDouble(i); if (d1 < d2) return nLess; else if (d1 > d2) return nGreater; } break; } } // know we know that the values are equal return false; } }; // ----------------------------------------------------------------------------- ::vos::ORef<OKeySet> OSortIndex::CreateKeySet() { Freeze(); ::vos::ORef<OKeySet> pKeySet = new OKeySet(); pKeySet->reserve(m_aKeyValues.size()); ::std::transform(m_aKeyValues.begin() ,m_aKeyValues.end() ,::std::back_inserter(*pKeySet) ,::std::select1st<TIntValuePairVector::value_type>()); pKeySet->setFrozen(); return pKeySet; } // ----------------------------------------------------------------------------- OSortIndex::OSortIndex( const ::std::vector<OKeyType>& _aKeyType, const ::std::vector<sal_Int16>& _aAscending) : m_bFrozen(sal_False) ,m_aAscending(_aAscending) ,m_aKeyType(_aKeyType) { } //------------------------------------------------------------------ OSortIndex::~OSortIndex() { } //------------------------------------------------------------------ void OSortIndex::AddKeyValue(OKeyValue * pKeyValue) { OSL_ENSURE(pKeyValue,"Can not be null here!"); if(m_bFrozen) { m_aKeyValues.push_back(TIntValuePairVector::value_type(pKeyValue->getValue(),NULL)); delete pKeyValue; } else m_aKeyValues.push_back(TIntValuePairVector::value_type(pKeyValue->getValue(),pKeyValue)); } //------------------------------------------------------------------ void OSortIndex::Freeze() { OSL_ENSURE(! m_bFrozen,"OSortIndex::Freeze: already frozen!"); // Sortierung: if (m_aKeyType[0] != SQL_ORDERBYKEY_NONE) // we will sort ourself when the first keyType say so ::std::sort(m_aKeyValues.begin(),m_aKeyValues.end(),TKeyValueFunc(this)); TIntValuePairVector::iterator aIter = m_aKeyValues.begin(); for(;aIter != m_aKeyValues.end();++aIter) { delete aIter->second; aIter->second = NULL; } m_bFrozen = sal_True; } //------------------------------------------------------------------ sal_Int32 OSortIndex::GetValue(sal_Int32 nPos) const { OSL_ENSURE(nPos > 0,"OSortIndex::GetValue: nPos == 0"); OSL_ENSURE(nPos <= m_aKeyValues.size(),"OSortIndex::GetValue: Zugriff ausserhalb der Array-Grenzen"); if (!m_bFrozen && m_aKeyType[0] != SQL_ORDERBYKEY_NONE) { OSL_ASSERT("OSortIndex::GetValue: Invalid use of index!"); return 0; } return m_aKeyValues[nPos-1].first; } // ----------------------------------------------------------------------------- OKeyValue::OKeyValue() { } // ----------------------------------------------------------------------------- OKeyValue::OKeyValue(sal_Int32 nVal) : m_nValue(nVal) { } // ----------------------------------------------------------------------------- OKeyValue::~OKeyValue() { } // ----------------------------------------------------------------------------- OKeyValue* OKeyValue::createKeyValue(sal_Int32 _nVal) { return new OKeyValue(_nVal); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before><commit_msg>update<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <sys/time.h> using namespace std; const int fac = 1; const int nnx = 256; const int nnxy = 65536; const int NN =1073741824 + 2*nnxy; double a[NN], b[NN]; int N; double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } int main (int argc, char **argv) { double time_begin, time_end; for (N=1024;N<NN && N>0; N*=2) { #pragma omp parallel { for (int i=0;i<NN;++i) { a[i]=i; } #pragma omp master { time_begin=wctime(); } for (int t=0;t<NN/N*fac;++t) { #pragma omp for nowait for (int i=0;i<N;++i) { a[i]=(b[i]+b[i+1]+b[i+2]+b[i+nnx]+b[i+2*nnx]+b[i+nnxy]+b[i+2*nnxy])/7.0; } #pragma omp for nowait for (int i=0;i<N;++i) { b[i]=a[i]; } } #pragma omp master { time_end=wctime(); double gb = 8.0*8*double(fac)*NN/1e9; double time_elapse=time_end - time_begin; cout << N << " " << a[N/2] << " gbps: " << gb/time_elapse << endl; } } } } <commit_msg>Supernazoi benchmark<commit_after>#include <iostream> #include <sys/time.h> using namespace std; const int fac = 1; const int nnx = 256; const int nnxy = 65536; const int NN =1073741824 + 2*nnxy; double a[NN], b[NN]; int N; double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } int main (int argc, char **argv) { double time_begin, time_end; for (N=1024;N<NN && N>0; N*=2) { if (N<0) break; #pragma omp parallel { for (int i=0;i<NN;++i) { a[i]=i; } #pragma omp master { time_begin=wctime(); } for (int t=0;t<NN/N*fac;++t) { #pragma omp for nowait for (int i=0;i<N;++i) { a[i]=(b[i]+b[i+1]+b[i+2]+b[i+nnx]+b[i+2*nnx]+b[i+nnxy]+b[i+2*nnxy])/7.0; } #pragma omp for nowait for (int i=0;i<N;++i) { b[i]=a[i]; } } #pragma omp master { time_end=wctime(); double gb = 8.0*8*double(fac)*NN/1e9; double time_elapse=time_end - time_begin; cout << N << " " << a[N/2] << " gbps: " << gb/time_elapse << endl; } } } } <|endoftext|>
<commit_before>/* * mod_compare - compare apache requests * * Copyright (C) 2013 Orange * * 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 "mod_compare.hh" #include "RequestInfo.hh" #include "CassandraDiff.h" #include "Utils.hh" #include <http_config.h> #include <assert.h> #include <stdexcept> #include <boost/thread/detail/singleton.hpp> #include <boost/archive/text_oarchive.hpp> #include <math.h> #include <boost/tokenizer.hpp> #include <iomanip> #include <apache2/httpd.h> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/posix_time/posix_time_io.hpp> #include <boost/date_time/time_facet.hpp> #include <boost/thread/locks.hpp> namespace CompareModule { void map2string(const std::map< std::string, std::string> &pMap, std::string &pString) { std::map< std::string, std::string>::const_iterator lIter; for ( lIter = pMap.begin(); lIter != pMap.end(); ++lIter ) { pString += lIter->first + ": " + lIter->second + "\n"; } } void writeDifferences(const DupModule::RequestInfo &pReqInfo, LibWsDiff::diffPrinter& printer, boost::posix_time::time_duration time) { double t=time.total_milliseconds(); if (t > 0){ printer.addInfo("ElapsedTime",t); } std::map< std::string, std::string >::const_iterator it = pReqInfo.mReqHeader.find("ELAPSED_TIME_BY_DUP"); std::string diffTime; try { if(it!=pReqInfo.mReqHeader.end()){ t=boost::lexical_cast<int>(it->second)-boost::lexical_cast<int>(pReqInfo.getElapsedTimeMS()); printer.addRuntime("DIFF",t); } } catch ( boost::bad_lexical_cast &e ) { Log::error(12, "Failed to cast ELAPSED_TIME_BY_DUP: %s to an int", it->second.c_str()); } #ifdef UNIT_TESTING printer.addInfo("Date","UNITTEST_TODAY_VALUE"); #else std::stringstream today; today<<boost::posix_time::microsec_clock::local_time(); printer.addInfo("Date",today.str()); #endif if(it!=pReqInfo.mReqHeader.end()){ printer.addRuntime("DUP",boost::lexical_cast<int>(it->second)); } printer.addRuntime("COMP",pReqInfo.getElapsedTimeMS()); if(pReqInfo.mRequest.back()=='?'){ printer.addRequestUri(pReqInfo.mRequest,pReqInfo.mReqBody); }else{ printer.addRequestUri(pReqInfo.mRequest); if(!pReqInfo.mReqBody.empty()){ printer.addInfo("ReqBody",pReqInfo.mReqBody); } } std::map< std::string, std::string>::const_iterator lIter; for ( lIter = pReqInfo.mReqHeader.begin(); lIter != pReqInfo.mReqHeader.end(); ++lIter ) { printer.addRequestHeader(lIter->first,lIter->second); } printer.addStatus("DUP",pReqInfo.mReqHttpStatus); printer.addStatus("COMP",pReqInfo.mDupResponseHttpStatus); writeCassandraDiff( pReqInfo.mId, printer ); std::string res; printer.retrieveDiff(res); if(!gWriteInFile){ std::string lLine; boost::lock_guard<boost::interprocess::named_mutex> fileLock(getGlobalMutex()); std::vector<std::string> resLines; boost::split(resLines,res,boost::is_any_of("\n")); for(std::vector<std::string>::iterator it= resLines.begin(); it!=resLines.end();it++) { writeInFacility(*it); } } else { if (gFile.is_open()){ boost::lock_guard<boost::interprocess::named_mutex> fileLock(getGlobalMutex()); gFile << res; gFile.flush(); } else { Log::error(12, "File not correctly opened"); } } } /** * @brief split the input string every 1024 characters and writes it in the syslog * @param pDiffLog string to split and to write in syslog */ void writeInFacility(std::string pDiffLog){ int lSplitSize = LOGMAXSIZE; int stringLength = pDiffLog.size(); for (int i = 0; i < stringLength ; i += lSplitSize) { if (i + lSplitSize > stringLength){ lSplitSize = stringLength - i; } Log::error(12, "%s", pDiffLog.substr(i, lSplitSize).c_str()); } } /** * @brief write request body and header in the syslog or in file with serialized boost method * @param req object containing the infos about the request */ void writeSerializedRequest(const DupModule::RequestInfo& req) { if(!gWriteInFile){ std::stringstream lSerialRequest; boost::archive::text_oarchive oa(lSerialRequest); oa << req; //no need to split on '\n' writeInFacility(lSerialRequest.str()); } else { if (gFile.is_open()){ boost::lock_guard<boost::interprocess::named_mutex> fileLock(getGlobalMutex()); boost::archive::text_oarchive oa(gFile); oa << req; } else { Log::error(12, "File not correctly opened"); } } } /** * @brief write the Cassandra differences in log file * @param pUniqueID the UNIQUE_ID of the request to check * @return true if there are differences, false otherwise */ void writeCassandraDiff(const std::string &pUniqueID, LibWsDiff::diffPrinter& printer) { typedef std::multimap<std::string, CassandraDiff::FieldInfo> tMultiMapDiff; CassandraDiff::Differences & lDiff = boost::detail::thread::singleton<CassandraDiff::Differences>::instance(); boost::lock_guard<boost::mutex> lLock(lDiff.getMutex()); std::pair <tMultiMapDiff::iterator, tMultiMapDiff::iterator> lPairIter; lPairIter = lDiff.equal_range(pUniqueID); if ( lPairIter.first == lPairIter.second ) { return; } for(;lPairIter.first!=lPairIter.second;++lPairIter.first){ printer.addCassandraDiff(lPairIter.first->second.mName, lPairIter.first->second.mMultivalueKey, lPairIter.first->second.mDBValue, lPairIter.first->second.mReqValue); } lDiff.erase(pUniqueID); } /** * @brief checks if there are differences in Cassandra * @param pUniqueID the UNIQUE_ID of the request to check * @return true if there are differences, false otherwise */ bool checkCassandraDiff(const std::string &pUniqueID) { typedef std::multimap<std::string, CassandraDiff::FieldInfo> tMultiMapDiff; CassandraDiff::Differences & lDiff = boost::detail::thread::singleton<CassandraDiff::Differences>::instance(); boost::lock_guard<boost::mutex> lLock(lDiff.getMutex()); std::pair <tMultiMapDiff::iterator, tMultiMapDiff::iterator> lPairIter; lPairIter = lDiff.equal_range(pUniqueID); if ( lPairIter.first == lPairIter.second ) { return false; } return true; } } <commit_msg>Debug log line<commit_after>/* * mod_compare - compare apache requests * * Copyright (C) 2013 Orange * * 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 "mod_compare.hh" #include "RequestInfo.hh" #include "CassandraDiff.h" #include "Utils.hh" #include <http_config.h> #include <assert.h> #include <stdexcept> #include <boost/thread/detail/singleton.hpp> #include <boost/archive/text_oarchive.hpp> #include <math.h> #include <boost/tokenizer.hpp> #include <iomanip> #include <apache2/httpd.h> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/posix_time/posix_time_io.hpp> #include <boost/date_time/time_facet.hpp> #include <boost/thread/locks.hpp> namespace CompareModule { void map2string(const std::map< std::string, std::string> &pMap, std::string &pString) { std::map< std::string, std::string>::const_iterator lIter; for ( lIter = pMap.begin(); lIter != pMap.end(); ++lIter ) { pString += lIter->first + ": " + lIter->second + "\n"; } } void writeDifferences(const DupModule::RequestInfo &pReqInfo, LibWsDiff::diffPrinter& printer, boost::posix_time::time_duration time) { double t=time.total_milliseconds(); if (t > 0){ printer.addInfo("ElapsedTime",t); } std::map< std::string, std::string >::const_iterator it = pReqInfo.mReqHeader.find("ELAPSED_TIME_BY_DUP"); std::string diffTime; try { if(it!=pReqInfo.mReqHeader.end()){ t=boost::lexical_cast<int>(it->second)-boost::lexical_cast<int>(pReqInfo.getElapsedTimeMS()); printer.addRuntime("DIFF",t); } } catch ( boost::bad_lexical_cast &e ) { Log::error(12, "Failed to cast ELAPSED_TIME_BY_DUP: %s to an int", it->second.c_str()); } std::cout << "DIFF " << pReqInfo.mId << " " << boost::posix_time::microsec_clock::local_time() << " " << pReqInfo.mRequest << std::endl; #ifdef UNIT_TESTING printer.addInfo("Date","UNITTEST_TODAY_VALUE"); #else std::stringstream today; today<<boost::posix_time::microsec_clock::local_time(); printer.addInfo("Date",today.str()); #endif if(it!=pReqInfo.mReqHeader.end()){ printer.addRuntime("DUP",boost::lexical_cast<int>(it->second)); } printer.addRuntime("COMP",pReqInfo.getElapsedTimeMS()); if(pReqInfo.mRequest.back()=='?'){ printer.addRequestUri(pReqInfo.mRequest,pReqInfo.mReqBody); }else{ printer.addRequestUri(pReqInfo.mRequest); if(!pReqInfo.mReqBody.empty()){ printer.addInfo("ReqBody",pReqInfo.mReqBody); } } std::map< std::string, std::string>::const_iterator lIter; for ( lIter = pReqInfo.mReqHeader.begin(); lIter != pReqInfo.mReqHeader.end(); ++lIter ) { printer.addRequestHeader(lIter->first,lIter->second); } printer.addStatus("DUP",pReqInfo.mReqHttpStatus); printer.addStatus("COMP",pReqInfo.mDupResponseHttpStatus); writeCassandraDiff( pReqInfo.mId, printer ); std::string res; printer.retrieveDiff(res); if(!gWriteInFile){ std::string lLine; boost::lock_guard<boost::interprocess::named_mutex> fileLock(getGlobalMutex()); std::vector<std::string> resLines; boost::split(resLines,res,boost::is_any_of("\n")); for(std::vector<std::string>::iterator it= resLines.begin(); it!=resLines.end();it++) { writeInFacility(*it); } } else { if (gFile.is_open()){ boost::lock_guard<boost::interprocess::named_mutex> fileLock(getGlobalMutex()); gFile << res; gFile.flush(); } else { Log::error(12, "File not correctly opened"); } } } /** * @brief split the input string every 1024 characters and writes it in the syslog * @param pDiffLog string to split and to write in syslog */ void writeInFacility(std::string pDiffLog){ int lSplitSize = LOGMAXSIZE; int stringLength = pDiffLog.size(); for (int i = 0; i < stringLength ; i += lSplitSize) { if (i + lSplitSize > stringLength){ lSplitSize = stringLength - i; } Log::error(12, "%s", pDiffLog.substr(i, lSplitSize).c_str()); } } /** * @brief write request body and header in the syslog or in file with serialized boost method * @param req object containing the infos about the request */ void writeSerializedRequest(const DupModule::RequestInfo& req) { if(!gWriteInFile){ std::stringstream lSerialRequest; boost::archive::text_oarchive oa(lSerialRequest); oa << req; //no need to split on '\n' writeInFacility(lSerialRequest.str()); } else { if (gFile.is_open()){ boost::lock_guard<boost::interprocess::named_mutex> fileLock(getGlobalMutex()); boost::archive::text_oarchive oa(gFile); oa << req; } else { Log::error(12, "File not correctly opened"); } } } /** * @brief write the Cassandra differences in log file * @param pUniqueID the UNIQUE_ID of the request to check * @return true if there are differences, false otherwise */ void writeCassandraDiff(const std::string &pUniqueID, LibWsDiff::diffPrinter& printer) { typedef std::multimap<std::string, CassandraDiff::FieldInfo> tMultiMapDiff; CassandraDiff::Differences & lDiff = boost::detail::thread::singleton<CassandraDiff::Differences>::instance(); boost::lock_guard<boost::mutex> lLock(lDiff.getMutex()); std::pair <tMultiMapDiff::iterator, tMultiMapDiff::iterator> lPairIter; lPairIter = lDiff.equal_range(pUniqueID); if ( lPairIter.first == lPairIter.second ) { return; } for(;lPairIter.first!=lPairIter.second;++lPairIter.first){ printer.addCassandraDiff(lPairIter.first->second.mName, lPairIter.first->second.mMultivalueKey, lPairIter.first->second.mDBValue, lPairIter.first->second.mReqValue); } lDiff.erase(pUniqueID); } /** * @brief checks if there are differences in Cassandra * @param pUniqueID the UNIQUE_ID of the request to check * @return true if there are differences, false otherwise */ bool checkCassandraDiff(const std::string &pUniqueID) { typedef std::multimap<std::string, CassandraDiff::FieldInfo> tMultiMapDiff; CassandraDiff::Differences & lDiff = boost::detail::thread::singleton<CassandraDiff::Differences>::instance(); boost::lock_guard<boost::mutex> lLock(lDiff.getMutex()); std::pair <tMultiMapDiff::iterator, tMultiMapDiff::iterator> lPairIter; lPairIter = lDiff.equal_range(pUniqueID); if ( lPairIter.first == lPairIter.second ) { return false; } return true; } } <|endoftext|>
<commit_before>/** ** \file runner/stacks.hh ** \brief Definition of runner::Stacks. */ #ifndef RUNNER_STACKS_HH # define RUNNER_STACKS_HH # include <ast/fwd.hh> # include <object/object.hh> // FIXME: action namespace runner { class Stacks { public: // Import types typedef object:: rObject rObject; typedef object::rrObject rrObject; /// Build static stacks Stacks(rObject lobby); /// Set values in the stacks void set(ast::rConstAssignment e, rObject v); void def(ast::rConstDeclaration e, rObject v); void def_arg(ast::rConstDeclaration e, rObject v); void def_captured(ast::rConstDeclaration e, rrObject v); /// Get values from the stacks rObject get(ast::rConstLocal e); rrObject rget(ast::rConstLocal e); /// Get and set 'this' and 'call' void self_set(rObject v); void call_set(rObject v); rObject self(); rObject call(); boost::function0<void> switch_self(rObject v); /// Signal the stacks a new execution is starting void execution_starts(const libport::Symbol& msg); /// Push new frames on the stacks to execute a function /** \param msg Name of the function being invoked (debug purpose only) * \param local Size of the local variable frame. * \param closed Size of the closed variable frame. * \param captured Size of the captured variable frame. * \param self Value of 'this' in the new frame. * \param call Value of 'call' in the new frame. * \return The action to restore the previous frame state. */ boost::function0<void> push_frame(const libport::Symbol& msg, unsigned local, unsigned closed, unsigned captured, rObject self, rObject call); private: /// Factored setter void set(unsigned local, bool closed, bool captured, rObject v); /// Factored definer void def(unsigned local, rObject v); void def(unsigned local, bool captured, rrObject v); /// Helper to restore a previous frame state void pop_frame(const libport::Symbol& msg, unsigned local, unsigned closed, unsigned captured); /// Helper to restore switched 'this' void switch_self_back(rObject v); /// The local stack typedef std::vector<rObject> local_stack_type; local_stack_type local_stack_; /// The related frame pointer unsigned local_pointer_; /// The double-indirection local stack, for captured and /// closed-over variables typedef std::vector<rrObject> rlocal_stack_type; rlocal_stack_type rlocal_stack_; /// The closed variables frame pointer unsigned closed_pointer_; /// The captured variables frame pointer unsigned captured_pointer_; }; } #endif <commit_msg>Document Stacks.<commit_after>/** ** \file runner/stacks.hh ** \brief Definition of runner::Stacks. */ #ifndef RUNNER_STACKS_HH # define RUNNER_STACKS_HH # include <ast/fwd.hh> # include <object/object.hh> // FIXME: action namespace runner { class Stacks { public: // Import types typedef object:: rObject rObject; typedef object::rrObject rrObject; /// Build static stacks Stacks(rObject lobby); /// Update the given value void set(ast::rConstAssignment e, rObject v); /// Define the given value void def(ast::rConstDeclaration e, rObject v); /// Bind given argument void def_arg(ast::rConstDeclaration e, rObject v); /// Bind given captured variable void def_captured(ast::rConstDeclaration e, rrObject v); /// Get value from the stack rObject get(ast::rConstLocal e); /// Get value by double pointer (e must be closed or captured) rrObject rget(ast::rConstLocal e); /// Set 'this' void self_set(rObject v); /// Set 'call' void call_set(rObject v); /// Get 'this' rObject self(); /// Get 'call' rObject call(); /// Switch the current 'this' /** \return the action to switch back to the previous 'this' */ boost::function0<void> switch_self(rObject v); /// Signal the stacks a new execution is starting void execution_starts(const libport::Symbol& msg); /// Push new frames on the stacks to execute a function /** \param msg Name of the function being invoked (debug purpose only) * \param local Size of the local variable frame. * \param closed Size of the closed variable frame. * \param captured Size of the captured variable frame. * \param self Value of 'this' in the new frame. * \param call Value of 'call' in the new frame. * \return The action to restore the previous frame state. */ boost::function0<void> push_frame(const libport::Symbol& msg, unsigned local, unsigned closed, unsigned captured, rObject self, rObject call); private: /// Factored setter void set(unsigned local, bool closed, bool captured, rObject v); /// Factored definer void def(unsigned local, rObject v); void def(unsigned local, bool captured, rrObject v); /// Helper to restore a previous frame state void pop_frame(const libport::Symbol& msg, unsigned local, unsigned closed, unsigned captured); /// Helper to restore switched 'this' void switch_self_back(rObject v); /// The local stack typedef std::vector<rObject> local_stack_type; local_stack_type local_stack_; /// The related frame pointer unsigned local_pointer_; /// The double-indirection local stack, for captured and /// closed-over variables typedef std::vector<rrObject> rlocal_stack_type; rlocal_stack_type rlocal_stack_; /// The closed variables frame pointer unsigned closed_pointer_; /// The captured variables frame pointer unsigned captured_pointer_; }; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2015, Wator Vapor All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of wator nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "wator.hpp" using namespace Wator; #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using namespace boost::property_tree; #include <boost/filesystem.hpp> #include <boost/foreach.hpp> namespace fs = boost::filesystem; #include <opencv2/core/core.hpp> #include <opencv2/opencv.hpp> #include <algorithm> using namespace std; /** * Constructor **/ ImageLayer::ImageLayer() :extension_({"jpg",".JPG",".png",".PNG",".tif",".TIF",".tiff",".TIFF"}) { INFO_VAR(this); } /** * Connect a Layer to Net. * @param [in] layer **/ CoulombLayer& ImageLayer::operator << (CoulombLayer &layer) { this->top_.push_back(&layer); layer.bottom(this); INFO_VAR(top_.size()); return layer; } /** * Connect a Layer to Net. * @param [in] layer **/ EinsteinLayer& ImageLayer::operator << (EinsteinLayer &layer) { this->top_.push_back(&layer); layer.bottom(this); INFO_VAR(top_.size()); return layer; } /** * load * @return None. **/ void ImageLayer::load(bool train) { TRACE_VAR(param_.root_); const fs::path path(param_.root_); BOOST_FOREACH(const fs::path& p, std::make_pair(fs::recursive_directory_iterator(path),fs::recursive_directory_iterator())){ if (!fs::is_directory(p)){ auto extension = p.extension().string(); auto itExt = std::find(extension_.begin(),extension_.end(),extension); if(itExt != extension_.end()){ INFO_VAR(p); mat_ = cv::imread(p.string()); pump(); for(auto &top:top_) { if (train) { top->round(); } else { top->forward(); } } } } } INFO_VAR("finnish load data"); } /* x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12 y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12 z1,z2,z3,z4,z5,z6,z7,z8,z9,z10,z11,z12 u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12 v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12 w1,w2,w3,w4,w5,w6,w7,w8,w9,w10,w11,w12 ------------------ x1,x2,x3,y1,y2,y3,z1,z2,z3, x4,x5,x6,y4,y5,y6,z4,z5,z6, x7,x8,x9,y7,y8,y9,z7,z8,z9, x10,x11,x12,y10,y11,y12,z10,z11,z12, u1,u2,u3,v1,v2,v3,w1,w2,w3, u4,u5,u6,v4,v5,v6,w4,w5,w6, u7,u8,u9,v7,v8,v9,w7,w8,w9, u10,u11,u12,v10,v11,v12,w10,w11,w12 */ void ImageLayer::pump(void) { blobs_.clear(); for(int i = 0;i < top_.size();i++ ) { INFO_VAR(mat_.cols); INFO_VAR(mat_.rows); INFO_VAR(mat_.channels()); auto blob = new Blob<uint8_t>(mat_.cols,mat_.rows,mat_.channels()); INFO_VAR(this); blobs_.push_back(blob); } std::vector<cv::Mat> planes; cv::split(mat_, planes); for(int channel = 0 ; channel < mat_.channels();channel++){ auto &mat = planes[channel]; for(int y = 0;y < mat.rows;y++){ for(int x = 0;x < mat.cols;x++){ auto byte = mat.at<uint8_t>(y, x); TRACE_VAR(x); TRACE_VAR(y); for(int i = 0;i < top_.size();i++){ int outH = 0; int outW = 0; CoulombLayer *clm = dynamic_cast<CoulombLayer*>(top_[i]); if(clm) { outH = clm->h_; outW = clm->w_; } EinsteinLayer *est = dynamic_cast<EinsteinLayer*>(top_[i]); if(est) { outH = est->h_; outW = est->w_; } TRACE_VAR(outW); TRACE_VAR(outH); int grid = ((y/outH) * (mat_.cols/outW))+ (x/outW) ; TRACE_VAR(grid); TRACE_VAR(channel); int index = channel * mat_.cols * mat_.rows; index += grid * outW * outH; index += (y%outH)*outW + x%outW ; TRACE_VAR(index); if(index > blobs_[i]->size_) { INFO_VAR(index); INFO_VAR(blobs_[i]->size_); continue; } blobs_[i]->data_[index] = byte; } } } } this->dump(planes); INFO_VAR(mat_.cols*mat_.rows*mat_.channels()); } /** * dump to png * @return None. **/ void ImageLayer::dump(const std::vector<cv::Mat> &planes){ static int counter = 0; for(int ch = 0 ; ch < mat_.channels();ch++){ string path = "dump.mat"; path += "."; path += std::to_string(counter); if(0 == ch){ path += ".B."; } if(1 == ch){ path += ".G."; } if(2 == ch){ path += ".R."; } path += ".png"; cv::imwrite(path ,planes[ch]); } ++counter; } <commit_msg>image layer cut out pixel of grid<commit_after>/* Copyright (c) 2015, Wator Vapor All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of wator nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "wator.hpp" using namespace Wator; #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using namespace boost::property_tree; #include <boost/filesystem.hpp> #include <boost/foreach.hpp> namespace fs = boost::filesystem; #include <opencv2/core/core.hpp> #include <opencv2/opencv.hpp> #include <algorithm> using namespace std; /** * Constructor **/ ImageLayer::ImageLayer() :extension_({"jpg",".JPG",".png",".PNG",".tif",".TIF",".tiff",".TIFF"}) { INFO_VAR(this); } /** * Connect a Layer to Net. * @param [in] layer **/ CoulombLayer& ImageLayer::operator << (CoulombLayer &layer) { this->top_.push_back(&layer); layer.bottom(this); INFO_VAR(top_.size()); return layer; } /** * Connect a Layer to Net. * @param [in] layer **/ EinsteinLayer& ImageLayer::operator << (EinsteinLayer &layer) { this->top_.push_back(&layer); layer.bottom(this); INFO_VAR(top_.size()); return layer; } /** * load * @return None. **/ void ImageLayer::load(bool train) { TRACE_VAR(param_.root_); const fs::path path(param_.root_); BOOST_FOREACH(const fs::path& p, std::make_pair(fs::recursive_directory_iterator(path),fs::recursive_directory_iterator())){ if (!fs::is_directory(p)){ auto extension = p.extension().string(); auto itExt = std::find(extension_.begin(),extension_.end(),extension); if(itExt != extension_.end()){ INFO_VAR(p); mat_ = cv::imread(p.string()); pump(); for(auto &top:top_) { if (train) { top->round(); } else { top->forward(); } } } } } INFO_VAR("finnish load data"); } /* x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12 y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12 z1,z2,z3,z4,z5,z6,z7,z8,z9,z10,z11,z12 u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12 v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12 w1,w2,w3,w4,w5,w6,w7,w8,w9,w10,w11,w12 ------------------ x1,x2,x3,y1,y2,y3,z1,z2,z3, x4,x5,x6,y4,y5,y6,z4,z5,z6, x7,x8,x9,y7,y8,y9,z7,z8,z9, x10,x11,x12,y10,y11,y12,z10,z11,z12, u1,u2,u3,v1,v2,v3,w1,w2,w3, u4,u5,u6,v4,v5,v6,w4,w5,w6, u7,u8,u9,v7,v8,v9,w7,w8,w9, u10,u11,u12,v10,v11,v12,w10,w11,w12 */ void ImageLayer::pump(void) { blobs_.clear(); for(int i = 0;i < top_.size();i++ ) { INFO_VAR(mat_.cols); INFO_VAR(mat_.rows); INFO_VAR(mat_.channels()); auto blob = new Blob<uint8_t>(mat_.cols,mat_.rows,mat_.channels()); INFO_VAR(this); blobs_.push_back(blob); } std::vector<cv::Mat> planes; cv::split(mat_, planes); for(int channel = 0 ; channel < mat_.channels();channel++){ auto &mat = planes[channel]; for(int y = 0;y < mat.rows;y++){ for(int x = 0;x < mat.cols;x++){ auto byte = mat.at<uint8_t>(y, x); TRACE_VAR(x); TRACE_VAR(y); for(int i = 0;i < top_.size();i++){ int outH = 0; int outW = 0; CoulombLayer *clm = dynamic_cast<CoulombLayer*>(top_[i]); if(clm) { outH = clm->h_; outW = clm->w_; } EinsteinLayer *est = dynamic_cast<EinsteinLayer*>(top_[i]); if(est) { outH = est->h_; outW = est->w_; } TRACE_VAR(outW); TRACE_VAR(outH); const int grid = ((y/outH) * (mat_.cols/outW))+ (x/outW) ; TRACE_VAR(grid); TRACE_VAR(channel); const int groundW = (mat_.cols/outW)*outW; const int groundH = (mat_.rows/outH)*outH; if(groundW < x || groundH < y) { // out side of last grid. continue; } TRACE_VAR(groundW); TRACE_VAR(groundH); int index = channel * groundW * groundH; index += grid * outW * outH; index += (y%outH)*outW + x%outW ; TRACE_VAR(index); if(index > blobs_[i]->size_) { INFO_VAR(index); INFO_VAR(blobs_[i]->size_); continue; } blobs_[i]->data_[index] = byte; } } } } this->dump(planes); INFO_VAR(mat_.cols*mat_.rows*mat_.channels()); } /** * dump to png * @return None. **/ void ImageLayer::dump(const std::vector<cv::Mat> &planes){ static int counter = 0; for(int ch = 0 ; ch < mat_.channels();ch++){ string path = "dump.mat"; path += "."; path += std::to_string(counter); if(0 == ch){ path += ".B."; } if(1 == ch){ path += ".G."; } if(2 == ch){ path += ".R."; } path += ".png"; cv::imwrite(path ,planes[ch]); } ++counter; } <|endoftext|>
<commit_before>/* * Listener on a TCP port. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_listener.hxx" #include "lb_instance.hxx" #include "lb_connection.hxx" #include "lb_config.hxx" #include "lb/HttpConnection.hxx" #include "ssl/ssl_factory.hxx" #include "ssl/DbSniCallback.hxx" #include "net/SocketAddress.hxx" void LbListener::OnAccept(UniqueSocketDescriptor &&new_fd, SocketAddress address) { switch (config.destination.GetProtocol()) { case LbProtocol::HTTP: NewLbHttpConnection(instance, config, ssl_factory, std::move(new_fd), address); break; case LbProtocol::TCP: lb_connection_new(instance, config, ssl_factory, std::move(new_fd), address); break; } } void LbListener::OnAcceptError(std::exception_ptr ep) { Log(2, "Failed to accept", ep); } std::string LbListener::MakeLogName() const noexcept { return "listener " + config.name; } /* * constructor * */ LbListener::LbListener(LbInstance &_instance, const LbListenerConfig &_config) :ServerSocket(_instance.event_loop), instance(_instance), config(_config) { } void LbListener::Setup() { assert(ssl_factory == nullptr); if (config.ssl) { /* prepare SSL support */ std::unique_ptr<SslSniCallback> sni_callback; if (config.cert_db != nullptr) { auto &cert_cache = instance.GetCertCache(*config.cert_db); sni_callback.reset(new DbSslSniCallback(cert_cache)); } ssl_factory = ssl_factory_new_server(config.ssl_config, std::move(sni_callback)); } Listen(config.bind_address, config.reuse_port, config.interface.empty() ? nullptr : config.interface.c_str()); if (config.destination.GetProtocol() == LbProtocol::HTTP || config.ssl) SetTcpDeferAccept(10); } LbListener::~LbListener() { if (ssl_factory != nullptr) ssl_factory_free(ssl_factory); } unsigned LbListener::FlushSSLSessionCache(long tm) { return ssl_factory != nullptr ? ssl_factory_flush(*ssl_factory, tm) : 0; } <commit_msg>lb_listener: catch and log exceptions in OnAccept()<commit_after>/* * Listener on a TCP port. * * author: Max Kellermann <mk@cm4all.com> */ #include "lb_listener.hxx" #include "lb_instance.hxx" #include "lb_connection.hxx" #include "lb_config.hxx" #include "lb/HttpConnection.hxx" #include "ssl/ssl_factory.hxx" #include "ssl/DbSniCallback.hxx" #include "net/SocketAddress.hxx" void LbListener::OnAccept(UniqueSocketDescriptor &&new_fd, SocketAddress address) try { switch (config.destination.GetProtocol()) { case LbProtocol::HTTP: NewLbHttpConnection(instance, config, ssl_factory, std::move(new_fd), address); break; case LbProtocol::TCP: lb_connection_new(instance, config, ssl_factory, std::move(new_fd), address); break; } } catch (const std::runtime_error &e) { Log(1, "Failed to setup accepted connection", e); } void LbListener::OnAcceptError(std::exception_ptr ep) { Log(2, "Failed to accept", ep); } std::string LbListener::MakeLogName() const noexcept { return "listener " + config.name; } /* * constructor * */ LbListener::LbListener(LbInstance &_instance, const LbListenerConfig &_config) :ServerSocket(_instance.event_loop), instance(_instance), config(_config) { } void LbListener::Setup() { assert(ssl_factory == nullptr); if (config.ssl) { /* prepare SSL support */ std::unique_ptr<SslSniCallback> sni_callback; if (config.cert_db != nullptr) { auto &cert_cache = instance.GetCertCache(*config.cert_db); sni_callback.reset(new DbSslSniCallback(cert_cache)); } ssl_factory = ssl_factory_new_server(config.ssl_config, std::move(sni_callback)); } Listen(config.bind_address, config.reuse_port, config.interface.empty() ? nullptr : config.interface.c_str()); if (config.destination.GetProtocol() == LbProtocol::HTTP || config.ssl) SetTcpDeferAccept(10); } LbListener::~LbListener() { if (ssl_factory != nullptr) ssl_factory_free(ssl_factory); } unsigned LbListener::FlushSSLSessionCache(long tm) { return ssl_factory != nullptr ? ssl_factory_flush(*ssl_factory, tm) : 0; } <|endoftext|>
<commit_before>// Copyright (c) 2016, The University of Texas at Austin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Leap.h" // comes from Leap Motion SDK #include <iostream> #include <sstream> #include <cstring> #include "ros/ros.h" #include "tf/transform_datatypes.h" #include "leap_motion_controller/LeapMotionOutput.h" /** Implementation of Leap::Listener class. */ class LeapListener : public Leap::Listener { public: virtual void onInit(const Leap::Controller&); virtual void onConnect(const Leap::Controller&); virtual void onDisconnect(const Leap::Controller&); virtual void onExit(const Leap::Controller&); virtual void onFrame(const Leap::Controller&); ros::Publisher ros_publisher_; // bool ros_msg_ready_; ///< TRUE when new leap_motion_controller::LeapMotionOutput message is ready to be sent. // leap_motion_controller::LeapMotionOutput ros_msg_; ///< Latest completed leap_motion_controller::LeapMotionOutput message. private: }; void LeapListener::onInit(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Initialized" << std::endl; } void LeapListener::onConnect(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Connected" << std::endl; controller.enableGesture(Leap::Gesture::TYPE_KEY_TAP); // enable recognition of the key tap gesture // Possible to configure KeyTapGesture parameters controller.config().setFloat("Gesture.KeyTap.MinDownVelocity", 50.0); controller.config().setFloat("Gesture.KeyTap.HistorySeconds", 0.1); controller.config().setFloat("Gesture.KeyTap.MinDistance", 3.0); controller.config().save(); } void LeapListener::onDisconnect(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Disconnected" << std::endl; } void LeapListener::onExit(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Exited" << std::endl; } /** This method is executed when new Leap motion frame is available. */ void LeapListener::onFrame(const Leap::Controller& controller) { // Get the most recent frame and report some basic information const Leap::Frame work_frame = controller.frame(); // Create a local instance of LeapMotionOutput message leap_motion_controller::LeapMotionOutput ros_msg; // Add ROS timestamp to ros_msg.header ros_msg.header.stamp = ros::Time::now(); // Set frame id ros_msg.header.frame_id = "leap_motion"; // FYI std::cout << "Frame id: " << work_frame.id() << ", timestamp: " << work_frame.timestamp() << ", hands: " << work_frame.hands().count() << ", extended fingers: " << work_frame.fingers().extended().count() << ", gestures: " << work_frame.gestures().count() << std::endl; // Getting hands Leap::HandList hands_in_frame = work_frame.hands(); // get HandList from frame ros_msg.left_hand = false; // by default set both hands false in msg; ros_msg.right_hand = false; if (hands_in_frame.count() > 2) ROS_INFO("WHAT?? WAY TOO MANY HANDS!!");// if, for some reason, there are more than 2 hands, that's NOT OK, imho else if (hands_in_frame.count() > 0) // if there are more than 0 hands { Leap::Hand left_hand, right_hand; // create empty objects for left_hand and right_hand for(int i = 0; i < hands_in_frame.count(); i++) // go thru all the elements in HandList { // If Hand is left if (hands_in_frame[i].isLeft()) { ros_msg.left_hand = true; // set ros_msg.left_hand TRUE left_hand = hands_in_frame[i]; // set this hand as left_hand printf("Lefty HERE! Sphere radius: %.1f; Pinch strength: %f\n", left_hand.sphereRadius(), left_hand.pinchStrength()); // FYI // convert palm position into meters and copy to ros_msg.left_palm_pos ros_msg.left_palm_pose.position.x = left_hand.palmPosition().x/1000; ros_msg.left_palm_pose.position.y = left_hand.palmPosition().y/1000; ros_msg.left_palm_pose.position.z = left_hand.palmPosition().z/1000; // Get hand's roll-pitch-yam and convert them into quaternion. // NOTE: Leap Motion roll-pith-yaw is from the perspective of human, so I am mapping it so that roll is about x-, pitch about y-, and yaw about z-axis. float l_yaw = left_hand.palmNormal().roll(); float l_roll = left_hand.direction().pitch(); float l_pitch = -left_hand.direction().yaw(); // Negating to comply with the right hand rule. printf("Lefty HERE! Roll: %.2f; Pitch: %.2f; Yaw: %.2f\n", l_roll, l_pitch, l_yaw); ros_msg.left_palm_pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(l_roll, l_pitch, l_yaw); // Put sphere radius and pinch strength into ROS message ros_msg.left_hand_sphere_radius = left_hand.sphereRadius(); ros_msg.left_hand_pinch_strength = left_hand.pinchStrength(); } // If Hand is right else if (hands_in_frame[i].isRight()) { ros_msg.right_hand = true; // set ros_msg.right_hand true right_hand = hands_in_frame[i]; // set this hand as right_hand printf("Righty HERE! Sphere radius: %.1f; Pinch strength: %f\n", right_hand.sphereRadius(), right_hand.pinchStrength()); // FYI // Convert palm position into meters and copy to ros_msg.right_palm_pos ros_msg.right_palm_pose.position.x = right_hand.palmPosition().x/1000; ros_msg.right_palm_pose.position.y = right_hand.palmPosition().y/1000; ros_msg.right_palm_pose.position.z = right_hand.palmPosition().z/1000; // Get hand's roll-pitch-yam and convert them into quaternion. // NOTE: Leap Motion roll-pith-yaw is from the perspective of human, so I am mapping it so that roll is about x-, pitch about y-, and yaw about z-axis. float r_yaw = right_hand.palmNormal().roll(); float r_roll = right_hand.direction().pitch(); float r_pitch = -right_hand.direction().yaw(); // Negating to comply with the right hand rule. printf("Righty HERE! Roll: %.2f; Pitch: %.2f; Yaw: %.2f\n", r_roll, r_pitch, r_yaw); ros_msg.right_palm_pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(r_roll, r_pitch, r_yaw); // Put sphere radius and pinch strength into ROS message ros_msg.right_hand_sphere_radius = right_hand.sphereRadius(); ros_msg.right_hand_pinch_strength = right_hand.pinchStrength(); } } // for } // else if (hands_in_frame.count() > 0) // Getting gestures Leap::GestureList gestures_in_frame = work_frame.gestures(); ros_msg.left_hand_key_tap = false; // by default set KEY_TAP gestures to false on both hands ros_msg.right_hand_key_tap = false; int left_count = 0; // number of gestures with left hand int right_count = 0; // number of gestures with right hand for (int j = 0; j < gestures_in_frame.count(); j++) { // go through all the gestures in the list if (gestures_in_frame[j].hands()[0].isValid() && gestures_in_frame[j].hands()[0].isLeft()) { // if the hand of j-th gesture is valid and left left_count++; // increment number of gestures with left hand ros_msg.left_hand_key_tap = true; // report that there was a lefthand_key_tap } // end if if (gestures_in_frame[j].hands()[0].isValid() && gestures_in_frame[j].hands()[0].isRight()) { // if the hand of j-th gesture is valid and right right_count++; // increment number of gestures with right hand ros_msg.right_hand_key_tap = true; // report that there was a righthand_key_tap } // end if } // end for // Copy msg to ros_msg_ and set ros_msg_ready_ TRUE. main() is using this data to publish ROS messages // ros_msg_ = msg; // ros_msg_ready_ = true; // Publish the ROS message based on this Leap Motion frame. ros_publisher_.publish( ros_msg ); } // end onFrame /** Main method. */ int main(int argc, char** argv) { // ROS stuff ros::init(argc, argv, "leap_motion"); // ros::AsyncSpinner spinner(1); // using async spinner // spinner.start(); // starting async spinner ros::NodeHandle nh; // ROS node handle // ros::Rate rate(1000); // Creates publisher that advertises LeapMotionOutput messages on rostopic /leapmotion_general // ros::Publisher leap_publisher = nh.advertise<leap_motion_controller::LeapMotionOutput>("leapmotion_general", 10); // Instance of LeapListener LeapListener listener; listener.ros_publisher_ = nh.advertise<leap_motion_controller::LeapMotionOutput>("leapmotion_general"/*"leap_motion_output"*/, 10); // Just in case. There are no ROS messages ready at start. // listener.ros_msg_ready_ = false; // Instance of LEAP Controller Leap::Controller controller; // Have the listener receive events from the controller controller.addListener(listener); // Keep this process running while ros is ok(); // while( ros::ok() ) // { // If a new ROS message has been composed // if ( listener.ros_msg_ready_ ) // { // leap_publisher.publish( listener.ros_msg_ ); // publish the most recent ros_msg_ // listener.ros_msg_ready_ = false; // set ros_msg_ready_ to FALSE // } // if // ros::spinOnce(); // rate.sleep(); // } // while // Keep this process running until Enter is pressed // std::cout << "Press Enter to quit..." << std::endl; // std::cin.get(); ros::spin(); // Remove the listener when done controller.removeListener(listener); return 0; } // main<commit_msg>Some code clean-up, removing stuff that was already commented out.<commit_after>// Copyright (c) 2016, The University of Texas at Austin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Leap.h" // comes from Leap Motion SDK #include <iostream> #include <sstream> #include <cstring> #include "ros/ros.h" #include "tf/transform_datatypes.h" #include "leap_motion_controller/LeapMotionOutput.h" /** Implementation of Leap::Listener class. */ class LeapListener : public Leap::Listener { public: virtual void onInit(const Leap::Controller&); virtual void onConnect(const Leap::Controller&); virtual void onDisconnect(const Leap::Controller&); virtual void onExit(const Leap::Controller&); virtual void onFrame(const Leap::Controller&); // ROS publisher for Leap Motion Controller data ros::Publisher ros_publisher_; private: }; void LeapListener::onInit(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Initialized" << std::endl; } void LeapListener::onConnect(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Connected" << std::endl; // Enable recognition of the key tap gesture controller.enableGesture(Leap::Gesture::TYPE_KEY_TAP); // Configure KeyTapGesture parameters controller.config().setFloat("Gesture.KeyTap.MinDownVelocity", 50.0); controller.config().setFloat("Gesture.KeyTap.HistorySeconds", 0.1); controller.config().setFloat("Gesture.KeyTap.MinDistance", 3.0); controller.config().save(); } void LeapListener::onDisconnect(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Disconnected" << std::endl; } void LeapListener::onExit(const Leap::Controller& controller) { std::cout << "Leap Motion Controller Exited" << std::endl; } /** This method is executed when new Leap motion frame is available. * It extracts relevant data from Leap::Frame and publishes a corresponding ROS message. */ void LeapListener::onFrame(const Leap::Controller& controller) { // Get the most recent frame const Leap::Frame work_frame = controller.frame(); // Create a local instance of LeapMotionOutput message leap_motion_controller::LeapMotionOutput ros_msg; // Add ROS timestamp to ros_msg.header ros_msg.header.stamp = ros::Time::now(); // Set ROS frame_id in ros_msg.header ros_msg.header.frame_id = "leap_motion"; // FYI std::cout << "Frame id: " << work_frame.id() << ", timestamp: " << work_frame.timestamp() << ", hands: " << work_frame.hands().count() << ", extended fingers: " << work_frame.fingers().extended().count() << ", gestures: " << work_frame.gestures().count() << std::endl; Leap::HandList hands_in_frame = work_frame.hands(); // get HandList from frame ros_msg.left_hand = false; // by default set both hands false in msg; ros_msg.right_hand = false; if (hands_in_frame.count() > 2) // if, for some reason, there are more than 2 hands, that's NOT OK, imho ROS_INFO("WHAT? There are more than 2 hands in the frame - that's way too many hands! Going to pretend that there are no hands until next frame."); else if (hands_in_frame.count() > 0) // if there are more than 0 hands { Leap::Hand left_hand, right_hand; // create empty objects for left_hand and right_hand for(int i = 0; i < hands_in_frame.count(); i++) // go thru all the elements in HandList { // If Hand is left if (hands_in_frame[i].isLeft()) { ros_msg.left_hand = true; // set ros_msg.left_hand TRUE left_hand = hands_in_frame[i]; // set this hand as left_hand printf("Lefty HERE! Sphere radius: %.1f; Pinch strength: %f\n", left_hand.sphereRadius(), left_hand.pinchStrength()); // FYI // convert palm position into meters and copy to ros_msg.left_palm_pos ros_msg.left_palm_pose.position.x = left_hand.palmPosition().x/1000; ros_msg.left_palm_pose.position.y = left_hand.palmPosition().y/1000; ros_msg.left_palm_pose.position.z = left_hand.palmPosition().z/1000; // Get hand's roll-pitch-yam and convert them into quaternion. // NOTE: Leap Motion roll-pith-yaw is from the perspective of human, so I am mapping it so that roll is about x-, pitch about y-, and yaw about z-axis. float l_yaw = left_hand.palmNormal().roll(); float l_roll = left_hand.direction().pitch(); float l_pitch = -left_hand.direction().yaw(); // Negating to comply with the right hand rule. printf("Lefty HERE! Roll: %.2f; Pitch: %.2f; Yaw: %.2f\n", l_roll, l_pitch, l_yaw); ros_msg.left_palm_pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(l_roll, l_pitch, l_yaw); // Put sphere radius and pinch strength into ROS message ros_msg.left_hand_sphere_radius = left_hand.sphereRadius(); ros_msg.left_hand_pinch_strength = left_hand.pinchStrength(); } // If Hand is right else if (hands_in_frame[i].isRight()) { ros_msg.right_hand = true; // set ros_msg.right_hand true right_hand = hands_in_frame[i]; // set this hand as right_hand printf("Righty HERE! Sphere radius: %.1f; Pinch strength: %f\n", right_hand.sphereRadius(), right_hand.pinchStrength()); // FYI // Convert palm position into meters and copy to ros_msg.right_palm_pos ros_msg.right_palm_pose.position.x = right_hand.palmPosition().x/1000; ros_msg.right_palm_pose.position.y = right_hand.palmPosition().y/1000; ros_msg.right_palm_pose.position.z = right_hand.palmPosition().z/1000; // Get hand's roll-pitch-yam and convert them into quaternion. // NOTE: Leap Motion roll-pith-yaw is from the perspective of human, so I am mapping it so that roll is about x-, pitch about y-, and yaw about z-axis. float r_yaw = right_hand.palmNormal().roll(); float r_roll = right_hand.direction().pitch(); float r_pitch = -right_hand.direction().yaw(); // Negating to comply with the right hand rule. printf("Righty HERE! Roll: %.2f; Pitch: %.2f; Yaw: %.2f\n", r_roll, r_pitch, r_yaw); ros_msg.right_palm_pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(r_roll, r_pitch, r_yaw); // Put sphere radius and pinch strength into ROS message ros_msg.right_hand_sphere_radius = right_hand.sphereRadius(); ros_msg.right_hand_pinch_strength = right_hand.pinchStrength(); } } // for } // else if (hands_in_frame.count() > 0) // Getting gestures // TODO Do I actually need gestures in this ROS driver or at all. If the answer is YES, perhaps add some other gestures, e.g. swipe and circle. // Maybe enable gestures with a YAML file // leap_motion_controller_data: // -left_hand_frame: "leap_motion" # that makes sense if you start using PoseStamped for palm, this way you can have different frames from different hands if you want // -right_hand_frame: "leap_motion" // -enable_key_tap: true // -enable_swipe: true // etc ... Leap::GestureList gestures_in_frame = work_frame.gestures(); ros_msg.left_hand_key_tap = false; // by default set KEY_TAP gestures to false on both hands ros_msg.right_hand_key_tap = false; // Since only KEY_TAP gestures have been enabled, any detected gesure is a KEY_TAP gesture. for (int j = 0; j < gestures_in_frame.count(); j++) // go through all the gestures in the list { // if the hand of j-th gesture is valid and left if (gestures_in_frame[j].hands()[0].isValid() && gestures_in_frame[j].hands()[0].isLeft()) { ros_msg.left_hand_key_tap = true; // report that there was a lefthand_key_tap } // end if // if the hand of j-th gesture is valid and right if (gestures_in_frame[j].hands()[0].isValid() && gestures_in_frame[j].hands()[0].isRight()) { ros_msg.right_hand_key_tap = true; // report that there was a righthand_key_tap } // end if } // end for // Publish the ROS message based on this Leap Motion Controller frame. ros_publisher_.publish( ros_msg ); } // end LeapListener::onFrame() /** Main method. */ int main(int argc, char** argv) { // ROS init ros::init(argc, argv, "leap_motion"); // ROS node handle ros::NodeHandle nh; // Instance of LeapListener LeapListener listener; // Set up ROS publisher for LeapListener // TODO change the topic name when doing code cleanup listener.ros_publisher_ = nh.advertise<leap_motion_controller::LeapMotionOutput>("leapmotion_general"/*"leap_motion_output"*/, 10); // Instance of LEAP Controller Leap::Controller controller; // Have the listener receive events from the controller controller.addListener(listener); // Do ros::spin() until CTRL+C is pressed ros::spin(); // Remove the listener when done controller.removeListener(listener); return 0; } // main<|endoftext|>
<commit_before>#ifndef MJOLNIR_READ_SYSTEM #define MJOLNIR_READ_SYSTEM #include <mjolnir/core/System.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <extlib/toml/toml.hpp> namespace mjolnir { template<typename boundaryT> struct read_boundary_impl; template<typename realT, typename coordT> struct read_boundary_impl<UnlimitedBoundary<realT, coordT>> { static UnlimitedBoundary<realT, coordT> invoke(const toml::Table& boundary) { return UnlimitedBoundary<realT, coordT>{}; } }; template<typename realT, typename coordT> struct read_boundary_impl<CubicPeriodicBoundary<realT, coordT>> { static CubicPeriodicBoundary<realT, coordT> invoke(const toml::Table& boundary) { const coordT upper(toml::get<std::array<realT, 3>>(boundary.at("upper"))); const coordT lower(toml::get<std::array<realT, 3>>(boundary.at("lower"))); return CubicPeriodicBoundary<realT, coordT>(lower, upper); } }; template<typename traitsT> typename traitsT::boundary_type read_boundary(const toml::Table& boundary) { return read_boundary_impl<typename traitsT::boundary_type>::invoke(boundary); } template<typename traitsT> std::vector<typename System<traitsT>::particle_type> read_particles(const toml::Table& system) { typedef typename traitsT::real_type real_type; typedef typename traitsT::coordinate_type coordinate_type; std::vector<typename System<traitsT>::particle_type> ps; const auto& particles = system.at("particles").cast<toml::value_t::Array>(); ps.reserve(particles.size()); for(const auto& p : particles) { const auto& params = p.cast<toml::value_t::Table>(); const auto mass = toml::get<real_type>(params.at("mass")); const coordinate_type pos = toml::get<std::array<real_type, 3>>(params.at("position")); const coordinate_type vel = toml::get<std::array<real_type, 3>>(params.at("velocity")); const coordinate_type f(0.,0.,0.); ps.emplace_back(make_particle(mass, pos, vel, f)); } return ps; } template<typename traitsT> System<traitsT> read_system(const toml::Table& data, std::size_t N) { typedef typename traitsT::real_type real_type; const auto& system_params = data.at("systems").cast<toml::value_t::Array>(); if(system_params.size() <= N) throw std::out_of_range("no enough systems: " + std::to_string(N)); const auto& system = system_params.at(N).cast<toml::value_t::Table>(); System<traitsT> sys(read_particles<traitsT>(system), read_boundary<traitsT>( system.at("boundary").cast<toml::value_t::Table>())); if(system.count("temperature") == 1) { sys.temperature() = toml::get<real_type>(system.at("temperature")); } if(system.count("ionic_strength") == 1) { sys.ionic_strength() = toml::get<real_type>(system.at("ionic_strength")); } if(system.count("pressure") == 1) { sys.pressure() = toml::get<real_type>(system.at("pressure")); } return sys; } }//mjolnir #endif //MJOLNIR_READ_SIMULATOR <commit_msg>use detail::value_at in read_system<commit_after>#ifndef MJOLNIR_READ_SYSTEM #define MJOLNIR_READ_SYSTEM #include <mjolnir/core/System.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <extlib/toml/toml.hpp> namespace mjolnir { template<typename boundaryT> struct read_boundary_impl; template<typename realT, typename coordT> struct read_boundary_impl<UnlimitedBoundary<realT, coordT>> { static UnlimitedBoundary<realT, coordT> invoke(const toml::Table& boundary) { return UnlimitedBoundary<realT, coordT>{}; } }; template<typename realT, typename coordT> struct read_boundary_impl<CubicPeriodicBoundary<realT, coordT>> { static CubicPeriodicBoundary<realT, coordT> invoke(const toml::Table& boundary) { const coordT upper(toml::get<std::array<realT, 3>>( detail::value_at(boundary, "upper", "[boundary]"))); const coordT lower(toml::get<std::array<realT, 3>>( detail::value_at(boundary, "lower", "[boundary]"))); return CubicPeriodicBoundary<realT, coordT>(lower, upper); } }; template<typename traitsT> typename traitsT::boundary_type read_boundary(const toml::Table& boundary) { return read_boundary_impl<typename traitsT::boundary_type>::invoke(boundary); } template<typename traitsT> std::vector<typename System<traitsT>::particle_type> read_particles(const toml::Table& system) { typedef typename traitsT::real_type real_type; typedef typename traitsT::coordinate_type coordinate_type; std::vector<typename System<traitsT>::particle_type> ps; const auto& particles = detail::value_at(system, "particles", "[system]" ).cast<toml::value_t::Array>(); ps.reserve(particles.size()); for(const auto& p : particles) { const auto& params = p.cast<toml::value_t::Table>(); const auto mass = toml::get<real_type>( detail::value_at(params, "mass", "<anonymous> in particles")); const coordinate_type pos = toml::get<std::array<real_type, 3>>( detail::value_at(params, "position", "<anonymous> in particles")); const coordinate_type vel = toml::get<std::array<real_type, 3>>( detail::value_at(params, "velocity", "<anonymous> in particles")); const coordinate_type f(0.,0.,0.); ps.emplace_back(make_particle(mass, pos, vel, f)); } return ps; } template<typename traitsT> System<traitsT> read_system(const toml::Table& data, std::size_t N) { typedef typename traitsT::real_type real_type; const auto& system_params = detail::value_at(data, "systems", "<root>" ).cast<toml::value_t::Array>(); if(system_params.size() <= N) { throw std::out_of_range("no enough systems: " + std::to_string(N)); } const auto& system = system_params.at(N).cast<toml::value_t::Table>(); System<traitsT> sys(read_particles<traitsT>(system), read_boundary<traitsT>(detail::value_at(system, "boundary" ).cast<toml::value_t::Table>())); if(system.count("temperature") == 1) { sys.temperature() = toml::get<real_type>(system.at("temperature")); } if(system.count("ionic_strength") == 1) { sys.ionic_strength() = toml::get<real_type>(system.at("ionic_strength")); } if(system.count("pressure") == 1) { sys.pressure() = toml::get<real_type>(system.at("pressure")); } return sys; } }//mjolnir #endif //MJOLNIR_READ_SIMULATOR <|endoftext|>
<commit_before>// Time: O(n^2) // Space: O(n) class Solution { public: void wallsAndGates(vector<vector<int>>& rooms) { for (int i = 0; i < rooms.size(); ++i) { for (int j = 0; j < rooms[0].size(); ++j) { if (rooms[i][j] == 0) { queue<tuple<int, int, int>> q; q.emplace(make_tuple(i + 1, j, 1)); q.emplace(make_tuple(i - 1, j, 1)); q.emplace(make_tuple(i, j + 1, 1)); q.emplace(make_tuple(i, j - 1, 1)); while (!q.empty()) { int ii, jj, dist; tie(ii, jj, dist) = q.front(); q.pop(); if (ii < 0 || jj < 0 || ii >= rooms.size() || jj >= rooms[0].size() || rooms[ii][jj] <= dist) { continue; } rooms[ii][jj] = dist; q.emplace(make_tuple(ii + 1, jj, dist + 1)); q.emplace(make_tuple(ii - 1, jj, dist + 1)); q.emplace(make_tuple(ii, jj + 1, dist + 1)); q.emplace(make_tuple(ii, jj - 1, dist + 1)); } } } } } }; <commit_msg>Update walls-and-gates.cpp<commit_after>// Time: O(m * n) // Space: O(m + n) class Solution { public: void wallsAndGates(vector<vector<int>>& rooms) { for (int i = 0; i < rooms.size(); ++i) { for (int j = 0; j < rooms[0].size(); ++j) { if (rooms[i][j] == 0) { queue<tuple<int, int, int>> q; q.emplace(make_tuple(i + 1, j, 1)); q.emplace(make_tuple(i - 1, j, 1)); q.emplace(make_tuple(i, j + 1, 1)); q.emplace(make_tuple(i, j - 1, 1)); while (!q.empty()) { int ii, jj, dist; tie(ii, jj, dist) = q.front(); q.pop(); if (ii < 0 || jj < 0 || ii >= rooms.size() || jj >= rooms[0].size() || rooms[ii][jj] <= dist) { continue; } rooms[ii][jj] = dist; q.emplace(make_tuple(ii + 1, jj, dist + 1)); q.emplace(make_tuple(ii - 1, jj, dist + 1)); q.emplace(make_tuple(ii, jj + 1, dist + 1)); q.emplace(make_tuple(ii, jj - 1, dist + 1)); } } } } } }; <|endoftext|>
<commit_before>/* * Contacts model item, represents a contact in the contactlist tree * This file is based on TelepathyQt4Yell Models * * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk> * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-model-item.h" #include "accounts-model.h" #include "../service-availability-checker.h" #include <QImage> #include <KGlobal> #include <TelepathyQt4/AvatarData> #include <TelepathyQt4/ContactCapabilities> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/RequestableChannelClassSpec> K_GLOBAL_STATIC_WITH_ARGS(ServiceAvailabilityChecker, s_krfbAvailableChecker, (QLatin1String("org.freedesktop.Telepathy.Client.krfb_rfb_handler"))); struct ContactModelItem::Private { Private(const Tp::ContactPtr &contact) : mContact(contact) { } Tp::ContactPtr mContact; }; ContactModelItem::ContactModelItem(const Tp::ContactPtr &contact) : mPriv(new Private(contact)) { (void) s_krfbAvailableChecker.operator->(); //start the d-bus query the first time this is called connect(contact.data(), SIGNAL(aliasChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarTokenChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(onChanged())); connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)), SLOT(onChanged())); connect(contact->manager()->connection()->selfContact().data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(locationUpdated(Tp::LocationInfo)), SLOT(onChanged())); connect(contact.data(), SIGNAL(infoFieldsChanged(Tp::Contact::InfoFields)), SLOT(onChanged())); connect(contact.data(), SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)), SLOT(onChanged())); connect(contact.data(), SIGNAL(publishStateChanged(Tp::Contact::PresenceState,QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(blockStatusChanged(bool)), SLOT(onChanged())); } ContactModelItem::~ContactModelItem() { delete mPriv; } QVariant ContactModelItem::data(int role) const { switch (role) { case AccountsModel::ItemRole: return QVariant::fromValue((ContactModelItem*)this); case AccountsModel::IdRole: return mPriv->mContact->id(); case Qt::DisplayRole: case AccountsModel::AliasRole: return mPriv->mContact->alias(); case AccountsModel::PresenceStatusRole: return mPriv->mContact->presence().status(); case AccountsModel::PresenceTypeRole: return mPriv->mContact->presence().type(); case AccountsModel::PresenceMessageRole: return mPriv->mContact->presence().statusMessage(); case AccountsModel::SubscriptionStateRole: return mPriv->mContact->subscriptionState(); case AccountsModel::PublishStateRole: return mPriv->mContact->publishState(); case AccountsModel::BlockedRole: return mPriv->mContact->isBlocked(); case AccountsModel::GroupsRole: return mPriv->mContact->groups(); case AccountsModel::AvatarRole: return mPriv->mContact->avatarData().fileName; case Qt::DecorationRole: return QImage(mPriv->mContact->avatarData().fileName); case AccountsModel::TextChatCapabilityRole: return mPriv->mContact->capabilities().textChats(); case AccountsModel::MediaCallCapabilityRole: return mPriv->mContact->capabilities().streamedMediaCalls(); case AccountsModel::AudioCallCapabilityRole: return audioCallCapability(); case AccountsModel::VideoCallCapabilityRole: return videoCallCapability(); case AccountsModel::UpgradeCallCapabilityRole: return mPriv->mContact->capabilities().upgradingStreamedMediaCalls(); case AccountsModel::FileTransferCapabilityRole: return fileTransferCapability(); case AccountsModel::DesktopSharingCapabilityRole: return desktopSharingCapability(); default: break; } return QVariant(); } bool ContactModelItem::setData(int role, const QVariant &value) { switch (role) { case AccountsModel::PublishStateRole: { Tp::Contact::PresenceState state; state = (Tp::Contact::PresenceState) value.toInt(); switch (state) { case Tp::Contact::PresenceStateYes: // authorize the contact and request its presence publication mPriv->mContact->authorizePresencePublication(); mPriv->mContact->requestPresenceSubscription(); return true; case Tp::Contact::PresenceStateNo: { // reject the presence publication and remove the contact mPriv->mContact->removePresencePublication(); QList<Tp::ContactPtr> contacts; contacts << mPriv->mContact; mPriv->mContact->manager()->removeContacts(contacts); return true; } default: return false; } } default: return false; } } void ContactModelItem::onChanged() { emit changed(this); } Tp::ContactPtr ContactModelItem::contact() const { return mPriv->mContact; } //return true if both you and the contact can handle audio calls. bool ContactModelItem::audioCallCapability() const { bool contactCanStreamAudio = mPriv->mContact->capabilities().streamedMediaAudioCalls(); bool selfCanStreamAudio = mPriv->mContact->manager()->connection()->selfContact()->capabilities().streamedMediaAudioCalls(); return contactCanStreamAudio && selfCanStreamAudio; } bool ContactModelItem::videoCallCapability() const { bool contactCanStreamVideo = mPriv->mContact->capabilities().streamedMediaVideoCalls(); bool selfCanStreamVideo = mPriv->mContact->manager()->connection()->selfContact()->capabilities().streamedMediaVideoCalls(); return contactCanStreamVideo && selfCanStreamVideo; } bool ContactModelItem::fileTransferCapability() const { bool contactCanHandleFiles = mPriv->mContact->capabilities().fileTransfers(); bool selfCanHandleFiles = mPriv->mContact->manager()->connection()->selfContact()->capabilities().fileTransfers(); return contactCanHandleFiles && selfCanHandleFiles; } bool ContactModelItem::desktopSharingCapability() const { bool contactCanHandleRfb = mPriv->mContact->capabilities().streamTubes("rfb"); bool selfCanHandleRfb = s_krfbAvailableChecker->isAvailable(); return contactCanHandleRfb && selfCanHandleRfb; } #include "contact-model-item.moc" <commit_msg>Improve comment.<commit_after>/* * Contacts model item, represents a contact in the contactlist tree * This file is based on TelepathyQt4Yell Models * * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk> * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-model-item.h" #include "accounts-model.h" #include "../service-availability-checker.h" #include <QImage> #include <KGlobal> #include <TelepathyQt4/AvatarData> #include <TelepathyQt4/ContactCapabilities> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/RequestableChannelClassSpec> K_GLOBAL_STATIC_WITH_ARGS(ServiceAvailabilityChecker, s_krfbAvailableChecker, (QLatin1String("org.freedesktop.Telepathy.Client.krfb_rfb_handler"))); struct ContactModelItem::Private { Private(const Tp::ContactPtr &contact) : mContact(contact) { } Tp::ContactPtr mContact; }; ContactModelItem::ContactModelItem(const Tp::ContactPtr &contact) : mPriv(new Private(contact)) { //This effectively constructs the s_krfbAvailableChecker object the first //time that this code is executed. This is to start the d-bus query early, so //that data are available when we need them later in desktopSharingCapability() (void) s_krfbAvailableChecker.operator->(); connect(contact.data(), SIGNAL(aliasChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarTokenChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(onChanged())); connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)), SLOT(onChanged())); connect(contact->manager()->connection()->selfContact().data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(locationUpdated(Tp::LocationInfo)), SLOT(onChanged())); connect(contact.data(), SIGNAL(infoFieldsChanged(Tp::Contact::InfoFields)), SLOT(onChanged())); connect(contact.data(), SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)), SLOT(onChanged())); connect(contact.data(), SIGNAL(publishStateChanged(Tp::Contact::PresenceState,QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(blockStatusChanged(bool)), SLOT(onChanged())); } ContactModelItem::~ContactModelItem() { delete mPriv; } QVariant ContactModelItem::data(int role) const { switch (role) { case AccountsModel::ItemRole: return QVariant::fromValue((ContactModelItem*)this); case AccountsModel::IdRole: return mPriv->mContact->id(); case Qt::DisplayRole: case AccountsModel::AliasRole: return mPriv->mContact->alias(); case AccountsModel::PresenceStatusRole: return mPriv->mContact->presence().status(); case AccountsModel::PresenceTypeRole: return mPriv->mContact->presence().type(); case AccountsModel::PresenceMessageRole: return mPriv->mContact->presence().statusMessage(); case AccountsModel::SubscriptionStateRole: return mPriv->mContact->subscriptionState(); case AccountsModel::PublishStateRole: return mPriv->mContact->publishState(); case AccountsModel::BlockedRole: return mPriv->mContact->isBlocked(); case AccountsModel::GroupsRole: return mPriv->mContact->groups(); case AccountsModel::AvatarRole: return mPriv->mContact->avatarData().fileName; case Qt::DecorationRole: return QImage(mPriv->mContact->avatarData().fileName); case AccountsModel::TextChatCapabilityRole: return mPriv->mContact->capabilities().textChats(); case AccountsModel::MediaCallCapabilityRole: return mPriv->mContact->capabilities().streamedMediaCalls(); case AccountsModel::AudioCallCapabilityRole: return audioCallCapability(); case AccountsModel::VideoCallCapabilityRole: return videoCallCapability(); case AccountsModel::UpgradeCallCapabilityRole: return mPriv->mContact->capabilities().upgradingStreamedMediaCalls(); case AccountsModel::FileTransferCapabilityRole: return fileTransferCapability(); case AccountsModel::DesktopSharingCapabilityRole: return desktopSharingCapability(); default: break; } return QVariant(); } bool ContactModelItem::setData(int role, const QVariant &value) { switch (role) { case AccountsModel::PublishStateRole: { Tp::Contact::PresenceState state; state = (Tp::Contact::PresenceState) value.toInt(); switch (state) { case Tp::Contact::PresenceStateYes: // authorize the contact and request its presence publication mPriv->mContact->authorizePresencePublication(); mPriv->mContact->requestPresenceSubscription(); return true; case Tp::Contact::PresenceStateNo: { // reject the presence publication and remove the contact mPriv->mContact->removePresencePublication(); QList<Tp::ContactPtr> contacts; contacts << mPriv->mContact; mPriv->mContact->manager()->removeContacts(contacts); return true; } default: return false; } } default: return false; } } void ContactModelItem::onChanged() { emit changed(this); } Tp::ContactPtr ContactModelItem::contact() const { return mPriv->mContact; } //return true if both you and the contact can handle audio calls. bool ContactModelItem::audioCallCapability() const { bool contactCanStreamAudio = mPriv->mContact->capabilities().streamedMediaAudioCalls(); bool selfCanStreamAudio = mPriv->mContact->manager()->connection()->selfContact()->capabilities().streamedMediaAudioCalls(); return contactCanStreamAudio && selfCanStreamAudio; } bool ContactModelItem::videoCallCapability() const { bool contactCanStreamVideo = mPriv->mContact->capabilities().streamedMediaVideoCalls(); bool selfCanStreamVideo = mPriv->mContact->manager()->connection()->selfContact()->capabilities().streamedMediaVideoCalls(); return contactCanStreamVideo && selfCanStreamVideo; } bool ContactModelItem::fileTransferCapability() const { bool contactCanHandleFiles = mPriv->mContact->capabilities().fileTransfers(); bool selfCanHandleFiles = mPriv->mContact->manager()->connection()->selfContact()->capabilities().fileTransfers(); return contactCanHandleFiles && selfCanHandleFiles; } bool ContactModelItem::desktopSharingCapability() const { bool contactCanHandleRfb = mPriv->mContact->capabilities().streamTubes("rfb"); bool selfCanHandleRfb = s_krfbAvailableChecker->isAvailable(); return contactCanHandleRfb && selfCanHandleRfb; } #include "contact-model-item.moc" <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Modules.h" #include "User.h" #include "znc.h" #include <queue> class CSocketSorter { public: CSocketSorter(Csock* p) { m_pSock = p; } bool operator<(const CSocketSorter& other) const { // The 'biggest' item is displayed first. // return false: this is first // return true: other is first // Listeners go to the top if (m_pSock->GetType() != other.m_pSock->GetType()) { if (m_pSock->GetType() == Csock::LISTENER) return false; if (other.m_pSock->GetType() == Csock::LISTENER) return true; } const CString& sMyName = m_pSock->GetSockName(); const CString& sMyName2 = sMyName.Token(1, true, "::"); bool bMyEmpty = sMyName2.empty(); const CString& sHisName = other.GetSock()->GetSockName(); const CString& sHisName2 = sHisName.Token(1, true, "::"); bool bHisEmpty = sHisName2.empty(); // Then sort by first token after "::" if (bMyEmpty && !bHisEmpty) return false; if (bHisEmpty && !bMyEmpty) return true; if (!bMyEmpty && !bHisEmpty) { int c = sMyName2.StrCmp(sHisName2); if (c < 0) return false; if (c > 0) return true; } // and finally sort by the whole socket name return sMyName.StrCmp(sHisName) > 0; } Csock* GetSock() const { return m_pSock; } private: Csock* m_pSock; }; class CListSockets : public CModule { public: MODCONSTRUCTOR(CListSockets) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage) { #ifndef MOD_LISTSOCKETS_ALLOW_EVERYONE if (!m_pUser->IsAdmin()) { sMessage = "You must be admin to use this module"; return false; } #endif return true; } virtual bool WebRequiresAdmin() { return true; } virtual CString GetWebMenuTitle() { return "List sockets"; } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName.empty() || sPageName == "index") { CSockManager& m = CZNC::Get().GetManager(); if (!m.size()) { return false; } std::priority_queue<CSocketSorter> socks; for (unsigned int a = 0; a < m.size(); a++) { socks.push(m[a]); } while (!socks.empty()) { Csock* pSocket = socks.top().GetSock(); socks.pop(); CTemplate& Row = Tmpl.AddRow("SocketsLoop"); Row["Name"] = pSocket->GetSockName(); Row["Created"] = GetCreatedTime(pSocket); Row["State"] = GetSocketState(pSocket); Row["SSL"] = pSocket->GetSSL() ? "Yes" : "No"; Row["Local"] = GetLocalHost(pSocket, true); Row["Remote"] = GetRemoteHost(pSocket, true); } return true; } return false; } virtual void OnModCommand(const CString& sLine) { CString sCommand = sLine.Token(0); CString sArg = sLine.Token(1, true); if (sCommand.Equals("LIST")) { bool bShowHosts = true; if (sArg.Equals("-n")) { bShowHosts = false; } ShowSocks(bShowHosts); } else { PutModule("Use 'list' to view a list of active sockets"); PutModule("Use 'list -n' if you want IP addresses to be displayed"); } } CString GetSocketState(Csock* pSocket) { switch (pSocket->GetType()) { case Csock::LISTENER: return "Listener"; case Csock::INBOUND: return "Inbound"; case Csock::OUTBOUND: if (pSocket->IsConnected()) return "Outbound"; else return "Connecting"; } return "UNKNOWN"; } CString GetCreatedTime(Csock* pSocket) { unsigned long long iStartTime = pSocket->GetStartTime(); time_t iTime = iStartTime / 1000; return FormatTime("%Y-%m-%d %H:%M:%S", iTime); } CString GetLocalHost(Csock* pSocket, bool bShowHosts) { CString sBindHost; if (bShowHosts) { sBindHost = pSocket->GetBindHost(); } if (sBindHost.empty()) { sBindHost = pSocket->GetLocalIP(); } return sBindHost + " " + CString(pSocket->GetLocalPort()); } CString GetRemoteHost(Csock* pSocket, bool bShowHosts) { CString sHost; u_short uPort; if (!bShowHosts) { sHost = pSocket->GetRemoteIP(); } // While connecting, there might be no ip available if (sHost.empty()) { sHost = pSocket->GetHostName(); } // While connecting, GetRemotePort() would return 0 if (pSocket->GetType() == Csock::OUTBOUND) { uPort = pSocket->GetPort(); } else { uPort = pSocket->GetRemotePort(); } if (uPort != 0) { return sHost + " " + CString(uPort); } return sHost; } void ShowSocks(bool bShowHosts) { CSockManager& m = CZNC::Get().GetManager(); if (!m.size()) { PutStatus("You have no open sockets."); return; } std::priority_queue<CSocketSorter> socks; for (unsigned int a = 0; a < m.size(); a++) { socks.push(m[a]); } CTable Table; Table.AddColumn("Name"); Table.AddColumn("Created"); Table.AddColumn("State"); #ifdef HAVE_LIBSSL Table.AddColumn("SSL"); #endif Table.AddColumn("Local"); Table.AddColumn("Remote"); while (!socks.empty()) { Csock* pSocket = socks.top().GetSock(); socks.pop(); Table.AddRow(); Table.SetCell("Name", pSocket->GetSockName()); Table.SetCell("Created", GetCreatedTime(pSocket)); Table.SetCell("State", GetSocketState(pSocket)); #ifdef HAVE_LIBSSL Table.SetCell("SSL", pSocket->GetSSL() ? "Yes" : "No"); #endif Table.SetCell("Local", GetLocalHost(pSocket, bShowHosts)); Table.SetCell("Remote", GetRemoteHost(pSocket, bShowHosts)); } PutModule(Table); return; } virtual ~CListSockets() { } CString FormatTime(const CString& sFormat, time_t tm = 0) const { char szTimestamp[1024]; if (tm == 0) { tm = time(NULL); } // offset is in hours tm += (time_t)(m_pUser->GetTimezoneOffset() * 60 * 60); strftime(szTimestamp, sizeof(szTimestamp) / sizeof(char), sFormat.c_str(), localtime(&tm)); return szTimestamp; } }; MODULEDEFS(CListSockets, "List active sockets") <commit_msg>listsockets: Ignore dereferenced sockets<commit_after>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Modules.h" #include "User.h" #include "znc.h" #include <queue> class CSocketSorter { public: CSocketSorter(Csock* p) { m_pSock = p; } bool operator<(const CSocketSorter& other) const { // The 'biggest' item is displayed first. // return false: this is first // return true: other is first // Listeners go to the top if (m_pSock->GetType() != other.m_pSock->GetType()) { if (m_pSock->GetType() == Csock::LISTENER) return false; if (other.m_pSock->GetType() == Csock::LISTENER) return true; } const CString& sMyName = m_pSock->GetSockName(); const CString& sMyName2 = sMyName.Token(1, true, "::"); bool bMyEmpty = sMyName2.empty(); const CString& sHisName = other.GetSock()->GetSockName(); const CString& sHisName2 = sHisName.Token(1, true, "::"); bool bHisEmpty = sHisName2.empty(); // Then sort by first token after "::" if (bMyEmpty && !bHisEmpty) return false; if (bHisEmpty && !bMyEmpty) return true; if (!bMyEmpty && !bHisEmpty) { int c = sMyName2.StrCmp(sHisName2); if (c < 0) return false; if (c > 0) return true; } // and finally sort by the whole socket name return sMyName.StrCmp(sHisName) > 0; } Csock* GetSock() const { return m_pSock; } private: Csock* m_pSock; }; class CListSockets : public CModule { public: MODCONSTRUCTOR(CListSockets) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage) { #ifndef MOD_LISTSOCKETS_ALLOW_EVERYONE if (!m_pUser->IsAdmin()) { sMessage = "You must be admin to use this module"; return false; } #endif return true; } std::priority_queue<CSocketSorter> GetSockets() { CSockManager& m = CZNC::Get().GetManager(); std::priority_queue<CSocketSorter> ret; for (unsigned int a = 0; a < m.size(); a++) { Csock* pSock = m[a]; // These sockets went through SwapSockByAddr. That means // another socket took over the connection from this // socket. So ignore this to avoid listing the // connection twice. if (pSock->GetCloseType() == Csock::CLT_DEREFERENCE) continue; ret.push(pSock); } return ret; } virtual bool WebRequiresAdmin() { return true; } virtual CString GetWebMenuTitle() { return "List sockets"; } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName.empty() || sPageName == "index") { if (CZNC::Get().GetManager().empty()) { return false; } std::priority_queue<CSocketSorter> socks = GetSockets(); while (!socks.empty()) { Csock* pSocket = socks.top().GetSock(); socks.pop(); CTemplate& Row = Tmpl.AddRow("SocketsLoop"); Row["Name"] = pSocket->GetSockName(); Row["Created"] = GetCreatedTime(pSocket); Row["State"] = GetSocketState(pSocket); Row["SSL"] = pSocket->GetSSL() ? "Yes" : "No"; Row["Local"] = GetLocalHost(pSocket, true); Row["Remote"] = GetRemoteHost(pSocket, true); } return true; } return false; } virtual void OnModCommand(const CString& sLine) { CString sCommand = sLine.Token(0); CString sArg = sLine.Token(1, true); if (sCommand.Equals("LIST")) { bool bShowHosts = true; if (sArg.Equals("-n")) { bShowHosts = false; } ShowSocks(bShowHosts); } else { PutModule("Use 'list' to view a list of active sockets"); PutModule("Use 'list -n' if you want IP addresses to be displayed"); } } CString GetSocketState(Csock* pSocket) { switch (pSocket->GetType()) { case Csock::LISTENER: return "Listener"; case Csock::INBOUND: return "Inbound"; case Csock::OUTBOUND: if (pSocket->IsConnected()) return "Outbound"; else return "Connecting"; } return "UNKNOWN"; } CString GetCreatedTime(Csock* pSocket) { unsigned long long iStartTime = pSocket->GetStartTime(); time_t iTime = iStartTime / 1000; return FormatTime("%Y-%m-%d %H:%M:%S", iTime); } CString GetLocalHost(Csock* pSocket, bool bShowHosts) { CString sBindHost; if (bShowHosts) { sBindHost = pSocket->GetBindHost(); } if (sBindHost.empty()) { sBindHost = pSocket->GetLocalIP(); } return sBindHost + " " + CString(pSocket->GetLocalPort()); } CString GetRemoteHost(Csock* pSocket, bool bShowHosts) { CString sHost; u_short uPort; if (!bShowHosts) { sHost = pSocket->GetRemoteIP(); } // While connecting, there might be no ip available if (sHost.empty()) { sHost = pSocket->GetHostName(); } // While connecting, GetRemotePort() would return 0 if (pSocket->GetType() == Csock::OUTBOUND) { uPort = pSocket->GetPort(); } else { uPort = pSocket->GetRemotePort(); } if (uPort != 0) { return sHost + " " + CString(uPort); } return sHost; } void ShowSocks(bool bShowHosts) { if (CZNC::Get().GetManager().empty()) { PutStatus("You have no open sockets."); return; } std::priority_queue<CSocketSorter> socks = GetSockets(); CTable Table; Table.AddColumn("Name"); Table.AddColumn("Created"); Table.AddColumn("State"); #ifdef HAVE_LIBSSL Table.AddColumn("SSL"); #endif Table.AddColumn("Local"); Table.AddColumn("Remote"); while (!socks.empty()) { Csock* pSocket = socks.top().GetSock(); socks.pop(); Table.AddRow(); Table.SetCell("Name", pSocket->GetSockName()); Table.SetCell("Created", GetCreatedTime(pSocket)); Table.SetCell("State", GetSocketState(pSocket)); #ifdef HAVE_LIBSSL Table.SetCell("SSL", pSocket->GetSSL() ? "Yes" : "No"); #endif Table.SetCell("Local", GetLocalHost(pSocket, bShowHosts)); Table.SetCell("Remote", GetRemoteHost(pSocket, bShowHosts)); } PutModule(Table); return; } virtual ~CListSockets() { } CString FormatTime(const CString& sFormat, time_t tm = 0) const { char szTimestamp[1024]; if (tm == 0) { tm = time(NULL); } // offset is in hours tm += (time_t)(m_pUser->GetTimezoneOffset() * 60 * 60); strftime(szTimestamp, sizeof(szTimestamp) / sizeof(char), sFormat.c_str(), localtime(&tm)); return szTimestamp; } }; MODULEDEFS(CListSockets, "List active sockets") <|endoftext|>
<commit_before>#include "nbind/nbind.h" #include "nbind/api.h" #include <X11/Xlib.h> #include "xdisplay.h" #include "screen.h" ScreenInfo::Screen ScreenInfo::Screen::main() { Display *display = XGetMainDisplay(); const int screen = DefaultScreen(display); return ScreenInfo::Screen( (size_t)DisplayWidth(display, screen), (size_t)DisplayHeight(display, screen), XDefaultDepth(display, screen) ); }; std::vector<ScreenInfo::Screen> ScreenInfo::Screen::all() { std::vector<ScreenInfo::Screen> result; Display *display = XGetMainDisplay(); const int screenCount = XScreenCount(display); printf("screenCount %d\n", screenCount); for (int index = 0; index < screenCount; index++) { size_t width = (size_t) DisplayWidth(display, index); printf("width %d\n", (int) width); size_t height = (size_t) DisplayHeight(display, index); printf("height %d\n", (int) height); int depth = XDefaultDepth(display, index); printf("depth %d\n", depth); ScreenInfo::Screen screen = ScreenInfo::Screen( width, height, depth ); result.push_back(screen); } return result; }; <commit_msg>Removed remaining log printf<commit_after>#include "nbind/nbind.h" #include "nbind/api.h" #include <X11/Xlib.h> #include "xdisplay.h" #include "screen.h" ScreenInfo::Screen ScreenInfo::Screen::main() { Display *display = XGetMainDisplay(); const int screen = DefaultScreen(display); return ScreenInfo::Screen( (size_t)DisplayWidth(display, screen), (size_t)DisplayHeight(display, screen), XDefaultDepth(display, screen) ); }; std::vector<ScreenInfo::Screen> ScreenInfo::Screen::all() { std::vector<ScreenInfo::Screen> result; Display *display = XGetMainDisplay(); const int screenCount = XScreenCount(display); // printf("screenCount %d\n", screenCount); for (int index = 0; index < screenCount; index++) { size_t width = (size_t) DisplayWidth(display, index); // printf("width %d\n", (int) width); size_t height = (size_t) DisplayHeight(display, index); // printf("height %d\n", (int) height); int depth = XDefaultDepth(display, index); // printf("depth %d\n", depth); ScreenInfo::Screen screen = ScreenInfo::Screen( width, height, depth ); result.push_back(screen); } return result; }; <|endoftext|>
<commit_before>/// /// @file pi_lmo1.cpp /// @brief Simple demonstration implementation of the /// Lagarias-Miller-Odlyzko prime counting algorithm. /// Usually in the Lagarias-Miller-Odlyzko algorithm phi(x, a) /// is calculated using a prime sieve but this simple /// implementation calculates phi(x, a) using the recursive /// formula with caching. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <pmath.hpp> #include <PhiCache.hpp> #include <stdint.h> #include <algorithm> #include <vector> using namespace std; namespace primecount { /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3)) operations, O(x^(1/3)) space. /// int64_t pi_lmo1(int64_t x) { if (x < 2) return 0; int64_t y = iroot<3>(x); int64_t pi_y = pi_meissel(y, 1); int64_t c = min(pi_y, PhiTiny::max_a()); int64_t S1 = 0; int64_t S2 = 0; vector<int32_t> lpf = generate_least_prime_factors(y); vector<int32_t> mu = generate_moebius(y); vector<int32_t> primes = generate_primes(y); // Calculate the contribution of the ordinary leaves for (int64_t n = 1; n <= y; n++) if (lpf[n] > primes[c]) S1 += mu[n] * phi(x / n, c); PhiCache cache(primes); // Calculate the contribution of the special leaves for (int64_t b = c + 1; b < pi_y; b++) for (int64_t m = (y / primes[b]) + 1; m <= y; m++) if (lpf[m] > primes[b]) S2 -= mu[m] * phi(x / (primes[b] * m), b - 1, &cache); int64_t phi = S1 + S2; int64_t sum = phi + pi_y - 1 - P2(x, y, 1); return sum; } } // namespace primecount <commit_msg>Add generate.hpp header<commit_after>/// /// @file pi_lmo1.cpp /// @brief Simple demonstration implementation of the /// Lagarias-Miller-Odlyzko prime counting algorithm. /// Usually in the Lagarias-Miller-Odlyzko algorithm phi(x, a) /// is calculated using a prime sieve but this simple /// implementation calculates phi(x, a) using the recursive /// formula with caching. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <generate.hpp> #include <pmath.hpp> #include <PhiCache.hpp> #include <stdint.h> #include <algorithm> #include <vector> using namespace std; namespace primecount { /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3)) operations, O(x^(1/3)) space. /// int64_t pi_lmo1(int64_t x) { if (x < 2) return 0; int64_t y = iroot<3>(x); int64_t pi_y = pi_meissel(y, 1); int64_t c = min(pi_y, PhiTiny::max_a()); int64_t S1 = 0; int64_t S2 = 0; vector<int32_t> lpf = generate_least_prime_factors(y); vector<int32_t> mu = generate_moebius(y); vector<int32_t> primes = generate_primes(y); // Calculate the contribution of the ordinary leaves for (int64_t n = 1; n <= y; n++) if (lpf[n] > primes[c]) S1 += mu[n] * phi(x / n, c); PhiCache cache(primes); // Calculate the contribution of the special leaves for (int64_t b = c + 1; b < pi_y; b++) for (int64_t m = (y / primes[b]) + 1; m <= y; m++) if (lpf[m] > primes[b]) S2 -= mu[m] * phi(x / (primes[b] * m), b - 1, &cache); int64_t phi = S1 + S2; int64_t sum = phi + pi_y - 1 - P2(x, y, 1); return sum; } } // namespace primecount <|endoftext|>
<commit_before>#include "loadOperator.hh" // std #include <string> // scidb #include "query/TypeSystem.h" #include "system/SystemCatalog.h" #include "array/Array.h" #include "array/DBArray.h" // pkg #include "H5Array.hh" #include "scidbConvert.hh" void loadHdf(std::string const& filePath, std::string const& hdfPath, std::string const& arrayName) { // Do something good. H5Array ha(filePath, hdfPath); std::cout << "Retrieving descriptor for " << filePath << " --> " << hdfPath << std::endl; boost::shared_ptr<scidb::ArrayDesc> dptr(ha.getArrayDesc()); dptr->setName(arrayName); std::cout << "Set array name. Getting catalog instance." << std::endl; scidb::SystemCatalog& catalog = *scidb::SystemCatalog::getInstance(); if(catalog.containsArray(arrayName)) { // delete if existing. catalog.deleteArray(arrayName); } // Get array id; hardcode partitioning scheme for now. scidb::ArrayID aid = catalog.addArray(*dptr, scidb::psLocalNode); scidb::DBArray array(aid); std::cout << "Added array to catalog and contructed dbarray." << std::endl; // Only handle single-attribute right now. int chunkMode = 0; // chunk mode (dense/sparse) chunkMode |= scidb::ChunkIterator::NO_EMPTY_CHECK; boost::shared_ptr<scidb::ArrayIterator> ai = array.getIterator(0); boost::shared_ptr<scidb::ChunkIterator> ci; int numChunks = ha.getSlabCount(); // FIXME int rank = ha.getRank(); // FIXME scidb::Coordinates chunkPos(rank); scidb::Coordinates coord(rank); //ArrayDescPtr ap = newArrayDesc(ha.getScidbAttrs(), ha.getScidbDims()); for(H5Array::SlabIter i = ha.begin(); i != ha.end(); ++i) { // FIXME: need to fix chunkPos and coord: what do they need to be? chunkPos = coord; ci = ai->newChunk(*i).getIterator(chunkMode); } // Fill results //res.setString("SomeArray"); // Fill in result: name of new array } <commit_msg>Implement possibly-close-correct chunk copy harness.<commit_after>#include "loadOperator.hh" // std #include <string> // scidb #include "query/TypeSystem.h" #include "system/SystemCatalog.h" #include "array/Array.h" #include "array/DBArray.h" // pkg #include "H5Array.hh" #include "scidbConvert.hh" void loadHdf(std::string const& filePath, std::string const& hdfPath, std::string const& arrayName) { // Do something good. H5Array ha(filePath, hdfPath); std::cout << "Retrieving descriptor for " << filePath << " --> " << hdfPath << std::endl; boost::shared_ptr<scidb::ArrayDesc> dptr(ha.getArrayDesc()); dptr->setName(arrayName); std::cout << "Set array name. Getting catalog instance." << std::endl; scidb::SystemCatalog& catalog = *scidb::SystemCatalog::getInstance(); if(catalog.containsArray(arrayName)) { // delete if existing. catalog.deleteArray(arrayName); } // Get array id; hardcode partitioning scheme for now. scidb::ArrayID aid = catalog.addArray(*dptr, scidb::psLocalNode); scidb::DBArray array(aid); std::cout << "Added array to catalog and contructed dbarray." << std::endl; // Only handle single-attribute right now. int chunkMode = 0; // chunk mode (dense/sparse) chunkMode |= scidb::ChunkIterator::NO_EMPTY_CHECK; boost::shared_ptr<scidb::ArrayIterator> ai = array.getIterator(0); //ArrayDescPtr ap = newArrayDesc(ha.getScidbAttrs(), ha.getScidbDims()); std::cout << "Iterating... " << std::endl; std::cout << "begin: " << ha.begin() << std::endl; std::cout << "end: " << ha.end() << std::endl; for(H5Array::SlabIter i = ha.begin(); i != ha.end(); ++i) { // FIXME: need to fix chunkPos and coord: what do they need to be? std::cout << i << std::endl; //ci = ai->newChunk(*i).getIterator(chunkMode); scidb::Chunk& outChunk = ai->newChunk(*i); outChunk.allocate(i.byteSize()); outChunk.setSparse(false); // Never sparse memcpy(outChunk.getData(), i.data(), i.byteSize()); outChunk.setCount(0); outChunk.write(); } // Fill results //res.setString("SomeArray"); // Fill in result: name of new array } <|endoftext|>
<commit_before>//$Id: ReadWriteMutex_Test.cpp 3456 2013-06-14 02:11:13Z jiaying $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright © 2010 SRCH2 Inc. All rights reserved */ #include "util/ReadWriteMutex.h" #include "util/Assert.h" #include <unistd.h> #include <time.h> #include <iostream> #include <cstdlib> #include <stdio.h> #include "util/mypthread.h" using namespace std; using namespace srch2::instantsearch; ReadWriteMutex rw_mutex(3); void *writer(void *seconds) { time_t t1, t2; time(&t1); ExceptionSafeRWLockForWrite autolock(rw_mutex); time(&t2); *((int *) seconds) = (int)difftime(t2, t1); printf("Write Thread\n"); sleep(2); pthread_exit(0); } void *reader(void *seconds) { time_t t1, t2; time(&t1); ExceptionSafeRWLockForRead autolock(rw_mutex); time(&t2); *((int *) seconds) = (int)difftime(t2, t1); printf("Read Thread\n"); sleep(2); pthread_exit(0); } void testReadLock() { pthread_t *threadReaders; int n, i, seconds; n = 4; seconds = 0; threadReaders = (pthread_t *) malloc(n * sizeof(*threadReaders)); for (i = 0; i < n; i++) { pthread_create(&threadReaders[i], NULL, reader, (void *)&seconds); } for (i = 0; i < n; i++) { pthread_join(threadReaders[i], NULL); } // seconds is the time that the last reader thread spent to get the read lock // since the max number of readers is set to 3, the 4th reader thread needs to wait for 1s ASSERT(seconds == 2); free(threadReaders); } void testWriteLock() { pthread_t *threadReaders; pthread_t *threadWriters; int n, i; int reader_seconds = 0; int writer_seconds[2]; n = 2; threadReaders = (pthread_t *) malloc((n+1) * sizeof(*threadReaders)); threadWriters = (pthread_t *) malloc(n * sizeof(*threadWriters)); // start 2 reader threads for (i = 0; i < n; i++) { pthread_create(&threadReaders[i], NULL, reader, (void *)&reader_seconds); } sleep(1); // start 2 writer threads for (i = 0; i < n; i++) { writer_seconds[i] = 0; pthread_create(&threadWriters[i], NULL, writer, (void *)&writer_seconds[i]); } sleep(4); // start the 3rd reader thread pthread_create(&threadReaders[n], NULL, reader, (void *)&reader_seconds); for (i = 0; i < n; i++) { pthread_join(threadReaders[i], NULL); } for (i = 0; i < n; i++) { pthread_join(threadWriters[i], NULL); } pthread_join(threadReaders[n], NULL); // the first writer thread needs to wait for the first two reader threads to unlock // the second writer thread needs to wait for the first writer thread to unlock ASSERT ( (writer_seconds[0] == 1 && writer_seconds[1] == 3) || (writer_seconds[0] == 3 && writer_seconds[1] == 1) ); // the third reader thread needs to wait for all the two writer threads to unlock ASSERT(reader_seconds == 1); free(threadReaders); free(threadWriters); } int main(int argc, char *argv[]) { testReadLock(); testWriteLock(); cout<<"\nReadWriteMutex unit tests passed.\n"; return 0; } <commit_msg>fixing readwriteMutex test<commit_after>//$Id: ReadWriteMutex_Test.cpp 3456 2013-06-14 02:11:13Z jiaying $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright © 2010 SRCH2 Inc. All rights reserved */ #include "util/ReadWriteMutex.h" #include "util/Assert.h" #include <unistd.h> #include <time.h> #include <iostream> #include <cstdlib> #include <stdio.h> #include "util/mypthread.h" using namespace std; using namespace srch2::instantsearch; ReadWriteMutex rw_mutex(3); void *writer(void *seconds) { { time_t t1, t2; time(&t1); ExceptionSafeRWLockForWrite autolock(rw_mutex); time(&t2); *((int *) seconds) = (int)difftime(t2, t1); printf("Write Thread\n"); sleep(2); } pthread_exit(0); } void *reader(void *seconds) { { time_t t1, t2; time(&t1); ExceptionSafeRWLockForRead autolock(rw_mutex); time(&t2); *((int *) seconds) = (int)difftime(t2, t1); printf("Read Thread\n"); sleep(2); } pthread_exit(0); } void testReadLock() { pthread_t *threadReaders; int n, i, seconds; n = 4; seconds = 0; threadReaders = (pthread_t *) malloc(n * sizeof(*threadReaders)); for (i = 0; i < n; i++) { pthread_create(&threadReaders[i], NULL, reader, (void *)&seconds); } for (i = 0; i < n; i++) { pthread_join(threadReaders[i], NULL); } // seconds is the time that the last reader thread spent to get the read lock // since the max number of readers is set to 3, the 4th reader thread needs to wait for 1s ASSERT(seconds == 2); free(threadReaders); } void testWriteLock() { pthread_t *threadReaders; pthread_t *threadWriters; int n, i; int reader_seconds = 0; int writer_seconds[2]; n = 2; threadReaders = (pthread_t *) malloc((n+1) * sizeof(*threadReaders)); threadWriters = (pthread_t *) malloc(n * sizeof(*threadWriters)); // start 2 reader threads for (i = 0; i < n; i++) { pthread_create(&threadReaders[i], NULL, reader, (void *)&reader_seconds); } sleep(1); // start 2 writer threads for (i = 0; i < n; i++) { writer_seconds[i] = 0; pthread_create(&threadWriters[i], NULL, writer, (void *)&writer_seconds[i]); } sleep(4); // start the 3rd reader thread pthread_create(&threadReaders[n], NULL, reader, (void *)&reader_seconds); for (i = 0; i < n; i++) { pthread_join(threadReaders[i], NULL); } for (i = 0; i < n; i++) { pthread_join(threadWriters[i], NULL); } pthread_join(threadReaders[n], NULL); // the first writer thread needs to wait for the first two reader threads to unlock // the second writer thread needs to wait for the first writer thread to unlock ASSERT ( (writer_seconds[0] == 1 && writer_seconds[1] == 3) || (writer_seconds[0] == 3 && writer_seconds[1] == 1) ); // the third reader thread needs to wait for all the two writer threads to unlock ASSERT(reader_seconds == 1); free(threadReaders); free(threadWriters); } int main(int argc, char *argv[]) { testReadLock(); testWriteLock(); cout<<"\nReadWriteMutex unit tests passed.\n"; return 0; } <|endoftext|>
<commit_before>#include <TestSupport.h> #include <ConfigKit/Common.h> #include <ConfigKit/TableTranslator.h> using namespace Passenger; using namespace std; namespace tut { struct ConfigKit_TranslationTest { }; DEFINE_TEST_GROUP(ConfigKit_TranslationTest); TEST_METHOD(1) { ConfigKit::TableTranslator translator; ConfigKit::Error error("Key {{foo}} is invalid when {{bar}} is given"); vector<ConfigKit::Error> errors; translator.add("bar", "main_bar"); translator.finalize(); errors.push_back(error); errors = translator.translate(errors); ensure_equals(errors.size(), 1u); ensure_equals(errors[0].getMessage(), "Key foo is invalid when main_bar is given"); } } <commit_msg>ConfigKit: add more tests for TableTranslator<commit_after>#include <TestSupport.h> #include <ConfigKit/Common.h> #include <ConfigKit/TableTranslator.h> using namespace Passenger; using namespace std; namespace tut { struct ConfigKit_TranslationTest { }; DEFINE_TEST_GROUP(ConfigKit_TranslationTest); TEST_METHOD(1) { set_test_name("Test TableTranslator document translation"); ConfigKit::TableTranslator translator; Json::Value doc; doc["foo"] = 123; doc["bar"] = 456; translator.add("bar", "main_bar"); translator.finalize(); doc = translator.translate(doc); ensure_equals(doc.size(), 2u); ensure_equals("Translating docs works", doc["foo"].asInt(), 123); ensure_equals("Translating docs works", doc["main_bar"].asInt(), 456); doc = translator.translate(doc); ensure_equals(doc.size(), 2u); ensure_equals("Translating docs is idempotent", doc["foo"].asInt(), 123); ensure_equals("Translating docs is idempotent", doc["main_bar"].asInt(), 456); doc = translator.reverseTranslate(doc); ensure_equals(doc.size(), 2u); ensure_equals("Reverse translating docs works", doc["foo"].asInt(), 123); ensure_equals("Reverse translating docs works", doc["bar"].asInt(), 456); doc = translator.reverseTranslate(doc); ensure_equals(doc.size(), 2u); ensure_equals("Reverse translating docs is idempotent", doc["foo"].asInt(), 123); ensure_equals("Reverse translating docs is idempotent", doc["bar"].asInt(), 456); } TEST_METHOD(2) { set_test_name("Test TableTranslator error translation"); ConfigKit::TableTranslator translator; ConfigKit::Error error("Key {{foo}} is invalid when {{bar}} is given"); vector<ConfigKit::Error> errors; errors.push_back(error); translator.add("bar", "main_bar"); translator.finalize(); errors = translator.translate(errors); ensure_equals(errors.size(), 1u); ensure_equals("Translating errors works", errors[0].getMessage(), "Key foo is invalid when main_bar is given"); errors = translator.translate(errors); ensure_equals(errors.size(), 1u); ensure_equals("Translating errors is idempotent", errors[0].getMessage(), "Key foo is invalid when main_bar is given"); errors = translator.reverseTranslate(errors); ensure_equals(errors.size(), 1u); ensure_equals("Reverse translating errors works", errors[0].getMessage(), "Key foo is invalid when bar is given"); errors = translator.reverseTranslate(errors); ensure_equals(errors.size(), 1u); ensure_equals("Reverse translating errors is idempotent", errors[0].getMessage(), "Key foo is invalid when bar is given"); } } <|endoftext|>
<commit_before>/* * libTML: A BEEP based Messaging Suite * Copyright (C) 2016 wobe-systems GmbH * * 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., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * You may find a copy of the license under this software is released * at COPYING file. This is LGPL software: you are welcome to develop * proprietary applications using this library without any royalty or * fee but returning back any change, improvement or addition in the * form of source code, project image, documentation patches, etc. * * Homepage: * http://www.libtml.org * * For professional support contact us: * * wobe-systems GmbH * support@libtml.org * * Contributors: * wobe-systems GmbH */ #include "tmlrt_Utils.h" #include "TestParams.h" #include "tmlrt_Connections.h" #include "tmlrt_MultipleListeners.h" #include "tmlrt_TLS.h" #include "tmlrt_SendingCommands.h" /** @brief Main function, accepts command line parameters * @param int argc : contains amount of arguments in argv * @param char* argv[] : contains input from user * @returns int : 0 if everything went okay, -1 if a failure/error occurred or the options of the user were not recognized */ #ifdef LINUX int main(int argc, char* argv[]) #else //LINUX int _tmain(int argc, char* argv[]) #endif { int result = -1; wcout << "=======================" << endl; wcout << " TML regression test " << endl; wcout << "=======================" << endl; wcout << endl; #if defined(_MEM_LEAK_CHECK_) && defined(_DEBUG) // enable memory leak report at program exit... _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); wcout << "Memory leak detection is enabled!" << endl; wcout << endl; // just for debugging: set memory allocation break point //_CrtSetBreakAlloc(-1); // <- pass here the {xxx} value from the leak report #endif wcout << (8 * sizeof(int)) << "bit" << endl; wcout << "UTF" << (8 * sizeof(SIDEX_TCHAR)) << endl; wcout << endl; wcout << "Programm is called with " << (argc - 1) << " parameter" << ((argc > 2) ? "s." : ".") << endl; for(int i = 1; i < argc; i++) { wcout << "Param" << i << " = " << argv[i] << endl; } wcout << endl; SIDEX_TCHAR* pArg = NULL; SIDEX_TCHAR* pBuf = NULL; if(argc > 1) { SIDEX_INT32 iLength = 0; switch(sizeof(SIDEX_TCHAR)) { case 1: { pArg = (SIDEX_TCHAR*)argv[1]; break; } case 2: { pBuf = (SIDEX_TCHAR*)UTF8toUTF16(argv[1], &iLength); pArg = pBuf; break; } case 4: { pBuf = (SIDEX_TCHAR*)UTF8toUTF32(argv[1], &iLength); pArg = pBuf; break; } } } TestParams = new CTestParams(pArg); if(TestParams) { initGlobalMutex(); SIDEX_TCHAR* pfn = TestParams->getParamsFileName(); if(pfn) { wcout << "Using params file: " << pfn << endl; } else { wcout << "Running without params file!" << endl; } wcout << endl; if(TestParams->isActingAsRepeater()) { wcout << "Acting as Repeater!" << endl; int maxIdleTime = TestParams->getMaxIdleTime(); wcout << "Max idle time = "; if(maxIdleTime <= 0) { wcout << "endless!" << endl; } else { wcout << maxIdleTime << "s" << endl; } wcout << endl; startRepeater(); } else { int i = 0, n = TestParams->getTestLoopCount(); wcout << "Tests - Start... ( " << n << " loop" << ((n > 1) ? "s )" : " )") << endl; wcout << endl; do { wcout << "----------------------------------------" << endl; wcout << " Loop #" << (i + 1) << endl; wcout << "----------------------------------------" << endl; wcout << endl; if(!testTmlConnections()) break; // test the connection API if(!testTmlMultiListeners()) break; // test the multi listener API if(!testTmlTLS()) break; // test the TLS encryption API if(!testTmlSendingCommands()) break; // test the sending commands API i++; } while(i < n); if(i == n) result = 0; wcout << endl; wcout << "Tests - " << (result ? S_FINISH_FAILED : S_FINISH_SUCCESS) << endl; wcout << endl; } DELETE_OBJ(TestParams); deleteGlobalMutex(); } DELETE_STR(pBuf); wcout << "========================================" << endl; wcout << endl; return(result); } <commit_msg>Set a return code on repeater mode (not really necessary)<commit_after>/* * libTML: A BEEP based Messaging Suite * Copyright (C) 2016 wobe-systems GmbH * * 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., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * You may find a copy of the license under this software is released * at COPYING file. This is LGPL software: you are welcome to develop * proprietary applications using this library without any royalty or * fee but returning back any change, improvement or addition in the * form of source code, project image, documentation patches, etc. * * Homepage: * http://www.libtml.org * * For professional support contact us: * * wobe-systems GmbH * support@libtml.org * * Contributors: * wobe-systems GmbH */ #include "tmlrt_Utils.h" #include "TestParams.h" #include "tmlrt_Connections.h" #include "tmlrt_MultipleListeners.h" #include "tmlrt_TLS.h" #include "tmlrt_SendingCommands.h" /** @brief Main function, accepts command line parameters * @param int argc : contains amount of arguments in argv * @param char* argv[] : contains input from user * @returns int : 0 if everything went okay, -1 if a failure/error occurred or the options of the user were not recognized */ #ifdef LINUX int main(int argc, char* argv[]) #else //LINUX int _tmain(int argc, char* argv[]) #endif { int result = -1; wcout << "=======================" << endl; wcout << " TML regression test " << endl; wcout << "=======================" << endl; wcout << endl; #if defined(_MEM_LEAK_CHECK_) && defined(_DEBUG) // enable memory leak report at program exit... _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); wcout << "Memory leak detection is enabled!" << endl; wcout << endl; // just for debugging: set memory allocation break point //_CrtSetBreakAlloc(-1); // <- pass here the {xxx} value from the leak report #endif wcout << (8 * sizeof(int)) << "bit" << endl; wcout << "UTF" << (8 * sizeof(SIDEX_TCHAR)) << endl; wcout << endl; wcout << "Programm is called with " << (argc - 1) << " parameter" << ((argc > 2) ? "s." : ".") << endl; for(int i = 1; i < argc; i++) { wcout << "Param" << i << " = " << argv[i] << endl; } wcout << endl; SIDEX_TCHAR* pArg = NULL; SIDEX_TCHAR* pBuf = NULL; if(argc > 1) { SIDEX_INT32 iLength = 0; switch(sizeof(SIDEX_TCHAR)) { case 1: { pArg = (SIDEX_TCHAR*)argv[1]; break; } case 2: { pBuf = (SIDEX_TCHAR*)UTF8toUTF16(argv[1], &iLength); pArg = pBuf; break; } case 4: { pBuf = (SIDEX_TCHAR*)UTF8toUTF32(argv[1], &iLength); pArg = pBuf; break; } } } TestParams = new CTestParams(pArg); if(TestParams) { initGlobalMutex(); SIDEX_TCHAR* pfn = TestParams->getParamsFileName(); if(pfn) { wcout << "Using params file: " << pfn << endl; } else { wcout << "Running without params file!" << endl; } wcout << endl; if(TestParams->isActingAsRepeater()) { wcout << "Acting as Repeater!" << endl; int maxIdleTime = TestParams->getMaxIdleTime(); wcout << "Max idle time = "; if(maxIdleTime <= 0) { wcout << "endless!" << endl; } else { wcout << maxIdleTime << "s" << endl; } wcout << endl; startRepeater(); result = 0; } else { int i = 0, n = TestParams->getTestLoopCount(); wcout << "Tests - Start... ( " << n << " loop" << ((n > 1) ? "s )" : " )") << endl; wcout << endl; do { wcout << "----------------------------------------" << endl; wcout << " Loop #" << (i + 1) << endl; wcout << "----------------------------------------" << endl; wcout << endl; if(!testTmlConnections()) break; // test the connection API if(!testTmlMultiListeners()) break; // test the multi listener API if(!testTmlTLS()) break; // test the TLS encryption API if(!testTmlSendingCommands()) break; // test the sending commands API i++; } while(i < n); if(i == n) result = 0; wcout << endl; wcout << "Tests - " << (result ? S_FINISH_FAILED : S_FINISH_SUCCESS) << endl; wcout << endl; } DELETE_OBJ(TestParams); deleteGlobalMutex(); } DELETE_STR(pBuf); wcout << "========================================" << endl; wcout << endl; return(result); } <|endoftext|>
<commit_before>// Copyright 2014 eric schkufza // // 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 <cassert> #include <cmath> #include <csignal> #include <unistd.h> #include "src/search/search.h" using namespace cpputil; using namespace std; using namespace std::chrono; using namespace x64asm; namespace { bool give_up_now = false; void handler(int sig, siginfo_t* siginfo, void* context) { give_up_now = true; } } // namespace namespace stoke { Search::Search(Transforms* transforms) : transforms_(transforms) { set_max_instrs(16); set_seed(0); set_timeout_itr(0); set_timeout_sec(0); set_beta(1.0); set_progress_callback(nullptr, nullptr); set_statistics_callback(nullptr, nullptr); set_statistics_interval(100000); static bool once = false; if (!once) { once = true; struct sigaction term_act; memset(&term_act, '\0', sizeof(term_act)); sigfillset(&term_act.sa_mask); term_act.sa_sigaction = handler; term_act.sa_flags = SA_ONSTACK; sigaction(SIGINT, &term_act, 0); } } Search& Search::set_mass(Move move, size_t mass) { vector<Move> new_moves; for (auto m : moves_) { if (m != move) { new_moves.push_back(m); } } for (size_t i = 0; i < mass; ++i) { new_moves.push_back(move); } moves_ = new_moves; int_ = decltype(int_)(0, moves_.size() - 1); return *this; } void Search::run(const Cfg& target, CostFunction& fxn, Init init, SearchState& state, vector<TUnit>& aux_fxn) { // Make sure target is correct with respect to itself assert(fxn(target).first); // Configure initial state configure(init, target, fxn, state, aux_fxn); if (!target.is_sound()) { cerr << "ERROR: the target reads undefined values, or leaves live out values undefined!" << endl; exit(1); } if (!state.current.is_sound()) { cerr << "ERROR: the initial rewrite reads undefined values, or leaves live out values undefined!" << endl; if (init == Init::EMPTY) { cerr << "Using --init zero will automatically prevent this problem." << endl; } else if (init == Init::ZERO) { cerr << "This is a bug, please report it." << endl; } exit(1); } // Make sure target and rewrite are sound to begin with assert(state.best_yet.is_sound()); assert(state.best_correct.is_sound()); // Early corner case bailouts if (state.current_cost == 0) { state.success = true; return; } else if (moves_.empty()) { state.success = false; return; } // Statistics callback variables vector<Statistics> statistics((size_t) Move::NUM_MOVES); const auto start = chrono::steady_clock::now(); give_up_now = false; for (size_t iterations = 0; (state.current_cost > 0) && !give_up_now; ++iterations) { // Invoke statistics callback if we've been running for long enough if ((statistics_cb_ != nullptr) && (iterations % interval_ == 0) && iterations > 0) { const auto dur = duration_cast<duration<double>>(steady_clock::now() - start); statistics_cb_({statistics, iterations, dur}, statistics_cb_arg_); } // This is just here to clean up the for loop; check early exit conditions if (iterations >= timeout_itr_) { break; } else if (duration_cast<duration<size_t>>(steady_clock::now() - start) >= timeout_sec_) { break; } // @todo Check cost function hasn't changed across iterations const auto move_type = moves_[int_(gen_)]; statistics[(size_t) move_type].num_proposed++; if (!transforms_->modify(state.current, move_type)) { continue; } statistics[(size_t) move_type].num_succeeded++; const auto p = prob_(gen_); const auto max = state.current_cost - (log(p) / beta_); const auto new_res = fxn(state.current, max + 1); const auto is_correct = new_res.first; const auto new_cost = new_res.second; // @todo Check that cost function hasnt' changed within an iteration if (new_cost > max) { transforms_->undo(state.current, move_type); continue; } statistics[(size_t) move_type].num_accepted++; state.current_cost = new_cost; const auto new_best_yet = new_cost < state.best_yet_cost; if (new_best_yet) { state.best_yet = state.current; state.best_yet_cost = new_cost; } const auto new_best_correct_yet = is_correct && ((new_cost == 0) || (new_cost < state.best_correct_cost)); if (new_best_correct_yet) { state.success = true; state.best_correct = state.current; state.best_correct_cost = new_cost; } if ((progress_cb_ != nullptr) && (new_best_yet || new_best_correct_yet)) { progress_cb_({state}, progress_cb_arg_); } } } void Search::stop() { give_up_now = true; } void Search::configure(Init init, const Cfg& target, CostFunction& fxn, SearchState& state, vector<TUnit>& aux_fxn) const { switch (init) { case Init::EMPTY: configure_empty(target, state); break; case Init::ZERO: configure_zero(target, state); break; case Init::TARGET: configure_target(target, state); break; case Init::PREVIOUS: // Does nothing. break; case Init::EXTENSION: configure_extension(target, state); break; default: assert(false); break; } // add dataflow information about function call targets for (const auto& fxn : aux_fxn) { auto code = fxn.code; auto lbl = code[0].get_operand<x64asm::Label>(0); state.current.add_summary(lbl, code.must_read_set(), code.must_write_set(), code.must_undef_set(), code.maybe_read_set(), code.maybe_write_set(), code.maybe_undef_set()); } state.current_cost = fxn(state.current).second; state.best_yet_cost = fxn(state.best_yet).second; state.best_correct_cost = fxn(state.best_correct).second; state.success = false; // Invariant 3: Best correct should be correct with respect to target assert(fxn(state.best_correct).first); // Invariant 4: Best yet should be less than or equal to correct cost assert(state.best_yet_cost <= state.current_cost); } void Search::configure_empty(const Cfg& target, SearchState& state) const { state.current = Cfg({{}}, target.def_ins(), target.live_outs()); for (size_t i = 0, ie = max_instrs_ - 1; i < ie; ++i) { state.current.get_code().push_back({NOP}); } state.current.get_code().push_back({RET}); state.current.recompute(); state.best_yet = state.current; state.best_correct = target; } Code Search::find_sound_code(const RegSet& def_ins, const RegSet& live_outs) { auto diff = live_outs - def_ins; vector<Instruction> code; // initialize all general purpose registers for (auto rit = diff.gp_begin(); rit != diff.gp_end(); ++rit) { auto reg = *rit; auto type = reg.type(); if (type == Type::R_64 || type == Type::RAX) { code.push_back(Instruction(MOV_R64_IMM64, {reg, Imm64(0)})); } else if (type == Type::R_32 || type == Type::EAX) { code.push_back(Instruction(MOV_R32_IMM32, {reg, Imm32(0)})); } else if (type == Type::R_16 || type == Type::AX || type == Type::DX) { code.push_back(Instruction(MOV_R16_IMM16, {reg, Imm16(0)})); } else if (type == Type::RL || type == Type::AL || type == Type::CL) { code.push_back(Instruction(MOV_RL_IMM8, {reg, Imm8(0)})); } else if (type == Type::RH) { code.push_back(Instruction(MOV_RH_IMM8, {reg, Imm8(0)})); } else if (type == Type::RB) { code.push_back(Instruction(MOV_RB_IMM8, {reg, Imm8(0)})); } } // initialize sse registers for (auto rit = diff.sse_begin(); rit != diff.sse_end(); ++rit) { auto reg = *rit; auto type = reg.type(); if (type == Type::XMM || type == Type::XMM_0) { code.push_back(Instruction(MOV_R32_IMM32, {Constants::eax(), Imm64(0)})); code.push_back(Instruction(MOVD_XMM_R32, {reg, Constants::eax()})); } else if (type == Type::YMM) { code.push_back(Instruction(MOV_R32_IMM32, {Constants::eax(), Imm64(0)})); code.push_back(Instruction(VMOVD_XMM_R32, {reg, Constants::eax()})); } } // flags bool regular = false; for (auto rit = diff.flags_begin(); rit != diff.flags_end(); ++rit) { auto reg = *rit; if ((reg == Constants::eflags_of() || reg == Constants::eflags_zf() || reg == Constants::eflags_sf() || reg == Constants::eflags_af() || reg == Constants::eflags_cf() || reg == Constants::eflags_pf()) && !regular) { regular = true; code.push_back(Instruction(MOV_R32_IMM32, {Constants::eax(), Imm64(0)})); code.push_back(Instruction(ADD_R32_IMM32, {Constants::eax(), Imm32(0)})); } } // remove statements if possible bool changed = true; while (changed) { changed = false; int i = 0; for (auto it = code.begin(); it != code.end(); ++it, ++i) { vector<Instruction> copy = code; copy.erase(copy.begin()+i); if (Cfg(Code(copy.begin(), copy.end()), def_ins, live_outs).is_sound()) { code = copy; changed = true; break; } } } return Code(code.begin(), code.end()); } void Search::configure_zero(const Cfg& target, SearchState& state) const { if (target.def_ins().contains(target.live_outs())) { // no need to initialize any registers configure_empty(target, state); return; } auto code = find_sound_code(target.def_ins(), target.live_outs()); state.current = Cfg(code, target.def_ins(), target.live_outs()); for (size_t i = code.size(), ie = max_instrs_ - 1; i < ie; ++i) { state.current.get_code().push_back({NOP}); } state.current.get_code().push_back({RET}); state.current.recompute(); state.best_yet = state.current; state.best_correct = target; } void Search::configure_target(const Cfg& target, SearchState& state) const { state.current = target; state.best_yet = target; state.best_correct = target; } void Search::configure_extension(const Cfg& target, SearchState& state) const { // Add user-defined logic here ... // Invariant 1: Search state should agree with target on boundary conditions. assert(state.current.def_ins() == target.def_ins()); assert(state.current.live_outs() == target.live_outs()); assert(state.best_yet.def_ins() == target.def_ins()); assert(state.best_yet.live_outs() == target.live_outs()); assert(state.best_correct.def_ins() == target.def_ins()); assert(state.best_correct.live_outs() == target.live_outs()); // Invariant 2: Search state must be in a valid state. This function isn't on // a critical path, so this can safely be accomplished by calling state.current.recompute(); state.best_yet.recompute(); state.best_correct.recompute(); // See Search::configure for additional invariants } } // namespace stoke <commit_msg>whitespace<commit_after>// Copyright 2014 eric schkufza // // 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 <cassert> #include <cmath> #include <csignal> #include <unistd.h> #include "src/search/search.h" using namespace cpputil; using namespace std; using namespace std::chrono; using namespace x64asm; namespace { bool give_up_now = false; void handler(int sig, siginfo_t* siginfo, void* context) { give_up_now = true; } } // namespace namespace stoke { Search::Search(Transforms* transforms) : transforms_(transforms) { set_max_instrs(16); set_seed(0); set_timeout_itr(0); set_timeout_sec(0); set_beta(1.0); set_progress_callback(nullptr, nullptr); set_statistics_callback(nullptr, nullptr); set_statistics_interval(100000); static bool once = false; if (!once) { once = true; struct sigaction term_act; memset(&term_act, '\0', sizeof(term_act)); sigfillset(&term_act.sa_mask); term_act.sa_sigaction = handler; term_act.sa_flags = SA_ONSTACK; sigaction(SIGINT, &term_act, 0); } } Search& Search::set_mass(Move move, size_t mass) { vector<Move> new_moves; for (auto m : moves_) { if (m != move) { new_moves.push_back(m); } } for (size_t i = 0; i < mass; ++i) { new_moves.push_back(move); } moves_ = new_moves; int_ = decltype(int_)(0, moves_.size() - 1); return *this; } void Search::run(const Cfg& target, CostFunction& fxn, Init init, SearchState& state, vector<TUnit>& aux_fxn) { // Make sure target is correct with respect to itself assert(fxn(target).first); // Configure initial state configure(init, target, fxn, state, aux_fxn); if (!target.is_sound()) { cerr << "ERROR: the target reads undefined values, or leaves live out values undefined!" << endl; exit(1); } if (!state.current.is_sound()) { cerr << "ERROR: the initial rewrite reads undefined values, or leaves live out values undefined!" << endl; if (init == Init::EMPTY) { cerr << "Using --init zero will automatically prevent this problem." << endl; } else if (init == Init::ZERO) { cerr << "This is a bug, please report it." << endl; } exit(1); } // Make sure target and rewrite are sound to begin with assert(state.best_yet.is_sound()); assert(state.best_correct.is_sound()); // Early corner case bailouts if (state.current_cost == 0) { state.success = true; return; } else if (moves_.empty()) { state.success = false; return; } // Statistics callback variables vector<Statistics> statistics((size_t) Move::NUM_MOVES); const auto start = chrono::steady_clock::now(); give_up_now = false; for (size_t iterations = 0; (state.current_cost > 0) && !give_up_now; ++iterations) { // Invoke statistics callback if we've been running for long enough if ((statistics_cb_ != nullptr) && (iterations % interval_ == 0) && iterations > 0) { const auto dur = duration_cast<duration<double>>(steady_clock::now() - start); statistics_cb_({statistics, iterations, dur}, statistics_cb_arg_); } // This is just here to clean up the for loop; check early exit conditions if (iterations >= timeout_itr_) { break; } else if (duration_cast<duration<size_t>>(steady_clock::now() - start) >= timeout_sec_) { break; } // @todo Check cost function hasn't changed across iterations const auto move_type = moves_[int_(gen_)]; statistics[(size_t) move_type].num_proposed++; if (!transforms_->modify(state.current, move_type)) { continue; } statistics[(size_t) move_type].num_succeeded++; const auto p = prob_(gen_); const auto max = state.current_cost - (log(p) / beta_); const auto new_res = fxn(state.current, max + 1); const auto is_correct = new_res.first; const auto new_cost = new_res.second; // @todo Check that cost function hasnt' changed within an iteration if (new_cost > max) { transforms_->undo(state.current, move_type); continue; } statistics[(size_t) move_type].num_accepted++; state.current_cost = new_cost; const auto new_best_yet = new_cost < state.best_yet_cost; if (new_best_yet) { state.best_yet = state.current; state.best_yet_cost = new_cost; } const auto new_best_correct_yet = is_correct && ((new_cost == 0) || (new_cost < state.best_correct_cost)); if (new_best_correct_yet) { state.success = true; state.best_correct = state.current; state.best_correct_cost = new_cost; } if ((progress_cb_ != nullptr) && (new_best_yet || new_best_correct_yet)) { progress_cb_({state}, progress_cb_arg_); } } } void Search::stop() { give_up_now = true; } void Search::configure(Init init, const Cfg& target, CostFunction& fxn, SearchState& state, vector<TUnit>& aux_fxn) const { switch (init) { case Init::EMPTY: configure_empty(target, state); break; case Init::ZERO: configure_zero(target, state); break; case Init::TARGET: configure_target(target, state); break; case Init::PREVIOUS: // Does nothing. break; case Init::EXTENSION: configure_extension(target, state); break; default: assert(false); break; } // add dataflow information about function call targets for (const auto& fxn : aux_fxn) { auto code = fxn.code; auto lbl = code[0].get_operand<x64asm::Label>(0); state.current.add_summary(lbl, code.must_read_set(), code.must_write_set(), code.must_undef_set(), code.maybe_read_set(), code.maybe_write_set(), code.maybe_undef_set()); } state.current_cost = fxn(state.current).second; state.best_yet_cost = fxn(state.best_yet).second; state.best_correct_cost = fxn(state.best_correct).second; state.success = false; // Invariant 3: Best correct should be correct with respect to target assert(fxn(state.best_correct).first); // Invariant 4: Best yet should be less than or equal to correct cost assert(state.best_yet_cost <= state.current_cost); } void Search::configure_empty(const Cfg& target, SearchState& state) const { state.current = Cfg({{}}, target.def_ins(), target.live_outs()); for (size_t i = 0, ie = max_instrs_ - 1; i < ie; ++i) { state.current.get_code().push_back({NOP}); } state.current.get_code().push_back({RET}); state.current.recompute(); state.best_yet = state.current; state.best_correct = target; } Code Search::find_sound_code(const RegSet& def_ins, const RegSet& live_outs) { auto diff = live_outs - def_ins; vector<Instruction> code; // initialize all general purpose registers for (auto rit = diff.gp_begin(); rit != diff.gp_end(); ++rit) { auto reg = *rit; auto type = reg.type(); if (type == Type::R_64 || type == Type::RAX) { code.push_back(Instruction(MOV_R64_IMM64, {reg, Imm64(0)})); } else if (type == Type::R_32 || type == Type::EAX) { code.push_back(Instruction(MOV_R32_IMM32, {reg, Imm32(0)})); } else if (type == Type::R_16 || type == Type::AX || type == Type::DX) { code.push_back(Instruction(MOV_R16_IMM16, {reg, Imm16(0)})); } else if (type == Type::RL || type == Type::AL || type == Type::CL) { code.push_back(Instruction(MOV_RL_IMM8, {reg, Imm8(0)})); } else if (type == Type::RH) { code.push_back(Instruction(MOV_RH_IMM8, {reg, Imm8(0)})); } else if (type == Type::RB) { code.push_back(Instruction(MOV_RB_IMM8, {reg, Imm8(0)})); } } // initialize sse registers for (auto rit = diff.sse_begin(); rit != diff.sse_end(); ++rit) { auto reg = *rit; auto type = reg.type(); if (type == Type::XMM || type == Type::XMM_0) { code.push_back(Instruction(MOV_R32_IMM32, {Constants::eax(), Imm64(0)})); code.push_back(Instruction(MOVD_XMM_R32, {reg, Constants::eax()})); } else if (type == Type::YMM) { code.push_back(Instruction(MOV_R32_IMM32, {Constants::eax(), Imm64(0)})); code.push_back(Instruction(VMOVD_XMM_R32, {reg, Constants::eax()})); } } // flags bool regular = false; for (auto rit = diff.flags_begin(); rit != diff.flags_end(); ++rit) { auto reg = *rit; if ((reg == Constants::eflags_of() || reg == Constants::eflags_zf() || reg == Constants::eflags_sf() || reg == Constants::eflags_af() || reg == Constants::eflags_cf() || reg == Constants::eflags_pf()) && !regular) { regular = true; code.push_back(Instruction(MOV_R32_IMM32, {Constants::eax(), Imm64(0)})); code.push_back(Instruction(ADD_R32_IMM32, {Constants::eax(), Imm32(0)})); } } // remove statements if possible bool changed = true; while (changed) { changed = false; int i = 0; for (auto it = code.begin(); it != code.end(); ++it, ++i) { vector<Instruction> copy = code; copy.erase(copy.begin()+i); if (Cfg(Code(copy.begin(), copy.end()), def_ins, live_outs).is_sound()) { code = copy; changed = true; break; } } } return Code(code.begin(), code.end()); } void Search::configure_zero(const Cfg& target, SearchState& state) const { if (target.def_ins().contains(target.live_outs())) { // no need to initialize any registers configure_empty(target, state); return; } auto code = find_sound_code(target.def_ins(), target.live_outs()); state.current = Cfg(code, target.def_ins(), target.live_outs()); for (size_t i = code.size(), ie = max_instrs_ - 1; i < ie; ++i) { state.current.get_code().push_back({NOP}); } state.current.get_code().push_back({RET}); state.current.recompute(); state.best_yet = state.current; state.best_correct = target; } void Search::configure_target(const Cfg& target, SearchState& state) const { state.current = target; state.best_yet = target; state.best_correct = target; } void Search::configure_extension(const Cfg& target, SearchState& state) const { // Add user-defined logic here ... // Invariant 1: Search state should agree with target on boundary conditions. assert(state.current.def_ins() == target.def_ins()); assert(state.current.live_outs() == target.live_outs()); assert(state.best_yet.def_ins() == target.def_ins()); assert(state.best_yet.live_outs() == target.live_outs()); assert(state.best_correct.def_ins() == target.def_ins()); assert(state.best_correct.live_outs() == target.live_outs()); // Invariant 2: Search state must be in a valid state. This function isn't on // a critical path, so this can safely be accomplished by calling state.current.recompute(); state.best_yet.recompute(); state.best_correct.recompute(); // See Search::configure for additional invariants } } // namespace stoke <|endoftext|>
<commit_before>#include <math.h> #include "server.hpp" #include "db_thread_info.hpp" #include "memcached/memcached.hpp" #include "diskinfo.hpp" #include "concurrency/cond_var.hpp" #include "logger.hpp" #include "server/cmd_args.hpp" #include "replication/master.hpp" #include "replication/slave.hpp" #include "replication/load_balancer.hpp" #include "control.hpp" int run_server(int argc, char *argv[]) { // Parse command line arguments cmd_config_t config = parse_cmd_args(argc, argv); // Open the log file, if necessary. if (config.log_file_name[0]) { log_file = fopen(config.log_file_name, "w"); } // Initial thread message to start server struct server_starter_t : public thread_message_t { cmd_config_t *cmd_config; thread_pool_t *thread_pool; void on_thread_switch() { coro_t::spawn(boost::bind(&server_main, cmd_config, thread_pool)); } } starter; starter.cmd_config = &config; // Run the server. thread_pool_t thread_pool(config.n_workers); starter.thread_pool = &thread_pool; thread_pool.run(&starter); logINF("Server is shut down.\n"); // Close the log file if necessary. if (config.log_file_name[0]) { fclose(log_file); log_file = stderr; } return 0; } static void server_shutdown() { // Shut down the server thread_message_t *old_interrupt_msg = thread_pool_t::set_interrupt_message(NULL); /* If the interrupt message already was NULL, that means that either shutdown() was for some reason called before we finished starting up or shutdown() was called twice and this is the second time. */ if (old_interrupt_msg) { if (continue_on_thread(get_num_threads()-1, old_interrupt_msg)) call_later_on_this_thread(old_interrupt_msg); } } #ifdef TIMEBOMB_DAYS namespace timebomb { static const long seconds_in_an_hour = 3600; static const long seconds_in_a_day = seconds_in_an_hour*24; static const long timebomb_check_period_in_sec = seconds_in_an_hour * 12; // Timebomb synchronization code is ugly: we don't want the timer to run when we have cancelled it, // but it's hard to do, since timers are asynchronous and can execute while we are trying to destroy them. // We could use a periodic timer, but then scheduling the last alarm precisely would be harder // (or we would have to use a separate one-shot timer). static spinlock_t timer_token_lock; static volatile bool no_more_checking; struct periodic_checker_t { periodic_checker_t(creation_timestamp_t creation_timestamp) : creation_timestamp(creation_timestamp), timer_token(NULL) { no_more_checking = false; check(this); } ~periodic_checker_t() { timer_token_lock.lock(); no_more_checking = true; if (timer_token) { cancel_timer(const_cast<timer_token_t*>(timer_token)); } timer_token_lock.unlock(); } static void check(periodic_checker_t *timebomb_checker) { timer_token_lock.lock(); if (!no_more_checking) { bool exploded = false; time_t time_now = time(NULL); double seconds_since_created = difftime(time_now, timebomb_checker->creation_timestamp); if (seconds_since_created < 0) { // time anomaly: database created in future (or we are in 2038) logERR("Error: Database creation timestamp is in the future.\n"); exploded = true; } else if (seconds_since_created > double(TIMEBOMB_DAYS)*seconds_in_a_day) { // trial is over logERR("Thank you for evaluating %s. Trial period has expired. To continue using the software, please contact RethinkDB <support@rethinkdb.com>.\n", PRODUCT_NAME); exploded = true; } else { double days_since_created = seconds_since_created / seconds_in_a_day; int days_left = ceil(double(TIMEBOMB_DAYS) - days_since_created); if (days_left > 1) { logWRN("This is a trial version of %s. It will expire in %d days.\n", PRODUCT_NAME, days_left); } else { logWRN("This is a trial version of %s. It will expire today.\n", PRODUCT_NAME); } exploded = false; } if (exploded) { server_shutdown(); } else { // schedule next check long seconds_left = ceil(double(TIMEBOMB_DAYS)*seconds_in_a_day - seconds_since_created) + 1; long seconds_till_check = min(seconds_left, timebomb_check_period_in_sec); timebomb_checker->timer_token = fire_timer_once(seconds_till_check * 1000, (void (*)(void*)) &check, timebomb_checker); } } timer_token_lock.unlock(); } private: creation_timestamp_t creation_timestamp; volatile timer_token_t *timer_token; }; } #endif void server_main(cmd_config_t *cmd_config, thread_pool_t *thread_pool) { /* Create a server object. It only exists so we can give pointers to it to other things. */ server_t server(cmd_config, thread_pool); { /* Pointers to our stores these are allocated dynamically so that we have explicit control of when and where their destructors get called*/ boost::scoped_ptr<replication::slave_t> slave_store; /* Start logger */ log_controller_t log_controller; /* Copy database filenames from private serializer configurations into a single vector of strings */ std::vector<std::string> db_filenames; std::vector<log_serializer_private_dynamic_config_t>& serializer_private = cmd_config->store_dynamic_config.serializer_private; std::vector<log_serializer_private_dynamic_config_t>::iterator it; for (it = serializer_private.begin(); it != serializer_private.end(); ++it) { db_filenames.push_back((*it).db_filename); } /* Check to see if there is an existing database */ struct : public btree_key_value_store_t::check_callback_t, public promise_t<bool> { void on_store_check(bool ok) { pulse(ok); } } check_cb; btree_key_value_store_t::check_existing(db_filenames, &check_cb); bool existing = check_cb.wait(); if (existing && cmd_config->create_store && !cmd_config->force_create) { fail_due_to_user_error( "It looks like there already is a database here. RethinkDB will abort in case you " "didn't mean to overwrite it. Run with the '--force' flag to override this warning."); } else { if (!existing) { cmd_config->create_store = true; } } /* Record information about disk drives to log file */ log_disk_info(cmd_config->store_dynamic_config.serializer_private); boost::scoped_ptr<replication::master_t> master; if (cmd_config->replication_master_active) { master.reset(new replication::master_t(thread_pool, cmd_config->replication_master_listen_port)); } /* Create store if necessary */ if (cmd_config->create_store) { logINF("Creating database...\n"); btree_key_value_store_t::create(&cmd_config->store_dynamic_config, &cmd_config->store_static_config); logINF("Done creating.\n"); } if (!cmd_config->shutdown_after_creation) { /* Start key-value store */ logINF("Loading database...\n"); snag_ptr_t<replication::master_t> master_ptr(master.get()); btree_key_value_store_t store(&cmd_config->store_dynamic_config, master_ptr); master_ptr.reset(); if (master) { master->register_key_value_store(&store); } debugf("server: Registered with master..\n"); server.get_store = &store; // Gets always go straight to the key-value store /* Are we a replication slave? */ if (cmd_config->replication_config.active) { debugf("server: Starting up as a slave..\n"); logINF("Starting up as a slave...\n"); slave_store.reset(new replication::slave_t(&store, cmd_config->replication_config, cmd_config->failover_config)); debugf("server: Constructed slave_t..\n"); server.set_store = slave_store.get(); } else { server.set_store = &store; /* So things can access it */ } /* Start connection acceptor */ struct : public conn_acceptor_t::handler_t { server_t *parent; void handle(tcp_conn_t *conn) { serve_memcache(conn, parent->get_store, parent->set_store); } } handler; handler.parent = &server; debugf("Adding failover callback...\n"); if (cmd_config->replication_config.active && cmd_config->failover_config.elb_port != -1) { elb_t elb(elb_t::slave, cmd_config->port); slave_store->failover.add_callback(&elb); } debugf("Starting conn_acceptor....\n"); try { conn_acceptor_t conn_acceptor(cmd_config->port, &handler); logINF("Server is now accepting memcache connections on port %d.\n", cmd_config->port); /* Wait for an order to shut down */ struct : public thread_message_t, public cond_t { void on_thread_switch() { pulse(); } } interrupt_cond; thread_pool_t::set_interrupt_message(&interrupt_cond); #ifdef TIMEBOMB_DAYS timebomb::periodic_checker_t timebomb_checker(store.multiplexer->creation_timestamp); #endif debugf("Waiting for interrupt....\n"); interrupt_cond.wait(); debugf("Received interrupt.\n"); logINF("Waiting for running operations to complete...\n"); } catch (conn_acceptor_t::address_in_use_exc_t) { debugf("Port %d is already in use -- aborting (debugf msg)...\n", cmd_config->port); logERR("Port %d is already in use -- aborting.\n", cmd_config->port); //TODO move into the conn_acceptor } // store destructor called here logINF("Waiting for changes to flush to disk...\n"); } else { logINF("Shutting down...\n"); } } /* The penultimate step of shutting down is to make sure that all messages have reached their destinations so that they can be freed. The way we do this is to send one final message to each core; when those messages all get back we know that all messages have been processed properly. Otherwise, logger shutdown messages would get "stuck" in the message hub when it shut down, leading to memory leaks. */ for (int i = 0; i < get_num_threads(); i++) { on_thread_t thread_switcher(i); } /* Finally tell the thread pool to stop. TODO: Eventually, the thread pool should stop automatically when server_main() returns. */ thread_pool->shutdown(); } /* Install the shutdown control for thread pool */ struct shutdown_control_t : public control_t { shutdown_control_t(std::string key) : control_t(key, "Shut down the server.") {} std::string call(UNUSED int argc, UNUSED char **argv) { server_shutdown(); // TODO: Only print this if there actually *is* a lot of unsaved data. return std::string("Shutting down... this may take time if there is a lot of unsaved data.\r\n"); } }; shutdown_control_t shutdown_control(std::string("shutdown")); struct malloc_control_t : public control_t { malloc_control_t(std::string key) : control_t(key, "tcmalloc-testing control.") { } std::string call(UNUSED int argc, UNUSED char **argv) { std::vector<void *> ptrs; ptrs.reserve(100000); std::string ret("HundredThousandComplete\r\n"); for (int i = 0; i < 100000; ++i) { void *ptr; int res = posix_memalign(&ptr, 4096, 131072); if (res != 0) { ret = strprintf("Failed at i = %d\r\n", i); break; } } for (int j = 0; j < int(ptrs.size()); ++j) { free(ptrs[j]); } return ret; } }; malloc_control_t malloc_control("malloc_control"); <commit_msg>Removed some no-longer-necessary debugfs.<commit_after>#include <math.h> #include "server.hpp" #include "db_thread_info.hpp" #include "memcached/memcached.hpp" #include "diskinfo.hpp" #include "concurrency/cond_var.hpp" #include "logger.hpp" #include "server/cmd_args.hpp" #include "replication/master.hpp" #include "replication/slave.hpp" #include "replication/load_balancer.hpp" #include "control.hpp" int run_server(int argc, char *argv[]) { // Parse command line arguments cmd_config_t config = parse_cmd_args(argc, argv); // Open the log file, if necessary. if (config.log_file_name[0]) { log_file = fopen(config.log_file_name, "w"); } // Initial thread message to start server struct server_starter_t : public thread_message_t { cmd_config_t *cmd_config; thread_pool_t *thread_pool; void on_thread_switch() { coro_t::spawn(boost::bind(&server_main, cmd_config, thread_pool)); } } starter; starter.cmd_config = &config; // Run the server. thread_pool_t thread_pool(config.n_workers); starter.thread_pool = &thread_pool; thread_pool.run(&starter); logINF("Server is shut down.\n"); // Close the log file if necessary. if (config.log_file_name[0]) { fclose(log_file); log_file = stderr; } return 0; } static void server_shutdown() { // Shut down the server thread_message_t *old_interrupt_msg = thread_pool_t::set_interrupt_message(NULL); /* If the interrupt message already was NULL, that means that either shutdown() was for some reason called before we finished starting up or shutdown() was called twice and this is the second time. */ if (old_interrupt_msg) { if (continue_on_thread(get_num_threads()-1, old_interrupt_msg)) call_later_on_this_thread(old_interrupt_msg); } } #ifdef TIMEBOMB_DAYS namespace timebomb { static const long seconds_in_an_hour = 3600; static const long seconds_in_a_day = seconds_in_an_hour*24; static const long timebomb_check_period_in_sec = seconds_in_an_hour * 12; // Timebomb synchronization code is ugly: we don't want the timer to run when we have cancelled it, // but it's hard to do, since timers are asynchronous and can execute while we are trying to destroy them. // We could use a periodic timer, but then scheduling the last alarm precisely would be harder // (or we would have to use a separate one-shot timer). static spinlock_t timer_token_lock; static volatile bool no_more_checking; struct periodic_checker_t { periodic_checker_t(creation_timestamp_t creation_timestamp) : creation_timestamp(creation_timestamp), timer_token(NULL) { no_more_checking = false; check(this); } ~periodic_checker_t() { timer_token_lock.lock(); no_more_checking = true; if (timer_token) { cancel_timer(const_cast<timer_token_t*>(timer_token)); } timer_token_lock.unlock(); } static void check(periodic_checker_t *timebomb_checker) { timer_token_lock.lock(); if (!no_more_checking) { bool exploded = false; time_t time_now = time(NULL); double seconds_since_created = difftime(time_now, timebomb_checker->creation_timestamp); if (seconds_since_created < 0) { // time anomaly: database created in future (or we are in 2038) logERR("Error: Database creation timestamp is in the future.\n"); exploded = true; } else if (seconds_since_created > double(TIMEBOMB_DAYS)*seconds_in_a_day) { // trial is over logERR("Thank you for evaluating %s. Trial period has expired. To continue using the software, please contact RethinkDB <support@rethinkdb.com>.\n", PRODUCT_NAME); exploded = true; } else { double days_since_created = seconds_since_created / seconds_in_a_day; int days_left = ceil(double(TIMEBOMB_DAYS) - days_since_created); if (days_left > 1) { logWRN("This is a trial version of %s. It will expire in %d days.\n", PRODUCT_NAME, days_left); } else { logWRN("This is a trial version of %s. It will expire today.\n", PRODUCT_NAME); } exploded = false; } if (exploded) { server_shutdown(); } else { // schedule next check long seconds_left = ceil(double(TIMEBOMB_DAYS)*seconds_in_a_day - seconds_since_created) + 1; long seconds_till_check = min(seconds_left, timebomb_check_period_in_sec); timebomb_checker->timer_token = fire_timer_once(seconds_till_check * 1000, (void (*)(void*)) &check, timebomb_checker); } } timer_token_lock.unlock(); } private: creation_timestamp_t creation_timestamp; volatile timer_token_t *timer_token; }; } #endif void server_main(cmd_config_t *cmd_config, thread_pool_t *thread_pool) { /* Create a server object. It only exists so we can give pointers to it to other things. */ server_t server(cmd_config, thread_pool); { /* Pointers to our stores these are allocated dynamically so that we have explicit control of when and where their destructors get called*/ boost::scoped_ptr<replication::slave_t> slave_store; /* Start logger */ log_controller_t log_controller; /* Copy database filenames from private serializer configurations into a single vector of strings */ std::vector<std::string> db_filenames; std::vector<log_serializer_private_dynamic_config_t>& serializer_private = cmd_config->store_dynamic_config.serializer_private; std::vector<log_serializer_private_dynamic_config_t>::iterator it; for (it = serializer_private.begin(); it != serializer_private.end(); ++it) { db_filenames.push_back((*it).db_filename); } /* Check to see if there is an existing database */ struct : public btree_key_value_store_t::check_callback_t, public promise_t<bool> { void on_store_check(bool ok) { pulse(ok); } } check_cb; btree_key_value_store_t::check_existing(db_filenames, &check_cb); bool existing = check_cb.wait(); if (existing && cmd_config->create_store && !cmd_config->force_create) { fail_due_to_user_error( "It looks like there already is a database here. RethinkDB will abort in case you " "didn't mean to overwrite it. Run with the '--force' flag to override this warning."); } else { if (!existing) { cmd_config->create_store = true; } } /* Record information about disk drives to log file */ log_disk_info(cmd_config->store_dynamic_config.serializer_private); boost::scoped_ptr<replication::master_t> master; if (cmd_config->replication_master_active) { master.reset(new replication::master_t(thread_pool, cmd_config->replication_master_listen_port)); } /* Create store if necessary */ if (cmd_config->create_store) { logINF("Creating database...\n"); btree_key_value_store_t::create(&cmd_config->store_dynamic_config, &cmd_config->store_static_config); logINF("Done creating.\n"); } if (!cmd_config->shutdown_after_creation) { /* Start key-value store */ logINF("Loading database...\n"); snag_ptr_t<replication::master_t> master_ptr(master.get()); btree_key_value_store_t store(&cmd_config->store_dynamic_config, master_ptr); master_ptr.reset(); if (master) { master->register_key_value_store(&store); } server.get_store = &store; // Gets always go straight to the key-value store /* Are we a replication slave? */ if (cmd_config->replication_config.active) { logINF("Starting up as a slave...\n"); slave_store.reset(new replication::slave_t(&store, cmd_config->replication_config, cmd_config->failover_config)); server.set_store = slave_store.get(); } else { server.set_store = &store; /* So things can access it */ } /* Start connection acceptor */ struct : public conn_acceptor_t::handler_t { server_t *parent; void handle(tcp_conn_t *conn) { serve_memcache(conn, parent->get_store, parent->set_store); } } handler; handler.parent = &server; if (cmd_config->replication_config.active && cmd_config->failover_config.elb_port != -1) { elb_t elb(elb_t::slave, cmd_config->port); slave_store->failover.add_callback(&elb); } try { conn_acceptor_t conn_acceptor(cmd_config->port, &handler); logINF("Server is now accepting memcache connections on port %d.\n", cmd_config->port); /* Wait for an order to shut down */ struct : public thread_message_t, public cond_t { void on_thread_switch() { pulse(); } } interrupt_cond; thread_pool_t::set_interrupt_message(&interrupt_cond); #ifdef TIMEBOMB_DAYS timebomb::periodic_checker_t timebomb_checker(store.multiplexer->creation_timestamp); #endif interrupt_cond.wait(); logINF("Waiting for running operations to complete...\n"); } catch (conn_acceptor_t::address_in_use_exc_t) { logERR("Port %d is already in use -- aborting.\n", cmd_config->port); //TODO move into the conn_acceptor } // store destructor called here logINF("Waiting for changes to flush to disk...\n"); } else { logINF("Shutting down...\n"); } } /* The penultimate step of shutting down is to make sure that all messages have reached their destinations so that they can be freed. The way we do this is to send one final message to each core; when those messages all get back we know that all messages have been processed properly. Otherwise, logger shutdown messages would get "stuck" in the message hub when it shut down, leading to memory leaks. */ for (int i = 0; i < get_num_threads(); i++) { on_thread_t thread_switcher(i); } /* Finally tell the thread pool to stop. TODO: Eventually, the thread pool should stop automatically when server_main() returns. */ thread_pool->shutdown(); } /* Install the shutdown control for thread pool */ struct shutdown_control_t : public control_t { shutdown_control_t(std::string key) : control_t(key, "Shut down the server.") {} std::string call(UNUSED int argc, UNUSED char **argv) { server_shutdown(); // TODO: Only print this if there actually *is* a lot of unsaved data. return std::string("Shutting down... this may take time if there is a lot of unsaved data.\r\n"); } }; shutdown_control_t shutdown_control(std::string("shutdown")); struct malloc_control_t : public control_t { malloc_control_t(std::string key) : control_t(key, "tcmalloc-testing control.") { } std::string call(UNUSED int argc, UNUSED char **argv) { std::vector<void *> ptrs; ptrs.reserve(100000); std::string ret("HundredThousandComplete\r\n"); for (int i = 0; i < 100000; ++i) { void *ptr; int res = posix_memalign(&ptr, 4096, 131072); if (res != 0) { ret = strprintf("Failed at i = %d\r\n", i); break; } } for (int j = 0; j < int(ptrs.size()); ++j) { free(ptrs[j]); } return ret; } }; malloc_control_t malloc_control("malloc_control"); <|endoftext|>
<commit_before>#include "state.h" #include "rccpp.h" #include "config.h" #include "interface/module.h" #include "interface/server.h" #include "interface/event.h" //#include "interface/thread.h" #include "interface/mutex.h" #include <c55/log.h> #include <iostream> #include <algorithm> extern server::Config g_server_config; namespace server { struct CState: public State, public interface::Server { struct ModuleWithMutex { interface::Mutex mutex; interface::Module *module; ModuleWithMutex(interface::Module *module=NULL): module(module){} }; up_<rccpp::Compiler> m_compiler; ss_ m_modules_path; sm_<ss_, ModuleWithMutex> m_modules; interface::Mutex m_modules_mutex; sv_<interface::Event> m_event_queue; interface::Mutex m_event_queue_mutex; sv_<sv_<ModuleWithMutex*>> m_event_subs; interface::Mutex m_event_subs_mutex; CState(): m_compiler(rccpp::createCompiler()) { m_compiler->include_directories.push_back( g_server_config.interface_path); m_compiler->include_directories.push_back( g_server_config.interface_path+"/.."); m_compiler->include_directories.push_back( g_server_config.interface_path+"/../../3rdparty/cereal/include"); } ~CState() { interface::MutexScope ms(m_modules_mutex); for(auto &pair : m_modules){ ModuleWithMutex &mwm = pair.second; // Don't lock; it would only cause deadlocks delete mwm.module; } } void load_module(const ss_ &module_name, const ss_ &path) { interface::MutexScope ms(m_modules_mutex); std::cerr<<"Loading module "<<module_name<<" from "<<path<<std::endl; ss_ build_dst = g_server_config.rccpp_build_path + "/"+module_name+".so"; m_compiler->include_directories.push_back(m_modules_path); m_compiler->build(module_name, path+"/server/init.cpp", build_dst); m_compiler->include_directories.pop_back(); interface::Module *m = static_cast<interface::Module*>( m_compiler->construct(module_name.c_str(), this)); m_modules[module_name] = ModuleWithMutex(m); { ModuleWithMutex &mwm = m_modules[module_name]; interface::MutexScope ms2(mwm.mutex); mwm.module->init(); } } void load_modules(const ss_ &path) { m_modules_path = path; ss_ first_module_path = path+"/__loader"; load_module("__loader", first_module_path); log_v("state", "asd"); emit_event(interface::Event("core:load_modules")); emit_event(interface::Event("core:start")); log_v("state", "asd2"); } ss_ get_modules_path() { return m_modules_path; } ss_ get_builtin_modules_path() { return g_server_config.share_path+"/builtin"; } /*interface::Module* get_module_u(const ss_ &module_name) { interface::MutexScope ms(m_modules_mutex); auto it = m_modules.find(module_name); if(it == m_modules.end()) return NULL; return it->second; } interface::Module* check_module_u(const ss_ &module_name) { interface::Module *m = get_module(module_name); if(m) return m; throw ModuleNotFoundException(ss_()+"Module not found: "+module_name); }*/ bool has_module(const ss_ &module_name) { interface::MutexScope ms(m_modules_mutex); auto it = m_modules.find(module_name); return (it != m_modules.end()); } void sub_event(struct interface::Module *module, const interface::Event::Type &type) { // Lock modules so that the subscribing one isn't removed asynchronously interface::MutexScope ms(m_modules_mutex); // Make sure module is a known instance ModuleWithMutex *mwm0 = NULL; ss_ module_name = "(unknown)"; for(auto &pair : m_modules){ ModuleWithMutex &mwm = pair.second; if(mwm.module == module){ mwm0 = &mwm; module_name = pair.first; break; } } if(mwm0 == nullptr){ std::cerr<<"sub_event(): Not a known module"<<std::endl; return; } interface::MutexScope ms2(m_event_subs_mutex); if(m_event_subs.size() <= type) m_event_subs.resize(type+1); sv_<ModuleWithMutex*> &sublist = m_event_subs[type]; if(std::find(sublist.begin(), sublist.end(), mwm0) != sublist.end()){ std::cerr<<"sub_event(): Already on list: "<<module_name<<std::endl; return; } std::cerr<<"sub_event(): "<<module_name<<" subscribed to "<<type<<std::endl; sublist.push_back(mwm0); } void emit_event(const interface::Event &event) { log_v("state", "emit_event(): type=%zu", event.type); interface::MutexScope ms(m_event_queue_mutex); m_event_queue.push_back(event); } void handle_events() { log_d("state", "handle_events()"); interface::MutexScope ms(m_modules_mutex); for(;;){ sv_<interface::Event> event_queue_snapshot; sv_<sv_<ModuleWithMutex*>> event_subs_snapshot; { interface::MutexScope ms2(m_event_queue_mutex); interface::MutexScope ms3(m_event_subs_mutex); m_event_queue.swap(event_queue_snapshot); m_event_subs.swap(event_subs_snapshot); } if(event_queue_snapshot.empty()){ break; } for(const interface::Event &event : event_queue_snapshot){ if(event_subs_snapshot.size() <= event.type) continue; sv_<ModuleWithMutex*> &sublist = event_subs_snapshot[event.type]; for(ModuleWithMutex *mwm : sublist){ mwm->module->event(event); } } } } }; State* createState() { return new CState(); } } <commit_msg>server/state: Fix startup events<commit_after>#include "state.h" #include "rccpp.h" #include "config.h" #include "interface/module.h" #include "interface/server.h" #include "interface/event.h" //#include "interface/thread.h" #include "interface/mutex.h" #include <c55/log.h> #include <iostream> #include <algorithm> extern server::Config g_server_config; namespace server { struct CState: public State, public interface::Server { struct ModuleWithMutex { interface::Mutex mutex; interface::Module *module; ModuleWithMutex(interface::Module *module=NULL): module(module){} }; up_<rccpp::Compiler> m_compiler; ss_ m_modules_path; sm_<ss_, ModuleWithMutex> m_modules; interface::Mutex m_modules_mutex; sv_<interface::Event> m_event_queue; interface::Mutex m_event_queue_mutex; sv_<sv_<ModuleWithMutex*>> m_event_subs; interface::Mutex m_event_subs_mutex; CState(): m_compiler(rccpp::createCompiler()) { m_compiler->include_directories.push_back( g_server_config.interface_path); m_compiler->include_directories.push_back( g_server_config.interface_path+"/.."); m_compiler->include_directories.push_back( g_server_config.interface_path+"/../../3rdparty/cereal/include"); } ~CState() { interface::MutexScope ms(m_modules_mutex); for(auto &pair : m_modules){ ModuleWithMutex &mwm = pair.second; // Don't lock; it would only cause deadlocks delete mwm.module; } } void load_module(const ss_ &module_name, const ss_ &path) { interface::MutexScope ms(m_modules_mutex); std::cerr<<"Loading module "<<module_name<<" from "<<path<<std::endl; ss_ build_dst = g_server_config.rccpp_build_path + "/"+module_name+".so"; m_compiler->include_directories.push_back(m_modules_path); m_compiler->build(module_name, path+"/server/init.cpp", build_dst); m_compiler->include_directories.pop_back(); interface::Module *m = static_cast<interface::Module*>( m_compiler->construct(module_name.c_str(), this)); m_modules[module_name] = ModuleWithMutex(m); { ModuleWithMutex &mwm = m_modules[module_name]; interface::MutexScope ms2(mwm.mutex); mwm.module->init(); } } void load_modules(const ss_ &path) { m_modules_path = path; ss_ first_module_path = path+"/__loader"; load_module("__loader", first_module_path); // Allow loader load other modules emit_event(interface::Event("core:load_modules")); handle_events(); // Now that everyone is listening, we can fire the start event emit_event(interface::Event("core:start")); handle_events(); } ss_ get_modules_path() { return m_modules_path; } ss_ get_builtin_modules_path() { return g_server_config.share_path+"/builtin"; } /*interface::Module* get_module_u(const ss_ &module_name) { interface::MutexScope ms(m_modules_mutex); auto it = m_modules.find(module_name); if(it == m_modules.end()) return NULL; return it->second; } interface::Module* check_module_u(const ss_ &module_name) { interface::Module *m = get_module(module_name); if(m) return m; throw ModuleNotFoundException(ss_()+"Module not found: "+module_name); }*/ bool has_module(const ss_ &module_name) { interface::MutexScope ms(m_modules_mutex); auto it = m_modules.find(module_name); return (it != m_modules.end()); } void sub_event(struct interface::Module *module, const interface::Event::Type &type) { // Lock modules so that the subscribing one isn't removed asynchronously interface::MutexScope ms(m_modules_mutex); // Make sure module is a known instance ModuleWithMutex *mwm0 = NULL; ss_ module_name = "(unknown)"; for(auto &pair : m_modules){ ModuleWithMutex &mwm = pair.second; if(mwm.module == module){ mwm0 = &mwm; module_name = pair.first; break; } } if(mwm0 == nullptr){ std::cerr<<"sub_event(): Not a known module"<<std::endl; return; } interface::MutexScope ms2(m_event_subs_mutex); if(m_event_subs.size() <= type+1) m_event_subs.resize(type+1); sv_<ModuleWithMutex*> &sublist = m_event_subs[type]; if(std::find(sublist.begin(), sublist.end(), mwm0) != sublist.end()){ std::cerr<<"sub_event(): Already on list: "<<module_name<<std::endl; return; } std::cerr<<"sub_event(): "<<module_name<<" subscribed to "<<type<<std::endl; sublist.push_back(mwm0); } void emit_event(const interface::Event &event) { log_v("state", "emit_event(): type=%zu", event.type); interface::MutexScope ms(m_event_queue_mutex); m_event_queue.push_back(event); } void handle_events() { log_d("state", "handle_events()"); for(;;){ log_d("state", "m_event_subs.size()=%zu", m_event_subs.size()); sv_<interface::Event> event_queue_snapshot; sv_<sv_<ModuleWithMutex*>> event_subs_snapshot; { interface::MutexScope ms2(m_event_queue_mutex); interface::MutexScope ms3(m_event_subs_mutex); // Swap to clear queue m_event_queue.swap(event_queue_snapshot); // Copy to leave subscriptions active event_subs_snapshot = m_event_subs; } if(event_queue_snapshot.empty()){ break; } for(const interface::Event &event : event_queue_snapshot){ if(event.type >= event_subs_snapshot.size()){ log_d("state", "handle_events(): %zu: No subs " "(event_subs_snapshot.size()=%zu)", event.type, event_subs_snapshot.size()); continue; } sv_<ModuleWithMutex*> &sublist = event_subs_snapshot[event.type]; if(sublist.empty()){ log_d("state", "handle_events(): %zu: No subs", event.type); continue; } log_d("state", "handle_events(): %zu: Handling", event.type); for(ModuleWithMutex *mwm : sublist){ interface::MutexScope mwm_ms(mwm->mutex); mwm->module->event(event); } } } } }; State* createState() { return new CState(); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: canvasgraphichelper.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-10-12 15:00:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cppcanvas.hxx" #include <canvasgraphichelper.hxx> #ifndef _COM_SUN_STAR_RENDERING_XGRAPHICDEVICE_HPP_ #include <com/sun/star/rendering/XGraphicDevice.hpp> #endif #ifndef _COM_SUN_STAR_RENDERING_XPOLYPOLYGON2D_HPP_ #include <com/sun/star/rendering/XPolyPolygon2D.hpp> #endif #ifndef _CANVAS_CANVASTOOLS_HXX #include <canvas/canvastools.hxx> #endif #ifndef _BGFX_TOOLS_CANVASTOOLS_HXX #include <basegfx/tools/canvastools.hxx> #endif #ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX #include <basegfx/matrix/b2dhommatrix.hxx> #endif #include <cppcanvas/polypolygon.hxx> #include <tools.hxx> using namespace ::com::sun::star; /* Implementation of CanvasGraphicHelper class */ namespace cppcanvas { namespace internal { CanvasGraphicHelper::CanvasGraphicHelper( const CanvasSharedPtr& rParentCanvas ) : maClipPolyPolygon(), mpCanvas( rParentCanvas ), mxGraphicDevice() { OSL_ENSURE( mpCanvas.get() != NULL && mpCanvas->getUNOCanvas().is(), "CanvasGraphicHelper::CanvasGraphicHelper: no valid canvas" ); if( mpCanvas.get() != NULL && mpCanvas->getUNOCanvas().is() ) { mxGraphicDevice = mpCanvas->getUNOCanvas()->getDevice(); } ::canvas::tools::initRenderState( maRenderState ); } void CanvasGraphicHelper::setTransformation( const ::basegfx::B2DHomMatrix& rMatrix ) { ::canvas::tools::setRenderStateTransform( maRenderState, rMatrix ); } ::basegfx::B2DHomMatrix CanvasGraphicHelper::getTransformation() const { ::basegfx::B2DHomMatrix aMatrix; return ::canvas::tools::getRenderStateTransform( aMatrix, maRenderState ); } void CanvasGraphicHelper::setClip( const ::basegfx::B2DPolyPolygon& rClipPoly ) { // TODO(T3): not thread-safe. B2DPolyPolygon employs copy-on-write maClipPolyPolygon = rClipPoly; maRenderState.Clip.clear(); } ::basegfx::B2DPolyPolygon CanvasGraphicHelper::getClip() const { return maClipPolyPolygon; } const rendering::RenderState& CanvasGraphicHelper::getRenderState() const { if( maClipPolyPolygon.count() && !maRenderState.Clip.is() ) { uno::Reference< rendering::XCanvas > xCanvas( mpCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return maRenderState; maRenderState.Clip = ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( xCanvas->getDevice(), maClipPolyPolygon ); } return maRenderState; } void CanvasGraphicHelper::setRGBAColor( Color::IntSRGBA aColor ) { maRenderState.DeviceColor = tools::intSRGBAToDoubleSequence( mxGraphicDevice, aColor ); } Color::IntSRGBA CanvasGraphicHelper::getRGBAColor() const { return tools::doubleSequenceToIntSRGBA( mxGraphicDevice, maRenderState.DeviceColor ); } void CanvasGraphicHelper::setCompositeOp( CompositeOp aOp ) { maRenderState.CompositeOperation = (sal_Int8)aOp; } CanvasGraphic::CompositeOp CanvasGraphicHelper::getCompositeOp() const { return static_cast<CompositeOp>(maRenderState.CompositeOperation); } CanvasSharedPtr CanvasGraphicHelper::getCanvas() const { return mpCanvas; } uno::Reference< rendering::XGraphicDevice > CanvasGraphicHelper::getGraphicDevice() const { return mxGraphicDevice; } } } <commit_msg>INTEGRATION: CWS presfixes12 (1.8.18); FILE MERGED 2007/06/19 11:25:23 thb 1.8.18.3: #i10000# Reversed order, seems that gcc does not handle the safe bool idiom correctly here 2007/06/18 14:33:23 thb 1.8.18.2: #i10000# Avoid boost::optional::get(), which changed semantics after 1.31 (breaks the build for --with-system-boost) 2007/03/08 21:37:07 thb 1.8.18.1: #i37778# Added extra setClip() method to be able to set no clip - setting a clip with zero polygons by definition clips everything<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: canvasgraphichelper.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2007-07-17 15:26:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cppcanvas.hxx" #include <canvasgraphichelper.hxx> #include <com/sun/star/rendering/XGraphicDevice.hpp> #include <com/sun/star/rendering/XPolyPolygon2D.hpp> #include <canvas/canvastools.hxx> #include <basegfx/tools/canvastools.hxx> #include <basegfx/matrix/b2dhommatrix.hxx> #include <cppcanvas/polypolygon.hxx> #include "tools.hxx" using namespace ::com::sun::star; /* Implementation of CanvasGraphicHelper class */ namespace cppcanvas { namespace internal { CanvasGraphicHelper::CanvasGraphicHelper( const CanvasSharedPtr& rParentCanvas ) : maClipPolyPolygon(), mpCanvas( rParentCanvas ), mxGraphicDevice() { OSL_ENSURE( mpCanvas.get() != NULL && mpCanvas->getUNOCanvas().is(), "CanvasGraphicHelper::CanvasGraphicHelper: no valid canvas" ); if( mpCanvas.get() != NULL && mpCanvas->getUNOCanvas().is() ) { mxGraphicDevice = mpCanvas->getUNOCanvas()->getDevice(); } ::canvas::tools::initRenderState( maRenderState ); } void CanvasGraphicHelper::setTransformation( const ::basegfx::B2DHomMatrix& rMatrix ) { ::canvas::tools::setRenderStateTransform( maRenderState, rMatrix ); } ::basegfx::B2DHomMatrix CanvasGraphicHelper::getTransformation() const { ::basegfx::B2DHomMatrix aMatrix; return ::canvas::tools::getRenderStateTransform( aMatrix, maRenderState ); } void CanvasGraphicHelper::setClip( const ::basegfx::B2DPolyPolygon& rClipPoly ) { // TODO(T3): not thread-safe. B2DPolyPolygon employs copy-on-write maClipPolyPolygon.reset( rClipPoly ); maRenderState.Clip.clear(); } void CanvasGraphicHelper::setClip() { maClipPolyPolygon.reset(); maRenderState.Clip.clear(); } ::basegfx::B2DPolyPolygon const* CanvasGraphicHelper::getClip() const { return !maClipPolyPolygon ? NULL : &(*maClipPolyPolygon); } const rendering::RenderState& CanvasGraphicHelper::getRenderState() const { if( maClipPolyPolygon && !maRenderState.Clip.is() ) { uno::Reference< rendering::XCanvas > xCanvas( mpCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return maRenderState; maRenderState.Clip = ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( xCanvas->getDevice(), *maClipPolyPolygon ); } return maRenderState; } void CanvasGraphicHelper::setRGBAColor( Color::IntSRGBA aColor ) { maRenderState.DeviceColor = tools::intSRGBAToDoubleSequence( mxGraphicDevice, aColor ); } Color::IntSRGBA CanvasGraphicHelper::getRGBAColor() const { return tools::doubleSequenceToIntSRGBA( mxGraphicDevice, maRenderState.DeviceColor ); } void CanvasGraphicHelper::setCompositeOp( CompositeOp aOp ) { maRenderState.CompositeOperation = (sal_Int8)aOp; } CanvasGraphic::CompositeOp CanvasGraphicHelper::getCompositeOp() const { return static_cast<CompositeOp>(maRenderState.CompositeOperation); } CanvasSharedPtr CanvasGraphicHelper::getCanvas() const { return mpCanvas; } uno::Reference< rendering::XGraphicDevice > CanvasGraphicHelper::getGraphicDevice() const { return mxGraphicDevice; } } } <|endoftext|>
<commit_before>/** * @file BoxPacketTest.cpp * @brief BoxPacket class tester. * @author zer0 * @date 2018-10-24 * @date 2018-11-07 (Rename: TbagPacketTest -> BoxPacketTest) */ #include <gtest/gtest.h> #include <tester/DemoAsset.hpp> #include <libtbag/proto/BoxPacket.hpp> using namespace libtbag; using namespace libtbag::proto; TEST(BoxPacketTest, UpdateSelf) { uint64_t const TEST_ID = 10; int32_t const TEST_TYPE = 20; int32_t const TEST_CODE = 30; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.update(BUILD_BUFFER)); ASSERT_EQ(TEST_ID, packet.id()); ASSERT_EQ(TEST_TYPE, packet.type()); ASSERT_EQ(TEST_CODE, packet.code()); ASSERT_TRUE(packet.boxes().empty()); } TEST(BoxPacketTest, UpdateSelf_BagEx) { using namespace libtbag::container; std::string const BAG_KEY = "bag"; Box bag; bag.resize<int32_t>(2, 3); ASSERT_EQ(BoxTypeTable::BTT_INT32, bag.getType()); ASSERT_EQ(2*3, bag.size()); ASSERT_EQ(2, bag.size(0)); ASSERT_EQ(3, bag.size(1)); for (int i = 0; i < bag.size(); ++i) { *(bag.cast<int32_t>() + i) = i; } BoxPacket::BoxMap map; map.insert(std::make_pair(BAG_KEY, bag)); ASSERT_EQ(1, map.size()); BoxPacket packet1; ASSERT_EQ(Err::E_SUCCESS, packet1.build(map)); auto const BUILD_BUFFER = packet1.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); BoxPacket packet2; ASSERT_EQ(Err::E_SUCCESS, packet2.update(BUILD_BUFFER)); ASSERT_FALSE(packet2.boxes().empty()); ASSERT_EQ(1, packet2.boxes().size()); auto bag_result = packet2.boxes()[BAG_KEY]; ASSERT_EQ(BoxTypeTable::BTT_INT32, bag_result.getType()); ASSERT_EQ(2*3, bag_result.size()); ASSERT_EQ(2, bag_result.size(0)); ASSERT_EQ(3, bag_result.size(1)); ASSERT_EQ(0, bag_result.at<int32_t>(0, 0)); ASSERT_EQ(1, bag_result.at<int32_t>(0, 1)); ASSERT_EQ(2, bag_result.at<int32_t>(0, 2)); ASSERT_EQ(3, bag_result.at<int32_t>(1, 0)); ASSERT_EQ(4, bag_result.at<int32_t>(1, 1)); ASSERT_EQ(5, bag_result.at<int32_t>(1, 2)); } TEST(BoxPacketTest, UpdateSelf_String) { std::string const TEST_TEXT = "BoxPacketTest.UpdateSelf_BagEx"; uint64_t const TEST_ID = 10; int32_t const TEST_TYPE = 20; int32_t const TEST_CODE = 30; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_TEXT, TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.update(BUILD_BUFFER)); ASSERT_EQ(TEST_ID, packet.id()); ASSERT_EQ(TEST_TYPE, packet.type()); ASSERT_EQ(TEST_CODE, packet.code()); ASSERT_FALSE(packet.boxes().empty()); ASSERT_EQ(1, packet.boxes().size()); ASSERT_EQ(TEST_TEXT, packet.boxes().begin()->first); ASSERT_FALSE(packet.boxes().begin()->second.exists()); } TEST(BoxPacketTest, UpdateSelf_KeyValue) { std::string const TEST_KEY = "BoxPacketTest"; std::string const TEST_VAL = "UpdateSelf_BagEx"; uint64_t const TEST_ID = 10; int32_t const TEST_TYPE = 20; int32_t const TEST_CODE = 30; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_KEY, TEST_VAL, TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.update(BUILD_BUFFER)); ASSERT_EQ(TEST_ID, packet.id()); ASSERT_EQ(TEST_TYPE, packet.type()); ASSERT_EQ(TEST_CODE, packet.code()); ASSERT_FALSE(packet.boxes().empty()); ASSERT_EQ(1, packet.boxes().size()); ASSERT_EQ(TEST_KEY, packet.boxes().begin()->first); ASSERT_TRUE(packet.boxes().begin()->second.exists()); ASSERT_EQ(TEST_VAL, packet.boxes().begin()->second.toString()); } TEST(BoxPacketTest, FindKey) { std::string const TEST_KEY = "BoxPacketTest"; std::string const TEST_VAL = "FindKey"; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_KEY, TEST_VAL)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); Err code = Err::E_UNKNOWN; auto bag1 = packet.findKey(BUILD_BUFFER, TEST_KEY, &code); ASSERT_EQ(Err::E_SUCCESS, code); ASSERT_TRUE(bag1.exists()); ASSERT_EQ(TEST_VAL, bag1.toString()); code = Err::E_UNKNOWN; auto bag2 = packet.findKey(BUILD_BUFFER, "NotFoundKey", &code); ASSERT_EQ(Err::E_ENFOUND, code); ASSERT_FALSE(bag2.exists()); } TEST(BoxPacketTest, Assign) { uint64_t const TEST_ID = 1; int32_t const TEST_TYPE = 2; int32_t const TEST_CODE = 3; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER1 = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER1.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.assign(BUILD_BUFFER1)); auto const BUILD_BUFFER2 = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER2.empty()); ASSERT_TRUE(std::equal(BUILD_BUFFER1.begin(), BUILD_BUFFER1.end(), BUILD_BUFFER2.begin(), BUILD_BUFFER2.end())); } TEST(BoxPacketTest, FileSaveLoad) { tttDir(true, true); auto const FILE_PATH = tttDir_Get() / "mats"; using namespace libtbag::container; std::string const BAG1_KEY = "bag1"; std::string const BAG1_VAL = "Test"; std::string const BAG2_KEY = "bag2"; std::vector<int32_t> const BAG2_VAL = {1, 2, 3, 4}; Box bag1 = BAG1_VAL; Box bag2 = BAG2_VAL; ASSERT_EQ(BoxTypeTable::BTT_INT8, bag1.getType()); ASSERT_EQ(BoxTypeTable::BTT_INT32, bag2.getType()); uint64_t const TEST_ID = 1; int32_t const TEST_TYPE = 2; int32_t const TEST_CODE = 3; BoxPacket::BoxMap map; map.insert(std::make_pair(BAG1_KEY, bag1)); map.insert(std::make_pair(BAG2_KEY, bag2)); ASSERT_EQ(2, map.size()); BoxPacket packet1; ASSERT_EQ(Err::E_SUCCESS, packet1.build(map, TEST_ID, TEST_TYPE, TEST_CODE)); ASSERT_FALSE(FILE_PATH.exists()); ASSERT_EQ(Err::E_SUCCESS, packet1.saveFile(FILE_PATH)); ASSERT_TRUE(FILE_PATH.exists()); BoxPacket packet2; ASSERT_EQ(Err::E_SUCCESS, packet2.loadFile(FILE_PATH)); ASSERT_EQ(TEST_ID, packet2.id()); ASSERT_EQ(TEST_TYPE, packet2.type()); ASSERT_EQ(TEST_CODE, packet2.code()); ASSERT_FALSE(packet2.boxes().empty()); ASSERT_EQ(2, packet2.boxes().size()); auto bag1_result = packet2.boxes()[BAG1_KEY]; auto bag2_result = packet2.boxes()[BAG2_KEY]; ASSERT_EQ(BoxTypeTable::BTT_INT8, bag1_result.getType()); ASSERT_EQ(BAG1_VAL.size(), bag1_result.size()); ASSERT_EQ(1, bag1_result.dims()); ASSERT_EQ(BAG1_VAL, bag1_result.toString()); ASSERT_EQ(BoxTypeTable::BTT_INT32, bag2_result.getType()); ASSERT_EQ(BAG2_VAL.size(), bag2_result.size()); ASSERT_EQ(1, bag2_result.dims()); auto * bag2_begin = bag2_result.cast<int32_t>(); auto * bag2_end = bag2_result.cast<int32_t>() + bag2_result.size(); ASSERT_TRUE(std::equal(BAG2_VAL.begin(), BAG2_VAL.end(), bag2_begin, bag2_end)); } <commit_msg>Create BoxPacketTest.UpdateSelf_DataSlice tester.<commit_after>/** * @file BoxPacketTest.cpp * @brief BoxPacket class tester. * @author zer0 * @date 2018-10-24 * @date 2018-11-07 (Rename: TbagPacketTest -> BoxPacketTest) */ #include <gtest/gtest.h> #include <tester/DemoAsset.hpp> #include <libtbag/proto/BoxPacket.hpp> using namespace libtbag; using namespace libtbag::proto; TEST(BoxPacketTest, UpdateSelf) { uint64_t const TEST_ID = 10; int32_t const TEST_TYPE = 20; int32_t const TEST_CODE = 30; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.update(BUILD_BUFFER)); ASSERT_EQ(TEST_ID, packet.id()); ASSERT_EQ(TEST_TYPE, packet.type()); ASSERT_EQ(TEST_CODE, packet.code()); ASSERT_TRUE(packet.boxes().empty()); } TEST(BoxPacketTest, UpdateSelf_DataSlice) { uint64_t const TEST_ID = 10; int32_t const TEST_TYPE = 20; int32_t const TEST_CODE = 30; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); auto const BUFFER_SIZE = BUILD_BUFFER.size(); BoxPacket::Buffer extend_buffer(BUFFER_SIZE + 1); std::copy(BUILD_BUFFER.begin(), BUILD_BUFFER.end(), extend_buffer.begin()); ASSERT_EQ(Err::E_PARSING, packet.update(extend_buffer.data(), BUFFER_SIZE - 1)); ASSERT_EQ(Err::E_SUCCESS, packet.update(extend_buffer.data(), BUFFER_SIZE + 0)); ASSERT_EQ(Err::E_SUCCESS, packet.update(extend_buffer.data(), BUFFER_SIZE + 1)); ASSERT_EQ(TEST_ID, packet.id()); ASSERT_EQ(TEST_TYPE, packet.type()); ASSERT_EQ(TEST_CODE, packet.code()); ASSERT_TRUE(packet.boxes().empty()); } TEST(BoxPacketTest, UpdateSelf_BagEx) { using namespace libtbag::container; std::string const BAG_KEY = "bag"; Box bag; bag.resize<int32_t>(2, 3); ASSERT_EQ(BoxTypeTable::BTT_INT32, bag.getType()); ASSERT_EQ(2*3, bag.size()); ASSERT_EQ(2, bag.size(0)); ASSERT_EQ(3, bag.size(1)); for (int i = 0; i < bag.size(); ++i) { *(bag.cast<int32_t>() + i) = i; } BoxPacket::BoxMap map; map.insert(std::make_pair(BAG_KEY, bag)); ASSERT_EQ(1, map.size()); BoxPacket packet1; ASSERT_EQ(Err::E_SUCCESS, packet1.build(map)); auto const BUILD_BUFFER = packet1.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); BoxPacket packet2; ASSERT_EQ(Err::E_SUCCESS, packet2.update(BUILD_BUFFER)); ASSERT_FALSE(packet2.boxes().empty()); ASSERT_EQ(1, packet2.boxes().size()); auto bag_result = packet2.boxes()[BAG_KEY]; ASSERT_EQ(BoxTypeTable::BTT_INT32, bag_result.getType()); ASSERT_EQ(2*3, bag_result.size()); ASSERT_EQ(2, bag_result.size(0)); ASSERT_EQ(3, bag_result.size(1)); ASSERT_EQ(0, bag_result.at<int32_t>(0, 0)); ASSERT_EQ(1, bag_result.at<int32_t>(0, 1)); ASSERT_EQ(2, bag_result.at<int32_t>(0, 2)); ASSERT_EQ(3, bag_result.at<int32_t>(1, 0)); ASSERT_EQ(4, bag_result.at<int32_t>(1, 1)); ASSERT_EQ(5, bag_result.at<int32_t>(1, 2)); } TEST(BoxPacketTest, UpdateSelf_String) { std::string const TEST_TEXT = "BoxPacketTest.UpdateSelf_BagEx"; uint64_t const TEST_ID = 10; int32_t const TEST_TYPE = 20; int32_t const TEST_CODE = 30; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_TEXT, TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.update(BUILD_BUFFER)); ASSERT_EQ(TEST_ID, packet.id()); ASSERT_EQ(TEST_TYPE, packet.type()); ASSERT_EQ(TEST_CODE, packet.code()); ASSERT_FALSE(packet.boxes().empty()); ASSERT_EQ(1, packet.boxes().size()); ASSERT_EQ(TEST_TEXT, packet.boxes().begin()->first); ASSERT_FALSE(packet.boxes().begin()->second.exists()); } TEST(BoxPacketTest, UpdateSelf_KeyValue) { std::string const TEST_KEY = "BoxPacketTest"; std::string const TEST_VAL = "UpdateSelf_BagEx"; uint64_t const TEST_ID = 10; int32_t const TEST_TYPE = 20; int32_t const TEST_CODE = 30; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_KEY, TEST_VAL, TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.update(BUILD_BUFFER)); ASSERT_EQ(TEST_ID, packet.id()); ASSERT_EQ(TEST_TYPE, packet.type()); ASSERT_EQ(TEST_CODE, packet.code()); ASSERT_FALSE(packet.boxes().empty()); ASSERT_EQ(1, packet.boxes().size()); ASSERT_EQ(TEST_KEY, packet.boxes().begin()->first); ASSERT_TRUE(packet.boxes().begin()->second.exists()); ASSERT_EQ(TEST_VAL, packet.boxes().begin()->second.toString()); } TEST(BoxPacketTest, FindKey) { std::string const TEST_KEY = "BoxPacketTest"; std::string const TEST_VAL = "FindKey"; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_KEY, TEST_VAL)); auto const BUILD_BUFFER = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER.empty()); Err code = Err::E_UNKNOWN; auto bag1 = packet.findKey(BUILD_BUFFER, TEST_KEY, &code); ASSERT_EQ(Err::E_SUCCESS, code); ASSERT_TRUE(bag1.exists()); ASSERT_EQ(TEST_VAL, bag1.toString()); code = Err::E_UNKNOWN; auto bag2 = packet.findKey(BUILD_BUFFER, "NotFoundKey", &code); ASSERT_EQ(Err::E_ENFOUND, code); ASSERT_FALSE(bag2.exists()); } TEST(BoxPacketTest, Assign) { uint64_t const TEST_ID = 1; int32_t const TEST_TYPE = 2; int32_t const TEST_CODE = 3; BoxPacket packet; ASSERT_EQ(Err::E_SUCCESS, packet.build(TEST_ID, TEST_TYPE, TEST_CODE)); auto const BUILD_BUFFER1 = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER1.empty()); ASSERT_EQ(Err::E_SUCCESS, packet.assign(BUILD_BUFFER1)); auto const BUILD_BUFFER2 = packet.toBuffer(); ASSERT_FALSE(BUILD_BUFFER2.empty()); ASSERT_TRUE(std::equal(BUILD_BUFFER1.begin(), BUILD_BUFFER1.end(), BUILD_BUFFER2.begin(), BUILD_BUFFER2.end())); } TEST(BoxPacketTest, FileSaveLoad) { tttDir(true, true); auto const FILE_PATH = tttDir_Get() / "mats"; using namespace libtbag::container; std::string const BAG1_KEY = "bag1"; std::string const BAG1_VAL = "Test"; std::string const BAG2_KEY = "bag2"; std::vector<int32_t> const BAG2_VAL = {1, 2, 3, 4}; Box bag1 = BAG1_VAL; Box bag2 = BAG2_VAL; ASSERT_EQ(BoxTypeTable::BTT_INT8, bag1.getType()); ASSERT_EQ(BoxTypeTable::BTT_INT32, bag2.getType()); uint64_t const TEST_ID = 1; int32_t const TEST_TYPE = 2; int32_t const TEST_CODE = 3; BoxPacket::BoxMap map; map.insert(std::make_pair(BAG1_KEY, bag1)); map.insert(std::make_pair(BAG2_KEY, bag2)); ASSERT_EQ(2, map.size()); BoxPacket packet1; ASSERT_EQ(Err::E_SUCCESS, packet1.build(map, TEST_ID, TEST_TYPE, TEST_CODE)); ASSERT_FALSE(FILE_PATH.exists()); ASSERT_EQ(Err::E_SUCCESS, packet1.saveFile(FILE_PATH)); ASSERT_TRUE(FILE_PATH.exists()); BoxPacket packet2; ASSERT_EQ(Err::E_SUCCESS, packet2.loadFile(FILE_PATH)); ASSERT_EQ(TEST_ID, packet2.id()); ASSERT_EQ(TEST_TYPE, packet2.type()); ASSERT_EQ(TEST_CODE, packet2.code()); ASSERT_FALSE(packet2.boxes().empty()); ASSERT_EQ(2, packet2.boxes().size()); auto bag1_result = packet2.boxes()[BAG1_KEY]; auto bag2_result = packet2.boxes()[BAG2_KEY]; ASSERT_EQ(BoxTypeTable::BTT_INT8, bag1_result.getType()); ASSERT_EQ(BAG1_VAL.size(), bag1_result.size()); ASSERT_EQ(1, bag1_result.dims()); ASSERT_EQ(BAG1_VAL, bag1_result.toString()); ASSERT_EQ(BoxTypeTable::BTT_INT32, bag2_result.getType()); ASSERT_EQ(BAG2_VAL.size(), bag2_result.size()); ASSERT_EQ(1, bag2_result.dims()); auto * bag2_begin = bag2_result.cast<int32_t>(); auto * bag2_end = bag2_result.cast<int32_t>() + bag2_result.size(); ASSERT_TRUE(std::equal(BAG2_VAL.begin(), BAG2_VAL.end(), bag2_begin, bag2_end)); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <reflection_binding.hpp> class test_class1 { public: int test_member1(int i) { return i * 2; } int test_member2() { return local_; } int test_member3() const { return local_; } private: int local_ = 111; }; TEST_CASE("test binding of member functions", "[member_function_detail::generic_member_function_bind_point]") { auto bind_point1 = &shadow::member_function_detail::generic_member_function_bind_point< decltype(&test_class1::test_member1), &test_class1::test_member1>; auto bind_point2 = &shadow::member_function_detail::generic_member_function_bind_point< decltype(&test_class1::test_member2), &test_class1::test_member2>; auto bind_point3 = &shadow::member_function_detail::generic_member_function_bind_point< decltype(&test_class1::test_member3), &test_class1::test_member3>; SECTION("create a test_class1 and an int") { shadow::any t1 = test_class1(); SECTION("create an int as argument and call 1") { shadow::any anint = 20; auto ret_val = bind_point1(t1, &anint); REQUIRE(ret_val.get<int>() == 40); } SECTION("call 2") { auto ret_val = bind_point2(t1, nullptr); REQUIRE(ret_val.get<int>() == 111); } SECTION("call 3") { auto ret_val = bind_point3(t1, nullptr); REQUIRE(ret_val.get<int>() == 111); } } } <commit_msg>Add unit test for modifying void member function. modified: tests/test_member_function_binding.cpp<commit_after>#include "catch.hpp" #include <reflection_binding.hpp> class test_class1 { public: int test_member1(int i) { return i * 2; } int test_member2() { return local_; } int test_member3() const { return local_; } void test_member4(int i) { local_ = i; } int local_ = 111; }; TEST_CASE("test binding of member functions", "[member_function_detail::generic_member_function_bind_point]") { auto bind_point1 = &shadow::member_function_detail::generic_member_function_bind_point< decltype(&test_class1::test_member1), &test_class1::test_member1>; auto bind_point2 = &shadow::member_function_detail::generic_member_function_bind_point< decltype(&test_class1::test_member2), &test_class1::test_member2>; auto bind_point3 = &shadow::member_function_detail::generic_member_function_bind_point< decltype(&test_class1::test_member3), &test_class1::test_member3>; auto bind_point4 = &shadow::member_function_detail::generic_member_function_bind_point< decltype(&test_class1::test_member4), &test_class1::test_member4>; SECTION("create a test_class1 and an int") { shadow::any t1 = test_class1(); SECTION("create an int as argument and call 1") { shadow::any anint = 20; auto ret_val = bind_point1(t1, &anint); REQUIRE(ret_val.get<int>() == 40); } SECTION("call 2") { auto ret_val = bind_point2(t1, nullptr); REQUIRE(ret_val.get<int>() == 111); } SECTION("call 3") { auto ret_val = bind_point3(t1, nullptr); REQUIRE(ret_val.get<int>() == 111); } SECTION("create an int as argument and call 4") { shadow::any anint = 44; bind_point4(t1, &anint); REQUIRE(t1.get<test_class1>().local_ == 44); } } } <|endoftext|>
<commit_before>// -*- coding: us-ascii-unix -*- #include "test-sys/test.hh" #include "geo/int-size.hh" #include "text/char-constants.hh" #include "text/split-string.hh" #include "util/optional.hh" #include "util/distinct.hh" namespace{ using namespace faint; class category_test_split_string; using px_per_char = Distinct<int, category_test_split_string, 0>; class TextInfo_split_string : public TextInfo{ public: TextInfo_split_string(px_per_char pixelsPerChar) : m_pixelsPerChar(pixelsPerChar.Get()) {} int GetWidth(const utf8_string& str) const override{ // For easier testing, simply make each character // m_pixelsPerChar-wide, rather than requiring a font and dc. return resigned(str.size()) * m_pixelsPerChar; } int ComputeRowHeight() const override{ FAIL(); } IntSize TextSize(const faint::utf8_string&) const override{ FAIL(); } private: int m_pixelsPerChar; }; } // namespace void test_split_string(){ using namespace faint; { // No splitting TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "This is sort of a sentence.", max_width_t(280.0)); ASSERT(lines.size() == 1); EQUAL(lines[0].text, "This is sort of a sentence."); NOT(lines[0].hardBreak); } { // Split at space TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Hello world", max_width_t(60.0)); ASSERT(lines.size() == 2); EQUAL(lines[0].text, "Hello "); NOT(lines[0].hardBreak); EQUAL(lines[1].text, "world"); NOT(lines[1].hardBreak); } { // Split at hard line break TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Hello\nworld", max_width_t(60.0)); ASSERT(lines.size() == 2); EQUAL(lines[0].text, "Hello "); // Fixme: extra space? VERIFY(lines[0].hardBreak); EQUAL(lines[1].text, "world"); NOT(lines[1].hardBreak); } { // Split within word TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Machiavellianism", max_width_t(80.0)); ASSERT(lines.size() == 2); EQUAL(lines[0].text, "Machiave"); NOT(lines[0].hardBreak); EQUAL(lines[1].text, "llianism"); NOT(lines[1].hardBreak); } { // Split within word TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Machiavellianism the employment of cunning and duplicity\nin statecraft or in general conduct", max_width_t(80.0)); ASSERT(lines.size() == 15); EQUAL(lines[0].text, "Machiave"); NOT(lines[0].hardBreak); EQUAL(lines[1].text, "llianism "); NOT(lines[1].hardBreak); EQUAL(lines[2].text, "the "); EQUAL(lines[3].text, "emplo"); EQUAL(lines[4].text, "yment of "); EQUAL(lines[5].text, "cunning "); EQUAL(lines[6].text, "and "); EQUAL(lines[7].text, "dupl"); EQUAL(lines[8].text, "icity "); EQUAL(lines[9].text, "in "); EQUAL(lines[10].text, "state"); EQUAL(lines[11].text, "craft or "); EQUAL(lines[12].text, "in "); EQUAL(lines[13].text, "general "); EQUAL(lines[14].text, "conduct"); } { TextInfo_split_string ti(px_per_char(10)); // Unicode auto lines = split_string(ti, utf8_string(5, chars::snowman) + " " + utf8_string(5, chars::greek_capital_letter_delta), max_width_t(60.0)); EQUAL(lines[0].text, utf8_string(5, chars::snowman) + " "); EQUAL(lines[1].text, utf8_string(5, chars::greek_capital_letter_delta)); } } <commit_msg>Removed incorrect fixme comment.<commit_after>// -*- coding: us-ascii-unix -*- #include "test-sys/test.hh" #include "geo/int-size.hh" #include "text/char-constants.hh" #include "text/split-string.hh" #include "util/optional.hh" #include "util/distinct.hh" namespace{ using namespace faint; class category_test_split_string; using px_per_char = Distinct<int, category_test_split_string, 0>; class TextInfo_split_string : public TextInfo{ public: TextInfo_split_string(px_per_char pixelsPerChar) : m_pixelsPerChar(pixelsPerChar.Get()) {} int GetWidth(const utf8_string& str) const override{ // For easier testing, simply make each character // m_pixelsPerChar-wide, rather than requiring a font and dc. return resigned(str.size()) * m_pixelsPerChar; } int ComputeRowHeight() const override{ FAIL(); } IntSize TextSize(const faint::utf8_string&) const override{ FAIL(); } private: int m_pixelsPerChar; }; } // namespace void test_split_string(){ using namespace faint; { // No splitting TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "This is sort of a sentence.", max_width_t(280.0)); ASSERT(lines.size() == 1); EQUAL(lines[0].text, "This is sort of a sentence."); NOT(lines[0].hardBreak); } { // Split at space TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Hello world", max_width_t(60.0)); ASSERT(lines.size() == 2); EQUAL(lines[0].text, "Hello "); NOT(lines[0].hardBreak); EQUAL(lines[1].text, "world"); NOT(lines[1].hardBreak); } { // Split at hard line break TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Hello\nworld", max_width_t(60.0)); ASSERT(lines.size() == 2); EQUAL(lines[0].text, "Hello "); // Space stands in for \n VERIFY(lines[0].hardBreak); EQUAL(lines[1].text, "world"); NOT(lines[1].hardBreak); } { // Split within word TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Machiavellianism", max_width_t(80.0)); ASSERT(lines.size() == 2); EQUAL(lines[0].text, "Machiave"); NOT(lines[0].hardBreak); EQUAL(lines[1].text, "llianism"); NOT(lines[1].hardBreak); } { // Split within word TextInfo_split_string ti(px_per_char(10)); auto lines = split_string(ti, "Machiavellianism the employment of cunning and duplicity\nin statecraft or in general conduct", max_width_t(80.0)); ASSERT(lines.size() == 15); EQUAL(lines[0].text, "Machiave"); NOT(lines[0].hardBreak); EQUAL(lines[1].text, "llianism "); NOT(lines[1].hardBreak); EQUAL(lines[2].text, "the "); EQUAL(lines[3].text, "emplo"); EQUAL(lines[4].text, "yment of "); EQUAL(lines[5].text, "cunning "); EQUAL(lines[6].text, "and "); EQUAL(lines[7].text, "dupl"); EQUAL(lines[8].text, "icity "); EQUAL(lines[9].text, "in "); EQUAL(lines[10].text, "state"); EQUAL(lines[11].text, "craft or "); EQUAL(lines[12].text, "in "); EQUAL(lines[13].text, "general "); EQUAL(lines[14].text, "conduct"); } { TextInfo_split_string ti(px_per_char(10)); // Unicode auto lines = split_string(ti, utf8_string(5, chars::snowman) + " " + utf8_string(5, chars::greek_capital_letter_delta), max_width_t(60.0)); EQUAL(lines[0].text, utf8_string(5, chars::snowman) + " "); EQUAL(lines[1].text, utf8_string(5, chars::greek_capital_letter_delta)); } } <|endoftext|>
<commit_before>/* * Renderer.cpp * * Renders the box2d content */ #include <vector> #include <stdio.h> #include <Box2D/Box2D.h> #include <SDL2/SDL.h> #include <SDL2/SDL_main.h> #include <SDL2/SDL2_gfxPrimitives.h> #include "Renderer.h" #include "UserData.h" const float Renderer::NUMERATOR = 7.0f; const float Renderer::DENOMINATOR = 9.0f; const float Renderer::SCALING = NUMERATOR / DENOMINATOR; const float Renderer::PADDING_PERCENT = (DENOMINATOR - NUMERATOR) / DENOMINATOR / 2; int Renderer::metersToPixels(const float &meters){ return round(meters * oneMeterInPX); } b2Vec2 Renderer::toScreenCoords(const b2Vec2 &position){ return b2Vec2 ( round(width * PADDING_PERCENT) + metersToPixels(position.x), round(height * PADDING_PERCENT) + metersToPixels(position.y) ); } Renderer::Renderer(int width, int height, const b2World *world) : width(width), height(height), world(world){ SDL_Init( SDL_INIT_VIDEO ); window = SDL_CreateWindow( "PinballBot", // window title SDL_WINDOWPOS_CENTERED, // initial x position SDL_WINDOWPOS_CENTERED, // initial y position this->width, // width, in pixels this->height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI //enables retina support ); if (window == nullptr) { printf("Could not create window: %s\n", SDL_GetError()); SDL_Quit(); return; } //updates the width and height if there's a high DPI and calc other vars afterwards SDL_GL_GetDrawableSize(window, &this->width, &this->height); oneMeterInPX = round(SCALING * this->height); /* one meter is equal to the height */ renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); //white background SDL_RenderClear(renderer); } Renderer::~Renderer(){ SDL_DestroyWindow(window); SDL_Quit(); } void Renderer::render(){ for(const b2Body *body = this->world->GetBodyList(); body; body = body->GetNext()){ UserData *userData = (UserData*) body->GetUserData(); if(!userData){ printf("DIDN'T DRAW! Body Position: X(%f), Y(%f); Type: N/A\n", body->GetPosition().x, body->GetPosition().y); } for(const b2Fixture *fixture = body->GetFixtureList(); fixture; fixture = fixture->GetNext()){ b2Shape::Type shapeType = fixture->GetType(); if (shapeType == b2Shape::e_circle ){ b2CircleShape* circleShape = (b2CircleShape*)fixture->GetShape(); this->drawCircle(body->GetPosition(), circleShape->m_radius, userData->red, userData->green, userData->blue, userData->alpha, userData->filled); }else if (shapeType == b2Shape::e_polygon ){ b2PolygonShape* polygonShape = (b2PolygonShape*)fixture->GetShape(); const b2Vec2 *vertices_orig = polygonShape->m_vertices; std::vector<b2Vec2> vertices(polygonShape->GetVertexCount()); for(int i=0;i < polygonShape->GetVertexCount();i++){ vertices[i] = body->GetWorldPoint(vertices_orig[i]); } this->drawPolygon(vertices.data(), polygonShape->GetVertexCount(), userData->red, userData->green, userData->blue, userData->alpha, userData->filled); }else if(shapeType == b2Shape::e_edge ){ b2EdgeShape* edgeShape = (b2EdgeShape*)fixture->GetShape(); drawLine(body->GetWorldPoint(edgeShape->m_vertex1), body->GetWorldPoint(edgeShape->m_vertex2), userData->red, userData->green, userData->blue, userData->alpha); }else if(shapeType == b2Shape::e_chain){ b2ChainShape* chainShape = (b2ChainShape*)fixture->GetShape(); for(int j=0;j < (chainShape->m_count - 1);j++){ drawLine(body->GetWorldPoint(chainShape->m_vertices[j]), body->GetWorldPoint(chainShape->m_vertices[j+1]), userData->red, userData->green, userData->blue, userData->alpha); } }else{ printf("Unknown shapeType: %d!", shapeType); } } } this->redraw(); } void Renderer::redraw(){ SDL_RenderPresent(renderer); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); } void Renderer::drawLine(const b2Vec2& p1, const b2Vec2& p2, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha){ b2Vec2 from = toScreenCoords(p1); b2Vec2 to = toScreenCoords(p2); lineRGBA(renderer, (Sint16) from.x, (Sint16) from.y, (Sint16) to.x, (Sint16) to.y, red, green, blue, alpha); } void Renderer::drawPolygon(const b2Vec2* vertices, int32 vertexCount, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ std::vector<short> x(vertexCount); std::vector<short> y(vertexCount); for(int i=0;i<vertexCount;i++){ b2Vec2 vec = toScreenCoords(vertices[i]); x[i] = (short) vec.x; y[i] = (short) vec.y; } if(filled){ filledPolygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); }else{ polygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); } } void Renderer::drawCircle(const b2Vec2& center, float32 radius, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ b2Vec2 coords = toScreenCoords(center); if(filled){ filledCircleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); }else{ circleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); } } <commit_msg>Accessed round() via the std namespace<commit_after>/* * Renderer.cpp * * Renders the box2d content */ #include <vector> #include <stdio.h> #include <cmath> #include <Box2D/Box2D.h> #include <SDL2/SDL.h> #include <SDL2/SDL_main.h> #include <SDL2/SDL2_gfxPrimitives.h> #include "Renderer.h" #include "UserData.h" const float Renderer::NUMERATOR = 7.0f; const float Renderer::DENOMINATOR = 9.0f; const float Renderer::SCALING = NUMERATOR / DENOMINATOR; const float Renderer::PADDING_PERCENT = (DENOMINATOR - NUMERATOR) / DENOMINATOR / 2; int Renderer::metersToPixels(const float &meters){ return round(meters * oneMeterInPX); } b2Vec2 Renderer::toScreenCoords(const b2Vec2 &position){ return b2Vec2 ( std::round(width * PADDING_PERCENT) + metersToPixels(position.x), std::round(height * PADDING_PERCENT) + metersToPixels(position.y) ); } Renderer::Renderer(int width, int height, const b2World *world) : width(width), height(height), world(world){ SDL_Init( SDL_INIT_VIDEO ); window = SDL_CreateWindow( "PinballBot", // window title SDL_WINDOWPOS_CENTERED, // initial x position SDL_WINDOWPOS_CENTERED, // initial y position this->width, // width, in pixels this->height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI //enables retina support ); if (window == nullptr) { printf("Could not create window: %s\n", SDL_GetError()); SDL_Quit(); return; } //updates the width and height if there's a high DPI and calc other vars afterwards SDL_GL_GetDrawableSize(window, &this->width, &this->height); oneMeterInPX = round(SCALING * this->height); /* one meter is equal to the height */ renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); //white background SDL_RenderClear(renderer); } Renderer::~Renderer(){ SDL_DestroyWindow(window); SDL_Quit(); } void Renderer::render(){ for(const b2Body *body = this->world->GetBodyList(); body; body = body->GetNext()){ UserData *userData = (UserData*) body->GetUserData(); if(!userData){ printf("DIDN'T DRAW! Body Position: X(%f), Y(%f); Type: N/A\n", body->GetPosition().x, body->GetPosition().y); } for(const b2Fixture *fixture = body->GetFixtureList(); fixture; fixture = fixture->GetNext()){ b2Shape::Type shapeType = fixture->GetType(); if (shapeType == b2Shape::e_circle ){ b2CircleShape* circleShape = (b2CircleShape*)fixture->GetShape(); this->drawCircle(body->GetPosition(), circleShape->m_radius, userData->red, userData->green, userData->blue, userData->alpha, userData->filled); }else if (shapeType == b2Shape::e_polygon ){ b2PolygonShape* polygonShape = (b2PolygonShape*)fixture->GetShape(); const b2Vec2 *vertices_orig = polygonShape->m_vertices; std::vector<b2Vec2> vertices(polygonShape->GetVertexCount()); for(int i=0;i < polygonShape->GetVertexCount();i++){ vertices[i] = body->GetWorldPoint(vertices_orig[i]); } this->drawPolygon(vertices.data(), polygonShape->GetVertexCount(), userData->red, userData->green, userData->blue, userData->alpha, userData->filled); }else if(shapeType == b2Shape::e_edge ){ b2EdgeShape* edgeShape = (b2EdgeShape*)fixture->GetShape(); drawLine(body->GetWorldPoint(edgeShape->m_vertex1), body->GetWorldPoint(edgeShape->m_vertex2), userData->red, userData->green, userData->blue, userData->alpha); }else if(shapeType == b2Shape::e_chain){ b2ChainShape* chainShape = (b2ChainShape*)fixture->GetShape(); for(int j=0;j < (chainShape->m_count - 1);j++){ drawLine(body->GetWorldPoint(chainShape->m_vertices[j]), body->GetWorldPoint(chainShape->m_vertices[j+1]), userData->red, userData->green, userData->blue, userData->alpha); } }else{ printf("Unknown shapeType: %d!", shapeType); } } } this->redraw(); } void Renderer::redraw(){ SDL_RenderPresent(renderer); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); } void Renderer::drawLine(const b2Vec2& p1, const b2Vec2& p2, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha){ b2Vec2 from = toScreenCoords(p1); b2Vec2 to = toScreenCoords(p2); lineRGBA(renderer, (Sint16) from.x, (Sint16) from.y, (Sint16) to.x, (Sint16) to.y, red, green, blue, alpha); } void Renderer::drawPolygon(const b2Vec2* vertices, int32 vertexCount, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ std::vector<short> x(vertexCount); std::vector<short> y(vertexCount); for(int i=0;i<vertexCount;i++){ b2Vec2 vec = toScreenCoords(vertices[i]); x[i] = (short) vec.x; y[i] = (short) vec.y; } if(filled){ filledPolygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); }else{ polygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); } } void Renderer::drawCircle(const b2Vec2& center, float32 radius, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ b2Vec2 coords = toScreenCoords(center); if(filled){ filledCircleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); }else{ circleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Erik Hallnor * Steve Reinhardt */ #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fstream> #include <list> #include <string> #include <vector> #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/str.hh" #include "base/trace.hh" #include "sim/eventq.hh" #include "sim/serialize.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" // For stat reset hack #include "sim/stat_control.hh" using namespace std; extern SimObject *resolveSimObject(const string &); // // The base implementations use to_number for parsing and '<<' for // displaying, suitable for integer types. // template <class T> bool parseParam(const string &s, T &value) { return to_number(s, value); } template <class T> void showParam(ostream &os, const T &value) { os << value; } // // Template specializations: // - char (8-bit integer) // - floating-point types // - bool // - string // // Treat 8-bit ints (chars) as ints on output, not as chars template <> void showParam(ostream &os, const char &value) { os << (int)value; } template <> void showParam(ostream &os, const unsigned char &value) { os << (unsigned int)value; } // Use sscanf() for FP types as to_number() only handles integers template <> bool parseParam(const string &s, float &value) { return (sscanf(s.c_str(), "%f", &value) == 1); } template <> bool parseParam(const string &s, double &value) { return (sscanf(s.c_str(), "%lf", &value) == 1); } template <> bool parseParam(const string &s, bool &value) { const string &ls = to_lower(s); if (ls == "true") { value = true; return true; } if (ls == "false") { value = false; return true; } return false; } // Display bools as strings template <> void showParam(ostream &os, const bool &value) { os << (value ? "true" : "false"); } // String requires no processing to speak of template <> bool parseParam(const string &s, string &value) { value = s; return true; } int Serializable::ckptMaxCount = 0; int Serializable::ckptCount = 0; int Serializable::ckptPrevCount = -1; void Serializable::nameOut(ostream &os) { os << "\n[" << name() << "]\n"; } void Serializable::nameOut(ostream &os, const string &_name) { os << "\n[" << _name << "]\n"; } template <class T> void paramOut(ostream &os, const string &name, const T &param) { os << name << "="; showParam(os, param); os << "\n"; } template <class T> void arrayParamOut(ostream &os, const string &name, const vector<T> &param) { typename vector<T>::size_type size = param.size(); os << name << "="; if (size > 0) showParam(os, param[0]); for (typename vector<T>::size_type i = 1; i < size; ++i) { os << " "; showParam(os, param[i]); } os << "\n"; } template <class T> void paramIn(Checkpoint *cp, const string &section, const string &name, T &param) { string str; if (!cp->find(section, name, str) || !parseParam(str, param)) { fatal("Can't unserialize '%s:%s'\n", section, name); } } template <class T> bool optParamIn(Checkpoint *cp, const string &section, const string &name, T &param) { string str; if (!cp->find(section, name, str) || !parseParam(str, param)) { warn("optional parameter %s:%s not present\n", section, name); return false; } else { return true; } } template <class T> void arrayParamOut(ostream &os, const string &name, const T *param, unsigned size) { os << name << "="; if (size > 0) showParam(os, param[0]); for (unsigned i = 1; i < size; ++i) { os << " "; showParam(os, param[i]); } os << "\n"; } template <class T> void arrayParamIn(Checkpoint *cp, const string &section, const string &name, T *param, unsigned size) { string str; if (!cp->find(section, name, str)) { fatal("Can't unserialize '%s:%s'\n", section, name); } // code below stolen from VectorParam<T>::parse(). // it would be nice to unify these somehow... vector<string> tokens; tokenize(tokens, str, ' '); // Need this if we were doing a vector // value.resize(tokens.size()); if (tokens.size() != size) { fatal("Array size mismatch on %s:%s'\n", section, name); } for (vector<string>::size_type i = 0; i < tokens.size(); i++) { // need to parse into local variable to handle vector<bool>, // for which operator[] returns a special reference class // that's not the same as 'bool&', (since it's a packed // vector) T scalar_value; if (!parseParam(tokens[i], scalar_value)) { string err("could not parse \""); err += str; err += "\""; fatal(err); } // assign parsed value to vector param[i] = scalar_value; } } template <class T> void arrayParamIn(Checkpoint *cp, const string &section, const string &name, vector<T> &param) { string str; if (!cp->find(section, name, str)) { fatal("Can't unserialize '%s:%s'\n", section, name); } // code below stolen from VectorParam<T>::parse(). // it would be nice to unify these somehow... vector<string> tokens; tokenize(tokens, str, ' '); // Need this if we were doing a vector // value.resize(tokens.size()); param.resize(tokens.size()); for (vector<string>::size_type i = 0; i < tokens.size(); i++) { // need to parse into local variable to handle vector<bool>, // for which operator[] returns a special reference class // that's not the same as 'bool&', (since it's a packed // vector) T scalar_value; if (!parseParam(tokens[i], scalar_value)) { string err("could not parse \""); err += str; err += "\""; fatal(err); } // assign parsed value to vector param[i] = scalar_value; } } void objParamIn(Checkpoint *cp, const string &section, const string &name, SimObject * &param) { if (!cp->findObj(section, name, param)) { fatal("Can't unserialize '%s:%s'\n", section, name); } } #define INSTANTIATE_PARAM_TEMPLATES(type) \ template void \ paramOut(ostream &os, const string &name, type const &param); \ template void \ paramIn(Checkpoint *cp, const string &section, \ const string &name, type & param); \ template bool \ optParamIn(Checkpoint *cp, const string &section, \ const string &name, type & param); \ template void \ arrayParamOut(ostream &os, const string &name, \ type const *param, unsigned size); \ template void \ arrayParamIn(Checkpoint *cp, const string &section, \ const string &name, type *param, unsigned size); \ template void \ arrayParamOut(ostream &os, const string &name, \ const vector<type> &param); \ template void \ arrayParamIn(Checkpoint *cp, const string &section, \ const string &name, vector<type> &param); INSTANTIATE_PARAM_TEMPLATES(signed char) INSTANTIATE_PARAM_TEMPLATES(unsigned char) INSTANTIATE_PARAM_TEMPLATES(signed short) INSTANTIATE_PARAM_TEMPLATES(unsigned short) INSTANTIATE_PARAM_TEMPLATES(signed int) INSTANTIATE_PARAM_TEMPLATES(unsigned int) INSTANTIATE_PARAM_TEMPLATES(signed long) INSTANTIATE_PARAM_TEMPLATES(unsigned long) INSTANTIATE_PARAM_TEMPLATES(signed long long) INSTANTIATE_PARAM_TEMPLATES(unsigned long long) INSTANTIATE_PARAM_TEMPLATES(bool) INSTANTIATE_PARAM_TEMPLATES(float) INSTANTIATE_PARAM_TEMPLATES(double) INSTANTIATE_PARAM_TEMPLATES(string) ///////////////////////////// /// Container for serializing global variables (not associated with /// any serialized object). class Globals : public Serializable { public: const string name() const; void serialize(ostream &os); void unserialize(Checkpoint *cp); }; /// The one and only instance of the Globals class. Globals globals; const string Globals::name() const { return "Globals"; } void Globals::serialize(ostream &os) { nameOut(os); SERIALIZE_SCALAR(curTick); nameOut(os, "MainEventQueue"); mainEventQueue.serialize(os); } void Globals::unserialize(Checkpoint *cp) { const string &section = name(); UNSERIALIZE_SCALAR(curTick); mainEventQueue.unserialize(cp, "MainEventQueue"); } Serializable::Serializable() { } Serializable::~Serializable() { } void Serializable::serialize(ostream &os) { } void Serializable::unserialize(Checkpoint *cp, const string &section) { } void Serializable::serializeAll(const string &cpt_dir) { setCheckpointDir(cpt_dir); string dir = Checkpoint::dir(); if (mkdir(dir.c_str(), 0775) == -1 && errno != EEXIST) fatal("couldn't mkdir %s\n", dir); string cpt_file = dir + Checkpoint::baseFilename; ofstream outstream(cpt_file.c_str()); time_t t = time(NULL); if (!outstream.is_open()) fatal("Unable to open file %s for writing\n", cpt_file.c_str()); outstream << "## checkpoint generated: " << ctime(&t); globals.serialize(outstream); SimObject::serializeAll(outstream); } void Serializable::unserializeAll(const string &cpt_dir) { setCheckpointDir(cpt_dir); string dir = Checkpoint::dir(); string cpt_file = dir + Checkpoint::baseFilename; string section = ""; DPRINTFR(Config, "Loading checkpoint dir '%s'\n", dir); Checkpoint *cp = new Checkpoint(dir, section); unserializeGlobals(cp); SimObject::unserializeAll(cp); } void Serializable::unserializeGlobals(Checkpoint *cp) { globals.unserialize(cp); } const char *Checkpoint::baseFilename = "m5.cpt"; static string checkpointDirBase; void setCheckpointDir(const string &name) { checkpointDirBase = name; if (checkpointDirBase[checkpointDirBase.size() - 1] != '/') checkpointDirBase += "/"; } string Checkpoint::dir() { // use csprintf to insert curTick into directory name if it // appears to have a format placeholder in it. return (checkpointDirBase.find("%") != string::npos) ? csprintf(checkpointDirBase, curTick) : checkpointDirBase; } void debug_serialize(const string &cpt_dir) { Serializable::serializeAll(cpt_dir); } //////////////////////////////////////////////////////////////////////// // // SerializableClass member definitions // //////////////////////////////////////////////////////////////////////// // Map of class names to SerializableBuilder creation functions. // Need to make this a pointer so we can force initialization on the // first reference; otherwise, some SerializableClass constructors // may be invoked before the classMap constructor. map<string, SerializableClass::CreateFunc> *SerializableClass::classMap = 0; // SerializableClass constructor: add mapping to classMap SerializableClass::SerializableClass(const string &className, CreateFunc createFunc) { if (classMap == NULL) classMap = new map<string, SerializableClass::CreateFunc>(); if ((*classMap)[className]) fatal("Error: simulation object class %s redefined\n", className); // add className --> createFunc to class map (*classMap)[className] = createFunc; } // // Serializable * SerializableClass::createObject(Checkpoint *cp, const string &section) { string className; if (!cp->find(section, "type", className)) { fatal("Serializable::create: no 'type' entry in section '%s'.\n", section); } CreateFunc createFunc = (*classMap)[className]; if (createFunc == NULL) { fatal("Serializable::create: no create function for class '%s'.\n", className); } Serializable *object = createFunc(cp, section); assert(object != NULL); return object; } Serializable * Serializable::create(Checkpoint *cp, const string &section) { Serializable *object = SerializableClass::createObject(cp, section); object->unserialize(cp, section); return object; } Checkpoint::Checkpoint(const string &cpt_dir, const string &path) : db(new IniFile), basePath(path), cptDir(cpt_dir) { string filename = cpt_dir + "/" + Checkpoint::baseFilename; if (!db->load(filename)) { fatal("Can't load checkpoint file '%s'\n", filename); } } bool Checkpoint::find(const string &section, const string &entry, string &value) { return db->find(section, entry, value); } bool Checkpoint::findObj(const string &section, const string &entry, SimObject *&value) { string path; if (!db->find(section, entry, path)) return false; value = resolveSimObject(path); return true; } bool Checkpoint::sectionExists(const string &section) { return db->sectionExists(section); } <commit_msg>checkpointing: fix minor bug Somehow we now need to explicitly specialize on 'signed char' and not just 'char' to catch cases like int8_t<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Erik Hallnor * Steve Reinhardt */ #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fstream> #include <list> #include <string> #include <vector> #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/str.hh" #include "base/trace.hh" #include "sim/eventq.hh" #include "sim/serialize.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" // For stat reset hack #include "sim/stat_control.hh" using namespace std; extern SimObject *resolveSimObject(const string &); // // The base implementations use to_number for parsing and '<<' for // displaying, suitable for integer types. // template <class T> bool parseParam(const string &s, T &value) { return to_number(s, value); } template <class T> void showParam(ostream &os, const T &value) { os << value; } // // Template specializations: // - char (8-bit integer) // - floating-point types // - bool // - string // // Treat 8-bit ints (chars) as ints on output, not as chars template <> void showParam(ostream &os, const signed char &value) { os << (int)value; } template <> void showParam(ostream &os, const unsigned char &value) { os << (unsigned int)value; } // Use sscanf() for FP types as to_number() only handles integers template <> bool parseParam(const string &s, float &value) { return (sscanf(s.c_str(), "%f", &value) == 1); } template <> bool parseParam(const string &s, double &value) { return (sscanf(s.c_str(), "%lf", &value) == 1); } template <> bool parseParam(const string &s, bool &value) { const string &ls = to_lower(s); if (ls == "true") { value = true; return true; } if (ls == "false") { value = false; return true; } return false; } // Display bools as strings template <> void showParam(ostream &os, const bool &value) { os << (value ? "true" : "false"); } // String requires no processing to speak of template <> bool parseParam(const string &s, string &value) { value = s; return true; } int Serializable::ckptMaxCount = 0; int Serializable::ckptCount = 0; int Serializable::ckptPrevCount = -1; void Serializable::nameOut(ostream &os) { os << "\n[" << name() << "]\n"; } void Serializable::nameOut(ostream &os, const string &_name) { os << "\n[" << _name << "]\n"; } template <class T> void paramOut(ostream &os, const string &name, const T &param) { os << name << "="; showParam(os, param); os << "\n"; } template <class T> void arrayParamOut(ostream &os, const string &name, const vector<T> &param) { typename vector<T>::size_type size = param.size(); os << name << "="; if (size > 0) showParam(os, param[0]); for (typename vector<T>::size_type i = 1; i < size; ++i) { os << " "; showParam(os, param[i]); } os << "\n"; } template <class T> void paramIn(Checkpoint *cp, const string &section, const string &name, T &param) { string str; if (!cp->find(section, name, str) || !parseParam(str, param)) { fatal("Can't unserialize '%s:%s'\n", section, name); } } template <class T> bool optParamIn(Checkpoint *cp, const string &section, const string &name, T &param) { string str; if (!cp->find(section, name, str) || !parseParam(str, param)) { warn("optional parameter %s:%s not present\n", section, name); return false; } else { return true; } } template <class T> void arrayParamOut(ostream &os, const string &name, const T *param, unsigned size) { os << name << "="; if (size > 0) showParam(os, param[0]); for (unsigned i = 1; i < size; ++i) { os << " "; showParam(os, param[i]); } os << "\n"; } template <class T> void arrayParamIn(Checkpoint *cp, const string &section, const string &name, T *param, unsigned size) { string str; if (!cp->find(section, name, str)) { fatal("Can't unserialize '%s:%s'\n", section, name); } // code below stolen from VectorParam<T>::parse(). // it would be nice to unify these somehow... vector<string> tokens; tokenize(tokens, str, ' '); // Need this if we were doing a vector // value.resize(tokens.size()); if (tokens.size() != size) { fatal("Array size mismatch on %s:%s'\n", section, name); } for (vector<string>::size_type i = 0; i < tokens.size(); i++) { // need to parse into local variable to handle vector<bool>, // for which operator[] returns a special reference class // that's not the same as 'bool&', (since it's a packed // vector) T scalar_value; if (!parseParam(tokens[i], scalar_value)) { string err("could not parse \""); err += str; err += "\""; fatal(err); } // assign parsed value to vector param[i] = scalar_value; } } template <class T> void arrayParamIn(Checkpoint *cp, const string &section, const string &name, vector<T> &param) { string str; if (!cp->find(section, name, str)) { fatal("Can't unserialize '%s:%s'\n", section, name); } // code below stolen from VectorParam<T>::parse(). // it would be nice to unify these somehow... vector<string> tokens; tokenize(tokens, str, ' '); // Need this if we were doing a vector // value.resize(tokens.size()); param.resize(tokens.size()); for (vector<string>::size_type i = 0; i < tokens.size(); i++) { // need to parse into local variable to handle vector<bool>, // for which operator[] returns a special reference class // that's not the same as 'bool&', (since it's a packed // vector) T scalar_value; if (!parseParam(tokens[i], scalar_value)) { string err("could not parse \""); err += str; err += "\""; fatal(err); } // assign parsed value to vector param[i] = scalar_value; } } void objParamIn(Checkpoint *cp, const string &section, const string &name, SimObject * &param) { if (!cp->findObj(section, name, param)) { fatal("Can't unserialize '%s:%s'\n", section, name); } } #define INSTANTIATE_PARAM_TEMPLATES(type) \ template void \ paramOut(ostream &os, const string &name, type const &param); \ template void \ paramIn(Checkpoint *cp, const string &section, \ const string &name, type & param); \ template bool \ optParamIn(Checkpoint *cp, const string &section, \ const string &name, type & param); \ template void \ arrayParamOut(ostream &os, const string &name, \ type const *param, unsigned size); \ template void \ arrayParamIn(Checkpoint *cp, const string &section, \ const string &name, type *param, unsigned size); \ template void \ arrayParamOut(ostream &os, const string &name, \ const vector<type> &param); \ template void \ arrayParamIn(Checkpoint *cp, const string &section, \ const string &name, vector<type> &param); INSTANTIATE_PARAM_TEMPLATES(signed char) INSTANTIATE_PARAM_TEMPLATES(unsigned char) INSTANTIATE_PARAM_TEMPLATES(signed short) INSTANTIATE_PARAM_TEMPLATES(unsigned short) INSTANTIATE_PARAM_TEMPLATES(signed int) INSTANTIATE_PARAM_TEMPLATES(unsigned int) INSTANTIATE_PARAM_TEMPLATES(signed long) INSTANTIATE_PARAM_TEMPLATES(unsigned long) INSTANTIATE_PARAM_TEMPLATES(signed long long) INSTANTIATE_PARAM_TEMPLATES(unsigned long long) INSTANTIATE_PARAM_TEMPLATES(bool) INSTANTIATE_PARAM_TEMPLATES(float) INSTANTIATE_PARAM_TEMPLATES(double) INSTANTIATE_PARAM_TEMPLATES(string) ///////////////////////////// /// Container for serializing global variables (not associated with /// any serialized object). class Globals : public Serializable { public: const string name() const; void serialize(ostream &os); void unserialize(Checkpoint *cp); }; /// The one and only instance of the Globals class. Globals globals; const string Globals::name() const { return "Globals"; } void Globals::serialize(ostream &os) { nameOut(os); SERIALIZE_SCALAR(curTick); nameOut(os, "MainEventQueue"); mainEventQueue.serialize(os); } void Globals::unserialize(Checkpoint *cp) { const string &section = name(); UNSERIALIZE_SCALAR(curTick); mainEventQueue.unserialize(cp, "MainEventQueue"); } Serializable::Serializable() { } Serializable::~Serializable() { } void Serializable::serialize(ostream &os) { } void Serializable::unserialize(Checkpoint *cp, const string &section) { } void Serializable::serializeAll(const string &cpt_dir) { setCheckpointDir(cpt_dir); string dir = Checkpoint::dir(); if (mkdir(dir.c_str(), 0775) == -1 && errno != EEXIST) fatal("couldn't mkdir %s\n", dir); string cpt_file = dir + Checkpoint::baseFilename; ofstream outstream(cpt_file.c_str()); time_t t = time(NULL); if (!outstream.is_open()) fatal("Unable to open file %s for writing\n", cpt_file.c_str()); outstream << "## checkpoint generated: " << ctime(&t); globals.serialize(outstream); SimObject::serializeAll(outstream); } void Serializable::unserializeAll(const string &cpt_dir) { setCheckpointDir(cpt_dir); string dir = Checkpoint::dir(); string cpt_file = dir + Checkpoint::baseFilename; string section = ""; DPRINTFR(Config, "Loading checkpoint dir '%s'\n", dir); Checkpoint *cp = new Checkpoint(dir, section); unserializeGlobals(cp); SimObject::unserializeAll(cp); } void Serializable::unserializeGlobals(Checkpoint *cp) { globals.unserialize(cp); } const char *Checkpoint::baseFilename = "m5.cpt"; static string checkpointDirBase; void setCheckpointDir(const string &name) { checkpointDirBase = name; if (checkpointDirBase[checkpointDirBase.size() - 1] != '/') checkpointDirBase += "/"; } string Checkpoint::dir() { // use csprintf to insert curTick into directory name if it // appears to have a format placeholder in it. return (checkpointDirBase.find("%") != string::npos) ? csprintf(checkpointDirBase, curTick) : checkpointDirBase; } void debug_serialize(const string &cpt_dir) { Serializable::serializeAll(cpt_dir); } //////////////////////////////////////////////////////////////////////// // // SerializableClass member definitions // //////////////////////////////////////////////////////////////////////// // Map of class names to SerializableBuilder creation functions. // Need to make this a pointer so we can force initialization on the // first reference; otherwise, some SerializableClass constructors // may be invoked before the classMap constructor. map<string, SerializableClass::CreateFunc> *SerializableClass::classMap = 0; // SerializableClass constructor: add mapping to classMap SerializableClass::SerializableClass(const string &className, CreateFunc createFunc) { if (classMap == NULL) classMap = new map<string, SerializableClass::CreateFunc>(); if ((*classMap)[className]) fatal("Error: simulation object class %s redefined\n", className); // add className --> createFunc to class map (*classMap)[className] = createFunc; } // // Serializable * SerializableClass::createObject(Checkpoint *cp, const string &section) { string className; if (!cp->find(section, "type", className)) { fatal("Serializable::create: no 'type' entry in section '%s'.\n", section); } CreateFunc createFunc = (*classMap)[className]; if (createFunc == NULL) { fatal("Serializable::create: no create function for class '%s'.\n", className); } Serializable *object = createFunc(cp, section); assert(object != NULL); return object; } Serializable * Serializable::create(Checkpoint *cp, const string &section) { Serializable *object = SerializableClass::createObject(cp, section); object->unserialize(cp, section); return object; } Checkpoint::Checkpoint(const string &cpt_dir, const string &path) : db(new IniFile), basePath(path), cptDir(cpt_dir) { string filename = cpt_dir + "/" + Checkpoint::baseFilename; if (!db->load(filename)) { fatal("Can't load checkpoint file '%s'\n", filename); } } bool Checkpoint::find(const string &section, const string &entry, string &value) { return db->find(section, entry, value); } bool Checkpoint::findObj(const string &section, const string &entry, SimObject *&value) { string path; if (!db->find(section, entry, path)) return false; value = resolveSimObject(path); return true; } bool Checkpoint::sectionExists(const string &section) { return db->sectionExists(section); } <|endoftext|>
<commit_before>#include <mzx/simple_event.h> namespace mzx { SimpleEventBase::ClassIndexType SimpleEventBase::class_index_counter_ = 0; SimpleEventBase::SimpleEventBase() { } SimpleEventBase::~SimpleEventBase() { } SimpleEventBase::ClassIndexType SimpleEventBase::ClassIndexCount() { return class_index_counter_; } } // namespace mzx <commit_msg>modify simple event manager<commit_after>#include <mzx/simple_event.h> namespace mzx { SimpleEventBase::ClassIndexType SimpleEventBase::class_index_counter_ = 0; SimpleEventBase::SimpleEventBase() { } SimpleEventBase::~SimpleEventBase() { } SimpleEventBase::ClassIndexType SimpleEventBase::ClassIndexCount() { return class_index_counter_; } SimpleEventManager::SimpleEventManager() { } SimpleEventManager::~SimpleEventManager() { } } // namespace mzx <|endoftext|>
<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "unit_tests.hpp" #include <functional> #include <ctime> using namespace mfem; struct LinearFormExtTest { enum { DLFEval, QLFEval, DLFGrad, VDLFEval, VQLFEval, VDLFGrad }; using vector_fct_t = void(const Vector&, Vector&); const double abs_tol = 1e-14, rel_tol = 1e-14; const char *mesh_filename; Mesh mesh; const int dim, vdim, ordering, gll, problem, p, q, SEED = 0x100001b3; H1_FECollection fec; FiniteElementSpace vfes, mfes; const Geometry::Type geom_type; IntegrationRules IntRulesGLL; const IntegrationRule *irGLL, *ir; Array<int> elem_marker; Vector one_vec, dim_vec, vdim_vec, vdim_dim_vec; ConstantCoefficient cst_coeff; VectorConstantCoefficient dim_cst_coeff, vdim_cst_coeff, vdim_dim_cst_coeff; std::function<vector_fct_t> vdim_vec_function = [&](const Vector&, Vector &y) { y.SetSize(vdim); y.Randomize(SEED);}; std::function<vector_fct_t> vector_fct; VectorFunctionCoefficient vdim_fct_coeff; QuadratureSpace qspace; QuadratureFunction q_function, q_vdim_function; QuadratureFunctionCoefficient qfc; VectorQuadratureFunctionCoefficient qfvc; LinearForm lf_dev, lf_std; LinearFormIntegrator *lfi_dev, *lfi_std; LinearFormExtTest(const char *mesh_filename, int vdim, int ordering, bool gll, int problem, int p): mesh_filename(mesh_filename), mesh(Mesh::LoadFromFile(mesh_filename)), dim(mesh.Dimension()), vdim(vdim), ordering(ordering), gll(gll), problem(problem), p(p), q(2*p + (gll?-1:3)), fec(p, dim), vfes(&mesh, &fec, vdim, ordering), mfes(&mesh, &fec, dim), geom_type(vfes.GetFE(0)->GetGeomType()), IntRulesGLL(0, Quadrature1D::GaussLobatto), irGLL(&IntRulesGLL.Get(geom_type, q)), ir(&IntRules.Get(geom_type, q)), elem_marker(), one_vec(1), dim_vec(dim), vdim_vec(vdim), vdim_dim_vec(vdim*dim), cst_coeff(M_PI), dim_cst_coeff((dim_vec.Randomize(SEED), dim_vec)), vdim_cst_coeff((vdim_vec.Randomize(SEED), vdim_vec)), vdim_dim_cst_coeff((vdim_dim_vec.Randomize(SEED), vdim_dim_vec)), vector_fct(vdim_vec_function), vdim_fct_coeff(vdim, vector_fct), qspace(&mesh, q), q_function(&qspace, 1), q_vdim_function(&qspace, vdim), qfc((q_function.Randomize(SEED), q_function)), qfvc((q_vdim_function.Randomize(SEED), q_vdim_function)), lf_dev(&vfes), lf_std(&vfes), lfi_dev(nullptr), lfi_std(nullptr) { for (int e = 0; e < mesh.GetNE(); e++) { mesh.SetAttribute(e, e%2?1:2); } mesh.SetAttributes(); MFEM_VERIFY(mesh.attributes.Size() == 2, "mesh attributes size error!"); elem_marker.SetSize(2); elem_marker[0] = 0; elem_marker[1] = 1; if (problem == DLFEval) { lfi_dev = new DomainLFIntegrator(cst_coeff); lfi_std = new DomainLFIntegrator(cst_coeff); } else if (problem == QLFEval) { lfi_dev = new QuadratureLFIntegrator(qfc,NULL); lfi_std = new QuadratureLFIntegrator(qfc,NULL); } else if (problem == DLFGrad) { lfi_dev = new DomainLFGradIntegrator(dim_cst_coeff); lfi_std = new DomainLFGradIntegrator(dim_cst_coeff); } else if (problem == VDLFEval) { lfi_dev = new VectorDomainLFIntegrator(vdim_fct_coeff); lfi_std = new VectorDomainLFIntegrator(vdim_fct_coeff); } else if (problem == VQLFEval) { lfi_dev = new VectorQuadratureLFIntegrator(qfvc,NULL); lfi_std = new VectorQuadratureLFIntegrator(qfvc,NULL); } else if (problem == VDLFGrad) { lfi_dev = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); lfi_std = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); } else { REQUIRE(false); } if (problem != QLFEval && problem != VQLFEval) { lfi_dev->SetIntRule(gll ? irGLL : ir); lfi_std->SetIntRule(gll ? irGLL : ir); } lf_dev.AddDomainIntegrator(lfi_dev, elem_marker); lf_std.AddDomainIntegrator(lfi_std, elem_marker); } void Run() { const bool scalar = problem == LinearFormExtTest::DLFEval || problem == LinearFormExtTest::QLFEval || problem == LinearFormExtTest::DLFGrad; REQUIRE((!scalar || vdim == 1)); const bool grad = problem == LinearFormExtTest::DLFGrad || problem == LinearFormExtTest::VDLFGrad; CAPTURE(dim, p, q, ordering, vdim, scalar, grad); const bool use_device = true; lf_dev.Assemble(use_device); const bool dont_use_device = false; lf_std.Assemble(dont_use_device); lf_std -= lf_dev; REQUIRE(0.0 == MFEM_Approx(lf_std*lf_std, abs_tol, rel_tol)); } }; TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]") { const bool all = launch_all_non_regression_tests; const auto mesh = all ? GENERATE("../../data/star.mesh", "../../data/star-q3.mesh", "../../data/fichera.mesh", "../../data/fichera-q3.mesh") : GENERATE("../../data/star-q3.mesh", "../../data/fichera-q3.mesh"); const auto p = all ? GENERATE(1,2,3,4,5,6) : GENERATE(1,3); const auto gll = GENERATE(false, true); SECTION("Scalar") { const auto problem = GENERATE(LinearFormExtTest::DLFEval, LinearFormExtTest::QLFEval, LinearFormExtTest::DLFGrad); LinearFormExtTest(mesh, 1, Ordering::byNODES, gll, problem, p).Run(); } SECTION("Vector") { const auto vdim = all ? GENERATE(1,5,7) : GENERATE(1,5); const auto ordering = GENERATE(Ordering::byVDIM, Ordering::byNODES); const auto problem = GENERATE(LinearFormExtTest::VDLFEval, LinearFormExtTest::VQLFEval, LinearFormExtTest::VDLFGrad); LinearFormExtTest(mesh, vdim, ordering, gll, problem, p).Run(); } } <commit_msg>Small changes to Linear Form Extension unit test<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "unit_tests.hpp" #include <functional> #include <ctime> using namespace mfem; struct LinearFormExtTest { enum { DLFEval, QLFEval, DLFGrad, VDLFEval, VQLFEval, VDLFGrad }; const double abs_tol = 1e-14, rel_tol = 1e-14; const char *mesh_filename; Mesh mesh; const int dim, vdim, ordering, gll, problem, p, q, SEED = 0x100001b3; H1_FECollection fec; FiniteElementSpace vfes; const Geometry::Type geom_type; IntegrationRules IntRulesGLL; const IntegrationRule *irGLL, *ir; Array<int> elem_marker; Vector one_vec, dim_vec, vdim_vec, vdim_dim_vec; ConstantCoefficient cst_coeff; VectorConstantCoefficient dim_cst_coeff, vdim_cst_coeff, vdim_dim_cst_coeff; QuadratureSpace qspace; QuadratureFunction q_function, q_vdim_function; QuadratureFunctionCoefficient qfc; VectorQuadratureFunctionCoefficient qfvc; LinearForm lf_dev, lf_std; LinearFormIntegrator *lfi_dev, *lfi_std; LinearFormExtTest(const char *mesh_filename, int vdim, int ordering, bool gll, int problem, int p): mesh_filename(mesh_filename), mesh(Mesh::LoadFromFile(mesh_filename)), dim(mesh.Dimension()), vdim(vdim), ordering(ordering), gll(gll), problem(problem), p(p), q(2*p + (gll?-1:3)), fec(p, dim), vfes(&mesh, &fec, vdim, ordering), geom_type(vfes.GetFE(0)->GetGeomType()), IntRulesGLL(0, Quadrature1D::GaussLobatto), irGLL(&IntRulesGLL.Get(geom_type, q)), ir(&IntRules.Get(geom_type, q)), elem_marker(), one_vec(1), dim_vec(dim), vdim_vec(vdim), vdim_dim_vec(vdim*dim), cst_coeff(M_PI), dim_cst_coeff((dim_vec.Randomize(SEED), dim_vec)), vdim_cst_coeff((vdim_vec.Randomize(SEED), vdim_vec)), vdim_dim_cst_coeff((vdim_dim_vec.Randomize(SEED), vdim_dim_vec)), qspace(&mesh, q), q_function(&qspace, 1), q_vdim_function(&qspace, vdim), qfc((q_function.Randomize(SEED), q_function)), qfvc((q_vdim_function.Randomize(SEED), q_vdim_function)), lf_dev(&vfes), lf_std(&vfes), lfi_dev(nullptr), lfi_std(nullptr) { for (int e = 0; e < mesh.GetNE(); e++) { mesh.SetAttribute(e, e%2?1:2); } mesh.SetAttributes(); MFEM_VERIFY(mesh.attributes.Size() == 2, "mesh attributes size error!"); elem_marker.SetSize(2); elem_marker[0] = 0; elem_marker[1] = 1; if (problem == DLFEval) { lfi_dev = new DomainLFIntegrator(cst_coeff); lfi_std = new DomainLFIntegrator(cst_coeff); } else if (problem == QLFEval) { lfi_dev = new QuadratureLFIntegrator(qfc,NULL); lfi_std = new QuadratureLFIntegrator(qfc,NULL); } else if (problem == DLFGrad) { lfi_dev = new DomainLFGradIntegrator(dim_cst_coeff); lfi_std = new DomainLFGradIntegrator(dim_cst_coeff); } else if (problem == VDLFEval) { lfi_dev = new VectorDomainLFIntegrator(vdim_cst_coeff); lfi_std = new VectorDomainLFIntegrator(vdim_cst_coeff); } else if (problem == VQLFEval) { lfi_dev = new VectorQuadratureLFIntegrator(qfvc,NULL); lfi_std = new VectorQuadratureLFIntegrator(qfvc,NULL); } else if (problem == VDLFGrad) { lfi_dev = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); lfi_std = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); } else { REQUIRE(false); } if (problem != QLFEval && problem != VQLFEval) { lfi_dev->SetIntRule(gll ? irGLL : ir); lfi_std->SetIntRule(gll ? irGLL : ir); } lf_dev.AddDomainIntegrator(lfi_dev, elem_marker); lf_std.AddDomainIntegrator(lfi_std, elem_marker); } void Run() { const bool scalar = problem == LinearFormExtTest::DLFEval || problem == LinearFormExtTest::QLFEval || problem == LinearFormExtTest::DLFGrad; REQUIRE((!scalar || vdim == 1)); const bool grad = problem == LinearFormExtTest::DLFGrad || problem == LinearFormExtTest::VDLFGrad; CAPTURE(mesh_filename, dim, p, q, ordering, vdim, scalar, grad); const bool use_device = true; lf_dev.Assemble(use_device); const bool dont_use_device = false; lf_std.Assemble(dont_use_device); lf_std -= lf_dev; REQUIRE(0.0 == MFEM_Approx(lf_std*lf_std, abs_tol, rel_tol)); } }; TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]") { const bool all = launch_all_non_regression_tests; const auto mesh = all ? GENERATE("../../data/star.mesh", "../../data/star-q3.mesh", "../../data/fichera.mesh", "../../data/fichera-q3.mesh") : GENERATE("../../data/star-q3.mesh", "../../data/fichera-q3.mesh"); const auto p = all ? GENERATE(1,2,3,4,5,6) : GENERATE(1,3); const auto gll = GENERATE(false, true); SECTION("Scalar") { const auto problem = GENERATE(LinearFormExtTest::DLFEval, LinearFormExtTest::QLFEval, LinearFormExtTest::DLFGrad); LinearFormExtTest(mesh, 1, Ordering::byNODES, gll, problem, p).Run(); } SECTION("Vector") { const auto vdim = all ? GENERATE(1,5,7) : GENERATE(1,5); const auto ordering = GENERATE(Ordering::byVDIM, Ordering::byNODES); const auto problem = GENERATE(LinearFormExtTest::VDLFEval, LinearFormExtTest::VQLFEval, LinearFormExtTest::VDLFGrad); LinearFormExtTest(mesh, vdim, ordering, gll, problem, p).Run(); } } <|endoftext|>
<commit_before>#include "socketgateway.h" #include <errno.h> #include <picojson.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include "logging.h" #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif using std::make_shared; using std::shared_ptr; SocketGateway::SocketGateway(const Config &config_in, command::Channel *commands_channel_in) : config(config_in), commands_channel(commands_channel_in) { unlink(config.network.socket_events_path.c_str()); unlink(config.network.socket_commands_path.c_str()); events_server_thread = make_shared<std::thread>(std::bind(&SocketGateway::eventsServer, this)); commands_server_thread = make_shared<std::thread>(std::bind(&SocketGateway::commandsServer, this)); } SocketGateway::~SocketGateway() { shutdown(commands_socket, SHUT_RD); shutdown(events_socket, SHUT_RD); for (std::vector<int>::iterator it = event_connections.begin(); it != event_connections.end(); ++it) { close(*it); } for (std::vector<int>::iterator it = command_connections.begin(); it != command_connections.end(); ++it) { close(*it); } for (std::vector<shared_ptr<std::thread> >::iterator it = command_workers.begin(); it != command_workers.end(); ++it) { (*it)->join(); } commands_server_thread->join(); events_server_thread->join(); unlink(config.network.socket_events_path.c_str()); unlink(config.network.socket_commands_path.c_str()); } void SocketGateway::commandsWorker(int socket, command::Channel *channel) { const int buff_size = 512; char buf[buff_size]; std::string data; while (ssize_t bytes = recv(socket, buf, buff_size, MSG_NOSIGNAL)) { if (bytes <= 0) break; if (bytes < buff_size) { buf[bytes] = '\0'; } data.append(buf); picojson::value item; picojson::default_parse_context ctx(&item); picojson::input<std::string::iterator> in(data.begin(), data.end()); if (picojson::_parse(ctx, in)) { data.erase(data.begin(), in.cur()); try { *channel << command::BaseCommand::fromPicoJson(item); } catch (...) { LOG_ERROR << "failed command deserealization: " << item.serialize(); } } } LOG_ERROR << "unix domain socket recv command error, errno: " << errno; close(socket); } void SocketGateway::eventsServer() { events_socket = socket(AF_UNIX, SOCK_STREAM, 0); struct sockaddr_un cli_addr, addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, config.network.socket_events_path.c_str(), sizeof(addr.sun_path) - 1); bind(events_socket, (struct sockaddr *)&addr, sizeof(addr)); listen(events_socket, 10); socklen_t clilen = sizeof(cli_addr); while (true) { int newsockfd = accept(events_socket, (struct sockaddr *)&cli_addr, &clilen); if (newsockfd != -1) { event_connections.push_back(newsockfd); } else { break; } } LOG_ERROR << "unix domain event socket accept error, errno: " << errno; close(events_socket); } void SocketGateway::commandsServer() { commands_socket = socket(AF_UNIX, SOCK_STREAM, 0); struct sockaddr_un cli_addr, addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, config.network.socket_commands_path.c_str(), sizeof(addr.sun_path) - 1); bind(commands_socket, (struct sockaddr *)&addr, sizeof(addr)); listen(commands_socket, 10); socklen_t clilen = sizeof(cli_addr); while (true) { int newsockfd = accept(commands_socket, (struct sockaddr *)&cli_addr, &clilen); if (newsockfd != -1) { command_connections.push_back(newsockfd); command_workers.push_back( make_shared<std::thread>(std::bind(&SocketGateway::commandsWorker, this, newsockfd, commands_channel))); } else { break; } } LOG_ERROR << "unix domain command socket accept error, errno: " << errno; close(commands_socket); } void SocketGateway::broadcast_event(const std::shared_ptr<event::BaseEvent> &event) { std::string json_event = event->toJson(); for (std::vector<int>::iterator it = event_connections.begin(); it != event_connections.end();) { ssize_t bytes_sent = send(*it, json_event.c_str(), json_event.size(), MSG_NOSIGNAL); if (bytes_sent != -1) { ++it; } else { LOG_ERROR << "unix domain socket write error, errno: " << errno; close(*it); it = event_connections.erase(it); } } } void SocketGateway::processEvent(const std::shared_ptr<event::BaseEvent> &event) { std::vector<std::string>::const_iterator find_iter = std::find(config.network.socket_events.begin(), config.network.socket_events.end(), event->variant); if (find_iter != config.network.socket_events.end()) { broadcast_event(event); } } <commit_msg>Do not give MSG_NOSIGNAL to `recv()`<commit_after>#include "socketgateway.h" #include <errno.h> #include <picojson.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include "logging.h" #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif using std::make_shared; using std::shared_ptr; SocketGateway::SocketGateway(const Config &config_in, command::Channel *commands_channel_in) : config(config_in), commands_channel(commands_channel_in) { unlink(config.network.socket_events_path.c_str()); unlink(config.network.socket_commands_path.c_str()); events_server_thread = make_shared<std::thread>(std::bind(&SocketGateway::eventsServer, this)); commands_server_thread = make_shared<std::thread>(std::bind(&SocketGateway::commandsServer, this)); } SocketGateway::~SocketGateway() { shutdown(commands_socket, SHUT_RD); shutdown(events_socket, SHUT_RD); for (std::vector<int>::iterator it = event_connections.begin(); it != event_connections.end(); ++it) { close(*it); } for (std::vector<int>::iterator it = command_connections.begin(); it != command_connections.end(); ++it) { close(*it); } for (std::vector<shared_ptr<std::thread> >::iterator it = command_workers.begin(); it != command_workers.end(); ++it) { (*it)->join(); } commands_server_thread->join(); events_server_thread->join(); unlink(config.network.socket_events_path.c_str()); unlink(config.network.socket_commands_path.c_str()); } void SocketGateway::commandsWorker(int socket, command::Channel *channel) { const int buff_size = 512; char buf[buff_size]; std::string data; while (ssize_t bytes = recv(socket, buf, buff_size, 0)) { if (bytes <= 0) break; if (bytes < buff_size) { buf[bytes] = '\0'; } data.append(buf); picojson::value item; picojson::default_parse_context ctx(&item); picojson::input<std::string::iterator> in(data.begin(), data.end()); if (picojson::_parse(ctx, in)) { data.erase(data.begin(), in.cur()); try { *channel << command::BaseCommand::fromPicoJson(item); } catch (...) { LOG_ERROR << "failed command deserealization: " << item.serialize(); } } } LOG_ERROR << "unix domain socket recv command error, errno: " << errno; close(socket); } void SocketGateway::eventsServer() { events_socket = socket(AF_UNIX, SOCK_STREAM, 0); struct sockaddr_un cli_addr, addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, config.network.socket_events_path.c_str(), sizeof(addr.sun_path) - 1); bind(events_socket, (struct sockaddr *)&addr, sizeof(addr)); listen(events_socket, 10); socklen_t clilen = sizeof(cli_addr); while (true) { int newsockfd = accept(events_socket, (struct sockaddr *)&cli_addr, &clilen); if (newsockfd != -1) { event_connections.push_back(newsockfd); } else { break; } } LOG_ERROR << "unix domain event socket accept error, errno: " << errno; close(events_socket); } void SocketGateway::commandsServer() { commands_socket = socket(AF_UNIX, SOCK_STREAM, 0); struct sockaddr_un cli_addr, addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, config.network.socket_commands_path.c_str(), sizeof(addr.sun_path) - 1); bind(commands_socket, (struct sockaddr *)&addr, sizeof(addr)); listen(commands_socket, 10); socklen_t clilen = sizeof(cli_addr); while (true) { int newsockfd = accept(commands_socket, (struct sockaddr *)&cli_addr, &clilen); if (newsockfd != -1) { command_connections.push_back(newsockfd); command_workers.push_back( make_shared<std::thread>(std::bind(&SocketGateway::commandsWorker, this, newsockfd, commands_channel))); } else { break; } } LOG_ERROR << "unix domain command socket accept error, errno: " << errno; close(commands_socket); } void SocketGateway::broadcast_event(const std::shared_ptr<event::BaseEvent> &event) { std::string json_event = event->toJson(); for (std::vector<int>::iterator it = event_connections.begin(); it != event_connections.end();) { ssize_t bytes_sent = send(*it, json_event.c_str(), json_event.size(), MSG_NOSIGNAL); if (bytes_sent != -1) { ++it; } else { LOG_ERROR << "unix domain socket write error, errno: " << errno; close(*it); it = event_connections.erase(it); } } } void SocketGateway::processEvent(const std::shared_ptr<event::BaseEvent> &event) { std::vector<std::string>::const_iterator find_iter = std::find(config.network.socket_events.begin(), config.network.socket_events.end(), event->variant); if (find_iter != config.network.socket_events.end()) { broadcast_event(event); } } <|endoftext|>
<commit_before>//===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BinaryHolder.h" #include "DebugMap.h" #include "dsymutil.h" #include "llvm/Object/MachO.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" namespace { using namespace llvm; using namespace llvm::dsymutil; using namespace llvm::object; class MachODebugMapParser { public: MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "", bool Verbose = false) : BinaryPath(BinaryPath), PathPrefix(PathPrefix), MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose), CurrentDebugMapObject(nullptr) {} /// \brief Parses and returns the DebugMap of the input binary. /// \returns an error in case the provided BinaryPath doesn't exist /// or isn't of a supported type. ErrorOr<std::unique_ptr<DebugMap>> parse(); private: std::string BinaryPath; std::string PathPrefix; /// Owns the MemoryBuffer for the main binary. BinaryHolder MainBinaryHolder; /// Map of the binary symbol addresses. StringMap<uint64_t> MainBinarySymbolAddresses; StringRef MainBinaryStrings; /// The constructed DebugMap. std::unique_ptr<DebugMap> Result; /// Owns the MemoryBuffer for the currently handled object file. BinaryHolder CurrentObjectHolder; /// Map of the currently processed object file symbol addresses. StringMap<uint64_t> CurrentObjectAddresses; /// Element of the debug map corresponfing to the current object file. DebugMapObject *CurrentDebugMapObject; void switchToNewDebugMapObject(StringRef Filename); void resetParserState(); uint64_t getMainBinarySymbolAddress(StringRef Name); void loadMainBinarySymbols(); void loadCurrentObjectFileSymbols(); void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type, uint8_t SectionIndex, uint16_t Flags, uint64_t Value); template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) { handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc, STE.n_value); } }; static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; } } /// Reset the parser state coresponding to the current object /// file. This is to be called after an object file is finished /// processing. void MachODebugMapParser::resetParserState() { CurrentObjectAddresses.clear(); CurrentDebugMapObject = nullptr; } /// Create a new DebugMapObject. This function resets the state of the /// parser that was referring to the last object file and sets /// everything up to add symbols to the new one. void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) { resetParserState(); SmallString<80> Path(PathPrefix); sys::path::append(Path, Filename); auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path); if (auto Error = MachOOrError.getError()) { Warning(Twine("cannot open debug object \"") + Path.str() + "\": " + Error.message() + "\n"); return; } loadCurrentObjectFileSymbols(); CurrentDebugMapObject = &Result->addDebugMapObject(Path); } static Triple getTriple(const object::MachOObjectFile &Obj) { Triple TheTriple("unknown-unknown-unknown"); TheTriple.setArch(Triple::ArchType(Obj.getArch())); TheTriple.setObjectFormat(Triple::MachO); return TheTriple; } /// This main parsing routine tries to open the main binary and if /// successful iterates over the STAB entries. The real parsing is /// done in handleStabSymbolTableEntry. ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() { auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath); if (auto Error = MainBinOrError.getError()) return Error; const MachOObjectFile &MainBinary = *MainBinOrError; loadMainBinarySymbols(); Result = make_unique<DebugMap>(getTriple(MainBinary)); MainBinaryStrings = MainBinary.getStringTableData(); for (const SymbolRef &Symbol : MainBinary.symbols()) { const DataRefImpl &DRI = Symbol.getRawDataRefImpl(); if (MainBinary.is64Bit()) handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI)); else handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI)); } resetParserState(); return std::move(Result); } /// Interpret the STAB entries to fill the DebugMap. void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type, uint8_t SectionIndex, uint16_t Flags, uint64_t Value) { if (!(Type & MachO::N_STAB)) return; const char *Name = &MainBinaryStrings.data()[StringIndex]; // An N_OSO entry represents the start of a new object file description. if (Type == MachO::N_OSO) return switchToNewDebugMapObject(Name); // If the last N_OSO object file wasn't found, // CurrentDebugMapObject will be null. Do not update anything // until we find the next valid N_OSO entry. if (!CurrentDebugMapObject) return; switch (Type) { case MachO::N_GSYM: // This is a global variable. We need to query the main binary // symbol table to find its address as it might not be in the // debug map (for common symbols). Value = getMainBinarySymbolAddress(Name); if (Value == UnknownAddressOrSize) return; break; case MachO::N_FUN: // Functions are scopes in STABS. They have an end marker that we // need to ignore. if (Name[0] == '\0') return; break; case MachO::N_STSYM: break; default: return; } auto ObjectSymIt = CurrentObjectAddresses.find(Name); if (ObjectSymIt == CurrentObjectAddresses.end()) return Warning("could not find object file symbol for symbol " + Twine(Name)); if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value)) return Warning(Twine("failed to insert symbol '") + Name + "' in the debug map."); } /// Load the current object file symbols into CurrentObjectAddresses. void MachODebugMapParser::loadCurrentObjectFileSymbols() { CurrentObjectAddresses.clear(); for (auto Sym : CurrentObjectHolder.Get().symbols()) { StringRef Name; uint64_t Addr; if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize || Sym.getName(Name)) continue; CurrentObjectAddresses[Name] = Addr; } } /// Lookup a symbol address in the main binary symbol table. The /// parser only needs to query common symbols, thus not every symbol's /// address is available through this function. uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) { auto Sym = MainBinarySymbolAddresses.find(Name); if (Sym == MainBinarySymbolAddresses.end()) return UnknownAddressOrSize; return Sym->second; } /// Load the interesting main binary symbols' addresses into /// MainBinarySymbolAddresses. void MachODebugMapParser::loadMainBinarySymbols() { const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>(); section_iterator Section = MainBinary.section_end(); for (const auto &Sym : MainBinary.symbols()) { SymbolRef::Type Type; // Skip undefined and STAB entries. if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) || (Type & SymbolRef::ST_Unknown)) continue; StringRef Name; uint64_t Addr; // The only symbols of interest are the global variables. These // are the only ones that need to be queried because the address // of common data won't be described in the debug map. All other // addresses should be fetched for the debug map. if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize || !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) || Section->isText() || Sym.getName(Name) || Name.size() == 0 || Name[0] == '\0') continue; MainBinarySymbolAddresses[Name] = Addr; } } namespace llvm { namespace dsymutil { llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose) { MachODebugMapParser Parser(InputFile, PrependPath, Verbose); return Parser.parse(); } } } <commit_msg>[dsymutil] clang-format a file<commit_after>//===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BinaryHolder.h" #include "DebugMap.h" #include "dsymutil.h" #include "llvm/Object/MachO.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" namespace { using namespace llvm; using namespace llvm::dsymutil; using namespace llvm::object; class MachODebugMapParser { public: MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "", bool Verbose = false) : BinaryPath(BinaryPath), PathPrefix(PathPrefix), MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose), CurrentDebugMapObject(nullptr) {} /// \brief Parses and returns the DebugMap of the input binary. /// \returns an error in case the provided BinaryPath doesn't exist /// or isn't of a supported type. ErrorOr<std::unique_ptr<DebugMap>> parse(); private: std::string BinaryPath; std::string PathPrefix; /// Owns the MemoryBuffer for the main binary. BinaryHolder MainBinaryHolder; /// Map of the binary symbol addresses. StringMap<uint64_t> MainBinarySymbolAddresses; StringRef MainBinaryStrings; /// The constructed DebugMap. std::unique_ptr<DebugMap> Result; /// Owns the MemoryBuffer for the currently handled object file. BinaryHolder CurrentObjectHolder; /// Map of the currently processed object file symbol addresses. StringMap<uint64_t> CurrentObjectAddresses; /// Element of the debug map corresponfing to the current object file. DebugMapObject *CurrentDebugMapObject; void switchToNewDebugMapObject(StringRef Filename); void resetParserState(); uint64_t getMainBinarySymbolAddress(StringRef Name); void loadMainBinarySymbols(); void loadCurrentObjectFileSymbols(); void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type, uint8_t SectionIndex, uint16_t Flags, uint64_t Value); template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) { handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc, STE.n_value); } }; static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; } } /// Reset the parser state coresponding to the current object /// file. This is to be called after an object file is finished /// processing. void MachODebugMapParser::resetParserState() { CurrentObjectAddresses.clear(); CurrentDebugMapObject = nullptr; } /// Create a new DebugMapObject. This function resets the state of the /// parser that was referring to the last object file and sets /// everything up to add symbols to the new one. void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) { resetParserState(); SmallString<80> Path(PathPrefix); sys::path::append(Path, Filename); auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path); if (auto Error = MachOOrError.getError()) { Warning(Twine("cannot open debug object \"") + Path.str() + "\": " + Error.message() + "\n"); return; } loadCurrentObjectFileSymbols(); CurrentDebugMapObject = &Result->addDebugMapObject(Path); } static Triple getTriple(const object::MachOObjectFile &Obj) { Triple TheTriple("unknown-unknown-unknown"); TheTriple.setArch(Triple::ArchType(Obj.getArch())); TheTriple.setObjectFormat(Triple::MachO); return TheTriple; } /// This main parsing routine tries to open the main binary and if /// successful iterates over the STAB entries. The real parsing is /// done in handleStabSymbolTableEntry. ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() { auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath); if (auto Error = MainBinOrError.getError()) return Error; const MachOObjectFile &MainBinary = *MainBinOrError; loadMainBinarySymbols(); Result = make_unique<DebugMap>(getTriple(MainBinary)); MainBinaryStrings = MainBinary.getStringTableData(); for (const SymbolRef &Symbol : MainBinary.symbols()) { const DataRefImpl &DRI = Symbol.getRawDataRefImpl(); if (MainBinary.is64Bit()) handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI)); else handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI)); } resetParserState(); return std::move(Result); } /// Interpret the STAB entries to fill the DebugMap. void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type, uint8_t SectionIndex, uint16_t Flags, uint64_t Value) { if (!(Type & MachO::N_STAB)) return; const char *Name = &MainBinaryStrings.data()[StringIndex]; // An N_OSO entry represents the start of a new object file description. if (Type == MachO::N_OSO) return switchToNewDebugMapObject(Name); // If the last N_OSO object file wasn't found, // CurrentDebugMapObject will be null. Do not update anything // until we find the next valid N_OSO entry. if (!CurrentDebugMapObject) return; switch (Type) { case MachO::N_GSYM: // This is a global variable. We need to query the main binary // symbol table to find its address as it might not be in the // debug map (for common symbols). Value = getMainBinarySymbolAddress(Name); if (Value == UnknownAddressOrSize) return; break; case MachO::N_FUN: // Functions are scopes in STABS. They have an end marker that we // need to ignore. if (Name[0] == '\0') return; break; case MachO::N_STSYM: break; default: return; } auto ObjectSymIt = CurrentObjectAddresses.find(Name); if (ObjectSymIt == CurrentObjectAddresses.end()) return Warning("could not find object file symbol for symbol " + Twine(Name)); if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value)) return Warning(Twine("failed to insert symbol '") + Name + "' in the debug map."); } /// Load the current object file symbols into CurrentObjectAddresses. void MachODebugMapParser::loadCurrentObjectFileSymbols() { CurrentObjectAddresses.clear(); for (auto Sym : CurrentObjectHolder.Get().symbols()) { StringRef Name; uint64_t Addr; if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize || Sym.getName(Name)) continue; CurrentObjectAddresses[Name] = Addr; } } /// Lookup a symbol address in the main binary symbol table. The /// parser only needs to query common symbols, thus not every symbol's /// address is available through this function. uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) { auto Sym = MainBinarySymbolAddresses.find(Name); if (Sym == MainBinarySymbolAddresses.end()) return UnknownAddressOrSize; return Sym->second; } /// Load the interesting main binary symbols' addresses into /// MainBinarySymbolAddresses. void MachODebugMapParser::loadMainBinarySymbols() { const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>(); section_iterator Section = MainBinary.section_end(); for (const auto &Sym : MainBinary.symbols()) { SymbolRef::Type Type; // Skip undefined and STAB entries. if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) || (Type & SymbolRef::ST_Unknown)) continue; StringRef Name; uint64_t Addr; // The only symbols of interest are the global variables. These // are the only ones that need to be queried because the address // of common data won't be described in the debug map. All other // addresses should be fetched for the debug map. if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize || !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) || Section->isText() || Sym.getName(Name) || Name.size() == 0 || Name[0] == '\0') continue; MainBinarySymbolAddresses[Name] = Addr; } } namespace llvm { namespace dsymutil { llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose) { MachODebugMapParser Parser(InputFile, PrependPath, Verbose); return Parser.parse(); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2012-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <Windows.h> #include <stdio.h> #include <wchar.h> #include <vector> #include <QString> #include <QFileInfo> #include <QDir> #include <TGlobal> #include <TWebApplication> #include <TSystemGlobal> namespace TreeFrog { extern int managerMain(int argc, char *argv[]); static SERVICE_STATUS_HANDLE statusHandle; static SERVICE_STATUS serviceStatus = { SERVICE_WIN32_OWN_PROCESS, // dwServiceType; SERVICE_START_PENDING, // dwCurrentState SERVICE_ACCEPT_STOP, // dwControlsAccepted NO_ERROR, // dwWin32ExitCode NO_ERROR, // dwServiceSpecificExitCode 0, // dwCheckPoint 0 // dwWaitHint }; static QString enumerateService(DWORD processId) { SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT); if (hSCM == NULL) { return QString(); } DWORD bufferSize = 0; DWORD requiredBufferSize = 0; DWORD totalServicesCount = 0; EnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, NULL, bufferSize, &requiredBufferSize, &totalServicesCount, NULL, NULL); std::vector<BYTE> buffer(requiredBufferSize); EnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, buffer.data(), buffer.size(), &requiredBufferSize, &totalServicesCount, NULL, NULL); QString name; LPENUM_SERVICE_STATUS_PROCESS services = reinterpret_cast<LPENUM_SERVICE_STATUS_PROCESS>(buffer.data()); for (unsigned int i = 0; i < totalServicesCount; ++i) { ENUM_SERVICE_STATUS_PROCESS service = services[i]; if (service.ServiceStatusProcess.dwProcessId == processId) { // This is your service. name = QString::fromUtf16((const ushort*)service.lpServiceName); break; } } CloseServiceHandle(hSCM); return name; } static QString serviceFilePath(const QString &serviceName) { QString result; // Open the Service Control Manager SC_HANDLE schSCManager = OpenSCManager( NULL, // local computer NULL, // ServicesActive database SC_MANAGER_ALL_ACCESS); // full access rights if (schSCManager) { // Try to open the service SC_HANDLE schService = OpenService( schSCManager, (const wchar_t*)serviceName.utf16(), SERVICE_QUERY_CONFIG); if (schService) { DWORD sizeNeeded = 0; char data[8 * 1024]; if (QueryServiceConfig(schService, (LPQUERY_SERVICE_CONFIG)data, 8 * 1024, &sizeNeeded)) { LPQUERY_SERVICE_CONFIG config = (LPQUERY_SERVICE_CONFIG)data; result = QString::fromUtf16((const ushort*)config->lpBinaryPathName); } CloseServiceHandle(schService); } CloseServiceHandle(schSCManager); } return result; } static void WINAPI serviceHandler(DWORD ctrl) { switch (ctrl) { case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_SHUTDOWN: tSystemInfo("Windows service: Received a stop-service request."); serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; serviceStatus.dwWaitHint = 30000; SetServiceStatus(statusHandle, &serviceStatus); Tf::app()->exit(0); break; case SERVICE_CONTROL_PAUSE: case SERVICE_CONTROL_CONTINUE: case SERVICE_CONTROL_INTERROGATE: tSystemWarn("Windows service: Received ctrl code: %ld ", ctrl); SetServiceStatus(statusHandle, &serviceStatus); break; default: tSystemWarn("Windows service: Invalid ctrl code: %ld ", ctrl); break; } } void WINAPI winServiceMain(DWORD, LPTSTR *) { QString serviceName = enumerateService(GetCurrentProcessId()); statusHandle = RegisterServiceCtrlHandler((const wchar_t*)serviceName.utf16(), serviceHandler); if (!statusHandle) return; // Service status serviceStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(statusHandle, &serviceStatus); // Main function int ret = 1; QString binary = serviceFilePath(serviceName); if (!binary.isEmpty()) { const char *args[1] = {binary.toStdString().c_str()}; try { QDir::setCurrent(QFileInfo(binary).absolutePath()); ret = managerMain(1, (char**)args); } catch (...) { } } // Service status serviceStatus.dwCurrentState = SERVICE_STOPPED; serviceStatus.dwWin32ExitCode = ret; SetServiceStatus(statusHandle, &serviceStatus); } } // namespace TreeFrog <commit_msg>updated indents.<commit_after>/* Copyright (c) 2012-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <Windows.h> #include <wchar.h> #include <vector> #include <QString> #include <QFileInfo> #include <QDir> #include <TGlobal> #include <TWebApplication> #include <TSystemGlobal> namespace TreeFrog { extern int managerMain(int argc, char *argv[]); static SERVICE_STATUS_HANDLE statusHandle; static SERVICE_STATUS serviceStatus = { SERVICE_WIN32_OWN_PROCESS, // dwServiceType; SERVICE_START_PENDING, // dwCurrentState SERVICE_ACCEPT_STOP, // dwControlsAccepted NO_ERROR, // dwWin32ExitCode NO_ERROR, // dwServiceSpecificExitCode 0, // dwCheckPoint 0 // dwWaitHint }; static QString enumerateService(DWORD processId) { SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT); if (hSCM == NULL) { return QString(); } DWORD bufferSize = 0; DWORD requiredBufferSize = 0; DWORD totalServicesCount = 0; EnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, NULL, bufferSize, &requiredBufferSize, &totalServicesCount, NULL, NULL); std::vector<BYTE> buffer(requiredBufferSize); EnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, buffer.data(), buffer.size(), &requiredBufferSize, &totalServicesCount, NULL, NULL); QString name; LPENUM_SERVICE_STATUS_PROCESS services = reinterpret_cast<LPENUM_SERVICE_STATUS_PROCESS>(buffer.data()); for (unsigned int i = 0; i < totalServicesCount; ++i) { ENUM_SERVICE_STATUS_PROCESS service = services[i]; if (service.ServiceStatusProcess.dwProcessId == processId) { // This is your service. name = QString::fromUtf16((const ushort*)service.lpServiceName); break; } } CloseServiceHandle(hSCM); return name; } static QString serviceFilePath(const QString &serviceName) { QString result; // Open the Service Control Manager SC_HANDLE schSCManager = OpenSCManager( NULL, // local computer NULL, // ServicesActive database SC_MANAGER_ALL_ACCESS); // full access rights if (schSCManager) { // Try to open the service SC_HANDLE schService = OpenService( schSCManager, (const wchar_t*)serviceName.utf16(), SERVICE_QUERY_CONFIG); if (schService) { DWORD sizeNeeded = 0; char data[8 * 1024]; if (QueryServiceConfig(schService, (LPQUERY_SERVICE_CONFIG)data, sizeof(data), &sizeNeeded)) { LPQUERY_SERVICE_CONFIG config = (LPQUERY_SERVICE_CONFIG)data; result = QString::fromUtf16((const ushort*)config->lpBinaryPathName); } CloseServiceHandle(schService); } CloseServiceHandle(schSCManager); } return result; } static void WINAPI serviceHandler(DWORD ctrl) { switch (ctrl) { case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_SHUTDOWN: tSystemInfo("Windows service: Received a stop-service request."); serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; serviceStatus.dwWaitHint = 30000; SetServiceStatus(statusHandle, &serviceStatus); Tf::app()->exit(0); break; case SERVICE_CONTROL_PAUSE: case SERVICE_CONTROL_CONTINUE: case SERVICE_CONTROL_INTERROGATE: tSystemWarn("Windows service: Received ctrl code: %ld ", ctrl); SetServiceStatus(statusHandle, &serviceStatus); break; default: tSystemWarn("Windows service: Invalid ctrl code: %ld ", ctrl); break; } } void WINAPI winServiceMain(DWORD, LPTSTR *) { QString serviceName = enumerateService(GetCurrentProcessId()); statusHandle = RegisterServiceCtrlHandler((const wchar_t*)serviceName.utf16(), serviceHandler); if (!statusHandle) return; // Service status serviceStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(statusHandle, &serviceStatus); // Main function int ret = 1; QString binary = serviceFilePath(serviceName); if (!binary.isEmpty()) { const char *args[1] = { binary.toStdString().c_str() }; try { QDir::setCurrent(QFileInfo(binary).absolutePath()); ret = managerMain(1, (char**)args); } catch (...) { } } // Service status serviceStatus.dwCurrentState = SERVICE_STOPPED; serviceStatus.dwWin32ExitCode = ret; SetServiceStatus(statusHandle, &serviceStatus); } } // namespace TreeFrog <|endoftext|>
<commit_before>#include <math.h> #include <stdio.h> #include <string.h> #include <algorithm> #include "timeEstimate.h" namespace cura { #define MINIMUM_PLANNER_SPEED 0.05// (mm/sec) const double max_feedrate[TimeEstimateCalculator::NUM_AXIS] = {600, 600, 40, 25}; const double minimumfeedrate = 0.01; const double acceleration = 3000; const double max_acceleration[TimeEstimateCalculator::NUM_AXIS] = {9000,9000,100,10000}; const double max_xy_jerk = 20.0; const double max_z_jerk = 0.4; const double max_e_jerk = 5.0; template<typename T> const T square(const T& a) { return a * a; } void TimeEstimateCalculator::setPosition(Position newPos) { currentPosition = newPos; } void TimeEstimateCalculator::reset() { blocks.clear(); } // Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the // acceleration within the allotted distance. static inline double max_allowable_speed(double acceleration, double target_velocity, double distance) { return sqrt(target_velocity*target_velocity-2*acceleration*distance); } // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the given acceleration: static inline float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration) { if (acceleration == 0) return 0.0; return (square(target_rate)-square(initial_rate)) / (2.0*acceleration); } // This function gives you the point at which you must start braking (at the rate of -acceleration) if // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after // a total travel of distance. This can be used to compute the intersection point between acceleration and // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed) static inline double intersection_distance(double initial_rate, double final_rate, double acceleration, double distance) { if (acceleration == 0.0) return 0.0; return (2.0*acceleration*distance-square(initial_rate)+square(final_rate)) / (4.0*acceleration); } // This function gives the time it needs to accelerate from an initial speed to reach a final distance. static inline double acceleration_time_from_distance(double initial_feedrate, double distance, double acceleration) { double discriminant = sqrt(square(initial_feedrate) - 2 * acceleration * -distance); return (-initial_feedrate + discriminant) / acceleration; } // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors. void TimeEstimateCalculator::calculate_trapezoid_for_block(Block *block, double entry_factor, double exit_factor) { double initial_feedrate = block->nominal_feedrate*entry_factor; double final_feedrate = block->nominal_feedrate*exit_factor; double acceleration = block->acceleration; double accelerate_distance = estimate_acceleration_distance(initial_feedrate, block->nominal_feedrate, acceleration); double decelerate_distance = estimate_acceleration_distance(block->nominal_feedrate, final_feedrate, -acceleration); // Calculate the size of Plateau of Nominal Rate. double plateau_distance = block->distance-accelerate_distance - decelerate_distance; // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will // have to use intersection_distance() to calculate when to abort acceleration and start braking // in order to reach the final_rate exactly at the end of this block. if (plateau_distance < 0) { accelerate_distance = intersection_distance(initial_feedrate, final_feedrate, acceleration, block->distance); accelerate_distance = std::max(accelerate_distance, 0.0); // Check limits due to numerical round-off accelerate_distance = std::min(accelerate_distance, block->distance);//(We can cast here to unsigned, because the above line ensures that we are above zero) plateau_distance = 0; } block->accelerate_until = accelerate_distance; block->decelerate_after = accelerate_distance+plateau_distance; block->initial_feedrate = initial_feedrate; block->final_feedrate = final_feedrate; } void TimeEstimateCalculator::plan(Position newPos, double feedrate) { Block block; memset(&block, 0, sizeof(block)); block.maxTravel = 0; for(unsigned int n=0; n<NUM_AXIS; n++) { block.delta[n] = newPos[n] - currentPosition[n]; block.absDelta[n] = fabs(block.delta[n]); block.maxTravel = std::max(block.maxTravel, block.absDelta[n]); } if (block.maxTravel <= 0) return; if (feedrate < minimumfeedrate) feedrate = minimumfeedrate; block.distance = sqrtf(square(block.absDelta[0]) + square(block.absDelta[1]) + square(block.absDelta[2])); if (block.distance == 0.0) block.distance = block.absDelta[3]; block.nominal_feedrate = feedrate; Position current_feedrate; Position current_abs_feedrate; double feedrate_factor = 1.0; for(unsigned int n=0; n<NUM_AXIS; n++) { current_feedrate[n] = block.delta[n] * feedrate / block.distance; current_abs_feedrate[n] = fabs(current_feedrate[n]); if (current_abs_feedrate[n] > max_feedrate[n]) feedrate_factor = std::min(feedrate_factor, max_feedrate[n] / current_abs_feedrate[n]); } //TODO: XY_FREQUENCY_LIMIT if(feedrate_factor < 1.0) { for(unsigned int n=0; n<NUM_AXIS; n++) { current_feedrate[n] *= feedrate_factor; current_abs_feedrate[n] *= feedrate_factor; } block.nominal_feedrate *= feedrate_factor; } block.acceleration = acceleration; for(unsigned int n=0; n<NUM_AXIS; n++) { if (block.acceleration * (block.absDelta[n] / block.distance) > max_acceleration[n]) block.acceleration = max_acceleration[n]; } double vmax_junction = max_xy_jerk/2; double vmax_junction_factor = 1.0; if(current_abs_feedrate[Z_AXIS] > max_z_jerk/2) vmax_junction = std::min(vmax_junction, max_z_jerk/2); if(current_abs_feedrate[E_AXIS] > max_e_jerk/2) vmax_junction = std::min(vmax_junction, max_e_jerk/2); vmax_junction = std::min(vmax_junction, block.nominal_feedrate); double safe_speed = vmax_junction; if ((blocks.size() > 0) && (previous_nominal_feedrate > 0.0001)) { double xy_jerk = sqrt(square(current_feedrate[X_AXIS]-previous_feedrate[X_AXIS])+square(current_feedrate[Y_AXIS]-previous_feedrate[Y_AXIS])); vmax_junction = block.nominal_feedrate; if (xy_jerk > max_xy_jerk) { vmax_junction_factor = (max_xy_jerk/xy_jerk); } if(fabs(current_feedrate[Z_AXIS] - previous_feedrate[Z_AXIS]) > max_z_jerk) { vmax_junction_factor = std::min(vmax_junction_factor, (max_z_jerk/fabs(current_feedrate[Z_AXIS] - previous_feedrate[Z_AXIS]))); } if(fabs(current_feedrate[E_AXIS] - previous_feedrate[E_AXIS]) > max_e_jerk) { vmax_junction_factor = std::min(vmax_junction_factor, (max_e_jerk/fabs(current_feedrate[E_AXIS] - previous_feedrate[E_AXIS]))); } vmax_junction = std::min(previous_nominal_feedrate, vmax_junction * vmax_junction_factor); // Limit speed to max previous speed } block.max_entry_speed = vmax_junction; double v_allowable = max_allowable_speed(-block.acceleration, MINIMUM_PLANNER_SPEED, block.distance); block.entry_speed = std::min(vmax_junction, v_allowable); block.nominal_length_flag = block.nominal_feedrate <= v_allowable; block.recalculate_flag = true; // Always calculate trapezoid for new block previous_feedrate = current_feedrate; previous_nominal_feedrate = block.nominal_feedrate; currentPosition = newPos; calculate_trapezoid_for_block(&block, block.entry_speed/block.nominal_feedrate, safe_speed/block.nominal_feedrate); blocks.push_back(block); } double TimeEstimateCalculator::calculate() { reverse_pass(); forward_pass(); recalculate_trapezoids(); double totalTime = 0; for(unsigned int n=0; n<blocks.size(); n++) { Block& block = blocks[n]; double plateau_distance = block.decelerate_after - block.accelerate_until; totalTime += acceleration_time_from_distance(block.initial_feedrate, block.accelerate_until, block.acceleration); totalTime += plateau_distance / block.nominal_feedrate; totalTime += acceleration_time_from_distance(block.final_feedrate, (block.distance - block.decelerate_after), block.acceleration); } return totalTime; } // The kernel called by accelerationPlanner::calculate() when scanning the plan from last to first entry. void TimeEstimateCalculator::planner_reverse_pass_kernel(Block *previous, Block *current, Block *next) { (void)previous; if(!current || !next) return; // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and // check for maximum allowable speed reductions to ensure maximum possible planned speed. if (current->entry_speed != current->max_entry_speed) { // If nominal length true, max junction speed is guaranteed to be reached. Only compute // for max allowable speed if block is decelerating and nominal length is false. if ((!current->nominal_length_flag) && (current->max_entry_speed > next->entry_speed)) { current->entry_speed = std::min(current->max_entry_speed, max_allowable_speed(-current->acceleration, next->entry_speed, current->distance)); } else { current->entry_speed = current->max_entry_speed; } current->recalculate_flag = true; } } void TimeEstimateCalculator::reverse_pass() { Block* block[3] = {nullptr, nullptr, nullptr}; for(unsigned int n=blocks.size()-1; int(n)>=0; n--) { block[2]= block[1]; block[1]= block[0]; block[0] = &blocks[n]; planner_reverse_pass_kernel(block[0], block[1], block[2]); } } // The kernel called by accelerationPlanner::calculate() when scanning the plan from first to last entry. void TimeEstimateCalculator::planner_forward_pass_kernel(Block *previous, Block *current, Block *next) { (void)next; if(!previous) return; // If the previous block is an acceleration block, but it is not long enough to complete the // full speed change within the block, we need to adjust the entry speed accordingly. Entry // speeds have already been reset, maximized, and reverse planned by reverse planner. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck. if (!previous->nominal_length_flag) { if (previous->entry_speed < current->entry_speed) { double entry_speed = std::min(current->entry_speed, max_allowable_speed(-previous->acceleration,previous->entry_speed,previous->distance) ); // Check for junction speed change if (current->entry_speed != entry_speed) { current->entry_speed = entry_speed; current->recalculate_flag = true; } } } } void TimeEstimateCalculator::forward_pass() { Block* block[3] = {nullptr, nullptr, nullptr}; for(unsigned int n=0; n<blocks.size(); n++) { block[0]= block[1]; block[1]= block[2]; block[2] = &blocks[n]; planner_forward_pass_kernel(block[0], block[1], block[2]); } planner_forward_pass_kernel(block[1], block[2], nullptr); } // Recalculates the trapezoid speed profiles for all blocks in the plan according to the // entry_factor for each junction. Must be called by planner_recalculate() after // updating the blocks. void TimeEstimateCalculator::recalculate_trapezoids() { Block *current; Block *next = nullptr; for(unsigned int n=0; n<blocks.size(); n--) { current = next; next = &blocks[n]; if (current) { // Recalculate if current block entry or exit junction speed has changed. if (current->recalculate_flag || next->recalculate_flag) { // NOTE: Entry and exit factors always > 0 by all previous logic operations. calculate_trapezoid_for_block(current, current->entry_speed/current->nominal_feedrate, next->entry_speed/current->nominal_feedrate); current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed } } } // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated. if(next != nullptr) { calculate_trapezoid_for_block(next, next->entry_speed/next->nominal_feedrate, MINIMUM_PLANNER_SPEED/next->nominal_feedrate); next->recalculate_flag = false; } } }//namespace cura<commit_msg>bugfix: timeEstimate recalculate trapezoids failed<commit_after>#include <math.h> #include <stdio.h> #include <string.h> #include <algorithm> #include "timeEstimate.h" namespace cura { #define MINIMUM_PLANNER_SPEED 0.05// (mm/sec) const double max_feedrate[TimeEstimateCalculator::NUM_AXIS] = {600, 600, 40, 25}; const double minimumfeedrate = 0.01; const double acceleration = 3000; const double max_acceleration[TimeEstimateCalculator::NUM_AXIS] = {9000,9000,100,10000}; const double max_xy_jerk = 20.0; const double max_z_jerk = 0.4; const double max_e_jerk = 5.0; template<typename T> const T square(const T& a) { return a * a; } void TimeEstimateCalculator::setPosition(Position newPos) { currentPosition = newPos; } void TimeEstimateCalculator::reset() { blocks.clear(); } // Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the // acceleration within the allotted distance. static inline double max_allowable_speed(double acceleration, double target_velocity, double distance) { return sqrt(target_velocity*target_velocity-2*acceleration*distance); } // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the given acceleration: static inline float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration) { if (acceleration == 0) return 0.0; return (square(target_rate)-square(initial_rate)) / (2.0*acceleration); } // This function gives you the point at which you must start braking (at the rate of -acceleration) if // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after // a total travel of distance. This can be used to compute the intersection point between acceleration and // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed) static inline double intersection_distance(double initial_rate, double final_rate, double acceleration, double distance) { if (acceleration == 0.0) return 0.0; return (2.0*acceleration*distance-square(initial_rate)+square(final_rate)) / (4.0*acceleration); } // This function gives the time it needs to accelerate from an initial speed to reach a final distance. static inline double acceleration_time_from_distance(double initial_feedrate, double distance, double acceleration) { double discriminant = sqrt(square(initial_feedrate) - 2 * acceleration * -distance); return (-initial_feedrate + discriminant) / acceleration; } // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors. void TimeEstimateCalculator::calculate_trapezoid_for_block(Block *block, double entry_factor, double exit_factor) { double initial_feedrate = block->nominal_feedrate*entry_factor; double final_feedrate = block->nominal_feedrate*exit_factor; double acceleration = block->acceleration; double accelerate_distance = estimate_acceleration_distance(initial_feedrate, block->nominal_feedrate, acceleration); double decelerate_distance = estimate_acceleration_distance(block->nominal_feedrate, final_feedrate, -acceleration); // Calculate the size of Plateau of Nominal Rate. double plateau_distance = block->distance-accelerate_distance - decelerate_distance; // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will // have to use intersection_distance() to calculate when to abort acceleration and start braking // in order to reach the final_rate exactly at the end of this block. if (plateau_distance < 0) { accelerate_distance = intersection_distance(initial_feedrate, final_feedrate, acceleration, block->distance); accelerate_distance = std::max(accelerate_distance, 0.0); // Check limits due to numerical round-off accelerate_distance = std::min(accelerate_distance, block->distance);//(We can cast here to unsigned, because the above line ensures that we are above zero) plateau_distance = 0; } block->accelerate_until = accelerate_distance; block->decelerate_after = accelerate_distance+plateau_distance; block->initial_feedrate = initial_feedrate; block->final_feedrate = final_feedrate; } void TimeEstimateCalculator::plan(Position newPos, double feedrate) { Block block; memset(&block, 0, sizeof(block)); block.maxTravel = 0; for(unsigned int n=0; n<NUM_AXIS; n++) { block.delta[n] = newPos[n] - currentPosition[n]; block.absDelta[n] = fabs(block.delta[n]); block.maxTravel = std::max(block.maxTravel, block.absDelta[n]); } if (block.maxTravel <= 0) return; if (feedrate < minimumfeedrate) feedrate = minimumfeedrate; block.distance = sqrtf(square(block.absDelta[0]) + square(block.absDelta[1]) + square(block.absDelta[2])); if (block.distance == 0.0) block.distance = block.absDelta[3]; block.nominal_feedrate = feedrate; Position current_feedrate; Position current_abs_feedrate; double feedrate_factor = 1.0; for(unsigned int n=0; n<NUM_AXIS; n++) { current_feedrate[n] = block.delta[n] * feedrate / block.distance; current_abs_feedrate[n] = fabs(current_feedrate[n]); if (current_abs_feedrate[n] > max_feedrate[n]) feedrate_factor = std::min(feedrate_factor, max_feedrate[n] / current_abs_feedrate[n]); } //TODO: XY_FREQUENCY_LIMIT if(feedrate_factor < 1.0) { for(unsigned int n=0; n<NUM_AXIS; n++) { current_feedrate[n] *= feedrate_factor; current_abs_feedrate[n] *= feedrate_factor; } block.nominal_feedrate *= feedrate_factor; } block.acceleration = acceleration; for(unsigned int n=0; n<NUM_AXIS; n++) { if (block.acceleration * (block.absDelta[n] / block.distance) > max_acceleration[n]) block.acceleration = max_acceleration[n]; } double vmax_junction = max_xy_jerk/2; double vmax_junction_factor = 1.0; if(current_abs_feedrate[Z_AXIS] > max_z_jerk/2) vmax_junction = std::min(vmax_junction, max_z_jerk/2); if(current_abs_feedrate[E_AXIS] > max_e_jerk/2) vmax_junction = std::min(vmax_junction, max_e_jerk/2); vmax_junction = std::min(vmax_junction, block.nominal_feedrate); double safe_speed = vmax_junction; if ((blocks.size() > 0) && (previous_nominal_feedrate > 0.0001)) { double xy_jerk = sqrt(square(current_feedrate[X_AXIS]-previous_feedrate[X_AXIS])+square(current_feedrate[Y_AXIS]-previous_feedrate[Y_AXIS])); vmax_junction = block.nominal_feedrate; if (xy_jerk > max_xy_jerk) { vmax_junction_factor = (max_xy_jerk/xy_jerk); } if(fabs(current_feedrate[Z_AXIS] - previous_feedrate[Z_AXIS]) > max_z_jerk) { vmax_junction_factor = std::min(vmax_junction_factor, (max_z_jerk/fabs(current_feedrate[Z_AXIS] - previous_feedrate[Z_AXIS]))); } if(fabs(current_feedrate[E_AXIS] - previous_feedrate[E_AXIS]) > max_e_jerk) { vmax_junction_factor = std::min(vmax_junction_factor, (max_e_jerk/fabs(current_feedrate[E_AXIS] - previous_feedrate[E_AXIS]))); } vmax_junction = std::min(previous_nominal_feedrate, vmax_junction * vmax_junction_factor); // Limit speed to max previous speed } block.max_entry_speed = vmax_junction; double v_allowable = max_allowable_speed(-block.acceleration, MINIMUM_PLANNER_SPEED, block.distance); block.entry_speed = std::min(vmax_junction, v_allowable); block.nominal_length_flag = block.nominal_feedrate <= v_allowable; block.recalculate_flag = true; // Always calculate trapezoid for new block previous_feedrate = current_feedrate; previous_nominal_feedrate = block.nominal_feedrate; currentPosition = newPos; calculate_trapezoid_for_block(&block, block.entry_speed/block.nominal_feedrate, safe_speed/block.nominal_feedrate); blocks.push_back(block); } double TimeEstimateCalculator::calculate() { reverse_pass(); forward_pass(); recalculate_trapezoids(); double totalTime = 0; for(unsigned int n=0; n<blocks.size(); n++) { Block& block = blocks[n]; double plateau_distance = block.decelerate_after - block.accelerate_until; totalTime += acceleration_time_from_distance(block.initial_feedrate, block.accelerate_until, block.acceleration); totalTime += plateau_distance / block.nominal_feedrate; totalTime += acceleration_time_from_distance(block.final_feedrate, (block.distance - block.decelerate_after), block.acceleration); } return totalTime; } // The kernel called by accelerationPlanner::calculate() when scanning the plan from last to first entry. void TimeEstimateCalculator::planner_reverse_pass_kernel(Block *previous, Block *current, Block *next) { (void)previous; if(!current || !next) return; // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and // check for maximum allowable speed reductions to ensure maximum possible planned speed. if (current->entry_speed != current->max_entry_speed) { // If nominal length true, max junction speed is guaranteed to be reached. Only compute // for max allowable speed if block is decelerating and nominal length is false. if ((!current->nominal_length_flag) && (current->max_entry_speed > next->entry_speed)) { current->entry_speed = std::min(current->max_entry_speed, max_allowable_speed(-current->acceleration, next->entry_speed, current->distance)); } else { current->entry_speed = current->max_entry_speed; } current->recalculate_flag = true; } } void TimeEstimateCalculator::reverse_pass() { Block* block[3] = {nullptr, nullptr, nullptr}; for(unsigned int n=blocks.size()-1; int(n)>=0; n--) { block[2]= block[1]; block[1]= block[0]; block[0] = &blocks[n]; planner_reverse_pass_kernel(block[0], block[1], block[2]); } } // The kernel called by accelerationPlanner::calculate() when scanning the plan from first to last entry. void TimeEstimateCalculator::planner_forward_pass_kernel(Block *previous, Block *current, Block *next) { (void)next; if(!previous) return; // If the previous block is an acceleration block, but it is not long enough to complete the // full speed change within the block, we need to adjust the entry speed accordingly. Entry // speeds have already been reset, maximized, and reverse planned by reverse planner. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck. if (!previous->nominal_length_flag) { if (previous->entry_speed < current->entry_speed) { double entry_speed = std::min(current->entry_speed, max_allowable_speed(-previous->acceleration,previous->entry_speed,previous->distance) ); // Check for junction speed change if (current->entry_speed != entry_speed) { current->entry_speed = entry_speed; current->recalculate_flag = true; } } } } void TimeEstimateCalculator::forward_pass() { Block* block[3] = {nullptr, nullptr, nullptr}; for(unsigned int n=0; n<blocks.size(); n++) { block[0]= block[1]; block[1]= block[2]; block[2] = &blocks[n]; planner_forward_pass_kernel(block[0], block[1], block[2]); } planner_forward_pass_kernel(block[1], block[2], nullptr); } // Recalculates the trapezoid speed profiles for all blocks in the plan according to the // entry_factor for each junction. Must be called by planner_recalculate() after // updating the blocks. void TimeEstimateCalculator::recalculate_trapezoids() { Block *current; Block *next = nullptr; for(unsigned int n=0; n<blocks.size(); n++) { current = next; next = &blocks[n]; if (current) { // Recalculate if current block entry or exit junction speed has changed. if (current->recalculate_flag || next->recalculate_flag) { // NOTE: Entry and exit factors always > 0 by all previous logic operations. calculate_trapezoid_for_block(current, current->entry_speed/current->nominal_feedrate, next->entry_speed/current->nominal_feedrate); current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed } } } // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated. if(next != nullptr) { calculate_trapezoid_for_block(next, next->entry_speed/next->nominal_feedrate, MINIMUM_PLANNER_SPEED/next->nominal_feedrate); next->recalculate_flag = false; } } }//namespace cura<|endoftext|>
<commit_before>/* * Certificate Verify Message * (C) 2004,2006,2011,2012 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/internal/tls_messages.h> #include <botan/internal/tls_reader.h> #include <botan/internal/assert.h> #include <botan/tls_exceptn.h> #include <botan/pubkey.h> #include <botan/rsa.h> #include <botan/dsa.h> #include <botan/loadstor.h> #include <memory> namespace Botan { /* * Create a new Certificate Verify message */ Certificate_Verify::Certificate_Verify(Record_Writer& writer, TLS_Handshake_Hash& hash, RandomNumberGenerator& rng, Version_Code version, const SecureVector<byte>& master_secret, const Private_Key* priv_key) { BOTAN_ASSERT_NONNULL(priv_key); std::string padding = ""; Signature_Format format = IEEE_1363; if(priv_key->algo_name() == "RSA") padding = "EMSA3(TLS.Digest.0)"; else if(priv_key->algo_name() == "DSA") { if(version == SSL_V3) padding = "Raw"; else padding = "EMSA1(SHA-1)"; format = DER_SEQUENCE; } else throw Invalid_Argument(priv_key->algo_name() + " is invalid/unknown for TLS signatures"); PK_Signer signer(*priv_key, padding, format); if(version == SSL_V3) { SecureVector<byte> md5_sha = hash.final_ssl3(master_secret); signature = signer.sign_message(&md5_sha[16], md5_sha.size()-16, rng); } else if(version == TLS_V10 || version == TLS_V11) { signature = signer.sign_message(hash.get_contents(), rng); } else throw TLS_Exception(PROTOCOL_VERSION, "Unknown TLS version in certificate verification"); send(writer, hash); } /* * Serialize a Certificate Verify message */ MemoryVector<byte> Certificate_Verify::serialize() const { MemoryVector<byte> buf; const u16bit sig_len = signature.size(); buf.push_back(get_byte(0, sig_len)); buf.push_back(get_byte(1, sig_len)); buf += signature; return buf; } /* * Deserialize a Certificate Verify message */ void Certificate_Verify::deserialize(const MemoryRegion<byte>& buf) { TLS_Data_Reader reader(buf); signature = reader.get_range<byte>(2, 0, 65535); } /* * Verify a Certificate Verify message */ bool Certificate_Verify::verify(const X509_Certificate& cert, TLS_Handshake_Hash& hash, Version_Code version, const SecureVector<byte>& master_secret) { std::auto_ptr<Public_Key> key(cert.subject_public_key()); std::string padding = ""; Signature_Format format = IEEE_1363; if(key->algo_name() == "RSA") { padding = "EMSA3(TLS.Digest.0)"; } else if(key->algo_name() == "DSA") { if(version == SSL_V3) padding = "Raw"; else padding = "EMSA1(SHA-1)"; format = DER_SEQUENCE; } else throw Invalid_Argument(key->algo_name() + " is invalid/unknown for TLS signatures"); PK_Verifier verifier(*key, padding, format); if(version == SSL_V3) { SecureVector<byte> md5_sha = hash.final_ssl3(master_secret); return verifier.verify_message(&md5_sha[16], md5_sha.size()-16, &signature[0], signature.size()); } else if(version == TLS_V10 || version == TLS_V11) return verifier.verify_message(hash.get_contents(), signature); else throw TLS_Exception(PROTOCOL_VERSION, "Unknown TLS version in certificate verification"); } } <commit_msg>Fix RSA client cert verification for SSLv3<commit_after>/* * Certificate Verify Message * (C) 2004,2006,2011,2012 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/internal/tls_messages.h> #include <botan/internal/tls_reader.h> #include <botan/internal/assert.h> #include <botan/tls_exceptn.h> #include <botan/pubkey.h> #include <botan/rsa.h> #include <botan/dsa.h> #include <botan/loadstor.h> #include <memory> namespace Botan { /* * Create a new Certificate Verify message */ Certificate_Verify::Certificate_Verify(Record_Writer& writer, TLS_Handshake_Hash& hash, RandomNumberGenerator& rng, Version_Code version, const SecureVector<byte>& master_secret, const Private_Key* priv_key) { BOTAN_ASSERT_NONNULL(priv_key); std::string padding = ""; Signature_Format format = IEEE_1363; if(priv_key->algo_name() == "RSA") { if(version == SSL_V3) padding = "EMSA3(Raw)"; else padding = "EMSA3(TLS.Digest.0)"; } else if(priv_key->algo_name() == "DSA") { if(version == SSL_V3) padding = "Raw"; else padding = "EMSA1(SHA-1)"; format = DER_SEQUENCE; } else throw Invalid_Argument(priv_key->algo_name() + " is invalid/unknown for TLS signatures"); PK_Signer signer(*priv_key, padding, format); if(version == SSL_V3) { SecureVector<byte> md5_sha = hash.final_ssl3(master_secret); if(priv_key->algo_name() == "DSA") signature = signer.sign_message(&md5_sha[16], md5_sha.size()-16, rng); else signature = signer.sign_message(md5_sha, rng); } else if(version == TLS_V10 || version == TLS_V11) { signature = signer.sign_message(hash.get_contents(), rng); } else throw TLS_Exception(PROTOCOL_VERSION, "Unknown TLS version in certificate verification"); send(writer, hash); } /* * Serialize a Certificate Verify message */ MemoryVector<byte> Certificate_Verify::serialize() const { MemoryVector<byte> buf; const u16bit sig_len = signature.size(); buf.push_back(get_byte(0, sig_len)); buf.push_back(get_byte(1, sig_len)); buf += signature; return buf; } /* * Deserialize a Certificate Verify message */ void Certificate_Verify::deserialize(const MemoryRegion<byte>& buf) { TLS_Data_Reader reader(buf); signature = reader.get_range<byte>(2, 0, 65535); } /* * Verify a Certificate Verify message */ bool Certificate_Verify::verify(const X509_Certificate& cert, TLS_Handshake_Hash& hash, Version_Code version, const SecureVector<byte>& master_secret) { std::auto_ptr<Public_Key> key(cert.subject_public_key()); std::string padding = ""; Signature_Format format = IEEE_1363; if(key->algo_name() == "RSA") { if(version == SSL_V3) padding = "EMSA3(Raw)"; else padding = "EMSA3(TLS.Digest.0)"; } else if(key->algo_name() == "DSA") { if(version == SSL_V3) padding = "Raw"; else padding = "EMSA1(SHA-1)"; format = DER_SEQUENCE; } else throw Invalid_Argument(key->algo_name() + " is invalid/unknown for TLS signatures"); PK_Verifier verifier(*key, padding, format); if(version == SSL_V3) { SecureVector<byte> md5_sha = hash.final_ssl3(master_secret); return verifier.verify_message(&md5_sha[16], md5_sha.size()-16, &signature[0], signature.size()); } else if(version == TLS_V10 || version == TLS_V11) return verifier.verify_message(hash.get_contents(), signature); else throw TLS_Exception(PROTOCOL_VERSION, "Unknown TLS version in certificate verification"); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.1 1999/11/09 01:04:45 twl * Initial revision * * Revision 1.2 1999/11/08 20:45:09 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XML4CDefs.hpp> #include <util/PlatformUtils.hpp> #include <util/Mutexes.hpp> // --------------------------------------------------------------------------- // XMLMutex: Constructors and Destructor // --------------------------------------------------------------------------- XMLMutex::XMLMutex() : fHandle(0) { } XMLMutex::~XMLMutex() { if (fHandle) { XMLPlatformUtils::closeMutex(fHandle); fHandle = 0; } } // --------------------------------------------------------------------------- // XMLMutex: Lock control methods // --------------------------------------------------------------------------- void XMLMutex::lock() { if (!fHandle) { void* tmpHandle = XMLPlatformUtils::makeMutex(); if (XMLPlatformUtils::compareAndSwap(&fHandle, tmpHandle, 0) != 0) XMLPlatformUtils::closeMutex(tmpHandle); } XMLPlatformUtils::lockMutex(fHandle); } void XMLMutex::unlock() { XMLPlatformUtils::unlockMutex(fHandle); } // --------------------------------------------------------------------------- // XMLMutexLock: Constructors and Destructor // --------------------------------------------------------------------------- XMLMutexLock::XMLMutexLock(XMLMutex* const toLock) : fToLock(toLock) { fToLock->lock(); } XMLMutexLock::~XMLMutexLock() { fToLock->unlock(); } <commit_msg>Got rid of attempts to fancy/schmanzy lazy eval mutex implementation and just force anyone who needs a global/static mutex to lazy eval that themselves.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.2 1999/12/02 19:42:35 roddey * Got rid of attempts to fancy/schmanzy lazy eval mutex implementation and just * force anyone who needs a global/static mutex to lazy eval that themselves. * * Revision 1.1.1.1 1999/11/09 01:04:45 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:09 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XML4CDefs.hpp> #include <util/PlatformUtils.hpp> #include <util/Mutexes.hpp> // --------------------------------------------------------------------------- // XMLMutex: Constructors and Destructor // --------------------------------------------------------------------------- XMLMutex::XMLMutex() : fHandle(0) { // Ask the per-platform driver to make us a mutex fHandle = XMLPlatformUtils::makeMutex(); } XMLMutex::~XMLMutex() { if (fHandle) { XMLPlatformUtils::closeMutex(fHandle); fHandle = 0; } } // --------------------------------------------------------------------------- // XMLMutex: Lock control methods // --------------------------------------------------------------------------- void XMLMutex::lock() { XMLPlatformUtils::lockMutex(fHandle); } void XMLMutex::unlock() { XMLPlatformUtils::unlockMutex(fHandle); } // --------------------------------------------------------------------------- // XMLMutexLock: Constructors and Destructor // --------------------------------------------------------------------------- XMLMutexLock::XMLMutexLock(XMLMutex* const toLock) : fToLock(toLock) { fToLock->lock(); } XMLMutexLock::~XMLMutexLock() { fToLock->unlock(); } <|endoftext|>
<commit_before>#pragma once #include <functional> #include <list> namespace otto::util { /// A signal that can be emitted /// /// Handlers can be connected, and stored in Connections to be automatically disconnected /// on destruction template<typename... Args> struct Signal; template<typename... Args> struct Connection; template<typename... Args> struct SlotRef { using Connection = Connection<Args...>; using Signal = Signal<Args...>; using Function = typename Signal::Function; using FuncIterator = typename Signal::FuncIterator; Signal* signal; FuncIterator func_iter; void call_now(Args...); }; template<typename... Args> struct Signal { using Connection = Connection<Args...>; using SlotRef = SlotRef<Args...>; using Function = std::function<void(Args...)>; using FuncIterator = typename std::list<Function>::iterator; SlotRef connect(const Function& func); SlotRef connect(Function&& func); template<typename T> SlotRef connect_member(T* inst, void (T::*func)(Args...)); template<typename T> SlotRef connect_member(const T* inst, void (T::*func)(Args...) const); void disconnect(SlotRef); void disconnect_all(); void emit(Args... a); private: std::list<Function> _slots; }; template<typename... Args> struct Connection { using Signal = Signal<Args...>; using SlotRef = SlotRef<Args...>; using Function = typename Signal::Function; using FuncIterator = typename Signal::FuncIterator; Connection(SlotRef) noexcept; Connection(const Connection&) = delete; Connection(Connection&&) noexcept = default; Connection& operator=(const Connection&) = delete; Connection& operator=(Connection&&) noexcept = default; operator SlotRef() const noexcept; ~Connection() noexcept; private: SlotRef slot_ref; }; // -- SlotRef IMPLEMENTATIONS -- // template<typename... Args> void SlotRef<Args...>::call_now(Args... args) { (*func_iter)(std::forward<Args>(args)...); } // -- Signal IMPLEMENTATIONS -- // template<typename... Args> auto Signal<Args...>::connect(const Function& func) -> SlotRef { return {this, _slots.insert(_slots.end(), func)}; } template<typename... Args> auto Signal<Args...>::connect(Function&& func) -> SlotRef { return {this, _slots.insert(_slots.end(), std::move(func))}; } template<typename... Args> template<typename T> auto Signal<Args...>::connect_member(T* inst, void (T::*func)(Args...)) -> SlotRef { return connect([inst, func](Args... args) { inst->*func(std::forward<Args>(args)...); }); } template<typename... Args> template<typename T> auto Signal<Args...>::connect_member(const T* inst, void (T::*func)(Args...) const) -> SlotRef { return connect([inst, func](Args... args) { inst->*func(std::forward<Args>(args)...); }); } template<typename... Args> void Signal<Args...>::disconnect(SlotRef sr) { _slots.erase(sr.func_iter); } template<typename... Args> void Signal<Args...>::emit(Args... args) { for (auto&& slot : _slots) { slot(args...); } } // -- Connection IMPLEMENTATIONS -- // template<typename... Args> Connection<Args...>::Connection(SlotRef sr) noexcept : slot_ref(sr) {} template<typename... Args> Connection<Args...>::~Connection() noexcept { slot_ref.signal->disconnect(slot_ref); } template<typename... Args> Connection<Args...>::operator SlotRef() const noexcept { return slot_ref; } } // namespace otto::util <commit_msg>Fix signals on gcc<commit_after>#pragma once #include <functional> #include <list> namespace otto::util { /// A signal that can be emitted /// /// Handlers can be connected, and stored in Connections to be automatically disconnected /// on destruction template<typename... Args> struct Signal; template<typename... Args> struct Connection; template<typename... Args> struct SlotRef { using Connection = otto::util::Connection<Args...>; using Signal = otto::util::Signal<Args...>; using Function = typename Signal::Function; using FuncIterator = typename Signal::FuncIterator; Signal* signal; FuncIterator func_iter; void call_now(Args...); }; template<typename... Args> struct Signal { using Connection = otto::util::Connection<Args...>; using SlotRef = otto::util::SlotRef<Args...>; using Function = std::function<void(Args...)>; using FuncIterator = typename std::list<Function>::iterator; SlotRef connect(const Function& func); SlotRef connect(Function&& func); template<typename T> SlotRef connect_member(T* inst, void (T::*func)(Args...)); template<typename T> SlotRef connect_member(const T* inst, void (T::*func)(Args...) const); void disconnect(SlotRef); void disconnect_all(); void emit(Args... a); private: std::list<Function> _slots; }; template<typename... Args> struct Connection { using Signal = otto::util::Signal<Args...>; using SlotRef = otto::util::SlotRef<Args...>; using Function = typename Signal::Function; using FuncIterator = typename Signal::FuncIterator; Connection(SlotRef) noexcept; Connection(const Connection&) = delete; Connection(Connection&&) noexcept = default; Connection& operator=(const Connection&) = delete; Connection& operator=(Connection&&) noexcept = default; operator SlotRef() const noexcept; ~Connection() noexcept; private: SlotRef slot_ref; }; // -- SlotRef IMPLEMENTATIONS -- // template<typename... Args> void SlotRef<Args...>::call_now(Args... args) { (*func_iter)(std::forward<Args>(args)...); } // -- Signal IMPLEMENTATIONS -- // template<typename... Args> auto Signal<Args...>::connect(const Function& func) -> SlotRef { return {this, _slots.insert(_slots.end(), func)}; } template<typename... Args> auto Signal<Args...>::connect(Function&& func) -> SlotRef { return {this, _slots.insert(_slots.end(), std::move(func))}; } template<typename... Args> template<typename T> auto Signal<Args...>::connect_member(T* inst, void (T::*func)(Args...)) -> SlotRef { return connect([inst, func](Args... args) { inst->*func(std::forward<Args>(args)...); }); } template<typename... Args> template<typename T> auto Signal<Args...>::connect_member(const T* inst, void (T::*func)(Args...) const) -> SlotRef { return connect([inst, func](Args... args) { inst->*func(std::forward<Args>(args)...); }); } template<typename... Args> void Signal<Args...>::disconnect(SlotRef sr) { _slots.erase(sr.func_iter); } template<typename... Args> void Signal<Args...>::emit(Args... args) { for (auto&& slot : _slots) { slot(args...); } } // -- Connection IMPLEMENTATIONS -- // template<typename... Args> Connection<Args...>::Connection(SlotRef sr) noexcept : slot_ref(sr) {} template<typename... Args> Connection<Args...>::~Connection() noexcept { slot_ref.signal->disconnect(slot_ref); } template<typename... Args> Connection<Args...>::operator SlotRef() const noexcept { return slot_ref; } } // namespace otto::util <|endoftext|>
<commit_before>// @(#)root/gl:$Id$ // Author: Timur Pocheptsov, Jun 2007 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <cassert> #include <algorithm> #include <set> #include "TGLFormat.h" #include "TGLWSIncludes.h" #include "TGLWidget.h" #include "TEnv.h" #include "TError.h" #include "TVirtualX.h" //______________________________________________________________________________ // // Encapsulation of format / contents of an OpenGL buffer. ClassImp(TGLFormat); std::vector<Int_t> TGLFormat::fgAvailableSamples; //______________________________________________________________________________ TGLFormat::TGLFormat() : fDoubleBuffered(kTRUE), fStereo(kFALSE), #ifdef WIN32 fDepthSize(32), #else fDepthSize(24), #endif fAccumSize(0), fStencilSize(8), fSamples(GetDefaultSamples()) { //Default ctor. Default surface is: //-double buffered //-RGBA //-with depth buffer //-no accumulation buffer //-with stencil //-multi-sampling depends on seeting of "OpenGL.Framebuffer.Multisample" } //______________________________________________________________________________ TGLFormat::TGLFormat(EFormatOptions opt) : fDoubleBuffered(opt & kDoubleBuffer), fStereo(kFALSE), #ifdef WIN32 fDepthSize(opt & kDepth ? 32 : 0), #else fDepthSize(opt & kDepth ? 16 : 0),//FIXFIX #endif fAccumSize(opt & kAccum ? 8 : 0), //I've never tested accumulation buffer size. fStencilSize(opt & kStencil ? 8 : 0), //I've never tested stencil buffer size. fSamples(opt & kMultiSample ? GetDefaultSamples() : 0) { //Define surface using options. } //______________________________________________________________________________ TGLFormat::~TGLFormat() { //Destructor. } //______________________________________________________________________________ Bool_t TGLFormat::operator == (const TGLFormat &rhs)const { //Check if two formats are equal. return fDoubleBuffered == rhs.fDoubleBuffered && fDepthSize == rhs.fDepthSize && fAccumSize == rhs.fAccumSize && fStencilSize == rhs.fStencilSize; } //______________________________________________________________________________ Bool_t TGLFormat::operator != (const TGLFormat &rhs)const { //Check for non-equality. return !(*this == rhs); } //______________________________________________________________________________ Int_t TGLFormat::GetDepthSize()const { //Get the size of depth buffer. return fDepthSize; } //______________________________________________________________________________ void TGLFormat::SetDepthSize(Int_t depth) { //Set the size of color buffer. assert(depth); fDepthSize = depth; } //______________________________________________________________________________ Bool_t TGLFormat::HasDepth()const { //Check, if this surface has depth buffer. return GetDepthSize() != 0; } //______________________________________________________________________________ Int_t TGLFormat::GetStencilSize()const { //Get the size of stencil buffer. return fStencilSize; } //______________________________________________________________________________ void TGLFormat::SetStencilSize(Int_t stencil) { //Set the size of stencil buffer. assert(stencil); fStencilSize = stencil; } //______________________________________________________________________________ Bool_t TGLFormat::HasStencil()const { //Check, if this surface has stencil buffer. return GetStencilSize() != 0; } //______________________________________________________________________________ Int_t TGLFormat::GetAccumSize()const { //Get the size of accum buffer. return fAccumSize; } //______________________________________________________________________________ void TGLFormat::SetAccumSize(Int_t accum) { //Set the size of accum buffer. assert(accum); fAccumSize = accum; } //______________________________________________________________________________ Bool_t TGLFormat::HasAccumBuffer()const { //Check, if this surface has accumulation buffer. return GetAccumSize() != 0; } //______________________________________________________________________________ Bool_t TGLFormat::IsDoubleBuffered()const { //Check, if the surface is double buffered. return fDoubleBuffered; } //______________________________________________________________________________ void TGLFormat::SetDoubleBuffered(Bool_t db) { //Set the surface as double/single buffered. fDoubleBuffered = db; } //______________________________________________________________________________ Bool_t TGLFormat::IsStereo()const { //Check, if the surface is stereo buffered. return fStereo; } //______________________________________________________________________________ void TGLFormat::SetStereo(Bool_t db) { //Set the surface as stereo/non-stereo buffered. fStereo = db; } //______________________________________________________________________________ Int_t TGLFormat::GetSamples()const { //Get the number of samples for multi-sampling. return fSamples; } //______________________________________________________________________________ void TGLFormat::SetSamples(Int_t samples) { //Set the number of samples for multi-sampling. fSamples = samples; } //______________________________________________________________________________ Bool_t TGLFormat::HasMultiSampling()const { //Check, if multi-sampling is requred. return fSamples != 0; } //______________________________________________________________________________ Int_t TGLFormat::GetDefaultSamples() { // Return default number of samples for multi-sampling. Int_t req = gEnv->GetValue("OpenGL.Framebuffer.Multisample", 0); // Avoid query of available multi-sample modes when not required. // Over ssh, SLC5 lies about supporting the GLX_SAMPLES_ARB // extension and then dies horribly when the query is made. if (req == 0) { return 0; } if (fgAvailableSamples.empty()) InitAvailableSamples(); std::vector<Int_t>::iterator i = fgAvailableSamples.begin(); while (i != fgAvailableSamples.end() - 1 && *i < req) ++i; if (*i != req) { Info("TGLFormat::GetDefaultSamples", "Requested multi-sampling %d not available, using %d. Adjusting default.", req, *i); gEnv->SetValue("OpenGL.Framebuffer.Multisample", *i); } return *i; } //______________________________________________________________________________ void TGLFormat::InitAvailableSamples() { std::set<Int_t> ns_set; ns_set.insert(0); TGLWidget *widget = TGLWidget::CreateDummy(); widget->MakeCurrent(); #ifdef WIN32 // Missing implementation. #else if (GLXEW_ARB_multisample) { Display *dpy = (Display*) gVirtualX->GetDisplay(); XVisualInfo tmpl; tmpl.screen = gVirtualX->GetScreen(); long mask = VisualScreenMask; int numVisuals, use_gl, ms_ns; XVisualInfo *vis = XGetVisualInfo(dpy, mask, &tmpl, &numVisuals); for (int i = 0; i < numVisuals; i++) { if (glXGetConfig(dpy, &vis[i], GLX_USE_GL, &use_gl) == 0) { glXGetConfig(dpy, &vis[i], GLX_SAMPLES_ARB, &ms_ns); ns_set.insert(ms_ns); } } XFree(vis); } #endif delete widget; fgAvailableSamples.reserve(ns_set.size()); for (std::set<Int_t>::iterator i = ns_set.begin(); i != ns_set.end(); ++i) { fgAvailableSamples.push_back(*i); } } <commit_msg>For unix be satisfied with the 16-bit depth buffer -- revert from previous change.<commit_after>// @(#)root/gl:$Id$ // Author: Timur Pocheptsov, Jun 2007 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <cassert> #include <algorithm> #include <set> #include "TGLFormat.h" #include "TGLWSIncludes.h" #include "TGLWidget.h" #include "TEnv.h" #include "TError.h" #include "TVirtualX.h" //______________________________________________________________________________ // // Encapsulation of format / contents of an OpenGL buffer. ClassImp(TGLFormat); std::vector<Int_t> TGLFormat::fgAvailableSamples; //______________________________________________________________________________ TGLFormat::TGLFormat() : fDoubleBuffered(kTRUE), fStereo(kFALSE), #ifdef WIN32 fDepthSize(32), #else // 16-bits needed for some virtual machines (VirtualBox) and Xming-mesa // (when running ssh from windows to linux). // All others seem to have 24-bit depth-buffers only and use this anyway. fDepthSize(16), #endif fAccumSize(0), fStencilSize(8), fSamples(GetDefaultSamples()) { //Default ctor. Default surface is: //-double buffered //-RGBA //-with depth buffer //-no accumulation buffer //-with stencil //-multi-sampling depends on seeting of "OpenGL.Framebuffer.Multisample" } //______________________________________________________________________________ TGLFormat::TGLFormat(EFormatOptions opt) : fDoubleBuffered(opt & kDoubleBuffer), fStereo(kFALSE), #ifdef WIN32 fDepthSize(opt & kDepth ? 32 : 0), #else fDepthSize(opt & kDepth ? 16 : 0),//FIXFIX #endif fAccumSize(opt & kAccum ? 8 : 0), //I've never tested accumulation buffer size. fStencilSize(opt & kStencil ? 8 : 0), //I've never tested stencil buffer size. fSamples(opt & kMultiSample ? GetDefaultSamples() : 0) { //Define surface using options. } //______________________________________________________________________________ TGLFormat::~TGLFormat() { //Destructor. } //______________________________________________________________________________ Bool_t TGLFormat::operator == (const TGLFormat &rhs)const { //Check if two formats are equal. return fDoubleBuffered == rhs.fDoubleBuffered && fDepthSize == rhs.fDepthSize && fAccumSize == rhs.fAccumSize && fStencilSize == rhs.fStencilSize; } //______________________________________________________________________________ Bool_t TGLFormat::operator != (const TGLFormat &rhs)const { //Check for non-equality. return !(*this == rhs); } //______________________________________________________________________________ Int_t TGLFormat::GetDepthSize()const { //Get the size of depth buffer. return fDepthSize; } //______________________________________________________________________________ void TGLFormat::SetDepthSize(Int_t depth) { //Set the size of color buffer. assert(depth); fDepthSize = depth; } //______________________________________________________________________________ Bool_t TGLFormat::HasDepth()const { //Check, if this surface has depth buffer. return GetDepthSize() != 0; } //______________________________________________________________________________ Int_t TGLFormat::GetStencilSize()const { //Get the size of stencil buffer. return fStencilSize; } //______________________________________________________________________________ void TGLFormat::SetStencilSize(Int_t stencil) { //Set the size of stencil buffer. assert(stencil); fStencilSize = stencil; } //______________________________________________________________________________ Bool_t TGLFormat::HasStencil()const { //Check, if this surface has stencil buffer. return GetStencilSize() != 0; } //______________________________________________________________________________ Int_t TGLFormat::GetAccumSize()const { //Get the size of accum buffer. return fAccumSize; } //______________________________________________________________________________ void TGLFormat::SetAccumSize(Int_t accum) { //Set the size of accum buffer. assert(accum); fAccumSize = accum; } //______________________________________________________________________________ Bool_t TGLFormat::HasAccumBuffer()const { //Check, if this surface has accumulation buffer. return GetAccumSize() != 0; } //______________________________________________________________________________ Bool_t TGLFormat::IsDoubleBuffered()const { //Check, if the surface is double buffered. return fDoubleBuffered; } //______________________________________________________________________________ void TGLFormat::SetDoubleBuffered(Bool_t db) { //Set the surface as double/single buffered. fDoubleBuffered = db; } //______________________________________________________________________________ Bool_t TGLFormat::IsStereo()const { //Check, if the surface is stereo buffered. return fStereo; } //______________________________________________________________________________ void TGLFormat::SetStereo(Bool_t db) { //Set the surface as stereo/non-stereo buffered. fStereo = db; } //______________________________________________________________________________ Int_t TGLFormat::GetSamples()const { //Get the number of samples for multi-sampling. return fSamples; } //______________________________________________________________________________ void TGLFormat::SetSamples(Int_t samples) { //Set the number of samples for multi-sampling. fSamples = samples; } //______________________________________________________________________________ Bool_t TGLFormat::HasMultiSampling()const { //Check, if multi-sampling is requred. return fSamples != 0; } //______________________________________________________________________________ Int_t TGLFormat::GetDefaultSamples() { // Return default number of samples for multi-sampling. Int_t req = gEnv->GetValue("OpenGL.Framebuffer.Multisample", 0); // Avoid query of available multi-sample modes when not required. // Over ssh, SLC5 lies about supporting the GLX_SAMPLES_ARB // extension and then dies horribly when the query is made. if (req == 0) { return 0; } if (fgAvailableSamples.empty()) InitAvailableSamples(); std::vector<Int_t>::iterator i = fgAvailableSamples.begin(); while (i != fgAvailableSamples.end() - 1 && *i < req) ++i; if (*i != req) { Info("TGLFormat::GetDefaultSamples", "Requested multi-sampling %d not available, using %d. Adjusting default.", req, *i); gEnv->SetValue("OpenGL.Framebuffer.Multisample", *i); } return *i; } //______________________________________________________________________________ void TGLFormat::InitAvailableSamples() { std::set<Int_t> ns_set; ns_set.insert(0); TGLWidget *widget = TGLWidget::CreateDummy(); widget->MakeCurrent(); #ifdef WIN32 // Missing implementation. #else if (GLXEW_ARB_multisample) { Display *dpy = (Display*) gVirtualX->GetDisplay(); XVisualInfo tmpl; tmpl.screen = gVirtualX->GetScreen(); long mask = VisualScreenMask; int numVisuals, use_gl, ms_ns; XVisualInfo *vis = XGetVisualInfo(dpy, mask, &tmpl, &numVisuals); for (int i = 0; i < numVisuals; i++) { if (glXGetConfig(dpy, &vis[i], GLX_USE_GL, &use_gl) == 0) { glXGetConfig(dpy, &vis[i], GLX_SAMPLES_ARB, &ms_ns); ns_set.insert(ms_ns); } } XFree(vis); } #endif delete widget; fgAvailableSamples.reserve(ns_set.size()); for (std::set<Int_t>::iterator i = ns_set.begin(); i != ns_set.end(); ++i) { fgAvailableSamples.push_back(*i); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: swfuno.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 07:40:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #include <stdio.h> #include <osl/mutex.hxx> #include <osl/thread.h> #include <cppuhelper/factory.hxx> #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; namespace swf { extern OUString FlashExportFilter_getImplementationName() throw ( RuntimeException ); extern sal_Bool SAL_CALL FlashExportFilter_supportsService( const OUString& ServiceName ) throw ( RuntimeException ); extern Sequence< OUString > SAL_CALL FlashExportFilter_getSupportedServiceNames() throw ( RuntimeException ); extern Reference< XInterface > SAL_CALL FlashExportFilter_createInstance( const Reference< XMultiServiceFactory > & rSMgr) throw ( Exception ); } extern rtl::OUString SWFDialog_getImplementationName () throw (com::sun::star::uno::RuntimeException); extern com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SWFDialog_getSupportedServiceNames() throw (com::sun::star::uno::RuntimeException); extern com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SWFDialog_createInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw( com::sun::star::uno::Exception ); using namespace ::swf; extern "C" { //================================================================================================== void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //================================================================================================== void singlecomponent_writeInfo( Reference< XRegistryKey >& xNewKey, const Sequence< OUString > & rSNL ) { const OUString * pArray = rSNL.getConstArray(); for ( sal_Int32 nPos = rSNL.getLength(); nPos--; ) xNewKey->createKey( pArray[nPos] ); } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if (pRegistryKey) { try { Reference< XRegistryKey > xNewKey( reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( FlashExportFilter_getImplementationName() ) ); xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) ); singlecomponent_writeInfo( xNewKey, FlashExportFilter_getSupportedServiceNames() ); xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SWFDialog_getImplementationName() ); xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) ); singlecomponent_writeInfo( xNewKey, SWFDialog_getSupportedServiceNames() ); return sal_True; } catch (InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_False; } //================================================================================================== void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; if( pServiceManager ) { Reference< XSingleServiceFactory > xFactory; OUString implName = OUString::createFromAscii( pImplName ); if ( implName.equals(FlashExportFilter_getImplementationName()) ) { xFactory = createSingleFactory( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), OUString::createFromAscii( pImplName ), FlashExportFilter_createInstance, FlashExportFilter_getSupportedServiceNames() ); } else if ( implName.equals(SWFDialog_getImplementationName()) ) { xFactory = createSingleFactory( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), OUString::createFromAscii( pImplName ), SWFDialog_createInstance, SWFDialog_getSupportedServiceNames() ); } if (xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } <commit_msg>INTEGRATION: CWS wfilter (1.3.52); FILE MERGED 2006/11/17 08:40:40 sj 1.3.52.1: #i69283# making filter module warning free<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: swfuno.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2006-12-01 14:26:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #include <stdio.h> #include <osl/mutex.hxx> #include <osl/thread.h> #include <cppuhelper/factory.hxx> #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; namespace swf { extern OUString FlashExportFilter_getImplementationName() throw ( RuntimeException ); extern sal_Bool SAL_CALL FlashExportFilter_supportsService( const OUString& ServiceName ) throw ( RuntimeException ); extern Sequence< OUString > SAL_CALL FlashExportFilter_getSupportedServiceNames() throw ( RuntimeException ); extern Reference< XInterface > SAL_CALL FlashExportFilter_createInstance( const Reference< XMultiServiceFactory > & rSMgr) throw ( Exception ); } extern rtl::OUString SWFDialog_getImplementationName () throw (com::sun::star::uno::RuntimeException); extern com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SWFDialog_getSupportedServiceNames() throw (com::sun::star::uno::RuntimeException); extern com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SWFDialog_createInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw( com::sun::star::uno::Exception ); using namespace ::swf; extern "C" { //================================================================================================== void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /* ppEnv */ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //================================================================================================== void singlecomponent_writeInfo( Reference< XRegistryKey >& xNewKey, const Sequence< OUString > & rSNL ) { const OUString * pArray = rSNL.getConstArray(); for ( sal_Int32 nPos = rSNL.getLength(); nPos--; ) xNewKey->createKey( pArray[nPos] ); } sal_Bool SAL_CALL component_writeInfo( void * /* pServiceManager */, void * pRegistryKey ) { if (pRegistryKey) { try { Reference< XRegistryKey > xNewKey( reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( FlashExportFilter_getImplementationName() ) ); xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) ); singlecomponent_writeInfo( xNewKey, FlashExportFilter_getSupportedServiceNames() ); xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SWFDialog_getImplementationName() ); xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) ); singlecomponent_writeInfo( xNewKey, SWFDialog_getSupportedServiceNames() ); return sal_True; } catch (InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_False; } //================================================================================================== void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /* pRegistryKey */ ) { void * pRet = 0; if( pServiceManager ) { Reference< XSingleServiceFactory > xFactory; OUString implName = OUString::createFromAscii( pImplName ); if ( implName.equals(FlashExportFilter_getImplementationName()) ) { xFactory = createSingleFactory( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), OUString::createFromAscii( pImplName ), FlashExportFilter_createInstance, FlashExportFilter_getSupportedServiceNames() ); } else if ( implName.equals(SWFDialog_getImplementationName()) ) { xFactory = createSingleFactory( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), OUString::createFromAscii( pImplName ), SWFDialog_createInstance, SWFDialog_getSupportedServiceNames() ); } if (xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ComposeDefaultKey.h" /* system headers */ #include <iostream> #include <vector> #include <string> /* common implementation headers */ #include "BzfEvent.h" #include "RemotePlayer.h" #include "KeyManager.h" #include "AutoCompleter.h" #include "BZDBCache.h" #include "AnsiCodes.h" #include "TextUtils.h" /* local implementation headers */ #include "LocalPlayer.h" #include "World.h" #include "HUDRenderer.h" #include "Roster.h" /* FIXME -- pulled from player.h */ void addMessage(const Player* player, const std::string& msg, int mode = 3, bool highlight=false, const char* oldColor=NULL); extern char messageMessage[PlayerIdPLen + MessageLen]; #define MAX_MESSAGE_HISTORY (20) extern HUDRenderer *hud; extern ServerLink* serverLink; extern DefaultCompleter completer; void selectNextRecipient (bool forward, bool robotIn); MessageQueue messageHistory; unsigned int messageHistoryIndex = 0; void printout(const std::string& name, void*) { std::cout << name << " = " << BZDB.get(name) << std::endl; } void listSetVars(const std::string& name, void*) { char message[MessageLen]; if (BZDB.getPermission(name) == StateDatabase::Locked) { if (BZDBCache::colorful) { sprintf(message, "/set %s%s %s%f %s%s", ColorStrings[RedColor].c_str(), name.c_str(), ColorStrings[GreenColor].c_str(), BZDB.eval(name), ColorStrings[BlueColor].c_str(), BZDB.get(name).c_str()); } else { sprintf(message, "/set %s <%f> %s", name.c_str(), BZDB.eval(name), BZDB.get(name).c_str()); } addMessage(LocalPlayer::getMyTank(), message, 2); } } bool ComposeDefaultKey::keyPress(const BzfKeyEvent& key) { bool sendIt; LocalPlayer *myTank = LocalPlayer::getMyTank(); if (KEYMGR.get(key, true) == "jump") { // jump while typing myTank->setJump(); } if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if ((key.button == BzfKeyEvent::Up) || (key.button == BzfKeyEvent::Down)) return true; } switch (key.ascii) { case 3: // ^C case 27: { // escape // case 127: // delete sendIt = false; // finished composing -- don't send break; } case 4: // ^D case 13: { // return sendIt = true; break; } case 6: { // ^F // auto completion std::string line1 = hud->getComposeString(); int lastSpace = line1.find_last_of(" \t"); std::string line2 = line1.substr(0, lastSpace+1); line2 += completer.complete(line1.substr(lastSpace+1)); hud->setComposeString(line2); return true; } default: { return false; } } if (sendIt) { std::string message = hud->getComposeString(); if (message.length() > 0) { const char* silence = message.c_str(); if (strncmp(silence, "SILENCE", 7) == 0) { Player *loudmouth = getPlayerByName(silence + 8); if (loudmouth) { silencePlayers.push_back(silence + 8); std::string message = "Silenced "; message += (silence + 8); addMessage(NULL, message); } } else if (strncmp(silence, "DUMP", 4) == 0) { BZDB.iterate(printout, NULL); } else if (strncmp(silence, "UNSILENCE", 9) == 0) { Player *loudmouth = getPlayerByName(silence + 10); if (loudmouth) { std::vector<std::string>::iterator it = silencePlayers.begin(); for (; it != silencePlayers.end(); it++) { if (*it == silence + 10) { silencePlayers.erase(it); std::string message = "Unsilenced "; message += (silence + 10); addMessage(NULL, message); break; } } } } else if (strncmp(silence, "SAVEWORLD", 9) == 0) { std::string path = silence + 10; if (World::getWorld()->writeWorld(path)) { addMessage(NULL, "World Saved"); } else { addMessage(NULL, "Invalid file name specified"); } } else if (message == "/set") { BZDB.iterate(listSetVars, NULL); #ifdef DEBUG } else if (strncmp(silence, "/localset", 9) == 0) { std::string params = silence + 9; std::vector<std::string> tokens = TextUtils::tokenize(params, " ", 2); if (tokens.size() == 2) { if (!(BZDB.getPermission(tokens[0]) == StateDatabase::Server)) { BZDB.setPersistent(tokens[0], BZDB.isPersistent(tokens[0])); BZDB.set(tokens[0], tokens[1]); std::string msg = "/localset " + tokens[0] + " " + tokens[1]; addMessage(NULL, msg); } } #endif } else { int i, mhLen = messageHistory.size(); for (i = 0; i < mhLen; i++) { if (messageHistory[i] == message) { messageHistory.erase(messageHistory.begin() + i); messageHistory.push_front(message); break; } } if (i == mhLen) { if (mhLen >= MAX_MESSAGE_HISTORY) { messageHistory.pop_back(); } messageHistory.push_front(message); } char messageBuffer[MessageLen]; memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, message.c_str(), MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); } } } messageHistoryIndex = 0; hud->setComposing(std::string()); HUDui::setDefaultKey(NULL); return true; } bool ComposeDefaultKey::keyRelease(const BzfKeyEvent& key) { LocalPlayer *myTank = LocalPlayer::getMyTank(); if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if (key.button == BzfKeyEvent::Up) { if (messageHistoryIndex < messageHistory.size()) { hud->setComposeString(messageHistory[messageHistoryIndex]); messageHistoryIndex++; } else hud->setComposeString(std::string()); return true; } else if (key.button == BzfKeyEvent::Down) { if (messageHistoryIndex > 0){ messageHistoryIndex--; hud->setComposeString(messageHistory[messageHistoryIndex]); } else hud->setComposeString(std::string()); return true; } else if ((key.shift == BzfKeyEvent::ShiftKey || (hud->getComposeString().length() == 0)) && (key.button == BzfKeyEvent::Left || key.button == BzfKeyEvent::Right)) { // exclude robot from private message recipient. // No point sending messages to robot (now) selectNextRecipient(key.button != BzfKeyEvent::Left, false); const Player *recipient = myTank->getRecipient(); if (recipient) { void* buf = messageMessage; buf = nboPackUByte(buf, recipient->getId()); std::string composePrompt = "Send to "; composePrompt += recipient->getCallSign(); composePrompt += ": "; hud->setComposing(composePrompt); } return false; } else if ((key.shift == 0) && (key.button == BzfKeyEvent::F2)) { // auto completion (F2) std::string line1 = hud->getComposeString(); int lastSpace = line1.find_last_of(" \t"); std::string line2 = line1.substr(0, lastSpace+1); line2 += completer.complete(line1.substr(lastSpace+1)); hud->setComposeString(line2); } } return keyPress(key); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Try to make the best on not segv when not in game<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ComposeDefaultKey.h" /* system headers */ #include <iostream> #include <vector> #include <string> /* common implementation headers */ #include "BzfEvent.h" #include "RemotePlayer.h" #include "KeyManager.h" #include "AutoCompleter.h" #include "BZDBCache.h" #include "AnsiCodes.h" #include "TextUtils.h" /* local implementation headers */ #include "LocalPlayer.h" #include "World.h" #include "HUDRenderer.h" #include "Roster.h" /* FIXME -- pulled from player.h */ void addMessage(const Player* player, const std::string& msg, int mode = 3, bool highlight=false, const char* oldColor=NULL); extern char messageMessage[PlayerIdPLen + MessageLen]; #define MAX_MESSAGE_HISTORY (20) extern HUDRenderer *hud; extern ServerLink* serverLink; extern DefaultCompleter completer; void selectNextRecipient (bool forward, bool robotIn); MessageQueue messageHistory; unsigned int messageHistoryIndex = 0; void printout(const std::string& name, void*) { std::cout << name << " = " << BZDB.get(name) << std::endl; } void listSetVars(const std::string& name, void*) { char message[MessageLen]; if (BZDB.getPermission(name) == StateDatabase::Locked) { if (BZDBCache::colorful) { sprintf(message, "/set %s%s %s%f %s%s", ColorStrings[RedColor].c_str(), name.c_str(), ColorStrings[GreenColor].c_str(), BZDB.eval(name), ColorStrings[BlueColor].c_str(), BZDB.get(name).c_str()); } else { sprintf(message, "/set %s <%f> %s", name.c_str(), BZDB.eval(name), BZDB.get(name).c_str()); } addMessage(LocalPlayer::getMyTank(), message, 2); } } bool ComposeDefaultKey::keyPress(const BzfKeyEvent& key) { bool sendIt; LocalPlayer *myTank = LocalPlayer::getMyTank(); if (myTank && KEYMGR.get(key, true) == "jump") { // jump while typing myTank->setJump(); } if (!myTank || myTank->getInputMethod() != LocalPlayer::Keyboard) { if ((key.button == BzfKeyEvent::Up) || (key.button == BzfKeyEvent::Down)) return true; } switch (key.ascii) { case 3: // ^C case 27: { // escape // case 127: // delete sendIt = false; // finished composing -- don't send break; } case 4: // ^D case 13: { // return sendIt = true; break; } case 6: { // ^F // auto completion std::string line1 = hud->getComposeString(); int lastSpace = line1.find_last_of(" \t"); std::string line2 = line1.substr(0, lastSpace+1); line2 += completer.complete(line1.substr(lastSpace+1)); hud->setComposeString(line2); return true; } default: { return false; } } if (sendIt) { std::string message = hud->getComposeString(); if (message.length() > 0) { const char* silence = message.c_str(); if (strncmp(silence, "SILENCE", 7) == 0) { Player *loudmouth = getPlayerByName(silence + 8); if (loudmouth) { silencePlayers.push_back(silence + 8); std::string message = "Silenced "; message += (silence + 8); addMessage(NULL, message); } } else if (strncmp(silence, "DUMP", 4) == 0) { BZDB.iterate(printout, NULL); } else if (strncmp(silence, "UNSILENCE", 9) == 0) { Player *loudmouth = getPlayerByName(silence + 10); if (loudmouth) { std::vector<std::string>::iterator it = silencePlayers.begin(); for (; it != silencePlayers.end(); it++) { if (*it == silence + 10) { silencePlayers.erase(it); std::string message = "Unsilenced "; message += (silence + 10); addMessage(NULL, message); break; } } } } else if (strncmp(silence, "SAVEWORLD", 9) == 0) { std::string path = silence + 10; if (World::getWorld()->writeWorld(path)) { addMessage(NULL, "World Saved"); } else { addMessage(NULL, "Invalid file name specified"); } } else if (message == "/set") { BZDB.iterate(listSetVars, NULL); #ifdef DEBUG } else if (strncmp(silence, "/localset", 9) == 0) { std::string params = silence + 9; std::vector<std::string> tokens = TextUtils::tokenize(params, " ", 2); if (tokens.size() == 2) { if (!(BZDB.getPermission(tokens[0]) == StateDatabase::Server)) { BZDB.setPersistent(tokens[0], BZDB.isPersistent(tokens[0])); BZDB.set(tokens[0], tokens[1]); std::string msg = "/localset " + tokens[0] + " " + tokens[1]; addMessage(NULL, msg); } } #endif } else if (serverLink) { int i, mhLen = messageHistory.size(); for (i = 0; i < mhLen; i++) { if (messageHistory[i] == message) { messageHistory.erase(messageHistory.begin() + i); messageHistory.push_front(message); break; } } if (i == mhLen) { if (mhLen >= MAX_MESSAGE_HISTORY) { messageHistory.pop_back(); } messageHistory.push_front(message); } char messageBuffer[MessageLen]; memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, message.c_str(), MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); } } } messageHistoryIndex = 0; hud->setComposing(std::string()); HUDui::setDefaultKey(NULL); return true; } bool ComposeDefaultKey::keyRelease(const BzfKeyEvent& key) { LocalPlayer *myTank = LocalPlayer::getMyTank(); if (!myTank || myTank->getInputMethod() != LocalPlayer::Keyboard) { if (key.button == BzfKeyEvent::Up) { if (messageHistoryIndex < messageHistory.size()) { hud->setComposeString(messageHistory[messageHistoryIndex]); messageHistoryIndex++; } else hud->setComposeString(std::string()); return true; } else if (key.button == BzfKeyEvent::Down) { if (messageHistoryIndex > 0){ messageHistoryIndex--; hud->setComposeString(messageHistory[messageHistoryIndex]); } else hud->setComposeString(std::string()); return true; } else if (myTank && ((key.shift == BzfKeyEvent::ShiftKey || (hud->getComposeString().length() == 0)) && (key.button == BzfKeyEvent::Left || key.button == BzfKeyEvent::Right))) { // exclude robot from private message recipient. // No point sending messages to robot (now) selectNextRecipient(key.button != BzfKeyEvent::Left, false); const Player *recipient = myTank->getRecipient(); if (recipient) { void* buf = messageMessage; buf = nboPackUByte(buf, recipient->getId()); std::string composePrompt = "Send to "; composePrompt += recipient->getCallSign(); composePrompt += ": "; hud->setComposing(composePrompt); } return false; } else if ((key.shift == 0) && (key.button == BzfKeyEvent::F2)) { // auto completion (F2) std::string line1 = hud->getComposeString(); int lastSpace = line1.find_last_of(" \t"); std::string line2 = line1.substr(0, lastSpace+1); line2 += completer.complete(line1.substr(lastSpace+1)); hud->setComposeString(line2); } } return keyPress(key); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr> * Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com> * Copyright (C) 2008 Charles Huet <packadal@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QDebug> #include <iostream> #include <gluon/audio/sound.h> #include <gluon/audio/engine.h> int main( int argc, char* argv[] ) { GluonAudio::Engine::instance(); GluonAudio::Sound* left = new GluonAudio::Sound( "/usr/share/sounds/alsa/Front_Left.wav" ); GluonAudio::Sound* right = new GluonAudio::Sound( "/usr/share/sounds/alsa/Front_Right.wav" ); GluonAudio::Sound* center = new GluonAudio::Sound( "/usr/share/sounds/alsa/Front_Center.wav" ); left->setPosition( -1, 0, 0 ); right->setPosition( 1, 0, 0 ); qDebug() << "Playing left. Press enter to continue."; left->play(); std::cin.get(); qDebug() << "Playing right. Press enter to continue."; right->play(); std::cin.get(); qDebug() << "Playing center. Press enter to continue."; center->play(); std::cin.get(); delete left; delete right; delete center; GluonAudio::Engine::close(); } <commit_msg>Eliminate the Standard Template Library usage from the first audio tutoria2.<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr> * Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com> * Copyright (C) 2008 Charles Huet <packadal@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <gluon/audio/sound.h> #include <gluon/audio/engine.h> #include <QDebug> int main( int argc, char* argv[] ) { GluonAudio::Engine::instance(); GluonAudio::Sound* left = new GluonAudio::Sound( "/usr/share/sounds/alsa/Front_Left.wav" ); GluonAudio::Sound* right = new GluonAudio::Sound( "/usr/share/sounds/alsa/Front_Right.wav" ); GluonAudio::Sound* center = new GluonAudio::Sound( "/usr/share/sounds/alsa/Front_Center.wav" ); left->setPosition( -1, 0, 0 ); right->setPosition( 1, 0, 0 ); qDebug() << "Playing left. Press enter to continue."; left->play(); QTextStream(stdin).readLine(); qDebug() << "Playing right. Press enter to continue."; right->play(); QTextStream(stdin).readLine(); qDebug() << "Playing center. Press enter to continue."; center->play(); QTextStream(stdin).readLine(); delete left; delete right; delete center; GluonAudio::Engine::close(); } <|endoftext|>
<commit_before><commit_msg>Fix two races in DirectoryWatcherInotify:<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sbintern.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-11-09 12:24:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SHL_HXX //autogen #include <tools/shl.hxx> #endif #include "sbintern.hxx" #include "sbunoobj.hxx" #include "token.hxx" // Tokenizer #include "symtbl.hxx" // Symbolverwaltung #include "parser.hxx" // Parser #include "codegen.hxx" // Code-Generator #include "basmgr.hxx" #pragma hdrstop SV_IMPL_PTRARR(SbErrorStack, SbErrorStackEntry*) SbiGlobals* GetSbData() { SbiGlobals** pp = (SbiGlobals**) ::GetAppData( SHL_SBC ); SbiGlobals* p = *pp; if( !p ) p = *pp = new SbiGlobals; return p; } SbiGlobals::SbiGlobals() { pInst = NULL; pMod = NULL; pSbFac= NULL; pUnoFac = NULL; pTypeFac = NULL; pOLEFac = NULL; pCompMod = NULL; // JSM nInst = 0; nCode = 0; nLine = 0; nCol1 = nCol2 = 0; bCompiler = FALSE; bGlobalInitErr = FALSE; bRunInit = FALSE; eLanguageMode = SB_LANG_BASIC; pErrStack = NULL; pTransliterationWrapper = NULL; bBlockCompilerError = FALSE; pAppBasMgr = NULL; } SbiGlobals::~SbiGlobals() { delete pErrStack; delete pSbFac; delete pUnoFac; delete pTransliterationWrapper; } <commit_msg>INTEGRATION: CWS ooo19126 (1.6.82); FILE MERGED 2005/09/05 14:36:05 rt 1.6.82.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sbintern.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-07 21:26:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SHL_HXX //autogen #include <tools/shl.hxx> #endif #include "sbintern.hxx" #include "sbunoobj.hxx" #include "token.hxx" // Tokenizer #include "symtbl.hxx" // Symbolverwaltung #include "parser.hxx" // Parser #include "codegen.hxx" // Code-Generator #include "basmgr.hxx" #pragma hdrstop SV_IMPL_PTRARR(SbErrorStack, SbErrorStackEntry*) SbiGlobals* GetSbData() { SbiGlobals** pp = (SbiGlobals**) ::GetAppData( SHL_SBC ); SbiGlobals* p = *pp; if( !p ) p = *pp = new SbiGlobals; return p; } SbiGlobals::SbiGlobals() { pInst = NULL; pMod = NULL; pSbFac= NULL; pUnoFac = NULL; pTypeFac = NULL; pOLEFac = NULL; pCompMod = NULL; // JSM nInst = 0; nCode = 0; nLine = 0; nCol1 = nCol2 = 0; bCompiler = FALSE; bGlobalInitErr = FALSE; bRunInit = FALSE; eLanguageMode = SB_LANG_BASIC; pErrStack = NULL; pTransliterationWrapper = NULL; bBlockCompilerError = FALSE; pAppBasMgr = NULL; } SbiGlobals::~SbiGlobals() { delete pErrStack; delete pSbFac; delete pUnoFac; delete pTransliterationWrapper; } <|endoftext|>
<commit_before>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> #include <stdio.h> #include <iostream> #include <limits.h> #include <gtest/gtest.h> #include "exec/parquet-common.h" #include "runtime/timestamp-value.h" using namespace std; namespace impala { template <typename T> void TestType(const T& v, int expected_byte_size) { uint8_t buffer[expected_byte_size]; EXPECT_EQ(ParquetPlainEncoder::ByteSize(v), expected_byte_size); int encoded_size = ParquetPlainEncoder::Encode(buffer, v); EXPECT_EQ(encoded_size, expected_byte_size); T result; int decoded_size = ParquetPlainEncoder::Decode(buffer, &result); EXPECT_EQ(decoded_size, expected_byte_size); EXPECT_EQ(result, v); } TEST(PlainEncoding, Basic) { int8_t i8 = 12; int16_t i16 = 123; int32_t i32 = 1234; int64_t i64 = 12345; float f = 1.23; double d = 1.23456; StringValue sv("Hello"); TimestampValue tv; TestType(i8, sizeof(int32_t)); TestType(i16, sizeof(int32_t)); TestType(i32, sizeof(int32_t)); TestType(i64, sizeof(int64_t)); TestType(f, sizeof(float)); TestType(d, sizeof(double)); TestType(sv, sizeof(int32_t) + sv.len); TestType(tv, 12); } } int main(int argc, char **argv) { impala::CpuInfo::Init(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Add missing include to parquet-plain-test.<commit_after>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> #include <stdio.h> #include <iostream> #include <limits.h> #include <gtest/gtest.h> #include "exec/parquet-common.h" #include "runtime/string-value.inline.h" #include "runtime/timestamp-value.h" using namespace std; namespace impala { template <typename T> void TestType(const T& v, int expected_byte_size) { uint8_t buffer[expected_byte_size]; EXPECT_EQ(ParquetPlainEncoder::ByteSize(v), expected_byte_size); int encoded_size = ParquetPlainEncoder::Encode(buffer, v); EXPECT_EQ(encoded_size, expected_byte_size); T result; int decoded_size = ParquetPlainEncoder::Decode(buffer, &result); EXPECT_EQ(decoded_size, expected_byte_size); EXPECT_EQ(result, v); } TEST(PlainEncoding, Basic) { int8_t i8 = 12; int16_t i16 = 123; int32_t i32 = 1234; int64_t i64 = 12345; float f = 1.23; double d = 1.23456; StringValue sv("Hello"); TimestampValue tv; TestType(i8, sizeof(int32_t)); TestType(i16, sizeof(int32_t)); TestType(i32, sizeof(int32_t)); TestType(i64, sizeof(int64_t)); TestType(f, sizeof(float)); TestType(d, sizeof(double)); TestType(sv, sizeof(int32_t) + sv.len); TestType(tv, 12); } } int main(int argc, char **argv) { impala::CpuInfo::Init(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <string> #include <unordered_map> #include <cctype> #include <cstdlib> #include "BibleReferenceParser.h" #include "StringUtil.h" #include "util.h" // Expects an input file with lines of the form XXX=YYY. All embedded spaces are significant. void LoadMapFromFile(const std::string &input_filename, std::unordered_map<std::string, std::string> * const map) { map->clear(); std::ifstream input(input_filename, std::ofstream::in); if (input.fail()) Error("Failed to open \"" + input_filename + "\" for reading!"); unsigned line_no(0); for (std::string line; std::getline(input, line); /* Intentionally empty! */) { ++line_no; const size_t equal_pos(line.find('=')); if (equal_pos == std::string::npos) Error("Missing equal-sign in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); const std::string book_name(line.substr(0, equal_pos)); const std::string code(line.substr(equal_pos + 1)); if (book_name.empty() or code.empty()) Error("Bad input in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); (*map)[book_name] = code; } } // Expects an input file with lines of the form XXX=AAA;BBB;CCC. All embedded spaces are significant. // Embedded slashes, equal-signs, and semicolons are expected to be escaped with a leading slash. void LoadMultimapFromFile(const std::string &input_filename, std::unordered_multimap<std::string, std::string> * const multimap) { multimap->clear(); std::ifstream input(input_filename, std::ofstream::in); if (input.fail()) Error("Failed to open \"" + input_filename + "\" for reading!"); unsigned line_no(0); for (std::string line; std::getline(input, line); /* Intentionally empty! */) { ++line_no; std::string key, value; bool in_key(true), escaped(false); for (const char ch : line) { if (escaped) { escaped = false; if (in_key) key += ch; else value += ch; } else if (ch == '\\') escaped = true; else if (ch == '=') { if (key.empty()) Error("Missing key in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); in_key = false; } else if (in_key) key += ch; else if (ch == ';') { if (value.empty()) Error("Ilegal empty value in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); multimap->emplace(key, value); value.clear(); } else value += ch; } if (key.empty() or value.empty()) Error("Bad input in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); } } void SplitIntoBookAndChaptersAndVerses(const std::string &bib_ref_candidate, std::string * const book_candidate, std::string * const chapters_and_verses_candidate) { book_candidate->clear(); chapters_and_verses_candidate->clear(); const size_t len(bib_ref_candidate.length()); if (len <= 3) *book_candidate = bib_ref_candidate; else if (isdigit(bib_ref_candidate[len - 1]) or (isalpha(bib_ref_candidate[len - 1]) and isdigit(bib_ref_candidate[len - 2]))) { const size_t last_space_pos(bib_ref_candidate.rfind(' ')); if (last_space_pos == std::string::npos) *book_candidate = bib_ref_candidate; else { *book_candidate = bib_ref_candidate.substr(0, last_space_pos); *chapters_and_verses_candidate = bib_ref_candidate.substr(last_space_pos + 1); } } else *book_candidate = bib_ref_candidate; } void Usage() { std::cerr << "usage: " << progname << " bible_reference_candidate books_of_the_bible_to_code_map\n"; std::cerr << " books_of_the_bible_to_canonical_form_map pericopes_to_codes_map\n"; std::exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 5) Usage(); // // Deal with pericopes first... // std::unordered_multimap<std::string, std::string> pericopes_to_codes_map; LoadMultimapFromFile(argv[4], &pericopes_to_codes_map); std::string bib_ref_candidate(StringUtil::Trim(StringUtil::ToLower(argv[1]))); StringUtil::CollapseWhitespace(&bib_ref_candidate); const auto begin_end(pericopes_to_codes_map.equal_range(bib_ref_candidate)); if (begin_end.first != begin_end.second) { for (auto pair(begin_end.first); pair != begin_end.second; ++pair) std::cout << pair->second << '\n'; return EXIT_SUCCESS; } // // ...now deal w/ ordinary references. // std::string book_candidate, chapters_and_verses_candidate; SplitIntoBookAndChaptersAndVerses(bib_ref_candidate, &book_candidate, &chapters_and_verses_candidate); // Map from noncanonical bible book forms to the canonical ones: std::unordered_map<std::string, std::string> books_of_the_bible_to_canonical_form_map; LoadMapFromFile(argv[3], &books_of_the_bible_to_canonical_form_map); const auto non_canonical_form_and_canonical_form(books_of_the_bible_to_canonical_form_map.find(book_candidate)); if (non_canonical_form_and_canonical_form != books_of_the_bible_to_canonical_form_map.end()) book_candidate = non_canonical_form_and_canonical_form->second; std::unordered_map<std::string, std::string> bible_books_to_codes_map; LoadMapFromFile(argv[2], &bible_books_to_codes_map); const auto bible_book_and_code(bible_books_to_codes_map.find(book_candidate)); if (bible_book_and_code == bible_books_to_codes_map.end()) return EXIT_FAILURE; // Unknown bible book! const std::string book_code(bible_book_and_code->second); if (chapters_and_verses_candidate.empty()) { std::cout << book_code << "00000:" << book_code << "99999"; return EXIT_SUCCESS; } std::set<std::pair<std::string, std::string>> start_end; if (not ParseBibleReference(bib_ref_candidate, book_code, &start_end)) return EXIT_FAILURE; for (const auto &pair : start_end) std::cout << pair.first << ':' << pair.second << '\n'; } <commit_msg>Fixed a bug and added a --debug flag to ease future debugging.<commit_after>#include <fstream> #include <iostream> #include <string> #include <unordered_map> #include <cctype> #include <cstdlib> #include <cstring> #include "BibleReferenceParser.h" #include "StringUtil.h" #include "util.h" // Expects an input file with lines of the form XXX=YYY. All embedded spaces are significant. void LoadMapFromFile(const std::string &input_filename, std::unordered_map<std::string, std::string> * const map) { map->clear(); std::ifstream input(input_filename, std::ofstream::in); if (input.fail()) Error("Failed to open \"" + input_filename + "\" for reading!"); unsigned line_no(0); for (std::string line; std::getline(input, line); /* Intentionally empty! */) { ++line_no; const size_t equal_pos(line.find('=')); if (equal_pos == std::string::npos) Error("Missing equal-sign in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); const std::string book_name(line.substr(0, equal_pos)); const std::string code(line.substr(equal_pos + 1)); if (book_name.empty() or code.empty()) Error("Bad input in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); (*map)[book_name] = code; } } // Expects an input file with lines of the form XXX=AAA;BBB;CCC. All embedded spaces are significant. // Embedded slashes, equal-signs, and semicolons are expected to be escaped with a leading slash. void LoadMultimapFromFile(const std::string &input_filename, std::unordered_multimap<std::string, std::string> * const multimap) { multimap->clear(); std::ifstream input(input_filename, std::ofstream::in); if (input.fail()) Error("Failed to open \"" + input_filename + "\" for reading!"); unsigned line_no(0); for (std::string line; std::getline(input, line); /* Intentionally empty! */) { ++line_no; std::string key, value; bool in_key(true), escaped(false); for (const char ch : line) { if (escaped) { escaped = false; if (in_key) key += ch; else value += ch; } else if (ch == '\\') escaped = true; else if (ch == '=') { if (key.empty()) Error("Missing key in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); in_key = false; } else if (in_key) key += ch; else if (ch == ';') { if (value.empty()) Error("Ilegal empty value in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); multimap->emplace(key, value); value.clear(); } else value += ch; } if (key.empty() or value.empty()) Error("Bad input in \"" + input_filename + "\" on line " + std::to_string(line_no) + "!"); } } void SplitIntoBookAndChaptersAndVerses(const std::string &bib_ref_candidate, std::string * const book_candidate, std::string * const chapters_and_verses_candidate) { book_candidate->clear(); chapters_and_verses_candidate->clear(); const size_t len(bib_ref_candidate.length()); if (len <= 3) *book_candidate = bib_ref_candidate; else if (isdigit(bib_ref_candidate[len - 1]) or (isalpha(bib_ref_candidate[len - 1]) and isdigit(bib_ref_candidate[len - 2]))) { const size_t last_space_pos(bib_ref_candidate.rfind(' ')); if (last_space_pos == std::string::npos) *book_candidate = bib_ref_candidate; else { *book_candidate = bib_ref_candidate.substr(0, last_space_pos); *chapters_and_verses_candidate = bib_ref_candidate.substr(last_space_pos + 1); } } else *book_candidate = bib_ref_candidate; } void Usage() { std::cerr << "usage: " << progname << " [--debug] bible_reference_candidate books_of_the_bible_to_code_map\n"; std::cerr << " books_of_the_bible_to_canonical_form_map pericopes_to_codes_map\n"; std::exit(EXIT_FAILURE); } int main(int argc, char **argv) { progname = argv[0]; bool verbose(false); if (argc == 6) { if (std::strcmp(argv[1], "--debug") != 0) Usage(); verbose = true; ++argv, --argc; } if (argc != 5) Usage(); // // Deal with pericopes first... // std::unordered_multimap<std::string, std::string> pericopes_to_codes_map; LoadMultimapFromFile(argv[4], &pericopes_to_codes_map); std::string bib_ref_candidate(StringUtil::Trim(StringUtil::ToLower(argv[1]))); StringUtil::CollapseWhitespace(&bib_ref_candidate); const auto begin_end(pericopes_to_codes_map.equal_range(bib_ref_candidate)); if (begin_end.first != begin_end.second) { if (verbose) std::cerr << "Found a pericope to codes mapping.\n"; for (auto pair(begin_end.first); pair != begin_end.second; ++pair) std::cout << pair->second << '\n'; return EXIT_SUCCESS; } // // ...now deal w/ ordinary references. // std::string book_candidate, chapters_and_verses_candidate; SplitIntoBookAndChaptersAndVerses(bib_ref_candidate, &book_candidate, &chapters_and_verses_candidate); if (verbose) { std::cerr << "book_candidate = \"" << book_candidate << "\"\n"; std::cerr << "chapters_and_verses_candidate = \"" << chapters_and_verses_candidate << "\"\n"; } // Map from noncanonical bible book forms to the canonical ones: std::unordered_map<std::string, std::string> books_of_the_bible_to_canonical_form_map; LoadMapFromFile(argv[3], &books_of_the_bible_to_canonical_form_map); const auto non_canonical_form_and_canonical_form(books_of_the_bible_to_canonical_form_map.find(book_candidate)); if (non_canonical_form_and_canonical_form != books_of_the_bible_to_canonical_form_map.end()) { if (verbose) std::cerr << "Replacing \"" << book_candidate << "\" with \"" << non_canonical_form_and_canonical_form->second << "\".\n"; book_candidate = non_canonical_form_and_canonical_form->second; } std::unordered_map<std::string, std::string> bible_books_to_codes_map; LoadMapFromFile(argv[2], &bible_books_to_codes_map); const auto bible_book_and_code(bible_books_to_codes_map.find(book_candidate)); if (bible_book_and_code == bible_books_to_codes_map.end()) { if (verbose) std::cerr << "No mapping from \"" << book_candidate << "\" to a book code was found!\n"; return EXIT_FAILURE; // Unknown bible book! } const std::string book_code(bible_book_and_code->second); if (verbose) std::cerr << "book code = \"" << book_code << "\"\n"; if (chapters_and_verses_candidate.empty()) { std::cout << book_code << "00000:" << book_code << "99999"; return EXIT_SUCCESS; } std::set<std::pair<std::string, std::string>> start_end; if (not ParseBibleReference(chapters_and_verses_candidate, book_code, &start_end)) { if (verbose) std::cerr << "The parsing of \"" << chapters_and_verses_candidate << "\" as chapters and verses failed!\n"; return EXIT_FAILURE; } for (const auto &pair : start_end) std::cout << pair.first << ':' << pair.second << '\n'; } <|endoftext|>
<commit_before>/* Description: This is a example code for Sandbox Electronics' I2C/SPI to UART bridge module. You can get one of those products on http://sandboxelectronics.com Version: V0.1 Release Date: 2014-02-16 Author: Tiequan Shao info@sandboxelectronics.com Lisence: CC BY-NC-SA 3.0 Please keep the above information when you use this code in your project. */ #include "SC16IS750.h" #ifndef _SC16IS750_H_ #define _SC16IS750_H_ #include "application.h" #ifdef ARDUINO #if (ARDUINO >= 100) #include <Arduino.h> #else #include <WProgram.h> #include <pins_arduino.h> #endif #elif USE_SPARK_CORE_V02 #include <spark_related_stuff_v2.h> #elif USE_SPARK_CORE_V01 #include <spark_related_stuff_v1.h> #endif /* #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif */ //Device Address //A:VDD //B:GND //C:SCL //D:SDA #define SC16IS750_ADDRESS_AA (0X90) #define SC16IS750_ADDRESS_AB (0X92) #define SC16IS750_ADDRESS_AC (0X94) #define SC16IS750_ADDRESS_AD (0X96) #define SC16IS750_ADDRESS_BA (0X98) #define SC16IS750_ADDRESS_BB (0X9A) #define SC16IS750_ADDRESS_BC (0X9C) #define SC16IS750_ADDRESS_BD (0X9E) #define SC16IS750_ADDRESS_CA (0XA0) #define SC16IS750_ADDRESS_CB (0XA2) #define SC16IS750_ADDRESS_CC (0XA4) #define SC16IS750_ADDRESS_CD (0XA6) #define SC16IS750_ADDRESS_DA (0XA8) #define SC16IS750_ADDRESS_DB (0XAA) #define SC16IS750_ADDRESS_DC (0XAC) #define SC16IS750_ADDRESS_DD (0XAE) //General Registers #define SC16IS750_REG_RHR (0x00) #define SC16IS750_REG_THR (0X00) #define SC16IS750_REG_IER (0X01) #define SC16IS750_REG_FCR (0X02) #define SC16IS750_REG_IIR (0X02) #define SC16IS750_REG_LCR (0X03) #define SC16IS750_REG_MCR (0X04) #define SC16IS750_REG_LSR (0X05) #define SC16IS750_REG_MSR (0X06) #define SC16IS750_REG_SPR (0X07) #define SC16IS750_REG_TCR (0X06) #define SC16IS750_REG_TLR (0X07) #define SC16IS750_REG_TXLVL (0X08) #define SC16IS750_REG_RXLVL (0X09) #define SC16IS750_REG_IODIR (0X0A) #define SC16IS750_REG_IOSTATE (0X0B) #define SC16IS750_REG_IOINTENA (0X0C) #define SC16IS750_REG_IOCONTROL (0X0E) #define SC16IS750_REG_EFCR (0X0F) //Special Registers #define SC16IS750_REG_DLL (0x00) #define SC16IS750_REG_DLH (0X01) //Enhanced Registers #define SC16IS750_REG_EFR (0X02) #define SC16IS750_REG_XON1 (0X04) #define SC16IS750_REG_XON2 (0X05) #define SC16IS750_REG_XOFF1 (0X06) #define SC16IS750_REG_XOFF2 (0X07) // #define SC16IS750_INT_CTS (0X80) #define SC16IS750_INT_RTS (0X40) #define SC16IS750_INT_XOFF (0X20) #define SC16IS750_INT_SLEEP (0X10) #define SC16IS750_INT_MODEM (0X08) #define SC16IS750_INT_LINE (0X04) #define SC16IS750_INT_THR (0X02) #define SC16IS750_INT_RHR (0X01) //Application Related #define SC16IS750_CRYSTCAL_FREQ (14745600UL) //#define SC16IS750_CRYSTCAL_FREQ (1843200UL) //#define SC16IS750_CRYSTCAL_FREQ (16000000UL) //#define SC16IS750_DEBUG_PRINT (0) #define SC16IS750_PROTOCOL_I2C (0) #define SC16IS750_PROTOCOL_SPI (1) class SC16IS750 // : public Stream { public: SC16IS750(uint8_t prtcl = SC16IS750_PROTOCOL_I2C, uint8_t addr = SC16IS750_ADDRESS_AD); void begin(uint32_t baud); int read(); size_t write(uint8_t val); int available(); void pinMode(uint8_t pin, uint8_t io); void digitalWrite(uint8_t pin, uint8_t value); uint8_t digitalRead(uint8_t pin); uint8_t ping(); // void setTimeout(uint32_t); // size_t readBytes(char *buffer, size_t length); int peek(); void flush(); uint8_t GPIOGetPortState(void); uint8_t InterruptPendingTest(void); void SetPinInterrupt(uint8_t io_int_ena); void InterruptControl(uint8_t int_ena); void ModemPin(uint8_t gpio); //gpio == 0, gpio[7:4] are modem pins, gpio == 1 gpio[7:4] are gpios void GPIOLatch(uint8_t latch); private: uint8_t device_address_sspin; uint8_t protocol; // uint32_t timeout; int16_t SetBaudrate(uint32_t baudrate); uint8_t ReadRegister(uint8_t reg_addr); void WriteRegister(uint8_t reg_addr, uint8_t val); void SetLine(uint8_t data_length, uint8_t parity_select, uint8_t stop_length ); void GPIOSetPinMode(uint8_t pin_number, uint8_t i_o); void GPIOSetPinState(uint8_t pin_number, uint8_t pin_state); uint8_t GPIOGetPinState(uint8_t pin_number); void GPIOSetPortMode(uint8_t port_io); void GPIOSetPortState(uint8_t port_state); void ResetDevice(void); void __isr(void); void FIFOEnable(uint8_t fifo_enable); void FIFOReset(uint8_t rx_fifo); void FIFOSetTriggerLevel(uint8_t rx_fifo, uint8_t length); uint8_t FIFOAvailableData(void); uint8_t FIFOAvailableSpace(void); void WriteByte(uint8_t val); int ReadByte(void); void EnableTransmit(uint8_t tx_enable); // int16_t readwithtimeout(); int peek_buf; uint8_t peek_flag; }; #endif <commit_msg>Update SC16IS750-library.cpp<commit_after>/* Description: This is a example code for Sandbox Electronics' I2C/SPI to UART bridge module. You can get one of those products on http://sandboxelectronics.com Version: V0.1 Release Date: 2014-02-16 Author: Tiequan Shao info@sandboxelectronics.com Lisence: CC BY-NC-SA 3.0 Please keep the above information when you use this code in your project. */ #include "SC16IS750-library.h" #ifndef _SC16IS750_H_ #define _SC16IS750_H_ #include "application.h" #ifdef ARDUINO #if (ARDUINO >= 100) #include <Arduino.h> #else #include <WProgram.h> #include <pins_arduino.h> #endif #elif USE_SPARK_CORE_V02 #include <spark_related_stuff_v2.h> #elif USE_SPARK_CORE_V01 #include <spark_related_stuff_v1.h> #endif /* #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif */ //Device Address //A:VDD //B:GND //C:SCL //D:SDA #define SC16IS750_ADDRESS_AA (0X90) #define SC16IS750_ADDRESS_AB (0X92) #define SC16IS750_ADDRESS_AC (0X94) #define SC16IS750_ADDRESS_AD (0X96) #define SC16IS750_ADDRESS_BA (0X98) #define SC16IS750_ADDRESS_BB (0X9A) #define SC16IS750_ADDRESS_BC (0X9C) #define SC16IS750_ADDRESS_BD (0X9E) #define SC16IS750_ADDRESS_CA (0XA0) #define SC16IS750_ADDRESS_CB (0XA2) #define SC16IS750_ADDRESS_CC (0XA4) #define SC16IS750_ADDRESS_CD (0XA6) #define SC16IS750_ADDRESS_DA (0XA8) #define SC16IS750_ADDRESS_DB (0XAA) #define SC16IS750_ADDRESS_DC (0XAC) #define SC16IS750_ADDRESS_DD (0XAE) //General Registers #define SC16IS750_REG_RHR (0x00) #define SC16IS750_REG_THR (0X00) #define SC16IS750_REG_IER (0X01) #define SC16IS750_REG_FCR (0X02) #define SC16IS750_REG_IIR (0X02) #define SC16IS750_REG_LCR (0X03) #define SC16IS750_REG_MCR (0X04) #define SC16IS750_REG_LSR (0X05) #define SC16IS750_REG_MSR (0X06) #define SC16IS750_REG_SPR (0X07) #define SC16IS750_REG_TCR (0X06) #define SC16IS750_REG_TLR (0X07) #define SC16IS750_REG_TXLVL (0X08) #define SC16IS750_REG_RXLVL (0X09) #define SC16IS750_REG_IODIR (0X0A) #define SC16IS750_REG_IOSTATE (0X0B) #define SC16IS750_REG_IOINTENA (0X0C) #define SC16IS750_REG_IOCONTROL (0X0E) #define SC16IS750_REG_EFCR (0X0F) //Special Registers #define SC16IS750_REG_DLL (0x00) #define SC16IS750_REG_DLH (0X01) //Enhanced Registers #define SC16IS750_REG_EFR (0X02) #define SC16IS750_REG_XON1 (0X04) #define SC16IS750_REG_XON2 (0X05) #define SC16IS750_REG_XOFF1 (0X06) #define SC16IS750_REG_XOFF2 (0X07) // #define SC16IS750_INT_CTS (0X80) #define SC16IS750_INT_RTS (0X40) #define SC16IS750_INT_XOFF (0X20) #define SC16IS750_INT_SLEEP (0X10) #define SC16IS750_INT_MODEM (0X08) #define SC16IS750_INT_LINE (0X04) #define SC16IS750_INT_THR (0X02) #define SC16IS750_INT_RHR (0X01) //Application Related #define SC16IS750_CRYSTCAL_FREQ (14745600UL) //#define SC16IS750_CRYSTCAL_FREQ (1843200UL) //#define SC16IS750_CRYSTCAL_FREQ (16000000UL) //#define SC16IS750_DEBUG_PRINT (0) #define SC16IS750_PROTOCOL_I2C (0) #define SC16IS750_PROTOCOL_SPI (1) class SC16IS750 // : public Stream { public: SC16IS750(uint8_t prtcl = SC16IS750_PROTOCOL_I2C, uint8_t addr = SC16IS750_ADDRESS_AD); void begin(uint32_t baud); int read(); size_t write(uint8_t val); int available(); void pinMode(uint8_t pin, uint8_t io); void digitalWrite(uint8_t pin, uint8_t value); uint8_t digitalRead(uint8_t pin); uint8_t ping(); // void setTimeout(uint32_t); // size_t readBytes(char *buffer, size_t length); int peek(); void flush(); uint8_t GPIOGetPortState(void); uint8_t InterruptPendingTest(void); void SetPinInterrupt(uint8_t io_int_ena); void InterruptControl(uint8_t int_ena); void ModemPin(uint8_t gpio); //gpio == 0, gpio[7:4] are modem pins, gpio == 1 gpio[7:4] are gpios void GPIOLatch(uint8_t latch); private: uint8_t device_address_sspin; uint8_t protocol; // uint32_t timeout; int16_t SetBaudrate(uint32_t baudrate); uint8_t ReadRegister(uint8_t reg_addr); void WriteRegister(uint8_t reg_addr, uint8_t val); void SetLine(uint8_t data_length, uint8_t parity_select, uint8_t stop_length ); void GPIOSetPinMode(uint8_t pin_number, uint8_t i_o); void GPIOSetPinState(uint8_t pin_number, uint8_t pin_state); uint8_t GPIOGetPinState(uint8_t pin_number); void GPIOSetPortMode(uint8_t port_io); void GPIOSetPortState(uint8_t port_state); void ResetDevice(void); void __isr(void); void FIFOEnable(uint8_t fifo_enable); void FIFOReset(uint8_t rx_fifo); void FIFOSetTriggerLevel(uint8_t rx_fifo, uint8_t length); uint8_t FIFOAvailableData(void); uint8_t FIFOAvailableSpace(void); void WriteByte(uint8_t val); int ReadByte(void); void EnableTransmit(uint8_t tx_enable); // int16_t readwithtimeout(); int peek_buf; uint8_t peek_flag; }; #endif <|endoftext|>
<commit_before>/** * @file uart.cpp * * @brief Contains uart access functionality * * Example usage: * @code * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * uart0.Transmite(byte); * } * * @endcode */ #include <stdint.h> #include <avr/io.h> #include <avr/interrupt.h> #include "uart.h" #include "util/ringbuffer.h" /********************************************************************************/ /*************************** EXTERN UART ACCESSORS ******************************/ /********************************************************************************/ /** * @brief Used to access uart0 * * On atmega2561:<b> * Pin2: RXD0 <b> * Pin3: TXD0 */ Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0); /** * @brief Used to access uart1 * * On atmega2561:<b> * Pin27: RXD0 <b> * Pin28: TXD0 */ Uart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1); /********************************************************************************/ /*************************** PRIVATE FUNCTIONS **********************************/ /********************************************************************************/ /** * @brief Calculates the clock scale needed to run uart at the specified baud rate. * * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000. * If not specified 9600 is used. * * @return 16-bit unsigned integer representing the baud scale value that * corresponds to the specified baudrate. */ uint16_t Uart::BaudScale(uint16_t baudrate) { return (((F_CPU / (baudrate * 16UL))) - 1); } /********************************************************************************/ /*************************** PUBLIC FUNCTIONS ***********************************/ /********************************************************************************/ /** * @brief Initializes uart with specified baud rate. * * @param ubrr Pointer to UBRRn usart baud rate register * @param ucsra Pointer to UCSRnA usart control and status register A. * @param ucsrb Pointer to CUSRnB usart control and status register B. * @param ucsrc Pointer to UCSRnC usart control and status register C. * @param udr Pointer to UDRn usart data register. * * Example usage: * @code * * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0); * Uart uart1(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0); * * @endcode */ Uart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr) { _ubrr = ubrr; _ucsra = ucsra; _ucsrb = ucsrb; _ucsrc = ucsrc; _udr = udr; } /** * @brief Initializes uart with specified baud rate. * * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000. * If not specified 9600 is used. * * Example usage: * @code * * uart0.Init(9600); * * @endcode */ void Uart::Init(uint16_t baudrate) { // initializing uart to specified baud rate *_ubrr = BaudScale(baudrate); // setting 8 data bits, 1 stop bit, no parity *_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01)); // enabling receiver and transmitter *_ucsrb = ((1 << RXEN0) | (1 << TXEN0)); // enabling uart interrupts *_ucsrb |= ((1 << RXCIE0)); } /** * @brief Returns true if there is data in the receive buffer, false otherwise. * * Example usage: * @code * * char byte; * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * } * * @endcode * * @return Returns true if there is data to read in buffer, false otherwise */ bool Uart::Available() { return !_rx_buffer.IsEmpty(); } /** * @brief Grabs a byte from the receive buffer. Note that a check should * be made to see if there is data in buffer, else you may receive garbage. * * Example usage: * @code * * char byte; * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * } * * @endcode * * @return Returns a byte from the uart buffer. If there is nothing in the buffer, * returns garbage. */ char Uart::Receive() { return _rx_buffer.Pop(); } /** * @brief Non-blocking uart transmit. * * @param Byte to transmit over uart. * * If data is currently being transmitted, add to buffer to be transmitted later. * Kicks off data register empty interrupt if no data is currently being transmitted. * * Example usage: * @code * char byte; * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * uart0.Transmite(byte); * } * * @endcode */ void Uart::Transmit(char byte) { // pushing byte to tx buffer, then kicking off transmit if none // already in progress _tx_buffer.Push(byte); // enable transmit data register empty interrupt *_ucsrb |= (1 << UDRIE0); } /** * @brief Prints characters 1 byte at a time until null terminator is reached. * * @param Pointer to character array with null terminator symbol at the end '\0'. * * Example usage: * @code * * uart0.Init(9600); * * uart0.Print("Hello World\n"); * * @endcode */ void Uart::Print(const char *byte) { while (*byte != '\0') { Transmit(*byte); byte++; } } /********************************************************************************/ /*************************** FRIEND FUNCTIONS ***********************************/ /********************************************************************************/ /** * @brief USART Receive handler, pushes byte to _rx_buffer for reading later. * * @param uart Pointer to uart instance we are reading from. */ void _RxRxcIsr(Uart *uart) { char rxbyte; // pushing byte to rxbuff rxbyte = *(uart->_udr); uart->_rx_buffer.Push(rxbyte); } /** * @brief USART Data Register Empty handler, pops byte from _tx_buffer and writes * to data register. * * @param uart Pointer to uart instance we are writing to. */ void _TxUdreIsr(Uart *uart) { char txbyte; txbyte = uart->_tx_buffer.Pop(); *(uart->_udr) = txbyte; if (uart->_tx_buffer.IsEmpty()) { *(uart->_ucsrb) &= ~(1 << UDRIE0); } } /********************************************************************************/ /********************************* ISRs *****************************************/ /********************************************************************************/ ISR(USART0_RX_vect) { _RxRxcIsr(&uart0); } ISR(USART1_RX_vect) { _RxRxcIsr(&uart1); } ISR(USART0_UDRE_vect) { _TxUdreIsr(&uart0); } ISR(USART1_UDRE_vect) { _TxUdreIsr(&uart1); } <commit_msg>Updated mistake in UART usage comment<commit_after>/** * @file uart.cpp * * @brief Contains uart access functionality * * Example usage: * @code * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * uart0.Transmite(byte); * } * * @endcode */ #include <stdint.h> #include <avr/io.h> #include <avr/interrupt.h> #include "uart.h" #include "util/ringbuffer.h" /********************************************************************************/ /*************************** EXTERN UART ACCESSORS ******************************/ /********************************************************************************/ /** * @brief Used to access uart0 * * On atmega2561:<b> * Pin2: RXD0 <b> * Pin3: TXD0 */ Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0); /** * @brief Used to access uart1 * * On atmega2561:<b> * Pin27: RXD0 <b> * Pin28: TXD0 */ Uart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1); /********************************************************************************/ /*************************** PRIVATE FUNCTIONS **********************************/ /********************************************************************************/ /** * @brief Calculates the clock scale needed to run uart at the specified baud rate. * * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000. * If not specified 9600 is used. * * @return 16-bit unsigned integer representing the baud scale value that * corresponds to the specified baudrate. */ uint16_t Uart::BaudScale(uint16_t baudrate) { return (((F_CPU / (baudrate * 16UL))) - 1); } /********************************************************************************/ /*************************** PUBLIC FUNCTIONS ***********************************/ /********************************************************************************/ /** * @brief Initializes uart with specified baud rate. * * @param ubrr Pointer to UBRRn usart baud rate register * @param ucsra Pointer to UCSRnA usart control and status register A. * @param ucsrb Pointer to CUSRnB usart control and status register B. * @param ucsrc Pointer to UCSRnC usart control and status register C. * @param udr Pointer to UDRn usart data register. * * Example usage: * @code * * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0); * Uart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1); * * @endcode */ Uart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr) { _ubrr = ubrr; _ucsra = ucsra; _ucsrb = ucsrb; _ucsrc = ucsrc; _udr = udr; } /** * @brief Initializes uart with specified baud rate. * * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000. * If not specified 9600 is used. * * Example usage: * @code * * uart0.Init(9600); * * @endcode */ void Uart::Init(uint16_t baudrate) { // initializing uart to specified baud rate *_ubrr = BaudScale(baudrate); // setting 8 data bits, 1 stop bit, no parity *_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01)); // enabling receiver and transmitter *_ucsrb = ((1 << RXEN0) | (1 << TXEN0)); // enabling uart interrupts *_ucsrb |= ((1 << RXCIE0)); } /** * @brief Returns true if there is data in the receive buffer, false otherwise. * * Example usage: * @code * * char byte; * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * } * * @endcode * * @return Returns true if there is data to read in buffer, false otherwise */ bool Uart::Available() { return !_rx_buffer.IsEmpty(); } /** * @brief Grabs a byte from the receive buffer. Note that a check should * be made to see if there is data in buffer, else you may receive garbage. * * Example usage: * @code * * char byte; * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * } * * @endcode * * @return Returns a byte from the uart buffer. If there is nothing in the buffer, * returns garbage. */ char Uart::Receive() { return _rx_buffer.Pop(); } /** * @brief Non-blocking uart transmit. * * @param Byte to transmit over uart. * * If data is currently being transmitted, add to buffer to be transmitted later. * Kicks off data register empty interrupt if no data is currently being transmitted. * * Example usage: * @code * char byte; * * uart0.Init(9600); * * if (uart0.Available()) * { * byte = uart0.Receive(); * uart0.Transmite(byte); * } * * @endcode */ void Uart::Transmit(char byte) { // pushing byte to tx buffer, then kicking off transmit if none // already in progress _tx_buffer.Push(byte); // enable transmit data register empty interrupt *_ucsrb |= (1 << UDRIE0); } /** * @brief Prints characters 1 byte at a time until null terminator is reached. * * @param Pointer to character array with null terminator symbol at the end '\0'. * * Example usage: * @code * * uart0.Init(9600); * * uart0.Print("Hello World\n"); * * @endcode */ void Uart::Print(const char *byte) { while (*byte != '\0') { Transmit(*byte); byte++; } } /********************************************************************************/ /*************************** FRIEND FUNCTIONS ***********************************/ /********************************************************************************/ /** * @brief USART Receive handler, pushes byte to _rx_buffer for reading later. * * @param uart Pointer to uart instance we are reading from. */ void _RxRxcIsr(Uart *uart) { char rxbyte; // pushing byte to rxbuff rxbyte = *(uart->_udr); uart->_rx_buffer.Push(rxbyte); } /** * @brief USART Data Register Empty handler, pops byte from _tx_buffer and writes * to data register. * * @param uart Pointer to uart instance we are writing to. */ void _TxUdreIsr(Uart *uart) { char txbyte; txbyte = uart->_tx_buffer.Pop(); *(uart->_udr) = txbyte; if (uart->_tx_buffer.IsEmpty()) { *(uart->_ucsrb) &= ~(1 << UDRIE0); } } /********************************************************************************/ /********************************* ISRs *****************************************/ /********************************************************************************/ ISR(USART0_RX_vect) { _RxRxcIsr(&uart0); } ISR(USART1_RX_vect) { _RxRxcIsr(&uart1); } ISR(USART0_UDRE_vect) { _TxUdreIsr(&uart0); } ISR(USART1_UDRE_vect) { _TxUdreIsr(&uart1); } <|endoftext|>
<commit_before>/* * Vulkan * * Copyright (C) 2015 LunarG, Inc. * * 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 <string.h> #include <stdlib.h> #include <assert.h> #include <unordered_map> #include "loader_platform.h" #include "vk_dispatch_table_helper.h" #include "vkLayer.h" // The following is #included again to catch certain OS-specific functions // being used: #include "loader_platform.h" #include "SPIRV/spirv.h" static std::unordered_map<void *, VkLayerDispatchTable *> tableMap; static VkLayerDispatchTable * initLayerTable(const VkBaseLayerObject *gpuw) { VkLayerDispatchTable *pTable; assert(gpuw); std::unordered_map<void *, VkLayerDispatchTable *>::const_iterator it = tableMap.find((void *) gpuw->baseObject); if (it == tableMap.end()) { pTable = new VkLayerDispatchTable; tableMap[(void *) gpuw->baseObject] = pTable; } else { return it->second; } layer_initialize_dispatch_table(pTable, gpuw->pGPA, (VkPhysicalGpu) gpuw->nextObject); return pTable; } VK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalGpu gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice) { VkLayerDispatchTable* pTable = tableMap[gpu]; VkResult result = pTable->CreateDevice(gpu, pCreateInfo, pDevice); // create a mapping for the device object into the dispatch table tableMap.emplace(*pDevice, pTable); return result; } VK_LAYER_EXPORT VkResult VKAPI vkEnumerateLayers(VkPhysicalGpu gpu, size_t maxLayerCount, size_t maxStringSize, size_t* pOutLayerCount, char* const* pOutLayers, void* pReserved) { if (pOutLayerCount == NULL || pOutLayers == NULL || pOutLayers[0] == NULL || pOutLayers[1] == NULL || pReserved == NULL) return VK_ERROR_INVALID_POINTER; if (maxLayerCount < 1) return VK_ERROR_INITIALIZATION_FAILED; *pOutLayerCount = 1; strncpy((char *) pOutLayers[0], "ShaderChecker", maxStringSize); return VK_SUCCESS; } struct extProps { uint32_t version; const char * const name; }; #define SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE 1 static const struct extProps shaderCheckerExts[SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE] = { // TODO what is the version? 0x10, "ShaderChecker", }; VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionInfo( VkExtensionInfoType infoType, uint32_t extensionIndex, size_t* pDataSize, void* pData) { VkResult result; /* This entrypoint is NOT going to init it's own dispatch table since loader calls here early */ VkExtensionProperties *ext_props; uint32_t *count; if (pDataSize == NULL) return VK_ERROR_INVALID_POINTER; switch (infoType) { case VK_EXTENSION_INFO_TYPE_COUNT: *pDataSize = sizeof(uint32_t); if (pData == NULL) return VK_SUCCESS; count = (uint32_t *) pData; *count = SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE; break; case VK_EXTENSION_INFO_TYPE_PROPERTIES: *pDataSize = sizeof(VkExtensionProperties); if (pData == NULL) return VK_SUCCESS; if (extensionIndex >= SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE) return VK_ERROR_INVALID_VALUE; ext_props = (VkExtensionProperties *) pData; ext_props->version = shaderCheckerExts[extensionIndex].version; strncpy(ext_props->extName, shaderCheckerExts[extensionIndex].name, VK_MAX_EXTENSION_NAME); ext_props->extName[VK_MAX_EXTENSION_NAME - 1] = '\0'; break; default: return VK_ERROR_INVALID_VALUE; }; return VK_SUCCESS; } VK_LAYER_EXPORT VkResult VKAPI vkCreateShader(VkDevice device, const VkShaderCreateInfo *pCreateInfo, VkShader *pShader) { VkLayerDispatchTable* pTable = tableMap[(VkBaseLayerObject *)device]; VkResult res = pTable->CreateShader(device, pCreateInfo, pShader); return res; } VK_LAYER_EXPORT void * VKAPI vkGetProcAddr(VkPhysicalGpu gpu, const char* pName) { if (gpu == NULL) return NULL; initLayerTable((const VkBaseLayerObject *) gpu); #define ADD_HOOK(fn) \ if (!strncmp(#fn, pName, sizeof(#fn))) \ return (void *) fn ADD_HOOK(vkGetProcAddr); ADD_HOOK(vkEnumerateLayers); ADD_HOOK(vkCreateDevice); ADD_HOOK(vkCreateShader); VkBaseLayerObject* gpuw = (VkBaseLayerObject *) gpu; if (gpuw->pGPA == NULL) return NULL; return gpuw->pGPA((VkPhysicalGpu) gpuw->nextObject, pName); } <commit_msg>shader_checker: capture spir-v for every shader at vkCreateShader time<commit_after>/* * Vulkan * * Copyright (C) 2015 LunarG, Inc. * * 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 <string.h> #include <stdlib.h> #include <assert.h> #include <unordered_map> #include <vector> #include "loader_platform.h" #include "vk_dispatch_table_helper.h" #include "vkLayer.h" // The following is #included again to catch certain OS-specific functions // being used: #include "loader_platform.h" #include "SPIRV/spirv.h" static std::unordered_map<void *, VkLayerDispatchTable *> tableMap; struct shader_source { std::vector<uint32_t> words; shader_source(VkShaderCreateInfo const *pCreateInfo) : words((uint32_t *)pCreateInfo->pCode, (uint32_t *)pCreateInfo->pCode + pCreateInfo->codeSize / sizeof(uint32_t)) { } }; static std::unordered_map<void *, shader_source *> shader_map; static VkLayerDispatchTable * initLayerTable(const VkBaseLayerObject *gpuw) { VkLayerDispatchTable *pTable; assert(gpuw); std::unordered_map<void *, VkLayerDispatchTable *>::const_iterator it = tableMap.find((void *) gpuw->baseObject); if (it == tableMap.end()) { pTable = new VkLayerDispatchTable; tableMap[(void *) gpuw->baseObject] = pTable; } else { return it->second; } layer_initialize_dispatch_table(pTable, gpuw->pGPA, (VkPhysicalGpu) gpuw->nextObject); return pTable; } VK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalGpu gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice) { VkLayerDispatchTable* pTable = tableMap[gpu]; VkResult result = pTable->CreateDevice(gpu, pCreateInfo, pDevice); // create a mapping for the device object into the dispatch table tableMap.emplace(*pDevice, pTable); return result; } VK_LAYER_EXPORT VkResult VKAPI vkEnumerateLayers(VkPhysicalGpu gpu, size_t maxLayerCount, size_t maxStringSize, size_t* pOutLayerCount, char* const* pOutLayers, void* pReserved) { if (pOutLayerCount == NULL || pOutLayers == NULL || pOutLayers[0] == NULL || pOutLayers[1] == NULL || pReserved == NULL) return VK_ERROR_INVALID_POINTER; if (maxLayerCount < 1) return VK_ERROR_INITIALIZATION_FAILED; *pOutLayerCount = 1; strncpy((char *) pOutLayers[0], "ShaderChecker", maxStringSize); return VK_SUCCESS; } struct extProps { uint32_t version; const char * const name; }; #define SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE 1 static const struct extProps shaderCheckerExts[SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE] = { // TODO what is the version? 0x10, "ShaderChecker", }; VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionInfo( VkExtensionInfoType infoType, uint32_t extensionIndex, size_t* pDataSize, void* pData) { VkResult result; /* This entrypoint is NOT going to init it's own dispatch table since loader calls here early */ VkExtensionProperties *ext_props; uint32_t *count; if (pDataSize == NULL) return VK_ERROR_INVALID_POINTER; switch (infoType) { case VK_EXTENSION_INFO_TYPE_COUNT: *pDataSize = sizeof(uint32_t); if (pData == NULL) return VK_SUCCESS; count = (uint32_t *) pData; *count = SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE; break; case VK_EXTENSION_INFO_TYPE_PROPERTIES: *pDataSize = sizeof(VkExtensionProperties); if (pData == NULL) return VK_SUCCESS; if (extensionIndex >= SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE) return VK_ERROR_INVALID_VALUE; ext_props = (VkExtensionProperties *) pData; ext_props->version = shaderCheckerExts[extensionIndex].version; strncpy(ext_props->extName, shaderCheckerExts[extensionIndex].name, VK_MAX_EXTENSION_NAME); ext_props->extName[VK_MAX_EXTENSION_NAME - 1] = '\0'; break; default: return VK_ERROR_INVALID_VALUE; }; return VK_SUCCESS; } VK_LAYER_EXPORT VkResult VKAPI vkCreateShader(VkDevice device, const VkShaderCreateInfo *pCreateInfo, VkShader *pShader) { VkLayerDispatchTable* pTable = tableMap[(VkBaseLayerObject *)device]; VkResult res = pTable->CreateShader(device, pCreateInfo, pShader); shader_map[(VkBaseLayerObject *) *pShader] = new shader_source(pCreateInfo); return res; } VK_LAYER_EXPORT void * VKAPI vkGetProcAddr(VkPhysicalGpu gpu, const char* pName) { if (gpu == NULL) return NULL; initLayerTable((const VkBaseLayerObject *) gpu); #define ADD_HOOK(fn) \ if (!strncmp(#fn, pName, sizeof(#fn))) \ return (void *) fn ADD_HOOK(vkGetProcAddr); ADD_HOOK(vkEnumerateLayers); ADD_HOOK(vkCreateDevice); ADD_HOOK(vkCreateShader); VkBaseLayerObject* gpuw = (VkBaseLayerObject *) gpu; if (gpuw->pGPA == NULL) return NULL; return gpuw->pGPA((VkPhysicalGpu) gpuw->nextObject, pName); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: hierarchyprovider.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kso $ $Date: 2001-07-03 11:16:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Kai Sommerfeld ( kso@sun.com ) * * ************************************************************************/ #ifndef _HIERARCHYPROVIDER_HXX #define _HIERARCHYPROVIDER_HXX #include <hash_map> #ifndef _UCBHELPER_PROVIDERHELPER_HXX #include <ucbhelper/providerhelper.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif namespace com { namespace sun { namespace star { namespace container { class XHierarchicalNameAccess; } } } } namespace hierarchy_ucp { //========================================================================= #define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME \ "com.sun.star.ucb.HierarchyContentProvider" #define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 41 #define HIERARCHY_URL_SCHEME \ "vnd.sun.star.hier" #define HIERARCHY_URL_SCHEME_LENGTH 17 #define HIERARCHY_FOLDER_CONTENT_TYPE \ "application/" HIERARCHY_URL_SCHEME "-folder" #define HIERARCHY_LINK_CONTENT_TYPE \ "application/" HIERARCHY_URL_SCHEME "-link" //========================================================================= struct ConfigProviderMapEntry { com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xConfigProvider; com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > xRootReadAccess; bool bTriedToGetRootReadAccess; // #82494# ConfigProviderMapEntry() : bTriedToGetRootReadAccess( false ) {} }; struct equalString { bool operator()( const rtl::OUString& rKey1, const rtl::OUString& rKey2 ) const { return !!( rKey1 == rKey2 ); } }; struct hashString { size_t operator()( const rtl::OUString & rName ) const { return rName.hashCode(); } }; typedef std::hash_map < rtl::OUString, // servcie specifier ConfigProviderMapEntry, hashString, equalString > ConfigProviderMap; //========================================================================= class HierarchyContentProvider : public ::ucb::ContentProviderImplHelper, public com::sun::star::lang::XInitialization { ConfigProviderMap m_aConfigProviderMap; public: HierarchyContentProvider( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rXSMgr ); virtual ~HierarchyContentProvider(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo XSERVICEINFO_DECL() // XContentProvider virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL queryContent( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( com::sun::star::ucb::IllegalIdentifierException, com::sun::star::uno::RuntimeException ); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw( ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException ); // Non-Interface methods com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > getConfigProvider( const rtl::OUString & rServiceSpecifier ); com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > getRootConfigReadNameAccess( const rtl::OUString & rServiceSpecifier ); }; } // namespace hierarchy_ucp #endif /* !_HIERARCHYPROVIDER_HXX */ <commit_msg>INTEGRATION: CWS relocinst (1.5.162); FILE MERGED 2004/04/22 11:30:21 kso 1.5.162.2: #116281# - OfficeInstallationDirectory -> OfficeInstallationDirectories 2004/04/13 08:39:11 kso 1.5.162.1: #116281# - Does no longer store absolute paths to the office installation dir.<commit_after>/************************************************************************* * * $RCSfile: hierarchyprovider.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-05-10 14:23:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Kai Sommerfeld ( kso@sun.com ) * * ************************************************************************/ #ifndef _HIERARCHYPROVIDER_HXX #define _HIERARCHYPROVIDER_HXX #include <hash_map> #ifndef _UCBHELPER_PROVIDERHELPER_HXX #include <ucbhelper/providerhelper.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif namespace com { namespace sun { namespace star { namespace container { class XHierarchicalNameAccess; } namespace util { class XOfficeInstallationDirectories; } } } } namespace hierarchy_ucp { //========================================================================= #define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME \ "com.sun.star.ucb.HierarchyContentProvider" #define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 41 #define HIERARCHY_URL_SCHEME \ "vnd.sun.star.hier" #define HIERARCHY_URL_SCHEME_LENGTH 17 #define HIERARCHY_FOLDER_CONTENT_TYPE \ "application/" HIERARCHY_URL_SCHEME "-folder" #define HIERARCHY_LINK_CONTENT_TYPE \ "application/" HIERARCHY_URL_SCHEME "-link" //========================================================================= struct ConfigProviderMapEntry { com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xConfigProvider; com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > xRootReadAccess; bool bTriedToGetRootReadAccess; // #82494# ConfigProviderMapEntry() : bTriedToGetRootReadAccess( false ) {} }; struct equalString { bool operator()( const rtl::OUString& rKey1, const rtl::OUString& rKey2 ) const { return !!( rKey1 == rKey2 ); } }; struct hashString { size_t operator()( const rtl::OUString & rName ) const { return rName.hashCode(); } }; typedef std::hash_map < rtl::OUString, // servcie specifier ConfigProviderMapEntry, hashString, equalString > ConfigProviderMap; //========================================================================= class HierarchyContentProvider : public ::ucb::ContentProviderImplHelper, public com::sun::star::lang::XInitialization { ConfigProviderMap m_aConfigProviderMap; com::sun::star::uno::Reference< com::sun::star::util::XOfficeInstallationDirectories > m_xOfficeInstDirs; public: HierarchyContentProvider( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rXSMgr ); virtual ~HierarchyContentProvider(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo XSERVICEINFO_DECL() // XContentProvider virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL queryContent( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( com::sun::star::ucb::IllegalIdentifierException, com::sun::star::uno::RuntimeException ); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw( ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException ); // Non-Interface methods com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > getConfigProvider( const rtl::OUString & rServiceSpecifier ); com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > getRootConfigReadNameAccess( const rtl::OUString & rServiceSpecifier ); // Note: may retrun an empty reference. com::sun::star::uno::Reference< com::sun::star::util::XOfficeInstallationDirectories > getOfficeInstallationDirectories(); }; } // namespace hierarchy_ucp #endif /* !_HIERARCHYPROVIDER_HXX */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: hierarchyservices.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kso $ $Date: 2001-07-03 11:16:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _HIERARCHYPROVIDER_HXX #include "hierarchyprovider.hxx" #endif #ifndef _HIERARCHYDATASOURCE_HXX #include "hierarchydatasource.hxx" #endif using namespace com::sun::star; using namespace hierarchy_ucp; //========================================================================= static sal_Bool writeInfo( void * pRegistryKey, const rtl::OUString & rImplementationName, uno::Sequence< rtl::OUString > const & rServiceNames ) { rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) ); aKeyName += rImplementationName; aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" ); uno::Reference< registry::XRegistryKey > xKey; try { xKey = static_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( aKeyName ); } catch ( registry::InvalidRegistryException const & ) { } if ( !xKey.is() ) return sal_False; sal_Bool bSuccess = sal_True; for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n ) { try { xKey->createKey( rServiceNames[ n ] ); } catch ( registry::InvalidRegistryException const & ) { bSuccess = sal_False; break; } } return bSuccess; } //========================================================================= extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //========================================================================= extern "C" sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { return pRegistryKey && ////////////////////////////////////////////////////////////////////// // Hierarchy Content Provider. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, HierarchyContentProvider::getImplementationName_Static(), HierarchyContentProvider::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // Hierarchy Data Source. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, HierarchyDataSource::getImplementationName_Static(), HierarchyDataSource::getSupportedServiceNames_Static() ); } //========================================================================= extern "C" void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; uno::Reference< lang::XMultiServiceFactory > xSMgr( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; ////////////////////////////////////////////////////////////////////// // Hierarchy Content Provider. ////////////////////////////////////////////////////////////////////// if ( HierarchyContentProvider::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = HierarchyContentProvider::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // Hierarchy Data Source. ////////////////////////////////////////////////////////////////////// else if ( HierarchyDataSource::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = HierarchyDataSource::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.278); FILE MERGED 2005/09/05 18:45:17 rt 1.4.278.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hierarchyservices.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:48:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _HIERARCHYPROVIDER_HXX #include "hierarchyprovider.hxx" #endif #ifndef _HIERARCHYDATASOURCE_HXX #include "hierarchydatasource.hxx" #endif using namespace com::sun::star; using namespace hierarchy_ucp; //========================================================================= static sal_Bool writeInfo( void * pRegistryKey, const rtl::OUString & rImplementationName, uno::Sequence< rtl::OUString > const & rServiceNames ) { rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) ); aKeyName += rImplementationName; aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" ); uno::Reference< registry::XRegistryKey > xKey; try { xKey = static_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( aKeyName ); } catch ( registry::InvalidRegistryException const & ) { } if ( !xKey.is() ) return sal_False; sal_Bool bSuccess = sal_True; for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n ) { try { xKey->createKey( rServiceNames[ n ] ); } catch ( registry::InvalidRegistryException const & ) { bSuccess = sal_False; break; } } return bSuccess; } //========================================================================= extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //========================================================================= extern "C" sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { return pRegistryKey && ////////////////////////////////////////////////////////////////////// // Hierarchy Content Provider. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, HierarchyContentProvider::getImplementationName_Static(), HierarchyContentProvider::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // Hierarchy Data Source. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, HierarchyDataSource::getImplementationName_Static(), HierarchyDataSource::getSupportedServiceNames_Static() ); } //========================================================================= extern "C" void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; uno::Reference< lang::XMultiServiceFactory > xSMgr( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; ////////////////////////////////////////////////////////////////////// // Hierarchy Content Provider. ////////////////////////////////////////////////////////////////////// if ( HierarchyContentProvider::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = HierarchyContentProvider::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // Hierarchy Data Source. ////////////////////////////////////////////////////////////////////// else if ( HierarchyDataSource::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = HierarchyDataSource::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } <|endoftext|>
<commit_before>/** @file distributed_local_regression.cc * * The driver for the distributed local regression. * * @author Dongryeol Lee (dongryel@cc.gatech.edu) */ #include "core/metric_kernels/lmetric.h" #include "core/tree/statistic.h" #include "core/table/distributed_table.h" #include "core/tree/gen_kdtree.h" #include "core/tree/gen_metric_tree.h" #include "core/math/math_lib.h" #include "mlpack/local_regression/local_regression_dualtree.h" #include "mlpack/distributed_local_regression/distributed_local_regression_dev.h" #include "mlpack/series_expansion/kernel_aux.h" template<typename KernelType, typename MetricType> void StartComputation( boost::mpi::communicator &world, boost::program_options::variables_map &vm) { // Tree type: hard-coded for a metric tree. typedef core::table::DistributedTable < core::tree::GenKdTree < mlpack::local_regression::LocalRegressionStatistic > > DistributedTableType; // Parse arguments for local regression. mlpack::distributed_local_regression::DistributedLocalRegressionArguments < DistributedTableType, MetricType > distributed_local_regression_arguments; if(mlpack::distributed_local_regression:: DistributedLocalRegressionArgumentParser::ParseArguments( world, vm, &distributed_local_regression_arguments)) { return; } // Instantiate a distributed local regression object. mlpack::distributed_local_regression::DistributedLocalRegression < DistributedTableType, KernelType, MetricType > distributed_local_regression_instance; distributed_local_regression_instance.Init( world, distributed_local_regression_arguments); // Compute the result. mlpack::local_regression::LocalRegressionResult local_regression_result; distributed_local_regression_instance.Compute( distributed_local_regression_arguments, &local_regression_result); // Output the local regression result to the file. std::cerr << "Writing the predictions to the file: " << distributed_local_regression_arguments.predictions_out_ << "\n"; local_regression_result.Print( distributed_local_regression_arguments.predictions_out_); } int main(int argc, char *argv[]) { // Initialize boost MPI. boost::mpi::environment env(argc, argv); boost::mpi::communicator world; // Seed the random number. core::math::global_random_number_state_.set_seed(time(NULL) + world.rank()); if(world.rank() == 0) { printf("%d processes are present...\n", world.size()); } boost::program_options::variables_map vm; if(mlpack::distributed_local_regression:: DistributedLocalRegressionArgumentParser::ConstructBoostVariableMap( world, argc, argv, &vm)) { return 0; } // Do a quick peek at the kernel and expansion type. std::string kernel_type = vm["kernel"].as<std::string>(); std::string series_expansion_type = vm["series_expansion_type"].as<std::string>(); if(kernel_type == "gaussian") { StartComputation < core::metric_kernels::GaussianKernel, core::metric_kernels::LMetric<2> > (world, vm); } else { // Only the multivariate expansion is available for the // Epanechnikov. StartComputation < core::metric_kernels::EpanKernel, core::metric_kernels::LMetric<2> > (world, vm); } return 0; } <commit_msg>Boost anycast error fixed for dist local regression.<commit_after>/** @file distributed_local_regression.cc * * The driver for the distributed local regression. * * @author Dongryeol Lee (dongryel@cc.gatech.edu) */ #include "core/metric_kernels/lmetric.h" #include "core/tree/statistic.h" #include "core/table/distributed_table.h" #include "core/tree/gen_kdtree.h" #include "core/tree/gen_metric_tree.h" #include "core/math/math_lib.h" #include "mlpack/local_regression/local_regression_dualtree.h" #include "mlpack/distributed_local_regression/distributed_local_regression_dev.h" #include "mlpack/series_expansion/kernel_aux.h" template<typename KernelType, typename MetricType> void StartComputation( boost::mpi::communicator &world, boost::program_options::variables_map &vm) { // Tree type: hard-coded for a metric tree. typedef core::table::DistributedTable < core::tree::GenKdTree < mlpack::local_regression::LocalRegressionStatistic > > DistributedTableType; // Parse arguments for local regression. mlpack::distributed_local_regression::DistributedLocalRegressionArguments < DistributedTableType, MetricType > distributed_local_regression_arguments; if(mlpack::distributed_local_regression:: DistributedLocalRegressionArgumentParser::ParseArguments( world, vm, &distributed_local_regression_arguments)) { return; } // Instantiate a distributed local regression object. mlpack::distributed_local_regression::DistributedLocalRegression < DistributedTableType, KernelType, MetricType > distributed_local_regression_instance; distributed_local_regression_instance.Init( world, distributed_local_regression_arguments); // Compute the result. mlpack::local_regression::LocalRegressionResult local_regression_result; distributed_local_regression_instance.Compute( distributed_local_regression_arguments, &local_regression_result); // Output the local regression result to the file. std::cerr << "Writing the predictions to the file: " << distributed_local_regression_arguments.predictions_out_ << "\n"; local_regression_result.Print( distributed_local_regression_arguments.predictions_out_); } int main(int argc, char *argv[]) { // Initialize boost MPI. boost::mpi::environment env(argc, argv); boost::mpi::communicator world; // Seed the random number. core::math::global_random_number_state_.set_seed(time(NULL) + world.rank()); if(world.rank() == 0) { printf("%d processes are present...\n", world.size()); } boost::program_options::variables_map vm; if(mlpack::distributed_local_regression:: DistributedLocalRegressionArgumentParser::ConstructBoostVariableMap( world, argc, argv, &vm)) { return 0; } // Do a quick peek at the kernel and expansion type. std::string kernel_type = vm["kernel"].as<std::string>(); if(kernel_type == "gaussian") { StartComputation < core::metric_kernels::GaussianKernel, core::metric_kernels::LMetric<2> > (world, vm); } else { // Only the multivariate expansion is available for the // Epanechnikov. StartComputation < core::metric_kernels::EpanKernel, core::metric_kernels::LMetric<2> > (world, vm); } return 0; } <|endoftext|>
<commit_before>/** * \file py_calc_model.cpp * \brief Python wrappers for calc_model, calc_model_data * \author Sergey Miryanov * \date 02.12.2009 * \copyright This source code is released under the terms of * the BSD License. See LICENSE for more details. * */ #include "boost_array_adapter.h" #include "stdafx.h" #include "calc_model.h" #include "py_calc_model.h" #include BS_FORCE_PLUGIN_IMPORT () #include "py_scal_wrapper.h" #include "py_data_class.h" #include BS_STOP_PLUGIN_IMPORT () // WTF?? #include "well_results_storage.h" #include "fip_results_storage.h" #include "export_python_wrapper.h" using namespace boost::python; namespace blue_sky { namespace python { template <typename T> int get_n_phases (T *t) { return t->n_phases; } template <typename T> bool get_is_water (T *t) { return t->is_water (); } template <typename T> bool get_is_gas (T *t) { return t->is_gas (); } template <typename T> bool get_is_oil (T *t) { return t->is_oil (); } template <typename T> smart_ptr <named_pbase, true> get_params (T *t) { return t->ts_params; } template <typename T> smart_ptr <typename T::scal_3p_t, true> get_scal_3p (T *t) { return t->scal_prop; } PY_EXPORTER (calc_model_exporter, default_exporter) .add_property ("n_phases", get_n_phases <T>) .add_property ("is_water", get_is_water <T>) .add_property ("is_gas", get_is_gas <T>) .add_property ("is_oil", get_is_oil <T>) .add_property ("params", get_params <T>) .add_property ("data", &T::data) .add_property ("saturation", &T::saturation_3p) .add_property ("pressure", &T::pressure) .add_property ("pvt_num", &T::n_pvt_regions) .add_property ("sat_num", &T::n_sat_regions) .add_property ("fip_num", &T::n_fip_regions) .add_property ("scal", get_scal_3p <T>) .add_property ("pvt_regions", &T::pvt_regions) .add_property ("sat_regions", &T::sat_regions) .add_property ("fip_regions", &T::fip_regions) .add_property ("rock_regions",&T::rock_regions) .add_property ("pvt_water", &T::pvt_water_array) .add_property ("pvt_gas", &T::pvt_gas_array) .add_property ("pvt_oil", &T::pvt_oil_array) PY_EXPORTER_END; PY_EXPORTER (calc_model_data_exporter, empty_exporter) .add_property ("cap_pressure", detail::boost_array_adapter (&T::cap_pressure)) .add_property ("s_deriv_cap_pressure", detail::boost_array_adapter (&T::s_deriv_cap_pressure)) .add_property ("relative_perm", detail::boost_array_adapter (&T::relative_perm)) .add_property ("s_deriv_relative_perm", detail::boost_array_adapter (&T::s_deriv_relative_perm)) .add_property ("p_deriv_gas_oil_ratio", &T::p_deriv_gas_oil_ratio) .add_property ("invers_fvf", detail::boost_array_adapter (&T::invers_fvf)) .add_property ("p_deriv_invers_fvf", detail::boost_array_adapter (&T::p_deriv_invers_fvf)) .add_property ("gor_deriv_invers_fvf", &T::gor_deriv_invers_fvf) .add_property ("invers_visc", detail::boost_array_adapter (&T::invers_viscosity)) .add_property ("p_deriv_invers_visc", detail::boost_array_adapter (&T::p_deriv_invers_viscosity)) .add_property ("gor_deriv_invers_visc", &T::gor_deriv_invers_viscosity) .add_property ("invers_visc_fvf", detail::boost_array_adapter (&T::invers_visc_fvf)) .add_property ("p_deriv_invers_visc_fvf", detail::boost_array_adapter (&T::p_deriv_invers_visc_fvf)) .add_property ("gor_deriv_invers_visc_fvf", &T::gor_deriv_invers_visc_fvf) .add_property ("density", detail::boost_array_adapter (&T::density)) .add_property ("p_deriv_density", detail::boost_array_adapter (&T::p_deriv_density)) .add_property ("gor_deriv_density", &T::gor_deriv_density) .add_property ("porosity", &T::porosity) .add_property ("p_deriv_porosity", &T::p_deriv_porosity) .add_property ("truns_mult", &T::truns_mult) .add_property ("p_deriv_truns_mult", &T::p_deriv_truns_mult) .add_property ("mobility", detail::boost_array_adapter (&T::mobility)) .add_property ("p_deriv_mobility", detail::boost_array_adapter (&T::p_deriv_mobility)) .add_property ("s_deriv_mobility", detail::boost_array_adapter (&T::s_deriv_mobility)) .add_property ("prev_fluid_volume", detail::boost_array_adapter (&T::prev_fluid_volume)) PY_EXPORTER_END; template <typename T> void export_calc_model_data_vector (const char *name) { class_ <T> (name) .def (vector_indexing_suite <T> ()) ; } void py_export_calc_model() { strategy_exporter::export_base_ext <calc_model_data, calc_model_data_exporter, class_type::concrete_class> ("calc_model_data"); export_calc_model_data_vector <shared_vector <calc_model_data <base_strategy_di> > > ("calc_model_data_vector_di"); export_calc_model_data_vector <shared_vector <calc_model_data <base_strategy_fi> > > ("calc_model_data_vector_fi"); export_calc_model_data_vector <shared_vector <calc_model_data <base_strategy_mixi> > > ("calc_model_data_vector_mixi"); strategy_exporter::export_base <calc_model, calc_model_exporter> ("calc_model"); } } //ns python } //ns bs <commit_msg>Edit: Fix export of pvt arrays and add pvt_array_iterator<commit_after>/** * \file py_calc_model.cpp * \brief Python wrappers for calc_model, calc_model_data * \author Sergey Miryanov * \date 02.12.2009 * \copyright This source code is released under the terms of * the BSD License. See LICENSE for more details. * */ #include "boost_array_adapter.h" #include "stdafx.h" #include "calc_model.h" #include "py_calc_model.h" #include BS_FORCE_PLUGIN_IMPORT () #include "py_scal_wrapper.h" #include "py_data_class.h" #include BS_STOP_PLUGIN_IMPORT () // WTF?? #include "well_results_storage.h" #include "fip_results_storage.h" #include "export_python_wrapper.h" using namespace boost::python; namespace blue_sky { namespace python { template <typename T> int get_n_phases (T *t) { return t->n_phases; } template <typename T> bool get_is_water (T *t) { return t->is_water (); } template <typename T> bool get_is_gas (T *t) { return t->is_gas (); } template <typename T> bool get_is_oil (T *t) { return t->is_oil (); } template <typename T> smart_ptr <named_pbase, true> get_params (T *t) { return t->ts_params; } template <typename T> smart_ptr <typename T::scal_3p_t, true> get_scal_3p (T *t) { return t->scal_prop; } PY_EXPORTER (calc_model_exporter, default_exporter) .add_property ("n_phases", get_n_phases <T>) .add_property ("is_water", get_is_water <T>) .add_property ("is_gas", get_is_gas <T>) .add_property ("is_oil", get_is_oil <T>) .add_property ("params", get_params <T>) .add_property ("data", &T::data) .add_property ("saturation", &T::saturation_3p) .add_property ("pressure", &T::pressure) .add_property ("pvt_num", &T::n_pvt_regions) .add_property ("sat_num", &T::n_sat_regions) .add_property ("fip_num", &T::n_fip_regions) .add_property ("scal", get_scal_3p <T>) .add_property ("pvt_regions", &T::pvt_regions) .add_property ("sat_regions", &T::sat_regions) .add_property ("fip_regions", &T::fip_regions) .add_property ("rock_regions",&T::rock_regions) .add_property ("pvt_water", &T::pvt_water_array) .add_property ("pvt_gas", &T::pvt_gas_array) .add_property ("pvt_oil", &T::pvt_oil_array) PY_EXPORTER_END; PY_EXPORTER (calc_model_data_exporter, empty_exporter) .add_property ("cap_pressure", detail::boost_array_adapter (&T::cap_pressure)) .add_property ("s_deriv_cap_pressure", detail::boost_array_adapter (&T::s_deriv_cap_pressure)) .add_property ("relative_perm", detail::boost_array_adapter (&T::relative_perm)) .add_property ("s_deriv_relative_perm", detail::boost_array_adapter (&T::s_deriv_relative_perm)) .add_property ("p_deriv_gas_oil_ratio", &T::p_deriv_gas_oil_ratio) .add_property ("invers_fvf", detail::boost_array_adapter (&T::invers_fvf)) .add_property ("p_deriv_invers_fvf", detail::boost_array_adapter (&T::p_deriv_invers_fvf)) .add_property ("gor_deriv_invers_fvf", &T::gor_deriv_invers_fvf) .add_property ("invers_visc", detail::boost_array_adapter (&T::invers_viscosity)) .add_property ("p_deriv_invers_visc", detail::boost_array_adapter (&T::p_deriv_invers_viscosity)) .add_property ("gor_deriv_invers_visc", &T::gor_deriv_invers_viscosity) .add_property ("invers_visc_fvf", detail::boost_array_adapter (&T::invers_visc_fvf)) .add_property ("p_deriv_invers_visc_fvf", detail::boost_array_adapter (&T::p_deriv_invers_visc_fvf)) .add_property ("gor_deriv_invers_visc_fvf", &T::gor_deriv_invers_visc_fvf) .add_property ("density", detail::boost_array_adapter (&T::density)) .add_property ("p_deriv_density", detail::boost_array_adapter (&T::p_deriv_density)) .add_property ("gor_deriv_density", &T::gor_deriv_density) .add_property ("porosity", &T::porosity) .add_property ("p_deriv_porosity", &T::p_deriv_porosity) .add_property ("truns_mult", &T::truns_mult) .add_property ("p_deriv_truns_mult", &T::p_deriv_truns_mult) .add_property ("mobility", detail::boost_array_adapter (&T::mobility)) .add_property ("p_deriv_mobility", detail::boost_array_adapter (&T::p_deriv_mobility)) .add_property ("s_deriv_mobility", detail::boost_array_adapter (&T::s_deriv_mobility)) .add_property ("prev_fluid_volume", detail::boost_array_adapter (&T::prev_fluid_volume)) PY_EXPORTER_END; template <typename T> void export_calc_model_data_vector (const char *name) { class_ <T> (name) .def (vector_indexing_suite <T> ()) ; } template <typename T> typename T::value_type get_pvt_item (T *t, size_t index) { return t->operator[] (index); } template <typename T> struct pvt_array_iterator { pvt_array_iterator (T *t) : array_ (t) , iterator_ (t->begin ()) , iterator_end_ (t->end ()) { } typename T::value_type next () { #ifdef _DEBUG if (iterator_end_ != array_->end ()) { bs_throw_exception ("PVT array iterator not more valid"); } #endif if (iterator_ == iterator_end_) { PyErr_SetString (PyExc_StopIteration, "No more data"); boost::python::throw_error_already_set (); } return *(iterator_++); } T *array_; typename T::iterator iterator_; typename T::iterator iterator_end_; }; template <typename T> pvt_array_iterator <T> get_pvt_iterator (T *t) { return pvt_array_iterator <T> (t); } template <typename T> void export_pvt_iterator (const char *name) { using namespace boost::python; class_ <pvt_array_iterator <T> > (name, init <T *> ()) .def ("next", &pvt_array_iterator <T>::next) .def ("__iter__", pass_through) ; } template <template <typename> class T> void export_pvt_array (const char *name) { typedef std::vector <smart_ptr <T <base_strategy_di> > > T_di; typedef std::vector <smart_ptr <T <base_strategy_fi> > > T_fi; typedef std::vector <smart_ptr <T <base_strategy_mixi> > > T_mixi; class_ <T_di> (std::string (std::string (name) + "_di").c_str ()) .def ("__getitem__", get_pvt_item <T_di>) .def ("__len__", &T_di::size) .def ("__iter__", get_pvt_iterator <T_di>) ; class_ <T_fi> (std::string (std::string (name) + "_fi").c_str ()) .def ("__getitem__", get_pvt_item <T_fi>) .def ("__len__", &T_fi::size) .def ("__iter__", get_pvt_iterator <T_fi>) ; class_ <T_mixi> (std::string (std::string (name) + "_mixi").c_str ()) .def ("__getitem__", get_pvt_item <T_mixi>) .def ("__len__", &T_mixi::size) .def ("__iter__", get_pvt_iterator <T_mixi>) ; export_pvt_iterator <T_di> ("pvt_array_iter_di"); export_pvt_iterator <T_fi> ("pvt_array_iter_fi"); export_pvt_iterator <T_mixi> ("pvt_array_iter_mixi"); } void py_export_calc_model() { strategy_exporter::export_base_ext <calc_model_data, calc_model_data_exporter, class_type::concrete_class> ("calc_model_data"); export_calc_model_data_vector <shared_vector <calc_model_data <base_strategy_di> > > ("calc_model_data_vector_di"); export_calc_model_data_vector <shared_vector <calc_model_data <base_strategy_fi> > > ("calc_model_data_vector_fi"); export_calc_model_data_vector <shared_vector <calc_model_data <base_strategy_mixi> > > ("calc_model_data_vector_mixi"); export_pvt_array <pvt_dead_oil> ("pvt_dead_oil_array"); export_pvt_array <pvt_water> ("pvt_water_array"); export_pvt_array <pvt_gas> ("pvt_gas"); strategy_exporter::export_base <calc_model, calc_model_exporter> ("calc_model"); } } //ns python } //ns bs <|endoftext|>
<commit_before>#include "Assignment2.h" TutorialApplication::TutorialApplication() : mTerrainGroup(0), mTerrainGlobals(0), mInfoLabel(0) { } TutorialApplication::~TutorialApplication() { } void TutorialApplication::createCamera() { mCamera = mSceneMgr->createCamera("PlayerCam"); mCamera->setPosition(Ogre::Vector3(0, 300, 500)); mCamera->lookAt(Ogre::Vector3(0, 0, 0)); mCamera->setNearClipDistance(5); mCameraMan = new OgreBites::SdkCameraMan(mCamera); } void TutorialApplication::createViewports() { Ogre::Viewport* vp = mWindow->addViewport(mCamera); vp->setBackgroundColour(Ogre::ColourValue(0, 0, 0)); mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth())/Ogre::Real(vp->getActualHeight())); } void TutorialApplication::createScene() { mCamera->setPosition(Ogre::Vector3(1683, 50, 2116)); mCamera->lookAt(Ogre::Vector3(1963, 50, 1660)); mCamera->setNearClipDistance(.1); bool infiniteClip = mRoot->getRenderSystem()->getCapabilities()->hasCapability( Ogre::RSC_INFINITE_FAR_PLANE); if (infiniteClip) mCamera->setFarClipDistance(0); else mCamera->setFarClipDistance(50000); mSceneMgr->setAmbientLight(Ogre::ColourValue(.2, .2, .2)); Ogre::Vector3 lightDir(.55, -.3, .75); lightDir.normalise(); Ogre::Light* light = mSceneMgr->createLight("TestLight"); light->setType(Ogre::Light::LT_DIRECTIONAL); light->setDirection(lightDir); light->setDiffuseColour(Ogre::ColourValue::White); light->setSpecularColour(Ogre::ColourValue(.4, .4, .4)); Ogre::Entity* ninjaEntity = mSceneMgr->createEntity("ninja.mesh"); Ogre::SceneNode* ninjaNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("ninjaNode", Ogre::Vector3(2000, 10, 1925)); ninjaEntity->setCastShadows(true); ninjaNode->attachObject(ninjaEntity); // Fog Ogre::ColourValue fadeColour(.9, .9, .9); mWindow->getViewport(0)->setBackgroundColour(fadeColour); mSceneMgr->setFog(Ogre::FOG_EXP2, fadeColour, 0.002); // Terrain mTerrainGlobals = OGRE_NEW Ogre::TerrainGlobalOptions(); mTerrainGroup = OGRE_NEW Ogre::TerrainGroup( mSceneMgr, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0); mTerrainGroup->setFilenameConvention(Ogre::String("terrain"), Ogre::String("dat")); mTerrainGroup->setOrigin(Ogre::Vector3::ZERO); configureTerrainDefaults(light); for (long x = 0; x <= 0; ++x) for (long y = 0; y <= 0; ++y) defineTerrain(x, y); mTerrainGroup->loadAllTerrains(true); if (mTerrainsImported) { Ogre::TerrainGroup::TerrainIterator ti = mTerrainGroup->getTerrainIterator(); while (ti.hasMoreElements()) { Ogre::Terrain* t = ti.getNext()->instance; initBlendMaps(t); } } mTerrainGroup->freeTemporaryResources(); // Sky Techniques // mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 300, false); mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); Ogre::Plane plane; plane.d = 1000; plane.normal = Ogre::Vector3::NEGATIVE_UNIT_Y; // mSceneMgr->setSkyPlane( // true, plane, "Examples/SpaceSkyPlane", 1500, 40, true, 1.5, 150, 150); } void TutorialApplication::createFrameListener() { BaseApplication::createFrameListener(); mInfoLabel = mTrayMgr->createLabel(OgreBites::TL_TOP, "TerrainInfo", "", 350); } void TutorialApplication::destroyScene() { OGRE_DELETE mTerrainGroup; OGRE_DELETE mTerrainGlobals; } bool TutorialApplication::frameRenderingQueued(const Ogre::FrameEvent& fe) { bool ret = BaseApplication::frameRenderingQueued(fe); if (mTerrainGroup->isDerivedDataUpdateInProgress()) { mTrayMgr->moveWidgetToTray(mInfoLabel, OgreBites::TL_TOP, 0); mInfoLabel->show(); if (mTerrainsImported) mInfoLabel->setCaption("Building terrain..."); else mInfoLabel->setCaption("Updating textures..."); } else { mTrayMgr->removeWidgetFromTray(mInfoLabel); mInfoLabel->hide(); if (mTerrainsImported) { mTerrainGroup->saveAllTerrains(true); mTerrainsImported = false; } } return ret; } void getTerrainImage(bool flipX, bool flipY, Ogre::Image& img) { img.load("terrain.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (flipX) img.flipAroundY(); if (flipY) img.flipAroundX(); } void TutorialApplication::defineTerrain(long x, long y) { Ogre::String filename = mTerrainGroup->generateFilename(x, y); bool exists = Ogre::ResourceGroupManager::getSingleton().resourceExists( mTerrainGroup->getResourceGroup(), filename); if (exists) mTerrainGroup->defineTerrain(x, y); else { Ogre::Image img; getTerrainImage(x % 2 != 0, y % 2 != 0, img); mTerrainGroup->defineTerrain(x, y, &img); mTerrainsImported = true; } } void TutorialApplication::initBlendMaps(Ogre::Terrain* terrain) { Ogre::Real minHeight0 = 70; Ogre::Real fadeDist0 = 40; Ogre::Real minHeight1 = 70; Ogre::Real fadeDist1 = 15; Ogre::TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1); Ogre::TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2); float* pBlend0 = blendMap0->getBlendPointer(); float* pBlend1 = blendMap1->getBlendPointer(); for (Ogre::uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y) { for (Ogre::uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x) { Ogre::Real tx, ty; blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty); Ogre::Real height = terrain->getHeightAtTerrainPosition(tx, ty); Ogre::Real val = (height - minHeight0) / fadeDist0; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); *pBlend0++ = val; val = (height - minHeight1) / fadeDist1; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); *pBlend1++ = val; } } blendMap0->dirty(); blendMap1->dirty(); blendMap0->update(); blendMap1->update(); } void TutorialApplication::configureTerrainDefaults(Ogre::Light* light) { mTerrainGlobals->setMaxPixelError(8); mTerrainGlobals->setCompositeMapDistance(3000); mTerrainGlobals->setLightMapDirection(light->getDerivedDirection()); mTerrainGlobals->setCompositeMapAmbient(mSceneMgr->getAmbientLight()); mTerrainGlobals->setCompositeMapDiffuse(light->getDiffuseColour()); Ogre::Terrain::ImportData& importData = mTerrainGroup->getDefaultImportSettings(); importData.terrainSize = 513; importData.worldSize = 12000.0; importData.inputScale = 600; importData.minBatchSize = 33; importData.maxBatchSize = 65; importData.layerList.resize(3); importData.layerList[0].worldSize = 100; importData.layerList[0].textureNames.push_back( "dirt_grayrocky_diffusespecular.dds"); importData.layerList[0].textureNames.push_back( "dirt_grayrocky_normalheight.dds"); importData.layerList[1].worldSize = 30; importData.layerList[1].textureNames.push_back( "grass_green-01_diffusespecular.dds"); importData.layerList[1].textureNames.push_back( "grass_green-01_normalheight.dds"); importData.layerList[2].worldSize = 200; importData.layerList[2].textureNames.push_back( "growth_weirdfungus-03_diffusespecular.dds"); importData.layerList[2].textureNames.push_back( "growth_weirdfungus-03_normalheight.dds"); } #if Ogre_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" #endif #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) #else int main(int argc, char *argv[]) #endif { // Create application object TutorialApplication app; try { app.go(); } catch( Ogre::Exception& e ) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl; #endif } return 0; } #ifdef __cplusplus } #endif<commit_msg>removed fog because it makes eveything hard to see<commit_after>#include "Assignment2.h" TutorialApplication::TutorialApplication() : mTerrainGroup(0), mTerrainGlobals(0), mInfoLabel(0) { } TutorialApplication::~TutorialApplication() { } void TutorialApplication::createCamera() { mCamera = mSceneMgr->createCamera("PlayerCam"); mCamera->setPosition(Ogre::Vector3(2000, 500, 2600)); mCamera->lookAt(Ogre::Vector3(2000, 25, 1660)); mCamera->setNearClipDistance(.1); mCameraMan = new OgreBites::SdkCameraMan(mCamera); } void TutorialApplication::createViewports() { Ogre::Viewport* vp = mWindow->addViewport(mCamera); vp->setBackgroundColour(Ogre::ColourValue(0, 0, 0)); mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth())/Ogre::Real(vp->getActualHeight())); } void TutorialApplication::createScene() { mCamera->setPosition(Ogre::Vector3(1683, 50, 2116)); mCamera->lookAt(Ogre::Vector3(1963, 50, 1660)); mCamera->setNearClipDistance(.1); bool infiniteClip = mRoot->getRenderSystem()->getCapabilities()->hasCapability( Ogre::RSC_INFINITE_FAR_PLANE); if (infiniteClip) mCamera->setFarClipDistance(0); else mCamera->setFarClipDistance(50000); mSceneMgr->setAmbientLight(Ogre::ColourValue(.2, .2, .2)); Ogre::Vector3 lightDir(.55, -.3, .75); lightDir.normalise(); Ogre::Light* light = mSceneMgr->createLight("TestLight"); light->setType(Ogre::Light::LT_DIRECTIONAL); light->setDirection(lightDir); light->setDiffuseColour(Ogre::ColourValue::White); light->setSpecularColour(Ogre::ColourValue(.4, .4, .4)); //ninja stuff Ogre::Entity* ninjaEntity = mSceneMgr->createEntity("ninja.mesh"); Ogre::SceneNode* ninjaNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("ninjaNode", Ogre::Vector3(2000, 10, 1925)); ninjaEntity->setCastShadows(true); ninjaNode->attachObject(ninjaEntity); Ogre::Light* spotLight = mSceneMgr->createLight("SpotLight"); spotLight->setDiffuseColour(0, 0, 1.0); spotLight->setSpecularColour(0, 0, 1.0); spotLight->setType(Ogre::Light::LT_SPOTLIGHT); spotLight->setDirection(-1, -1, 0); spotLight->setPosition(Ogre::Vector3(2000, 20, 1925)); // Terrain mTerrainGlobals = OGRE_NEW Ogre::TerrainGlobalOptions(); mTerrainGroup = OGRE_NEW Ogre::TerrainGroup( mSceneMgr, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0); mTerrainGroup->setFilenameConvention(Ogre::String("terrain"), Ogre::String("dat")); mTerrainGroup->setOrigin(Ogre::Vector3::ZERO); configureTerrainDefaults(light); for (long x = 0; x <= 0; ++x) for (long y = 0; y <= 0; ++y) defineTerrain(x, y); mTerrainGroup->loadAllTerrains(true); if (mTerrainsImported) { Ogre::TerrainGroup::TerrainIterator ti = mTerrainGroup->getTerrainIterator(); while (ti.hasMoreElements()) { Ogre::Terrain* t = ti.getNext()->instance; initBlendMaps(t); } } mTerrainGroup->freeTemporaryResources(); //sky mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); Ogre::Plane plane; plane.d = 1000; plane.normal = Ogre::Vector3::NEGATIVE_UNIT_Y; } void TutorialApplication::createFrameListener() { BaseApplication::createFrameListener(); mInfoLabel = mTrayMgr->createLabel(OgreBites::TL_TOP, "TerrainInfo", "", 350); } void TutorialApplication::destroyScene() { OGRE_DELETE mTerrainGroup; OGRE_DELETE mTerrainGlobals; } bool TutorialApplication::frameRenderingQueued(const Ogre::FrameEvent& fe) { bool ret = BaseApplication::frameRenderingQueued(fe); if (mTerrainGroup->isDerivedDataUpdateInProgress()) { mTrayMgr->moveWidgetToTray(mInfoLabel, OgreBites::TL_TOP, 0); mInfoLabel->show(); if (mTerrainsImported) mInfoLabel->setCaption("Building terrain..."); else mInfoLabel->setCaption("Updating textures..."); } else { mTrayMgr->removeWidgetFromTray(mInfoLabel); mInfoLabel->hide(); if (mTerrainsImported) { mTerrainGroup->saveAllTerrains(true); mTerrainsImported = false; } } return ret; } void getTerrainImage(bool flipX, bool flipY, Ogre::Image& img) { img.load("terrain.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (flipX) img.flipAroundY(); if (flipY) img.flipAroundX(); } void TutorialApplication::defineTerrain(long x, long y) { Ogre::String filename = mTerrainGroup->generateFilename(x, y); bool exists = Ogre::ResourceGroupManager::getSingleton().resourceExists( mTerrainGroup->getResourceGroup(), filename); if (exists) mTerrainGroup->defineTerrain(x, y); else { Ogre::Image img; getTerrainImage(x % 2 != 0, y % 2 != 0, img); mTerrainGroup->defineTerrain(x, y, &img); mTerrainsImported = true; } } void TutorialApplication::initBlendMaps(Ogre::Terrain* terrain) { Ogre::Real minHeight0 = 70; Ogre::Real fadeDist0 = 40; Ogre::Real minHeight1 = 70; Ogre::Real fadeDist1 = 15; Ogre::TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1); Ogre::TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2); float* pBlend0 = blendMap0->getBlendPointer(); float* pBlend1 = blendMap1->getBlendPointer(); for (Ogre::uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y) { for (Ogre::uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x) { Ogre::Real tx, ty; blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty); Ogre::Real height = terrain->getHeightAtTerrainPosition(tx, ty); Ogre::Real val = (height - minHeight0) / fadeDist0; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); *pBlend0++ = val; val = (height - minHeight1) / fadeDist1; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); *pBlend1++ = val; } } blendMap0->dirty(); blendMap1->dirty(); blendMap0->update(); blendMap1->update(); } void TutorialApplication::configureTerrainDefaults(Ogre::Light* light) { mTerrainGlobals->setMaxPixelError(8); mTerrainGlobals->setCompositeMapDistance(3000); mTerrainGlobals->setLightMapDirection(light->getDerivedDirection()); mTerrainGlobals->setCompositeMapAmbient(mSceneMgr->getAmbientLight()); mTerrainGlobals->setCompositeMapDiffuse(light->getDiffuseColour()); Ogre::Terrain::ImportData& importData = mTerrainGroup->getDefaultImportSettings(); importData.terrainSize = 513; importData.worldSize = 12000.0; importData.inputScale = 600; importData.minBatchSize = 33; importData.maxBatchSize = 65; importData.layerList.resize(3); importData.layerList[0].worldSize = 100; importData.layerList[0].textureNames.push_back( "dirt_grayrocky_diffusespecular.dds"); importData.layerList[0].textureNames.push_back( "dirt_grayrocky_normalheight.dds"); importData.layerList[1].worldSize = 30; importData.layerList[1].textureNames.push_back( "grass_green-01_diffusespecular.dds"); importData.layerList[1].textureNames.push_back( "grass_green-01_normalheight.dds"); importData.layerList[2].worldSize = 200; importData.layerList[2].textureNames.push_back( "growth_weirdfungus-03_diffusespecular.dds"); importData.layerList[2].textureNames.push_back( "growth_weirdfungus-03_normalheight.dds"); } #if Ogre_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" #endif #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) #else int main(int argc, char *argv[]) #endif { // Create application object TutorialApplication app; try { app.go(); } catch( Ogre::Exception& e ) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl; #endif } return 0; } #ifdef __cplusplus } #endif<|endoftext|>