text
stringlengths
54
60.6k
<commit_before><commit_msg>Wrap GL loading logs in branches<commit_after><|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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 JPetCmdParser.cpp */ #include "JPetCmdParser.h" #include <iostream> #include "../JPetCommonTools/JPetCommonTools.h" #include "../JPetLoggerInclude.h" #include "../JPetScopeConfigParser/JPetScopeConfigParser.h" #include <stdexcept> JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options") { fOptionsDescriptions.add_options() ("help,h", "Displays this help message.") ("type,t", po::value<std::string>()->required()->implicit_value(""), "Type of file: hld, gz, root or scope.") ("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open.") ("outputPath,o", po::value<std::string>(), "Location to which the outputFiles will be saved.") ("range,r", po::value< std::vector<int> >()->multitoken()->default_value({ -1, -1}, ""), "Range of events to process e.g. -r 1 1000 .") ("param,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.") ("runId,i", po::value<int>(), "Run id.") ("progressBar,b", "Progress bar.") ("localDB,l", po::value<std::string>(), "The file to use as the parameter database.") ("localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved."); } JPetCmdParser::~JPetCmdParser() { /**/ } std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv) { po::variables_map variablesMap; if (argc == 1) { ERROR("No options provided."); std::cerr << getOptionsDescription() << "\n"; throw std::invalid_argument("No options provided."); } po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap); /* print out help */ if (variablesMap.count("help")) { std::cout << getOptionsDescription() << "\n"; exit(0); } po::notify(variablesMap); if (!areCorrectOptions(variablesMap)) { throw std::invalid_argument("Wrong user options provided! Check the log!"); } return generateOptions(variablesMap); } bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const { /* Parse range of events */ if (variablesMap.count("range")) { if (variablesMap["range"].as< std::vector<int> >().size() != 2) { ERROR("Wrong number of bounds in range."); std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl; return false; } if ( variablesMap["range"].as< std::vector<int> >()[0] > variablesMap["range"].as< std::vector<int> >()[1]) { ERROR("Wrong range of events."); std::cerr << "Wrong range of events." << std::endl; return false; } } if (!isCorrectFileType(getFileType(variablesMap))) { ERROR("Wrong type of file."); std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl; std::cerr << "Possible options: hld, zip, root or scope" << std::endl; return false; } if (isRunNumberSet(variablesMap)) { int l_runId = variablesMap["runId"].as<int>(); if (l_runId <= 0) { ERROR("Run id must be a number larger than 0."); std::cerr << "Run id must be a number larger than 0." << l_runId << std::endl; return false; } } if (isProgressBarSet(variablesMap)) { int l_progressBar = variablesMap["progressBar"].as<int>(); if (l_progressBar != 0 && l_progressBar != 1) { ERROR("Wrong parameter of progressbar."); std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl; return false; } } if (isLocalDBSet(variablesMap)) { std::string localDBName = getLocalDBName(variablesMap); if ( !JPetCommonTools::ifFileExisting(localDBName) ) { ERROR("File : " + localDBName + " does not exist."); std::cerr << "File : " << localDBName << " does not exist" << std::endl; return false; } } std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >()); for (unsigned int i = 0; i < fileNames.size(); i++) { if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) { std::string fileName = fileNames[i]; ERROR("File : " + fileName + " does not exist."); std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl; return false; } } /// The run number option is neclegted if the input file is set as "scope" if (isRunNumberSet(variablesMap)) { if (getFileType(variablesMap) == "scope") { WARNING("Run number was specified but the input file type is a scope!\n The run number will be ignored!"); } } /// Check if output path exists if (isOutputPath(variablesMap)) { auto dir = getOutputPath(variablesMap); if (!JPetCommonTools::isDirectory(dir)) { ERROR("Output directory : " + dir + " does not exist."); std::cerr << "Output directory: " << dir << " does not exist" << std::endl; return false; } } return true; } std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const { std::map<std::string, std::string> options = JPetOptions::getDefaultOptions(); auto fileType = getFileType(optsMap); if (isCorrectFileType(fileType)) { options.at("inputFileType") = fileType; } if (isOutputPath(optsMap)) { options.at("outputPath") = JPetCommonTools::appendSlashToPathIfAbsent(getOutputPath(optsMap)); } if (isRunNumberSet(optsMap)) { options.at("runId") = std::to_string(getRunNumber(optsMap)); } if (isProgressBarSet(optsMap)) { options.at("progressBar") = "true"; } if (isLocalDBSet(optsMap)) { options["localDB"] = getLocalDBName(optsMap); } if (isLocalDBCreateSet(optsMap)) { options["localDBCreate"] = getLocalDBCreateName(optsMap); } auto firstEvent = getLowerEventBound(optsMap); auto lastEvent = getHigherEventBound(optsMap); if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent); if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent); auto files = getFileNames(optsMap); std::vector<JPetOptions> optionContainer; /// In case of scope there is one special input file /// which is a json config file which must be parsed. /// Based on its content the set of input directories are generated. /// The input directories contain data files. /// The config input file name also should be stored in a special option field. if (fileType == "scope") { assert(files.size() == 1); /// there should be only file which is config. auto configFileName = files.front(); options.at("scopeConfigFile") = configFileName; JPetScopeConfigParser scopeConfigParser; /// The scope module must use a fake input file name which will be used to /// produce the correct output file names by the following modules. /// At the same time, the input directory with true input files must be /// also added. The container of pairs <directory, fileName> is generated /// based on the content of the configuration file. JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName); for (auto dirAndFile : dirsAndFiles) { options.at("scopeInputDirectory") = dirAndFile.first; options.at("inputFile") = dirAndFile.second; optionContainer.push_back(JPetOptions(options)); } } else { /// for every single input file we create separate JPetOptions for (auto file : files) { options.at("inputFile") = file; optionContainer.push_back(JPetOptions(options)); } } return optionContainer; } //#endif /* __CINT__ */ <commit_msg>Fixed small typo in description of files which can be analysed with framework<commit_after>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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 JPetCmdParser.cpp */ #include "JPetCmdParser.h" #include <iostream> #include "../JPetCommonTools/JPetCommonTools.h" #include "../JPetLoggerInclude.h" #include "../JPetScopeConfigParser/JPetScopeConfigParser.h" #include <stdexcept> JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options") { fOptionsDescriptions.add_options() ("help,h", "Displays this help message.") ("type,t", po::value<std::string>()->required()->implicit_value(""), "Type of file: hld, zip, root or scope.") ("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open.") ("outputPath,o", po::value<std::string>(), "Location to which the outputFiles will be saved.") ("range,r", po::value< std::vector<int> >()->multitoken()->default_value({ -1, -1}, ""), "Range of events to process e.g. -r 1 1000 .") ("param,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.") ("runId,i", po::value<int>(), "Run id.") ("progressBar,b", "Progress bar.") ("localDB,l", po::value<std::string>(), "The file to use as the parameter database.") ("localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved."); } JPetCmdParser::~JPetCmdParser() { /**/ } std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv) { po::variables_map variablesMap; if (argc == 1) { ERROR("No options provided."); std::cerr << getOptionsDescription() << "\n"; throw std::invalid_argument("No options provided."); } po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap); /* print out help */ if (variablesMap.count("help")) { std::cout << getOptionsDescription() << "\n"; exit(0); } po::notify(variablesMap); if (!areCorrectOptions(variablesMap)) { throw std::invalid_argument("Wrong user options provided! Check the log!"); } return generateOptions(variablesMap); } bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const { /* Parse range of events */ if (variablesMap.count("range")) { if (variablesMap["range"].as< std::vector<int> >().size() != 2) { ERROR("Wrong number of bounds in range."); std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl; return false; } if ( variablesMap["range"].as< std::vector<int> >()[0] > variablesMap["range"].as< std::vector<int> >()[1]) { ERROR("Wrong range of events."); std::cerr << "Wrong range of events." << std::endl; return false; } } if (!isCorrectFileType(getFileType(variablesMap))) { ERROR("Wrong type of file."); std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl; std::cerr << "Possible options: hld, zip, root or scope" << std::endl; return false; } if (isRunNumberSet(variablesMap)) { int l_runId = variablesMap["runId"].as<int>(); if (l_runId <= 0) { ERROR("Run id must be a number larger than 0."); std::cerr << "Run id must be a number larger than 0." << l_runId << std::endl; return false; } } if (isProgressBarSet(variablesMap)) { int l_progressBar = variablesMap["progressBar"].as<int>(); if (l_progressBar != 0 && l_progressBar != 1) { ERROR("Wrong parameter of progressbar."); std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl; return false; } } if (isLocalDBSet(variablesMap)) { std::string localDBName = getLocalDBName(variablesMap); if ( !JPetCommonTools::ifFileExisting(localDBName) ) { ERROR("File : " + localDBName + " does not exist."); std::cerr << "File : " << localDBName << " does not exist" << std::endl; return false; } } std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >()); for (unsigned int i = 0; i < fileNames.size(); i++) { if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) { std::string fileName = fileNames[i]; ERROR("File : " + fileName + " does not exist."); std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl; return false; } } /// The run number option is neclegted if the input file is set as "scope" if (isRunNumberSet(variablesMap)) { if (getFileType(variablesMap) == "scope") { WARNING("Run number was specified but the input file type is a scope!\n The run number will be ignored!"); } } /// Check if output path exists if (isOutputPath(variablesMap)) { auto dir = getOutputPath(variablesMap); if (!JPetCommonTools::isDirectory(dir)) { ERROR("Output directory : " + dir + " does not exist."); std::cerr << "Output directory: " << dir << " does not exist" << std::endl; return false; } } return true; } std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const { std::map<std::string, std::string> options = JPetOptions::getDefaultOptions(); auto fileType = getFileType(optsMap); if (isCorrectFileType(fileType)) { options.at("inputFileType") = fileType; } if (isOutputPath(optsMap)) { options.at("outputPath") = JPetCommonTools::appendSlashToPathIfAbsent(getOutputPath(optsMap)); } if (isRunNumberSet(optsMap)) { options.at("runId") = std::to_string(getRunNumber(optsMap)); } if (isProgressBarSet(optsMap)) { options.at("progressBar") = "true"; } if (isLocalDBSet(optsMap)) { options["localDB"] = getLocalDBName(optsMap); } if (isLocalDBCreateSet(optsMap)) { options["localDBCreate"] = getLocalDBCreateName(optsMap); } auto firstEvent = getLowerEventBound(optsMap); auto lastEvent = getHigherEventBound(optsMap); if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent); if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent); auto files = getFileNames(optsMap); std::vector<JPetOptions> optionContainer; /// In case of scope there is one special input file /// which is a json config file which must be parsed. /// Based on its content the set of input directories are generated. /// The input directories contain data files. /// The config input file name also should be stored in a special option field. if (fileType == "scope") { assert(files.size() == 1); /// there should be only file which is config. auto configFileName = files.front(); options.at("scopeConfigFile") = configFileName; JPetScopeConfigParser scopeConfigParser; /// The scope module must use a fake input file name which will be used to /// produce the correct output file names by the following modules. /// At the same time, the input directory with true input files must be /// also added. The container of pairs <directory, fileName> is generated /// based on the content of the configuration file. JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName); for (auto dirAndFile : dirsAndFiles) { options.at("scopeInputDirectory") = dirAndFile.first; options.at("inputFile") = dirAndFile.second; optionContainer.push_back(JPetOptions(options)); } } else { /// for every single input file we create separate JPetOptions for (auto file : files) { options.at("inputFile") = file; optionContainer.push_back(JPetOptions(options)); } } return optionContainer; } //#endif /* __CINT__ */ <|endoftext|>
<commit_before>#include "limit_quote.h" <commit_msg>Update limit_quote.cpp<commit_after>#include <cstddef> #include "Limit_quote.h" double Limit_quote::net_price(size_t n) const { if(n<=max_qty) return n*price*(1-discount); else return max_qty*price*(1-discount)+(n-max_qty)*price; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "../common/tutorial/tutorial_device.h" #if 0 const int numSpheres = 1000; const int numPhi = 5; #else const int numSpheres = 20; const int numPhi = 120; //const int numPhi = 400; #endif const int numTheta = 2*numPhi; /* scene data */ RTCDevice g_device = nullptr; RTCScene g_scene = nullptr; Vec3fa position[numSpheres]; Vec3fa colors[numSpheres+1]; float radius[numSpheres]; int disabledID = -1; /* render function to use */ renderPixelFunc renderPixel; /* error reporting function */ void error_handler(const RTCError code, const char* str) { printf("Embree: "); switch (code) { case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break; case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break; case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break; case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break; case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break; case RTC_CANCELLED : printf("RTC_CANCELLED"); break; default : printf("invalid error code"); break; } if (str) { printf(" ("); while (*str) putchar(*str++); printf(")\n"); } exit(1); } /* adds a sphere to the scene */ unsigned int createSphere (RTCGeometryFlags flags, const Vec3fa& pos, const float r) { /* create a triangulated sphere */ unsigned int mesh = rtcNewTriangleMesh (g_scene, flags, 2*numTheta*(numPhi-1), numTheta*(numPhi+1)); /* map triangle and vertex buffer */ Vertex* vertices = (Vertex* ) rtcMapBuffer(g_scene,mesh,RTC_VERTEX_BUFFER); Triangle* triangles = (Triangle*) rtcMapBuffer(g_scene,mesh,RTC_INDEX_BUFFER); /* create sphere geometry */ int tri = 0; const float rcpNumTheta = rcp((float)numTheta); const float rcpNumPhi = rcp((float)numPhi); for (int phi=0; phi<=numPhi; phi++) { for (int theta=0; theta<numTheta; theta++) { const float phif = phi*float(pi)*rcpNumPhi; const float thetaf = theta*2.0f*float(pi)*rcpNumTheta; Vertex& v = vertices[phi*numTheta+theta]; v.x = pos.x + r*sin(phif)*sin(thetaf); v.y = pos.y + r*cos(phif); v.z = pos.z + r*sin(phif)*cos(thetaf); } if (phi == 0) continue; for (int theta=1; theta<=numTheta; theta++) { int p00 = (phi-1)*numTheta+theta-1; int p01 = (phi-1)*numTheta+theta%numTheta; int p10 = phi*numTheta+theta-1; int p11 = phi*numTheta+theta%numTheta; if (phi > 1) { triangles[tri].v0 = p10; triangles[tri].v1 = p00; triangles[tri].v2 = p01; tri++; } if (phi < numPhi) { triangles[tri].v0 = p11; triangles[tri].v1 = p10; triangles[tri].v2 = p01; tri++; } } } rtcUnmapBuffer(g_scene,mesh,RTC_VERTEX_BUFFER); rtcUnmapBuffer(g_scene,mesh,RTC_INDEX_BUFFER); return mesh; } /* adds a ground plane to the scene */ unsigned int addGroundPlane (RTCScene scene_i) { /* create a triangulated plane with 2 triangles and 4 vertices */ unsigned int mesh = rtcNewTriangleMesh (scene_i, RTC_GEOMETRY_STATIC, 2, 4); /* set vertices */ Vertex* vertices = (Vertex*) rtcMapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); vertices[0].x = -10; vertices[0].y = -2; vertices[0].z = -10; vertices[1].x = -10; vertices[1].y = -2; vertices[1].z = +10; vertices[2].x = +10; vertices[2].y = -2; vertices[2].z = -10; vertices[3].x = +10; vertices[3].y = -2; vertices[3].z = +10; rtcUnmapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); /* set triangles */ Triangle* triangles = (Triangle*) rtcMapBuffer(scene_i,mesh,RTC_INDEX_BUFFER); triangles[0].v0 = 0; triangles[0].v1 = 2; triangles[0].v2 = 1; triangles[1].v0 = 1; triangles[1].v1 = 2; triangles[1].v2 = 3; rtcUnmapBuffer(scene_i,mesh,RTC_INDEX_BUFFER); return mesh; } /* called by the C++ code for initialization */ extern "C" void device_init (char* cfg) { /* create new Embree device */ g_device = rtcNewDevice(cfg); /* set error handler */ rtcDeviceSetErrorFunction(g_device,error_handler); /* create scene */ g_scene = rtcDeviceNewScene(g_device,RTC_SCENE_DYNAMIC /* | RTC_SCENE_ROBUST */, RTC_INTERSECT1); /* create some triangulated spheres */ for (int i=0; i<numSpheres; i++) { const float phi = i*2.0f*float(pi)/numSpheres; const float r = 2.0f*float(pi)/numSpheres; const Vec3fa p = 2.0f*Vec3fa(sin(phi),0.0f,-cos(phi)); //RTCGeometryFlags flags = i%3 == 0 ? RTC_GEOMETRY_STATIC : i%3 == 1 ? RTC_GEOMETRY_DEFORMABLE : RTC_GEOMETRY_DYNAMIC; RTCGeometryFlags flags = i%2 ? RTC_GEOMETRY_DEFORMABLE : RTC_GEOMETRY_DYNAMIC; //RTCGeometryFlags flags = RTC_GEOMETRY_DEFORMABLE; int id = createSphere(flags,p,r); position[id] = p; radius[id] = r; colors[id].x = (i%16+1)/17.0f; colors[id].y = (i%8+1)/9.0f; colors[id].z = (i%4+1)/5.0f; } /* add ground plane to scene */ int id = addGroundPlane(g_scene); colors[id] = Vec3fa(1.0f,1.0f,1.0f); /* commit changes to scene */ rtcCommit (g_scene); /* set start render mode */ renderPixel = renderPixelStandard; key_pressed_handler = device_key_pressed_default; } /* animates the sphere */ void animateSphere (int taskIndex, Vertex* vertices, const float rcpNumTheta, const float rcpNumPhi, const Vec3fa& pos, const float r, const float f) { int phi = taskIndex; for (int theta = 0; theta<numTheta; theta++) { Vertex* v = &vertices[phi*numTheta+theta]; const float phif = phi*float(pi)*rcpNumPhi; const float thetaf = theta*2.0f*float(pi)*rcpNumTheta; v->x = pos.x + r*sin(f*phif)*sin(thetaf); v->y = pos.y + r*cos(phif); v->z = pos.z + r*sin(f*phif)*cos(thetaf); } } /* task that renders a single screen tile */ Vec3fa renderPixelStandard(float x, float y, const Vec3fa& vx, const Vec3fa& vy, const Vec3fa& vz, const Vec3fa& p) { /* initialize ray */ RTCRay ray; ray.org = p; ray.dir = normalize(x*vx + y*vy + vz); ray.tnear = 0.0f; ray.tfar = inf; ray.geomID = RTC_INVALID_GEOMETRY_ID; ray.primID = RTC_INVALID_GEOMETRY_ID; ray.mask = -1; ray.time = 0; /* intersect ray with scene */ rtcIntersect(g_scene,ray); /* shade pixels */ Vec3fa color = Vec3fa(0.0f); if (ray.geomID != RTC_INVALID_GEOMETRY_ID) { Vec3fa diffuse = colors[ray.geomID]; color = color + diffuse*0.1f; // FIXME: += Vec3fa lightDir = normalize(Vec3fa(-1,-1,-1)); /* initialize shadow ray */ RTCRay shadow; shadow.org = ray.org + ray.tfar*ray.dir; shadow.dir = neg(lightDir); shadow.tnear = 0.001f; shadow.tfar = inf; shadow.geomID = 1; shadow.primID = 0; shadow.mask = -1; shadow.time = 0; /* trace shadow ray */ rtcOccluded(g_scene,shadow); /* add light contribution */ if (shadow.geomID) color = color + diffuse*clamp(-dot(lightDir,normalize(ray.Ng)),0.0f,1.0f); // FIXME: += } return color; } /* task that renders a single screen tile */ void renderTile(int taskIndex, int* pixels, const int width, const int height, const float time, const Vec3fa& vx, const Vec3fa& vy, const Vec3fa& vz, const Vec3fa& p, const int numTilesX, const int numTilesY) { const int tileY = taskIndex / numTilesX; const int tileX = taskIndex - tileY * numTilesX; const int x0 = tileX * TILE_SIZE_X; const int x1 = min(x0+TILE_SIZE_X,width); const int y0 = tileY * TILE_SIZE_Y; const int y1 = min(y0+TILE_SIZE_Y,height); for (int y = y0; y<y1; y++) for (int x = x0; x<x1; x++) { /* calculate pixel color */ Vec3fa color = renderPixel(x,y,vx,vy,vz,p); /* write color to framebuffer */ unsigned int r = (unsigned int) (255.0f * clamp(color.x,0.0f,1.0f)); unsigned int g = (unsigned int) (255.0f * clamp(color.y,0.0f,1.0f)); unsigned int b = (unsigned int) (255.0f * clamp(color.z,0.0f,1.0f)); pixels[y*width+x] = (b << 16) + (g << 8) + r; } } /* animates a sphere */ void animateSphere (int id, float time) { /* animate vertices */ Vertex* vertices = (Vertex*) rtcMapBuffer(g_scene,id,RTC_VERTEX_BUFFER); const float rcpNumTheta = rcp((float)numTheta); const float rcpNumPhi = rcp((float)numPhi); const Vec3fa pos = position[id]; const float r = radius[id]; const float f = 2.0f*(1.0f+0.5f*sin(time)); /* loop over all vertices */ #if 1 // enables parallel execution launch_animateSphere(animateSphere,numPhi+1,vertices,rcpNumTheta,rcpNumPhi,pos,r,f); #else for (int phi = 0; phi <numPhi+1; phi++) for (int theta = 0; theta<numTheta; theta++) { Vertex* v = &vertices[phi*numTheta+theta]; const float phif = phi*float(pi)*rcpNumPhi; const float thetaf = theta*2.0f*float(pi)*rcpNumTheta; v->x = pos.x+r*sin(f*phif)*sin(thetaf); v->y = pos.y+r*cos(phif); v->z = pos.z+r*sin(f*phif)*cos(thetaf); } #endif rtcUnmapBuffer(g_scene,id,RTC_VERTEX_BUFFER); /* update mesh */ rtcUpdate (g_scene,id); } /* called by the C++ code to render */ extern "C" void device_render (int* pixels, const int width, const int height, const float time, const Vec3fa& vx, const Vec3fa& vy, const Vec3fa& vz, const Vec3fa& p) { /* animate sphere */ for (int i=0; i<numSpheres; i++) animateSphere(i,time+i); /* commit changes to scene */ rtcCommit (g_scene); /* render all pixels */ const int numTilesX = (width +TILE_SIZE_X-1)/TILE_SIZE_X; const int numTilesY = (height+TILE_SIZE_Y-1)/TILE_SIZE_Y; launch_renderTile(numTilesX*numTilesY,pixels,width,height,time,vx,vy,vz,p,numTilesX,numTilesY); } /* called by the C++ code for cleanup */ extern "C" void device_cleanup () { rtcDeleteScene (g_scene); rtcDeleteDevice(g_device); } <commit_msg>updates<commit_after>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "../common/tutorial/tutorial_device.h" #if 0 const int numSpheres = 1000; const int numPhi = 5; #else const int numSpheres = 20; const int numPhi = 120; //const int numPhi = 400; #endif const int numTheta = 2*numPhi; /* scene data */ RTCDevice g_device = nullptr; RTCScene g_scene = nullptr; Vec3fa position[numSpheres]; Vec3fa colors[numSpheres+1]; float radius[numSpheres]; int disabledID = -1; /* render function to use */ renderPixelFunc renderPixel; /* error reporting function */ void error_handler(const RTCError code, const char* str) { printf("Embree: "); switch (code) { case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break; case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break; case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break; case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break; case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break; case RTC_CANCELLED : printf("RTC_CANCELLED"); break; default : printf("invalid error code"); break; } if (str) { printf(" ("); while (*str) putchar(*str++); printf(")\n"); } exit(1); } /* adds a sphere to the scene */ unsigned int createSphere (RTCGeometryFlags flags, const Vec3fa& pos, const float r) { /* create a triangulated sphere */ unsigned int mesh = rtcNewTriangleMesh (g_scene, flags, 2*numTheta*(numPhi-1), numTheta*(numPhi+1)); /* map triangle and vertex buffer */ Vertex* vertices = (Vertex* ) rtcMapBuffer(g_scene,mesh,RTC_VERTEX_BUFFER); Triangle* triangles = (Triangle*) rtcMapBuffer(g_scene,mesh,RTC_INDEX_BUFFER); /* create sphere geometry */ int tri = 0; const float rcpNumTheta = rcp((float)numTheta); const float rcpNumPhi = rcp((float)numPhi); for (int phi=0; phi<=numPhi; phi++) { for (int theta=0; theta<numTheta; theta++) { const float phif = phi*float(pi)*rcpNumPhi; const float thetaf = theta*2.0f*float(pi)*rcpNumTheta; Vertex& v = vertices[phi*numTheta+theta]; v.x = pos.x + r*sin(phif)*sin(thetaf); v.y = pos.y + r*cos(phif); v.z = pos.z + r*sin(phif)*cos(thetaf); } if (phi == 0) continue; for (int theta=1; theta<=numTheta; theta++) { int p00 = (phi-1)*numTheta+theta-1; int p01 = (phi-1)*numTheta+theta%numTheta; int p10 = phi*numTheta+theta-1; int p11 = phi*numTheta+theta%numTheta; if (phi > 1) { triangles[tri].v0 = p10; triangles[tri].v1 = p00; triangles[tri].v2 = p01; tri++; } if (phi < numPhi) { triangles[tri].v0 = p11; triangles[tri].v1 = p10; triangles[tri].v2 = p01; tri++; } } } rtcUnmapBuffer(g_scene,mesh,RTC_VERTEX_BUFFER); rtcUnmapBuffer(g_scene,mesh,RTC_INDEX_BUFFER); return mesh; } /* adds a ground plane to the scene */ unsigned int addGroundPlane (RTCScene scene_i) { /* create a triangulated plane with 2 triangles and 4 vertices */ unsigned int mesh = rtcNewTriangleMesh (scene_i, RTC_GEOMETRY_STATIC, 2, 4); /* set vertices */ Vertex* vertices = (Vertex*) rtcMapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); vertices[0].x = -10; vertices[0].y = -2; vertices[0].z = -10; vertices[1].x = -10; vertices[1].y = -2; vertices[1].z = +10; vertices[2].x = +10; vertices[2].y = -2; vertices[2].z = -10; vertices[3].x = +10; vertices[3].y = -2; vertices[3].z = +10; rtcUnmapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); /* set triangles */ Triangle* triangles = (Triangle*) rtcMapBuffer(scene_i,mesh,RTC_INDEX_BUFFER); triangles[0].v0 = 0; triangles[0].v1 = 2; triangles[0].v2 = 1; triangles[1].v0 = 1; triangles[1].v1 = 2; triangles[1].v2 = 3; rtcUnmapBuffer(scene_i,mesh,RTC_INDEX_BUFFER); return mesh; } /* called by the C++ code for initialization */ extern "C" void device_init (char* cfg) { /* create new Embree device */ g_device = rtcNewDevice(cfg); /* set error handler */ rtcDeviceSetErrorFunction(g_device,error_handler); /* create scene */ g_scene = rtcDeviceNewScene(g_device,RTC_SCENE_DYNAMIC | RTC_SCENE_ROBUST , RTC_INTERSECT1); /* create some triangulated spheres */ for (int i=0; i<numSpheres; i++) { const float phi = i*2.0f*float(pi)/numSpheres; const float r = 2.0f*float(pi)/numSpheres; const Vec3fa p = 2.0f*Vec3fa(sin(phi),0.0f,-cos(phi)); //RTCGeometryFlags flags = i%3 == 0 ? RTC_GEOMETRY_STATIC : i%3 == 1 ? RTC_GEOMETRY_DEFORMABLE : RTC_GEOMETRY_DYNAMIC; RTCGeometryFlags flags = i%2 ? RTC_GEOMETRY_DEFORMABLE : RTC_GEOMETRY_DYNAMIC; //RTCGeometryFlags flags = RTC_GEOMETRY_DEFORMABLE; int id = createSphere(flags,p,r); position[id] = p; radius[id] = r; colors[id].x = (i%16+1)/17.0f; colors[id].y = (i%8+1)/9.0f; colors[id].z = (i%4+1)/5.0f; } /* add ground plane to scene */ int id = addGroundPlane(g_scene); colors[id] = Vec3fa(1.0f,1.0f,1.0f); /* commit changes to scene */ rtcCommit (g_scene); /* set start render mode */ renderPixel = renderPixelStandard; key_pressed_handler = device_key_pressed_default; } /* animates the sphere */ void animateSphere (int taskIndex, Vertex* vertices, const float rcpNumTheta, const float rcpNumPhi, const Vec3fa& pos, const float r, const float f) { int phi = taskIndex; for (int theta = 0; theta<numTheta; theta++) { Vertex* v = &vertices[phi*numTheta+theta]; const float phif = phi*float(pi)*rcpNumPhi; const float thetaf = theta*2.0f*float(pi)*rcpNumTheta; v->x = pos.x + r*sin(f*phif)*sin(thetaf); v->y = pos.y + r*cos(phif); v->z = pos.z + r*sin(f*phif)*cos(thetaf); } } /* task that renders a single screen tile */ Vec3fa renderPixelStandard(float x, float y, const Vec3fa& vx, const Vec3fa& vy, const Vec3fa& vz, const Vec3fa& p) { /* initialize ray */ RTCRay ray; ray.org = p; ray.dir = normalize(x*vx + y*vy + vz); ray.tnear = 0.0f; ray.tfar = inf; ray.geomID = RTC_INVALID_GEOMETRY_ID; ray.primID = RTC_INVALID_GEOMETRY_ID; ray.mask = -1; ray.time = 0; /* intersect ray with scene */ rtcIntersect(g_scene,ray); /* shade pixels */ Vec3fa color = Vec3fa(0.0f); if (ray.geomID != RTC_INVALID_GEOMETRY_ID) { Vec3fa diffuse = colors[ray.geomID]; color = color + diffuse*0.1f; // FIXME: += Vec3fa lightDir = normalize(Vec3fa(-1,-1,-1)); /* initialize shadow ray */ RTCRay shadow; shadow.org = ray.org + ray.tfar*ray.dir; shadow.dir = neg(lightDir); shadow.tnear = 0.001f; shadow.tfar = inf; shadow.geomID = 1; shadow.primID = 0; shadow.mask = -1; shadow.time = 0; /* trace shadow ray */ rtcOccluded(g_scene,shadow); /* add light contribution */ if (shadow.geomID) color = color + diffuse*clamp(-dot(lightDir,normalize(ray.Ng)),0.0f,1.0f); // FIXME: += } return color; } /* task that renders a single screen tile */ void renderTile(int taskIndex, int* pixels, const int width, const int height, const float time, const Vec3fa& vx, const Vec3fa& vy, const Vec3fa& vz, const Vec3fa& p, const int numTilesX, const int numTilesY) { const int tileY = taskIndex / numTilesX; const int tileX = taskIndex - tileY * numTilesX; const int x0 = tileX * TILE_SIZE_X; const int x1 = min(x0+TILE_SIZE_X,width); const int y0 = tileY * TILE_SIZE_Y; const int y1 = min(y0+TILE_SIZE_Y,height); for (int y = y0; y<y1; y++) for (int x = x0; x<x1; x++) { /* calculate pixel color */ Vec3fa color = renderPixel(x,y,vx,vy,vz,p); /* write color to framebuffer */ unsigned int r = (unsigned int) (255.0f * clamp(color.x,0.0f,1.0f)); unsigned int g = (unsigned int) (255.0f * clamp(color.y,0.0f,1.0f)); unsigned int b = (unsigned int) (255.0f * clamp(color.z,0.0f,1.0f)); pixels[y*width+x] = (b << 16) + (g << 8) + r; } } /* animates a sphere */ void animateSphere (int id, float time) { /* animate vertices */ Vertex* vertices = (Vertex*) rtcMapBuffer(g_scene,id,RTC_VERTEX_BUFFER); const float rcpNumTheta = rcp((float)numTheta); const float rcpNumPhi = rcp((float)numPhi); const Vec3fa pos = position[id]; const float r = radius[id]; const float f = 2.0f*(1.0f+0.5f*sin(time)); /* loop over all vertices */ #if 1 // enables parallel execution launch_animateSphere(animateSphere,numPhi+1,vertices,rcpNumTheta,rcpNumPhi,pos,r,f); #else for (int phi = 0; phi <numPhi+1; phi++) for (int theta = 0; theta<numTheta; theta++) { Vertex* v = &vertices[phi*numTheta+theta]; const float phif = phi*float(pi)*rcpNumPhi; const float thetaf = theta*2.0f*float(pi)*rcpNumTheta; v->x = pos.x+r*sin(f*phif)*sin(thetaf); v->y = pos.y+r*cos(phif); v->z = pos.z+r*sin(f*phif)*cos(thetaf); } #endif rtcUnmapBuffer(g_scene,id,RTC_VERTEX_BUFFER); /* update mesh */ rtcUpdate (g_scene,id); } /* called by the C++ code to render */ extern "C" void device_render (int* pixels, const int width, const int height, const float time, const Vec3fa& vx, const Vec3fa& vy, const Vec3fa& vz, const Vec3fa& p) { /* animate sphere */ for (int i=0; i<numSpheres; i++) animateSphere(i,time+i); /* commit changes to scene */ rtcCommit (g_scene); /* render all pixels */ const int numTilesX = (width +TILE_SIZE_X-1)/TILE_SIZE_X; const int numTilesY = (height+TILE_SIZE_Y-1)/TILE_SIZE_Y; launch_renderTile(numTilesX*numTilesY,pixels,width,height,time,vx,vy,vz,p,numTilesX,numTilesY); } /* called by the C++ code for cleanup */ extern "C" void device_cleanup () { rtcDeleteScene (g_scene); rtcDeleteDevice(g_device); } <|endoftext|>
<commit_before>/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame authors. * * 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 "AFCPluginManager.h" #include "SDK/Core/Base/AFPlatform.hpp" #if ARK_PLATFORM == PLATFORM_UNIX #include <unistd.h> #include <netdb.h> #include <arpa/inet.h> #include <signal.h> #include <sys/prctl.h> #endif #if ARK_PLATFORM == PLATFORM_WIN #include <Dbghelp.h> #pragma comment(lib, "DbgHelp") #if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG #pragma comment(lib, "AFCore_d.lib") #else #pragma comment(lib, "AFCore.lib") #endif bool bExitApp = false; std::thread gBackThread; // 创建Dump文件 void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException) { // 创建Dump文件 HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // Dump信息 MINIDUMP_EXCEPTION_INFORMATION dumpInfo; dumpInfo.ExceptionPointers = pException; dumpInfo.ThreadId = GetCurrentThreadId(); dumpInfo.ClientPointers = TRUE; // 写入Dump文件内容 MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); CloseHandle(hDumpFile); } // 处理Unhandled Exception的回调函数 long ApplicationCrashHandler(EXCEPTION_POINTERS* pException) { time_t t = time(0); char szDmupName[MAX_PATH]; tm* ptm = localtime(&t); sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); CreateDumpFile(szDmupName, pException); FatalAppExit(-1, szDmupName); return EXCEPTION_EXECUTE_HANDLER; } #endif void CloseXButton() { #if ARK_PLATFORM == PLATFORM_WIN HWND hWnd = GetConsoleWindow(); if(hWnd) { HMENU hMenu = GetSystemMenu(hWnd, FALSE); EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND); } #endif } void InitDaemon() { #if ARK_PLATFORM == PLATFORM_UNIX daemon(1, 0); // ignore signals signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTERM, SIG_IGN); #endif } void EchoArkLogo() { #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif std::cout << " _ _ ____ _ _ _ " << std::endl; std::cout << " / \\ _ __| | __ / ___|| |_ _ _ __| (_) ___ " << std::endl; std::cout << " / _ \\ | '__| |/ / \\___ \\| __| | | |/ _` | |/ _ \\ " << std::endl; std::cout << " / ___ \\| | | < ___) | |_| |_| | (_| | | (_) |" << std::endl; std::cout << " /_/ \\_\\_| |_|\\_\\ |____/ \\__|\\__,_|\\__,_|_|\\___/ " << std::endl; std::cout << std::endl; std::cout << "COPYRIGHT (c) 2013-2018 Ark Studio" << std::endl; std::cout << "All RIGHTS RESERVED." << std::endl; std::cout << "HTTPS://ARKGAME.NET" << std::endl; std::cout << "********************************************" << std::endl; #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif } void Usage() { std::cout << "Ark PluginLoader usage:" << std::endl; std::cout << "./PluginLoader [options]" << std::endl; std::cout << "Option:" << std::endl; std::cout << "\t" << "-d, Run as daemon, just take effect in Linux" << std::endl; std::cout << "\t" << "-x, Remove close button, just take effect in Windows" << std::endl; std::cout << "\t" << "cfg=plugin.xml, plugin configuration files" << std::endl; std::cout << "\t" << "app_id=1, set application's id" << std::endl; std::cout << "\t" << "app_name=GameServer, set application's name" << std::endl; std::cout << "i.e. ./PluginLoader -d -x cfg=plugin.xml app_id=1 app_name=my_test" << std::endl; } void ThreadFunc() { while(!bExitApp) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::string s; std::cin >> s; std::transform(s.begin(), s.end(), s.begin(), ::tolower); if(s == "exit") { bExitApp = true; } else if(s == "help") { Usage(); } } } void CreateBackThread() { gBackThread = std::thread(std::bind(&ThreadFunc)); //std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl; } struct ApplicationConfig { bool deamon = true; //run as deamon, Linux bool xbutton = true; //close X button in windows std::string plugin_file = "Plugin.xml"; //config file int app_id = 0; //app id std::string app_name = ""; //app name }; #if ARK_PLATFORM == PLATFORM_UNIX extern char** environ; struct environ_guard { public: ~environ_guard() { if(env_buf) { delete[] env_buf; env_buf = nullptr; } if(environ) { delete[] environ; environ = nullptr; } } char* env_buf; char** environ; }; environ_guard g_new_environ_guard{ nullptr, nullptr }; int realloc_environ() { int var_count = 0; int env_size = 0; { char** ep = environ; while(*ep) { env_size += std::strlen(*ep) + 1; ++var_count; ++ep; } } char* new_env_buf = new char[env_size]; std::memcpy((void *)new_env_buf, (void *)*environ, env_size); char** new_env = new char*[var_count + 1]; { int var = 0; int offset = 0; char** ep = environ; while(*ep) { new_env[var++] = (new_env_buf + offset); offset += std::strlen(*ep) + 1; ++ep; } } new_env[var_count] = 0; // RAII to prevent memory leak g_new_environ_guard = environ_guard{ new_env_buf, new_env }; environ = new_env; return env_size; } void setproctitle(const char* title, int argc, char** argv) { int argv_size = 0; for(int i = 0; i < argc; ++i) { int len = std::strlen(argv[i]); std::memset(argv[i], 0, len); argv_size += len; } int to_be_copied = std::strlen(title); if(argv_size <= to_be_copied) { int env_size = realloc_environ(); if(env_size < to_be_copied) { to_be_copied = env_size; } } std::strncpy(argv[0], title, to_be_copied); *(argv[0] + to_be_copied) = 0; } #endif bool ProcArgList(int argc, char* argv[]) { //Echo logo EchoArkLogo(); //Analyse arg list ApplicationConfig config; for(int i = 0; i < argc; ++i) { std::string arg = argv[i]; if(arg == "-d") { config.deamon = true; } else if(arg == "-x") { config.xbutton = true; } else if(arg.find("cfg") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.plugin_file = arg.substr(pos + 1, arg.length() - pos - 1); } } else if(arg.find("app_id") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_id = ARK_LEXICAL_CAST<int>(arg.substr(pos + 1, arg.length() - pos - 1)); } } else if(arg.find("app_name") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_name = arg.substr(pos + 1, arg.length() - pos - 1); } } } if(config.deamon) { #if ARK_PLATFORM == PLATFORM_UNIX //Run as a daemon process signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); #endif } if(config.xbutton) { #if ARK_PLATFORM == PLATFORM_WIN SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler); CloseXButton(); #endif } //暂时还从plugin.xml中获取app id,不做强制要求 //如果要做多开,则需要自己处理 //if(config.app_id == 0) //{ // std::cout << "parameter app_id is invalid, please check." << std::endl; // return false; //} //暂时app name也可以不用传参 //if(config.app_name.empty()) //{ // std::cout << "parameter app_name is invalid, please check." << std::endl; // return false; //} //Set plugin file AFCPluginManager::GetInstancePtr()->SetConfigName(config.plugin_file); AFCPluginManager::GetInstancePtr()->SetAppID(config.app_id); std::string process_name = "[" + config.app_name + ":" + ARK_TO_STRING(config.app_id) + "]"; //Set process name #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTitle(process_name.c_str()); #elif ARK_PLATFORM == PLATFORM_UNIX setproctitle(process_name, argc, argv); #endif //Create back thread, for some cmd CreateBackThread(); return true; } void MainLoop() { #if ARK_PLATFORM == PLATFORM_WIN __try { AFCPluginManager::GetInstancePtr()->Update(); } __except(ApplicationCrashHandler(GetExceptionInformation())) { } #else AFCPluginManager::GetInstancePtr()->Update(); #endif } int main(int argc, char* argv[]) { //arg list //-d, Run as daemon, just take effect in Linux //-x, Remove close button, just take effect in Windows //cfg=plugin.xml, plugin configuration files //app_id=1, set application's id //app_name=GameServer, set application's name if(!ProcArgList(argc, argv)) { std::cout << "Application parameter is invalid, please check it..." << std::endl; Usage(); return -1; } AFCPluginManager::GetInstancePtr()->Init(); AFCPluginManager::GetInstancePtr()->PostInit(); AFCPluginManager::GetInstancePtr()->CheckConfig(); AFCPluginManager::GetInstancePtr()->PreUpdate(); while(!bExitApp) //DEBUG版本崩溃,RELEASE不崩 { while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if(bExitApp) { break; } MainLoop(); } } AFCPluginManager::GetInstancePtr()->PreShut(); AFCPluginManager::GetInstancePtr()->Shut(); AFCPluginManager::GetInstancePtr()->ReleaseInstance(); gBackThread.join(); return 0; }<commit_msg>fix wrong code moving<commit_after>/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame authors. * * 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 "AFCPluginManager.h" #include "SDK/Core/Base/AFPlatform.hpp" #if ARK_PLATFORM == PLATFORM_UNIX #include <unistd.h> #include <netdb.h> #include <arpa/inet.h> #include <signal.h> #include <sys/prctl.h> #endif bool bExitApp = false; std::thread gBackThread; #if ARK_PLATFORM == PLATFORM_WIN #include <Dbghelp.h> #pragma comment(lib, "DbgHelp") #if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG #pragma comment(lib, "AFCore_d.lib") #else #pragma comment(lib, "AFCore.lib") #endif // 创建Dump文件 void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException) { // 创建Dump文件 HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // Dump信息 MINIDUMP_EXCEPTION_INFORMATION dumpInfo; dumpInfo.ExceptionPointers = pException; dumpInfo.ThreadId = GetCurrentThreadId(); dumpInfo.ClientPointers = TRUE; // 写入Dump文件内容 MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); CloseHandle(hDumpFile); } // 处理Unhandled Exception的回调函数 long ApplicationCrashHandler(EXCEPTION_POINTERS* pException) { time_t t = time(0); char szDmupName[MAX_PATH]; tm* ptm = localtime(&t); sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); CreateDumpFile(szDmupName, pException); FatalAppExit(-1, szDmupName); return EXCEPTION_EXECUTE_HANDLER; } #endif void CloseXButton() { #if ARK_PLATFORM == PLATFORM_WIN HWND hWnd = GetConsoleWindow(); if(hWnd) { HMENU hMenu = GetSystemMenu(hWnd, FALSE); EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND); } #endif } void InitDaemon() { #if ARK_PLATFORM == PLATFORM_UNIX daemon(1, 0); // ignore signals signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTERM, SIG_IGN); #endif } void EchoArkLogo() { #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif std::cout << " _ _ ____ _ _ _ " << std::endl; std::cout << " / \\ _ __| | __ / ___|| |_ _ _ __| (_) ___ " << std::endl; std::cout << " / _ \\ | '__| |/ / \\___ \\| __| | | |/ _` | |/ _ \\ " << std::endl; std::cout << " / ___ \\| | | < ___) | |_| |_| | (_| | | (_) |" << std::endl; std::cout << " /_/ \\_\\_| |_|\\_\\ |____/ \\__|\\__,_|\\__,_|_|\\___/ " << std::endl; std::cout << std::endl; std::cout << "COPYRIGHT (c) 2013-2018 Ark Studio" << std::endl; std::cout << "All RIGHTS RESERVED." << std::endl; std::cout << "HTTPS://ARKGAME.NET" << std::endl; std::cout << "********************************************" << std::endl; #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif } void Usage() { std::cout << "Ark PluginLoader usage:" << std::endl; std::cout << "./PluginLoader [options]" << std::endl; std::cout << "Option:" << std::endl; std::cout << "\t" << "-d, Run as daemon, just take effect in Linux" << std::endl; std::cout << "\t" << "-x, Remove close button, just take effect in Windows" << std::endl; std::cout << "\t" << "cfg=plugin.xml, plugin configuration files" << std::endl; std::cout << "\t" << "app_id=1, set application's id" << std::endl; std::cout << "\t" << "app_name=GameServer, set application's name" << std::endl; std::cout << "i.e. ./PluginLoader -d -x cfg=plugin.xml app_id=1 app_name=my_test" << std::endl; } void ThreadFunc() { while(!bExitApp) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::string s; std::cin >> s; std::transform(s.begin(), s.end(), s.begin(), ::tolower); if(s == "exit") { bExitApp = true; } else if(s == "help") { Usage(); } } } void CreateBackThread() { gBackThread = std::thread(std::bind(&ThreadFunc)); //std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl; } struct ApplicationConfig { bool deamon = true; //run as deamon, Linux bool xbutton = true; //close X button in windows std::string plugin_file = "Plugin.xml"; //config file int app_id = 0; //app id std::string app_name = ""; //app name }; #if ARK_PLATFORM == PLATFORM_UNIX extern char** environ; struct environ_guard { public: ~environ_guard() { if(env_buf) { delete[] env_buf; env_buf = nullptr; } if(environ) { delete[] environ; environ = nullptr; } } char* env_buf; char** environ; }; environ_guard g_new_environ_guard{ nullptr, nullptr }; int realloc_environ() { int var_count = 0; int env_size = 0; { char** ep = environ; while(*ep) { env_size += std::strlen(*ep) + 1; ++var_count; ++ep; } } char* new_env_buf = new char[env_size]; std::memcpy((void *)new_env_buf, (void *)*environ, env_size); char** new_env = new char*[var_count + 1]; { int var = 0; int offset = 0; char** ep = environ; while(*ep) { new_env[var++] = (new_env_buf + offset); offset += std::strlen(*ep) + 1; ++ep; } } new_env[var_count] = 0; // RAII to prevent memory leak g_new_environ_guard = environ_guard{ new_env_buf, new_env }; environ = new_env; return env_size; } void setproctitle(const char* title, int argc, char** argv) { int argv_size = 0; for(int i = 0; i < argc; ++i) { int len = std::strlen(argv[i]); std::memset(argv[i], 0, len); argv_size += len; } int to_be_copied = std::strlen(title); if(argv_size <= to_be_copied) { int env_size = realloc_environ(); if(env_size < to_be_copied) { to_be_copied = env_size; } } std::strncpy(argv[0], title, to_be_copied); *(argv[0] + to_be_copied) = 0; } #endif bool ProcArgList(int argc, char* argv[]) { //Echo logo EchoArkLogo(); //Analyse arg list ApplicationConfig config; for(int i = 0; i < argc; ++i) { std::string arg = argv[i]; if(arg == "-d") { config.deamon = true; } else if(arg == "-x") { config.xbutton = true; } else if(arg.find("cfg") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.plugin_file = arg.substr(pos + 1, arg.length() - pos - 1); } } else if(arg.find("app_id") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_id = ARK_LEXICAL_CAST<int>(arg.substr(pos + 1, arg.length() - pos - 1)); } } else if(arg.find("app_name") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_name = arg.substr(pos + 1, arg.length() - pos - 1); } } } if(config.deamon) { #if ARK_PLATFORM == PLATFORM_UNIX //Run as a daemon process signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); #endif } if(config.xbutton) { #if ARK_PLATFORM == PLATFORM_WIN SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler); CloseXButton(); #endif } //暂时还从plugin.xml中获取app id,不做强制要求 //如果要做多开,则需要自己处理 //if(config.app_id == 0) //{ // std::cout << "parameter app_id is invalid, please check." << std::endl; // return false; //} //暂时app name也可以不用传参 //if(config.app_name.empty()) //{ // std::cout << "parameter app_name is invalid, please check." << std::endl; // return false; //} //Set plugin file AFCPluginManager::GetInstancePtr()->SetConfigName(config.plugin_file); AFCPluginManager::GetInstancePtr()->SetAppID(config.app_id); std::string process_name = "[" + config.app_name + ":" + ARK_TO_STRING(config.app_id) + "]"; //Set process name #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTitle(process_name.c_str()); #elif ARK_PLATFORM == PLATFORM_UNIX setproctitle(process_name, argc, argv); #endif //Create back thread, for some cmd CreateBackThread(); return true; } void MainLoop() { #if ARK_PLATFORM == PLATFORM_WIN __try { AFCPluginManager::GetInstancePtr()->Update(); } __except(ApplicationCrashHandler(GetExceptionInformation())) { } #else AFCPluginManager::GetInstancePtr()->Update(); #endif } int main(int argc, char* argv[]) { //arg list //-d, Run as daemon, just take effect in Linux //-x, Remove close button, just take effect in Windows //cfg=plugin.xml, plugin configuration files //app_id=1, set application's id //app_name=GameServer, set application's name if(!ProcArgList(argc, argv)) { std::cout << "Application parameter is invalid, please check it..." << std::endl; Usage(); return -1; } AFCPluginManager::GetInstancePtr()->Init(); AFCPluginManager::GetInstancePtr()->PostInit(); AFCPluginManager::GetInstancePtr()->CheckConfig(); AFCPluginManager::GetInstancePtr()->PreUpdate(); while(!bExitApp) //DEBUG版本崩溃,RELEASE不崩 { while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if(bExitApp) { break; } MainLoop(); } } AFCPluginManager::GetInstancePtr()->PreShut(); AFCPluginManager::GetInstancePtr()->Shut(); AFCPluginManager::GetInstancePtr()->ReleaseInstance(); gBackThread.join(); return 0; }<|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: voxel_grid.hpp 1600 2011-07-07 16:55:51Z shapovalov $ * */ #ifndef PCL_FILTERS_IMPL_FAST_VOXEL_GRID_H_ #define PCL_FILTERS_IMPL_FAST_VOXEL_GRID_H_ #include "pcl/common/common.h" #include "pcl/filters/fast_voxel_grid.h" ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FastVoxelGrid<PointT>::flush (PointCloud &output, size_t op, he *hhe, int rgba_index, int centroid_size) { hhe->centroid /= hhe->count; pcl::for_each_type <FieldList> (pcl::xNdCopyEigenPointFunctor <PointT> (hhe->centroid, output.points[op])); // ---[ RGB special case if (rgba_index >= 0) { // pack r/g/b into rgb float r = hhe->centroid[centroid_size-3], g = hhe->centroid[centroid_size-2], b = hhe->centroid[centroid_size-1]; int rgb = ((int)r) << 16 | ((int)g) << 8 | ((int)b); memcpy (((char *)&output.points[op]) + rgba_index, &rgb, sizeof (float)); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FastVoxelGrid<PointT>::applyFilter (PointCloud &output) { int centroid_size = 4; if (downsample_all_data_) centroid_size = boost::mpl::size<FieldList>::value; // ---[ RGB special case std::vector<sensor_msgs::PointField> fields; int rgba_index = -1; rgba_index = pcl::getFieldIndex (*input_, "rgb", fields); if (rgba_index == -1) rgba_index = pcl::getFieldIndex (*input_, "rgba", fields); if (rgba_index >= 0) { rgba_index = fields[rgba_index].offset; centroid_size += 3; } for (size_t i = 0; i < histsize; i++) { history[i].count = 0; history[i].centroid = Eigen::VectorXf::Zero (centroid_size); } Eigen::VectorXf scratch = Eigen::VectorXf::Zero (centroid_size); output.points.resize (input_->points.size ()); // size output for worst case size_t op = 0; // output pointer for (size_t cp = 0; cp < input_->points.size (); ++cp) { int ix = (int)floor (input_->points[cp].x * inverse_leaf_size_[0]); int iy = (int)floor (input_->points[cp].y * inverse_leaf_size_[1]); int iz = (int)floor (input_->points[cp].z * inverse_leaf_size_[2]); unsigned int hash = (ix * 7171 + iy * 3079 + iz * 4231) & (histsize - 1); he *hhe = &history[hash]; if (hhe->count && ((ix != hhe->ix) || (iy != hhe->iy) || (iz != hhe->iz))) { flush (output, op++, hhe, rgba_index, centroid_size); hhe->count = 0; hhe->centroid.setZero ();// = Eigen::VectorXf::Zero (centroid_size); } hhe->ix = ix; hhe->iy = iy; hhe->iz = iz; hhe->count++; // Unpack the point into scratch, then accumulate // ---[ RGB special case if (rgba_index >= 0) { // fill r/g/b data int rgb; memcpy (&rgb, ((char *)&(input_->points[cp])) + rgba_index, sizeof (int)); scratch[centroid_size-3] = (rgb>>16) & 0x0000ff; scratch[centroid_size-2] = (rgb>>8) & 0x0000ff; scratch[centroid_size-1] = (rgb) & 0x0000ff; } pcl::for_each_type <FieldList> (xNdCopyPointEigenFunctor <PointT> (input_->points[cp], scratch)); hhe->centroid += scratch; } for (size_t i = 0; i < histsize; i++) { he *hhe = &history[i]; if (hhe->count) flush (output, op++, hhe, rgba_index, centroid_size); } output.points.resize (op); output.width = output.points.size (); output.height = 1; // downsampling breaks the organized structure output.is_dense = false; // we filter out invalid points } #define PCL_INSTANTIATE_FastVoxelGrid(T) template class PCL_EXPORTS pcl::FastVoxelGrid<T>; #endif // PCL_FILTERS_IMPL_FAST_VOXEL_GRID_H_ <commit_msg>changed bitshifting RGB to use the new struct<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: voxel_grid.hpp 1600 2011-07-07 16:55:51Z shapovalov $ * */ #ifndef PCL_FILTERS_IMPL_FAST_VOXEL_GRID_H_ #define PCL_FILTERS_IMPL_FAST_VOXEL_GRID_H_ #include "pcl/common/common.h" #include "pcl/filters/fast_voxel_grid.h" ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FastVoxelGrid<PointT>::flush (PointCloud &output, size_t op, he *hhe, int rgba_index, int centroid_size) { hhe->centroid /= hhe->count; pcl::for_each_type <FieldList> (pcl::xNdCopyEigenPointFunctor <PointT> (hhe->centroid, output.points[op])); // ---[ RGB special case if (rgba_index >= 0) { // pack r/g/b into rgb float r = hhe->centroid[centroid_size-3], g = hhe->centroid[centroid_size-2], b = hhe->centroid[centroid_size-1]; int rgb = ((int)r) << 16 | ((int)g) << 8 | ((int)b); memcpy (((char *)&output.points[op]) + rgba_index, &rgb, sizeof (float)); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FastVoxelGrid<PointT>::applyFilter (PointCloud &output) { int centroid_size = 4; if (downsample_all_data_) centroid_size = boost::mpl::size<FieldList>::value; // ---[ RGB special case std::vector<sensor_msgs::PointField> fields; int rgba_index = -1; rgba_index = pcl::getFieldIndex (*input_, "rgb", fields); if (rgba_index == -1) rgba_index = pcl::getFieldIndex (*input_, "rgba", fields); if (rgba_index >= 0) { rgba_index = fields[rgba_index].offset; centroid_size += 3; } for (size_t i = 0; i < histsize; i++) { history[i].count = 0; history[i].centroid = Eigen::VectorXf::Zero (centroid_size); } Eigen::VectorXf scratch = Eigen::VectorXf::Zero (centroid_size); output.points.resize (input_->points.size ()); // size output for worst case size_t op = 0; // output pointer for (size_t cp = 0; cp < input_->points.size (); ++cp) { int ix = (int)floor (input_->points[cp].x * inverse_leaf_size_[0]); int iy = (int)floor (input_->points[cp].y * inverse_leaf_size_[1]); int iz = (int)floor (input_->points[cp].z * inverse_leaf_size_[2]); unsigned int hash = (ix * 7171 + iy * 3079 + iz * 4231) & (histsize - 1); he *hhe = &history[hash]; if (hhe->count && ((ix != hhe->ix) || (iy != hhe->iy) || (iz != hhe->iz))) { flush (output, op++, hhe, rgba_index, centroid_size); hhe->count = 0; hhe->centroid.setZero ();// = Eigen::VectorXf::Zero (centroid_size); } hhe->ix = ix; hhe->iy = iy; hhe->iz = iz; hhe->count++; // Unpack the point into scratch, then accumulate // ---[ RGB special case if (rgba_index >= 0) { // fill r/g/b data pcl::RGB rgb; memcpy (&rgb, ((char *)&(input_->points[cp])) + rgba_index, sizeof (RGB)); scratch[centroid_size-3] = rgb.r; scratch[centroid_size-2] = rgb.g; scratch[centroid_size-1] = rgb.b; } pcl::for_each_type <FieldList> (xNdCopyPointEigenFunctor <PointT> (input_->points[cp], scratch)); hhe->centroid += scratch; } for (size_t i = 0; i < histsize; i++) { he *hhe = &history[i]; if (hhe->count) flush (output, op++, hhe, rgba_index, centroid_size); } output.points.resize (op); output.width = output.points.size (); output.height = 1; // downsampling breaks the organized structure output.is_dense = false; // we filter out invalid points } #define PCL_INSTANTIATE_FastVoxelGrid(T) template class PCL_EXPORTS pcl::FastVoxelGrid<T>; #endif // PCL_FILTERS_IMPL_FAST_VOXEL_GRID_H_ <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <fc/io/json.hpp> #include <fc/io/stdio.hpp> #include <fc/network/http/server.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/cli.hpp> #include <fc/rpc/http_api.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/smart_ref_impl.hpp> #include <graphene/app/api.hpp> #include <graphene/chain/protocol/protocol.hpp> #include <graphene/egenesis/egenesis.hpp> #include <graphene/utilities/key_conversion.hpp> #include <graphene/wallet/wallet.hpp> #include <fc/interprocess/signals.hpp> #include <boost/program_options.hpp> #include <fc/log/console_appender.hpp> #include <fc/log/file_appender.hpp> #include <fc/log/logger.hpp> #include <fc/log/logger_config.hpp> #ifdef WIN32 # include <signal.h> #else # include <csignal> #endif using namespace graphene::app; using namespace graphene::chain; using namespace graphene::utilities; using namespace graphene::wallet; using namespace std; namespace bpo = boost::program_options; int main( int argc, char** argv ) { try { boost::program_options::options_description opts; opts.add_options() ("help,h", "Print this help message and exit.") ("server-rpc-endpoint,s", bpo::value<string>()->implicit_value("ws://127.0.0.1:8090"), "Server websocket RPC endpoint") ("server-rpc-user,u", bpo::value<string>(), "Server Username") ("server-rpc-password,p", bpo::value<string>(), "Server Password") ("rpc-endpoint,r", bpo::value<string>()->implicit_value("127.0.0.1:8091"), "Endpoint for wallet websocket RPC to listen on") ("rpc-tls-endpoint,t", bpo::value<string>()->implicit_value("127.0.0.1:8092"), "Endpoint for wallet websocket TLS RPC to listen on") ("rpc-tls-certificate,c", bpo::value<string>()->implicit_value("server.pem"), "PEM certificate for wallet websocket TLS RPC") ("rpc-http-endpoint,H", bpo::value<string>()->implicit_value("127.0.0.1:8093"), "Endpoint for wallet HTTP RPC to listen on") ("daemon,d", "Run the wallet in daemon mode" ) ("wallet-file,w", bpo::value<string>()->implicit_value("wallet.json"), "wallet to load") ("chain-id", bpo::value<string>(), "chain ID to connect to"); bpo::variables_map options; bpo::store( bpo::parse_command_line(argc, argv, opts), options ); if( options.count("help") ) { std::cout << opts << "\n"; return 0; } fc::path data_dir; fc::logging_config cfg; fc::path log_dir = data_dir / "logs"; fc::file_appender::config ac; ac.filename = log_dir / "rpc" / "rpc.log"; ac.flush = true; ac.rotate = true; ac.rotation_interval = fc::hours( 1 ); ac.rotation_limit = fc::days( 1 ); std::cout << "Logging RPC to file: " << (data_dir / ac.filename).preferred_string() << "\n"; cfg.appenders.push_back(fc::appender_config( "default", "console", fc::variant(fc::console_appender::config()))); cfg.appenders.push_back(fc::appender_config( "rpc", "file", fc::variant(ac))); cfg.loggers = { fc::logger_config("default"), fc::logger_config( "rpc") }; cfg.loggers.front().level = fc::log_level::info; cfg.loggers.front().appenders = {"default"}; cfg.loggers.back().level = fc::log_level::debug; cfg.loggers.back().appenders = {"rpc"}; //fc::configure_logging( cfg ); fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key"))); idump( (key_to_wif( committee_private_key ) ) ); fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan"))); public_key_type nathan_pub_key = nathan_private_key.get_public_key(); idump( (nathan_pub_key) ); idump( (key_to_wif( nathan_private_key ) ) ); // // TODO: We read wallet_data twice, once in main() to grab the // socket info, again in wallet_api when we do // load_wallet_file(). Seems like this could be better // designed. // wallet_data wdata; fc::path wallet_file( options.count("wallet-file") ? options.at("wallet-file").as<string>() : "wallet.json"); if( fc::exists( wallet_file ) ) { wdata = fc::json::from_file( wallet_file ).as<wallet_data>(); if( options.count("chain-id") ) { // the --chain-id on the CLI must match the chain ID embedded in the wallet file if( chain_id_type(options.at("chain-id").as<std::string>()) != wdata.chain_id ) { std::cout << "Chain ID in wallet file does not match specified chain ID\n"; return 1; } } } else { if( options.count("chain-id") ) { wdata.chain_id = chain_id_type(options.at("chain-id").as<std::string>()); std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from CLI)\n"; } else { wdata.chain_id = graphene::egenesis::get_egenesis_chain_id(); std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from egenesis)\n"; } } // but allow CLI to override if( options.count("server-rpc-endpoint") ) wdata.ws_server = options.at("server-rpc-endpoint").as<std::string>(); if( options.count("server-rpc-user") ) wdata.ws_user = options.at("server-rpc-user").as<std::string>(); if( options.count("server-rpc-password") ) wdata.ws_password = options.at("server-rpc-password").as<std::string>(); fc::http::websocket_client client; idump((wdata.ws_server)); auto con = client.connect( wdata.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); auto remote_api = apic->get_remote_api< login_api >(1); edump((wdata.ws_user)(wdata.ws_password) ); // TODO: Error message here FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api ); wapiptr->set_wallet_filename( wallet_file.generic_string() ); wapiptr->load_wallet_file(); fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); for( auto& name_formatter : wapiptr->get_result_formatters() ) wallet_cli->format_result( name_formatter.first, name_formatter.second ); boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{ cerr << "Server has disconnected us.\n"; wallet_cli->stop(); })); (void)(closed_connection); if( wapiptr->is_new() ) { std::cout << "Please use the set_password method to initialize a new wallet before continuing\n"; wallet_cli->set_prompt( "new >>> " ); } else wallet_cli->set_prompt( "locked >>> " ); boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) { wallet_cli->set_prompt( locked ? "locked >>> " : "unlocked >>> " ); })); auto _websocket_server = std::make_shared<fc::http::websocket_server>(); if( options.count("rpc-endpoint") ) { _websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){ std::cout << "here... \n"; wlog("." ); auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c); wsc->register_api(wapi); c->set_session_data( wsc ); }); ilog( "Listening for incoming RPC requests on ${p}", ("p", options.at("rpc-endpoint").as<string>() )); _websocket_server->listen( fc::ip::endpoint::from_string(options.at("rpc-endpoint").as<string>()) ); _websocket_server->start_accept(); } string cert_pem = "server.pem"; if( options.count( "rpc-tls-certificate" ) ) cert_pem = options.at("rpc-tls-certificate").as<string>(); auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem); if( options.count("rpc-tls-endpoint") ) { _websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){ auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c); wsc->register_api(wapi); c->set_session_data( wsc ); }); ilog( "Listening for incoming TLS RPC requests on ${p}", ("p", options.at("rpc-tls-endpoint").as<string>() )); _websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at("rpc-tls-endpoint").as<string>()) ); _websocket_tls_server->start_accept(); } auto _http_server = std::make_shared<fc::http::server>(); if( options.count("rpc-http-endpoint" ) ) { ilog( "Listening for incoming HTTP RPC requests on ${p}", ("p", options.at("rpc-http-endpoint").as<string>() ) ); _http_server->listen( fc::ip::endpoint::from_string( options.at( "rpc-http-endpoint" ).as<string>() ) ); // // due to implementation, on_request() must come AFTER listen() // _http_server->on_request( [&]( const fc::http::request& req, const fc::http::server::response& resp ) { std::shared_ptr< fc::rpc::http_api_connection > conn = std::make_shared< fc::rpc::http_api_connection>(); conn->register_api( wapi ); conn->on_request( req, resp ); } ); } if( !options.count( "daemon" ) ) { wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } else { fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler"); fc::set_signal_handler([&exit_promise](int signal) { exit_promise->set_value(signal); }, SIGINT); ilog( "Entering Daemon Mode, ^C to exit" ); exit_promise->wait(); } wapi->save_wallet_file(wallet_file.generic_string()); locked_connection.disconnect(); closed_connection.disconnect(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; return -1; } return 0; } <commit_msg>remove the not required logging<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <fc/io/json.hpp> #include <fc/io/stdio.hpp> #include <fc/network/http/server.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/cli.hpp> #include <fc/rpc/http_api.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/smart_ref_impl.hpp> #include <graphene/app/api.hpp> #include <graphene/chain/protocol/protocol.hpp> #include <graphene/egenesis/egenesis.hpp> #include <graphene/utilities/key_conversion.hpp> #include <graphene/wallet/wallet.hpp> #include <fc/interprocess/signals.hpp> #include <boost/program_options.hpp> #include <fc/log/console_appender.hpp> #include <fc/log/file_appender.hpp> #include <fc/log/logger.hpp> #include <fc/log/logger_config.hpp> #ifdef WIN32 # include <signal.h> #else # include <csignal> #endif using namespace graphene::app; using namespace graphene::chain; using namespace graphene::utilities; using namespace graphene::wallet; using namespace std; namespace bpo = boost::program_options; int main( int argc, char** argv ) { try { boost::program_options::options_description opts; opts.add_options() ("help,h", "Print this help message and exit.") ("server-rpc-endpoint,s", bpo::value<string>()->implicit_value("ws://127.0.0.1:8090"), "Server websocket RPC endpoint") ("server-rpc-user,u", bpo::value<string>(), "Server Username") ("server-rpc-password,p", bpo::value<string>(), "Server Password") ("rpc-endpoint,r", bpo::value<string>()->implicit_value("127.0.0.1:8091"), "Endpoint for wallet websocket RPC to listen on") ("rpc-tls-endpoint,t", bpo::value<string>()->implicit_value("127.0.0.1:8092"), "Endpoint for wallet websocket TLS RPC to listen on") ("rpc-tls-certificate,c", bpo::value<string>()->implicit_value("server.pem"), "PEM certificate for wallet websocket TLS RPC") ("rpc-http-endpoint,H", bpo::value<string>()->implicit_value("127.0.0.1:8093"), "Endpoint for wallet HTTP RPC to listen on") ("daemon,d", "Run the wallet in daemon mode" ) ("wallet-file,w", bpo::value<string>()->implicit_value("wallet.json"), "wallet to load") ("chain-id", bpo::value<string>(), "chain ID to connect to"); bpo::variables_map options; bpo::store( bpo::parse_command_line(argc, argv, opts), options ); if( options.count("help") ) { std::cout << opts << "\n"; return 0; } fc::path data_dir; fc::logging_config cfg; fc::path log_dir = data_dir / "logs"; fc::file_appender::config ac; ac.filename = log_dir / "rpc" / "rpc.log"; ac.flush = true; ac.rotate = true; ac.rotation_interval = fc::hours( 1 ); ac.rotation_limit = fc::days( 1 ); std::cout << "Logging RPC to file: " << (data_dir / ac.filename).preferred_string() << "\n"; cfg.appenders.push_back(fc::appender_config( "default", "console", fc::variant(fc::console_appender::config()))); cfg.appenders.push_back(fc::appender_config( "rpc", "file", fc::variant(ac))); cfg.loggers = { fc::logger_config("default"), fc::logger_config( "rpc") }; cfg.loggers.front().level = fc::log_level::info; cfg.loggers.front().appenders = {"default"}; cfg.loggers.back().level = fc::log_level::debug; cfg.loggers.back().appenders = {"rpc"}; //fc::configure_logging( cfg ); fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key"))); idump( (key_to_wif( committee_private_key ) ) ); fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan"))); public_key_type nathan_pub_key = nathan_private_key.get_public_key(); idump( (nathan_pub_key) ); idump( (key_to_wif( nathan_private_key ) ) ); // // TODO: We read wallet_data twice, once in main() to grab the // socket info, again in wallet_api when we do // load_wallet_file(). Seems like this could be better // designed. // wallet_data wdata; fc::path wallet_file( options.count("wallet-file") ? options.at("wallet-file").as<string>() : "wallet.json"); if( fc::exists( wallet_file ) ) { wdata = fc::json::from_file( wallet_file ).as<wallet_data>(); if( options.count("chain-id") ) { // the --chain-id on the CLI must match the chain ID embedded in the wallet file if( chain_id_type(options.at("chain-id").as<std::string>()) != wdata.chain_id ) { std::cout << "Chain ID in wallet file does not match specified chain ID\n"; return 1; } } } else { if( options.count("chain-id") ) { wdata.chain_id = chain_id_type(options.at("chain-id").as<std::string>()); std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from CLI)\n"; } else { wdata.chain_id = graphene::egenesis::get_egenesis_chain_id(); std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from egenesis)\n"; } } // but allow CLI to override if( options.count("server-rpc-endpoint") ) wdata.ws_server = options.at("server-rpc-endpoint").as<std::string>(); if( options.count("server-rpc-user") ) wdata.ws_user = options.at("server-rpc-user").as<std::string>(); if( options.count("server-rpc-password") ) wdata.ws_password = options.at("server-rpc-password").as<std::string>(); fc::http::websocket_client client; idump((wdata.ws_server)); auto con = client.connect( wdata.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); auto remote_api = apic->get_remote_api< login_api >(1); edump((wdata.ws_user)(wdata.ws_password) ); // TODO: Error message here FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api ); wapiptr->set_wallet_filename( wallet_file.generic_string() ); wapiptr->load_wallet_file(); fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); for( auto& name_formatter : wapiptr->get_result_formatters() ) wallet_cli->format_result( name_formatter.first, name_formatter.second ); boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{ cerr << "Server has disconnected us.\n"; wallet_cli->stop(); })); (void)(closed_connection); if( wapiptr->is_new() ) { std::cout << "Please use the set_password method to initialize a new wallet before continuing\n"; wallet_cli->set_prompt( "new >>> " ); } else wallet_cli->set_prompt( "locked >>> " ); boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) { wallet_cli->set_prompt( locked ? "locked >>> " : "unlocked >>> " ); })); auto _websocket_server = std::make_shared<fc::http::websocket_server>(); if( options.count("rpc-endpoint") ) { _websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){ //std::cout << "here... \n"; //wlog("." ); auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c); wsc->register_api(wapi); c->set_session_data( wsc ); }); ilog( "Listening for incoming RPC requests on ${p}", ("p", options.at("rpc-endpoint").as<string>() )); _websocket_server->listen( fc::ip::endpoint::from_string(options.at("rpc-endpoint").as<string>()) ); _websocket_server->start_accept(); } string cert_pem = "server.pem"; if( options.count( "rpc-tls-certificate" ) ) cert_pem = options.at("rpc-tls-certificate").as<string>(); auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem); if( options.count("rpc-tls-endpoint") ) { _websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){ auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c); wsc->register_api(wapi); c->set_session_data( wsc ); }); ilog( "Listening for incoming TLS RPC requests on ${p}", ("p", options.at("rpc-tls-endpoint").as<string>() )); _websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at("rpc-tls-endpoint").as<string>()) ); _websocket_tls_server->start_accept(); } auto _http_server = std::make_shared<fc::http::server>(); if( options.count("rpc-http-endpoint" ) ) { ilog( "Listening for incoming HTTP RPC requests on ${p}", ("p", options.at("rpc-http-endpoint").as<string>() ) ); _http_server->listen( fc::ip::endpoint::from_string( options.at( "rpc-http-endpoint" ).as<string>() ) ); // // due to implementation, on_request() must come AFTER listen() // _http_server->on_request( [&]( const fc::http::request& req, const fc::http::server::response& resp ) { std::shared_ptr< fc::rpc::http_api_connection > conn = std::make_shared< fc::rpc::http_api_connection>(); conn->register_api( wapi ); conn->on_request( req, resp ); } ); } if( !options.count( "daemon" ) ) { wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } else { fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler"); fc::set_signal_handler([&exit_promise](int signal) { exit_promise->set_value(signal); }, SIGINT); ilog( "Entering Daemon Mode, ^C to exit" ); exit_promise->wait(); } wapi->save_wallet_file(wallet_file.generic_string()); locked_connection.disconnect(); closed_connection.disconnect(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; return -1; } return 0; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <file.hpp> #include <system.hpp> #include <errors.hpp> #include <print.hpp> int main(int, char*[]){ auto fd = open("/sys/uptime"); if(fd.valid()){ auto buffer = new char[64]; auto content_result = read(*fd, buffer, 64); if(content_result.valid()){ auto chars = *content_result; std::string value_str; value_str.reserve(chars); for(size_t i = 0; i < chars; ++i){ value_str += buffer[i]; } auto value = std::parse(value_str); printf("Uptime: %u:%u:%u\n", value / 3600, (value % 3600) / 60, value % 60); } else { printf("cat: error: %s\n", std::error_message(content_result.error())); } delete[] buffer; close(*fd); } else { printf("cat: error: %s\n", std::error_message(fd.error())); } exit(0); }<commit_msg>Fix error messages<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <file.hpp> #include <system.hpp> #include <errors.hpp> #include <print.hpp> int main(int, char*[]){ auto fd = open("/sys/uptime"); if(fd.valid()){ auto buffer = new char[64]; auto content_result = read(*fd, buffer, 64); if(content_result.valid()){ auto chars = *content_result; std::string value_str; value_str.reserve(chars); for(size_t i = 0; i < chars; ++i){ value_str += buffer[i]; } auto value = std::parse(value_str); printf("Uptime: %u:%u:%u\n", value / 3600, (value % 3600) / 60, value % 60); } else { printf("uptime: error: %s\n", std::error_message(content_result.error())); } delete[] buffer; close(*fd); } else { printf("uptime: error: %s\n", std::error_message(fd.error())); } exit(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 "mutex.h" #include "sandbox_impl.h" // This is a C++ implementation of trusted_thread.cc. Since it trusts // the contents of the stack, it is not secure. It is intended to be // a reference implementation. This code can be used as an aid to // understanding what the real trusted thread does, since this code // should be easier to read than assembly code. It can also be used // as a test bed for changes to the trusted thread. namespace playground { void die(const char *msg) { sys_write(2, msg, strlen(msg)); sys_exit_group(1); } #define TO_STRING_1(x) #x #define TO_STRING(x) TO_STRING_1(x) #define assert(expr) { \ if (!(expr)) die("assertion failed at " __FILE__ ":" TO_STRING(__LINE__) \ ": " #expr "\n"); } // Perform a syscall given an array of syscall arguments. extern "C" long DoSyscall(long regs[7]); asm( ".pushsection .text, \"ax\", @progbits\n" ".global DoSyscall\n" "DoSyscall:\n" #if defined(__x86_64__) "push %rdi\n" "push %rsi\n" "push %rdx\n" "push %r10\n" "push %r8\n" "push %r9\n" // Set up syscall arguments "mov 0x00(%rdi), %rax\n" // Skip 0x08 (%rdi): this comes last "mov 0x10(%rdi), %rsi\n" "mov 0x18(%rdi), %rdx\n" "mov 0x20(%rdi), %r10\n" "mov 0x28(%rdi), %r8\n" "mov 0x30(%rdi), %r9\n" "mov 0x08(%rdi), %rdi\n" "syscall\n" "pop %r9\n" "pop %r8\n" "pop %r10\n" "pop %rdx\n" "pop %rsi\n" "pop %rdi\n" "ret\n" #elif defined(__i386__) "push %ebx\n" "push %ecx\n" "push %edx\n" "push %esi\n" "push %edi\n" "push %ebp\n" "mov 4+24(%esp), %ecx\n" // Set up syscall arguments "mov 0x00(%ecx), %eax\n" "mov 0x04(%ecx), %ebx\n" // Skip 0x08 (%ecx): this comes last "mov 0x0c(%ecx), %edx\n" "mov 0x10(%ecx), %esi\n" "mov 0x14(%ecx), %edi\n" "mov 0x18(%ecx), %ebp\n" "mov 0x08(%ecx), %ecx\n" "int $0x80\n" "pop %ebp\n" "pop %edi\n" "pop %esi\n" "pop %edx\n" "pop %ecx\n" "pop %ebx\n" "ret\n" #else #error Unsupported target platform #endif ".popsection\n" ); void ReturnFromCloneSyscall(SecureMem::Args *secureMem) { // TODO(mseaborn): Call sigreturn() to unblock signals. #if defined(__x86_64__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->rsi; // Account for the x86-64 red zone adjustment that our syscall // interceptor does when returning from the system call. stack = (void**) ((char*) stack - 128); *--stack = secureMem->ret; *--stack = secureMem->r15; *--stack = secureMem->r14; *--stack = secureMem->r13; *--stack = secureMem->r12; *--stack = secureMem->r11; *--stack = secureMem->r10; *--stack = secureMem->r9; *--stack = secureMem->r8; *--stack = secureMem->rdi; *--stack = secureMem->rsi; *--stack = secureMem->rdx; *--stack = secureMem->rcx; *--stack = secureMem->rbx; *--stack = secureMem->rbp; asm("mov %0, %%rsp\n" "pop %%rbp\n" "pop %%rbx\n" "pop %%rcx\n" "pop %%rdx\n" "pop %%rsi\n" "pop %%rdi\n" "pop %%r8\n" "pop %%r9\n" "pop %%r10\n" "pop %%r11\n" "pop %%r12\n" "pop %%r13\n" "pop %%r14\n" "pop %%r15\n" "mov $0, %%rax\n" "ret\n" : : "m"(stack)); #elif defined(__i386__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->ecx; *--stack = secureMem->ret; *--stack = secureMem->ebp; *--stack = secureMem->edi; *--stack = secureMem->esi; *--stack = secureMem->edx; *--stack = secureMem->ecx; *--stack = secureMem->ebx; asm("mov %0, %%esp\n" "pop %%ebx\n" "pop %%ecx\n" "pop %%edx\n" "pop %%esi\n" "pop %%edi\n" "pop %%ebp\n" "mov $0, %%eax\n" "ret\n" : : "m"(stack)); #else #error Unsupported target platform #endif } void InitCustomTLS(void *addr) { Sandbox::SysCalls sys; #if defined(__x86_64__) int rc = sys.arch_prctl(ARCH_SET_GS, addr); assert(rc == 0); #elif defined(__i386__) struct user_desc u; u.entry_number = (typeof u.entry_number)-1; u.base_addr = (long) addr; u.limit = 0xfffff; u.seg_32bit = 1; u.contents = 0; u.read_exec_only = 0; u.limit_in_pages = 1; u.seg_not_present = 0; u.useable = 1; int rc = sys.set_thread_area(&u); assert(rc == 0); asm volatile("movw %w0, %%fs" : : "q"(8 * u.entry_number + 3)); #else #error Unsupported target platform #endif } void UnlockSyscallMutex() { Sandbox::SysCalls sys; // TODO(mseaborn): Use clone() to be the same as trusted_thread.cc. int pid = sys.fork(); assert(pid >= 0); if (pid == 0) { int rc = sys.mprotect(&Sandbox::syscall_mutex_, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); Mutex::unlockMutex(&Sandbox::syscall_mutex_); sys._exit(0); } int status; int rc = sys.waitpid(pid, &status, 0); assert(rc == pid); assert(status == 0); } // Allocate a stack that is never freed. char *AllocateStack() { Sandbox::SysCalls sys; int stack_size = 0x1000; #if defined(__i386__) void *stack = sys.mmap2(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #else void *stack = sys.mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #endif assert(stack != MAP_FAILED); return (char *) stack + stack_size; } int HandleNewThread(void *arg) { SecureMem::Args *secureMem = (SecureMem::Args *) arg; CreateReferenceTrustedThread(secureMem->newSecureMem); ReturnFromCloneSyscall(secureMem); return 0; } struct ThreadArgs { SecureMem::Args *secureMem; int threadFd; }; int TrustedThread(void *arg) { struct ThreadArgs *args = (struct ThreadArgs *) arg; SecureMem::Args *secureMem = args->secureMem; int fd = args->threadFd; Sandbox::SysCalls sys; int sequence_no = 2; while (1) { long syscall_args[7]; memset(syscall_args, 0, sizeof(syscall_args)); int got = sys.read(fd, syscall_args, 4); assert(got == 4); long syscall_result; int sysnum = syscall_args[0]; if (sysnum == -1 || sysnum == -2) { // Syscall where the registers have been checked by the trusted // process, e.g. munmap() ranges must be OK. // Doesn't need extra memory region. assert(secureMem->sequence == sequence_no); sequence_no += 2; if (secureMem->syscallNum == __NR_exit) { int rc = sys.close(fd); assert(rc == 0); rc = sys.close(secureMem->threadFdPub); assert(rc == 0); } else if (secureMem->syscallNum == __NR_clone) { assert(sysnum == -2); // Note that HandleNewThread() does UnlockSyscallMutex() for us. #if defined(__x86_64__) long clone_flags = (long) secureMem->rdi; int *pid_ptr = (int *) secureMem->rdx; int *tid_ptr = (int *) secureMem->r10; void *tls_info = secureMem->r8; #elif defined(__i386__) long clone_flags = (long) secureMem->ebx; int *pid_ptr = (int *) secureMem->edx; void *tls_info = secureMem->esi; int *tid_ptr = (int *) secureMem->edi; #else #error Unsupported target platform #endif syscall_result = sys.clone(HandleNewThread, (void *) AllocateStack(), clone_flags, (void *) secureMem, pid_ptr, tls_info, tid_ptr); assert(syscall_result > 0); int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); continue; } memcpy(syscall_args, &secureMem->syscallNum, sizeof(syscall_args)); // We release the mutex before doing the syscall, because we // have now copied the arguments. if (sysnum == -2) UnlockSyscallMutex(); } else if (sysnum == -3) { // RDTSC request. Send back a dummy answer. int timestamp[2] = {0, 0}; int sent = sys.write(fd, (char *) timestamp, sizeof(timestamp)); assert(sent == 8); continue; } else { int rest_size = sizeof(syscall_args) - sizeof(long); got = sys.read(fd, &syscall_args[1], rest_size); assert(got == rest_size); } syscall_result = DoSyscall(syscall_args); int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); } return 0; } void CreateReferenceTrustedThread(SecureMem::Args *secureMem) { // We are in the nascent thread. Sandbox::SysCalls sys; int socks[2]; int rc = sys.socketpair(AF_UNIX, SOCK_STREAM, 0, socks); assert(rc == 0); int threadFdPub = socks[0]; int threadFd = socks[1]; // Create trusted thread. // We omit CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID. int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM; // Assumes that the stack grows down. char *stack_top = AllocateStack() - sizeof(struct ThreadArgs); struct ThreadArgs *thread_args = (struct ThreadArgs *) stack_top; thread_args->threadFd = threadFd; thread_args->secureMem = secureMem; rc = sys.clone(TrustedThread, stack_top, flags, thread_args, NULL, NULL, NULL); assert(rc > 0); // Make the thread state pages usable. rc = sys.mprotect(secureMem, 0x1000, PROT_READ); assert(rc == 0); rc = sys.mprotect(((char *) secureMem) + 0x1000, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); // Using cookie as the start is a little odd because other code in // syscall.c works around this when addressing from %fs. void *tls = (void*) &secureMem->cookie; InitCustomTLS(tls); UnlockSyscallMutex(); int tid = sys.gettid(); assert(tid > 0); // Send the socket FDs to the trusted process. // TODO(mseaborn): Don't duplicate this struct in trusted_process.cc struct { SecureMem::Args* self; int tid; int fdPub; } __attribute__((packed)) data; data.self = secureMem; data.tid = tid; data.fdPub = threadFdPub; bool ok = Sandbox::sendFd(Sandbox::cloneFdPub_, threadFdPub, threadFd, (void *) &data, sizeof(data)); assert(ok); // Wait for the trusted process to fill out the thread state for us. char byte_message; int got = sys.read(threadFdPub, &byte_message, 1); assert(got == 1); assert(byte_message == 0); // Switch to seccomp mode. rc = sys.prctl(PR_SET_SECCOMP, 1); assert(rc == 0); } } <commit_msg>Bring reference_trusted_thread.cc into line with real implementation<commit_after>// 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 "mutex.h" #include "sandbox_impl.h" // This is a C++ implementation of trusted_thread.cc. Since it trusts // the contents of the stack, it is not secure. It is intended to be // a reference implementation. This code can be used as an aid to // understanding what the real trusted thread does, since this code // should be easier to read than assembly code. It can also be used // as a test bed for changes to the trusted thread. namespace playground { void die(const char *msg) { sys_write(2, msg, strlen(msg)); sys_exit_group(1); } #define TO_STRING_1(x) #x #define TO_STRING(x) TO_STRING_1(x) #define assert(expr) { \ if (!(expr)) die("assertion failed at " __FILE__ ":" TO_STRING(__LINE__) \ ": " #expr "\n"); } // Perform a syscall given an array of syscall arguments. extern "C" long DoSyscall(long regs[7]); asm( ".pushsection .text, \"ax\", @progbits\n" ".global DoSyscall\n" "DoSyscall:\n" #if defined(__x86_64__) "push %rdi\n" "push %rsi\n" "push %rdx\n" "push %r10\n" "push %r8\n" "push %r9\n" // Set up syscall arguments "mov 0x00(%rdi), %rax\n" // Skip 0x08 (%rdi): this comes last "mov 0x10(%rdi), %rsi\n" "mov 0x18(%rdi), %rdx\n" "mov 0x20(%rdi), %r10\n" "mov 0x28(%rdi), %r8\n" "mov 0x30(%rdi), %r9\n" "mov 0x08(%rdi), %rdi\n" "syscall\n" "pop %r9\n" "pop %r8\n" "pop %r10\n" "pop %rdx\n" "pop %rsi\n" "pop %rdi\n" "ret\n" #elif defined(__i386__) "push %ebx\n" "push %ecx\n" "push %edx\n" "push %esi\n" "push %edi\n" "push %ebp\n" "mov 4+24(%esp), %ecx\n" // Set up syscall arguments "mov 0x00(%ecx), %eax\n" "mov 0x04(%ecx), %ebx\n" // Skip 0x08 (%ecx): this comes last "mov 0x0c(%ecx), %edx\n" "mov 0x10(%ecx), %esi\n" "mov 0x14(%ecx), %edi\n" "mov 0x18(%ecx), %ebp\n" "mov 0x08(%ecx), %ecx\n" "int $0x80\n" "pop %ebp\n" "pop %edi\n" "pop %esi\n" "pop %edx\n" "pop %ecx\n" "pop %ebx\n" "ret\n" #else #error Unsupported target platform #endif ".popsection\n" ); void ReturnFromCloneSyscall(SecureMem::Args *secureMem) { // TODO(mseaborn): Call sigreturn() to unblock signals. #if defined(__x86_64__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->rsi; // Account for the x86-64 red zone adjustment that our syscall // interceptor does when returning from the system call. stack = (void**) ((char*) stack - 128); *--stack = secureMem->ret; *--stack = secureMem->r15; *--stack = secureMem->r14; *--stack = secureMem->r13; *--stack = secureMem->r12; *--stack = secureMem->r11; *--stack = secureMem->r10; *--stack = secureMem->r9; *--stack = secureMem->r8; *--stack = secureMem->rdi; *--stack = secureMem->rsi; *--stack = secureMem->rdx; *--stack = secureMem->rcx; *--stack = secureMem->rbx; *--stack = secureMem->rbp; asm("mov %0, %%rsp\n" "pop %%rbp\n" "pop %%rbx\n" "pop %%rcx\n" "pop %%rdx\n" "pop %%rsi\n" "pop %%rdi\n" "pop %%r8\n" "pop %%r9\n" "pop %%r10\n" "pop %%r11\n" "pop %%r12\n" "pop %%r13\n" "pop %%r14\n" "pop %%r15\n" "mov $0, %%rax\n" "ret\n" : : "m"(stack)); #elif defined(__i386__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->ecx; *--stack = secureMem->ret; *--stack = secureMem->ebp; *--stack = secureMem->edi; *--stack = secureMem->esi; *--stack = secureMem->edx; *--stack = secureMem->ecx; *--stack = secureMem->ebx; asm("mov %0, %%esp\n" "pop %%ebx\n" "pop %%ecx\n" "pop %%edx\n" "pop %%esi\n" "pop %%edi\n" "pop %%ebp\n" "mov $0, %%eax\n" "ret\n" : : "m"(stack)); #else #error Unsupported target platform #endif } void InitCustomTLS(void *addr) { Sandbox::SysCalls sys; #if defined(__x86_64__) int rc = sys.arch_prctl(ARCH_SET_GS, addr); assert(rc == 0); #elif defined(__i386__) struct user_desc u; u.entry_number = (typeof u.entry_number)-1; u.base_addr = (long) addr; u.limit = 0xfffff; u.seg_32bit = 1; u.contents = 0; u.read_exec_only = 0; u.limit_in_pages = 1; u.seg_not_present = 0; u.useable = 1; int rc = sys.set_thread_area(&u); assert(rc == 0); asm volatile("movw %w0, %%fs" : : "q"(8 * u.entry_number + 3)); #else #error Unsupported target platform #endif } void UnlockSyscallMutex() { Sandbox::SysCalls sys; // TODO(mseaborn): Use clone() to be the same as trusted_thread.cc. int pid = sys.fork(); assert(pid >= 0); if (pid == 0) { int rc = sys.mprotect(&Sandbox::syscall_mutex_, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); Mutex::unlockMutex(&Sandbox::syscall_mutex_); sys._exit(0); } int status; int rc = sys.waitpid(pid, &status, 0); assert(rc == pid); assert(status == 0); } // Allocate a stack that is never freed. char *AllocateStack() { Sandbox::SysCalls sys; int stack_size = 0x1000; #if defined(__i386__) void *stack = sys.mmap2(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #else void *stack = sys.mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #endif assert(stack != MAP_FAILED); return (char *) stack + stack_size; } int HandleNewThread(void *arg) { SecureMem::Args *secureMem = (SecureMem::Args *) arg; CreateReferenceTrustedThread(secureMem->newSecureMem); ReturnFromCloneSyscall(secureMem); return 0; } struct ThreadArgs { SecureMem::Args *secureMem; int threadFd; }; int TrustedThread(void *arg) { struct ThreadArgs *args = (struct ThreadArgs *) arg; SecureMem::Args *secureMem = args->secureMem; int fd = args->threadFd; Sandbox::SysCalls sys; int sequence_no = 2; while (1) { long syscall_args[7]; memset(syscall_args, 0, sizeof(syscall_args)); int got = sys.read(fd, syscall_args, 4); assert(got == 4); long syscall_result; int sysnum = syscall_args[0]; if (sysnum == -1 || sysnum == -2) { // Syscall where the registers have been checked by the trusted // process, e.g. munmap() ranges must be OK. // Doesn't need extra memory region. assert(secureMem->sequence == sequence_no); sequence_no += 2; if (secureMem->syscallNum == __NR_exit) { assert(sysnum == -2); int rc = sys.close(fd); assert(rc == 0); rc = sys.close(secureMem->threadFdPub); assert(rc == 0); // Make the thread's memory area inaccessible as a sanity check. rc = sys.mprotect(secureMem, 0x2000, PROT_NONE); assert(rc == 0); // Although the thread exit syscall does not read from the // secure memory area, we use the mutex for it to ensure that // the trusted process and trusted thread are synchronised. // We do not want the trusted process to think that the // thread's memory area has been freed while the trusted // thread is still reading from it. UnlockSyscallMutex(); // Fall through to exit the thread. } else if (secureMem->syscallNum == __NR_clone) { assert(sysnum == -2); // Note that HandleNewThread() does UnlockSyscallMutex() for us. #if defined(__x86_64__) long clone_flags = (long) secureMem->rdi; int *pid_ptr = (int *) secureMem->rdx; int *tid_ptr = (int *) secureMem->r10; void *tls_info = secureMem->r8; #elif defined(__i386__) long clone_flags = (long) secureMem->ebx; int *pid_ptr = (int *) secureMem->edx; void *tls_info = secureMem->esi; int *tid_ptr = (int *) secureMem->edi; #else #error Unsupported target platform #endif syscall_result = sys.clone(HandleNewThread, (void *) AllocateStack(), clone_flags, (void *) secureMem, pid_ptr, tls_info, tid_ptr); assert(syscall_result > 0); int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); continue; } memcpy(syscall_args, &secureMem->syscallNum, sizeof(syscall_args)); } else if (sysnum == -3) { // RDTSC request. Send back a dummy answer. int timestamp[2] = {0, 0}; int sent = sys.write(fd, (char *) timestamp, sizeof(timestamp)); assert(sent == 8); continue; } else { int rest_size = sizeof(syscall_args) - sizeof(long); got = sys.read(fd, &syscall_args[1], rest_size); assert(got == rest_size); } syscall_result = DoSyscall(syscall_args); if (sysnum == -2) { // This syscall involves reading from the secure memory area for // the thread. We should only unlock this area when the syscall // has completed. Otherwise, the trusted process might // overwrite the data while the kernel is still reading it. UnlockSyscallMutex(); } int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); } return 0; } void CreateReferenceTrustedThread(SecureMem::Args *secureMem) { // We are in the nascent thread. Sandbox::SysCalls sys; int socks[2]; int rc = sys.socketpair(AF_UNIX, SOCK_STREAM, 0, socks); assert(rc == 0); int threadFdPub = socks[0]; int threadFd = socks[1]; // Create trusted thread. // We omit CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID. int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM; // Assumes that the stack grows down. char *stack_top = AllocateStack() - sizeof(struct ThreadArgs); struct ThreadArgs *thread_args = (struct ThreadArgs *) stack_top; thread_args->threadFd = threadFd; thread_args->secureMem = secureMem; rc = sys.clone(TrustedThread, stack_top, flags, thread_args, NULL, NULL, NULL); assert(rc > 0); // Make the thread state pages usable. rc = sys.mprotect(secureMem, 0x1000, PROT_READ); assert(rc == 0); rc = sys.mprotect(((char *) secureMem) + 0x1000, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); // Using cookie as the start is a little odd because other code in // syscall.c works around this when addressing from %fs. void *tls = (void*) &secureMem->cookie; InitCustomTLS(tls); UnlockSyscallMutex(); int tid = sys.gettid(); assert(tid > 0); // Send the socket FDs to the trusted process. // TODO(mseaborn): Don't duplicate this struct in trusted_process.cc struct { SecureMem::Args* self; int tid; int fdPub; } __attribute__((packed)) data; data.self = secureMem; data.tid = tid; data.fdPub = threadFdPub; bool ok = Sandbox::sendFd(Sandbox::cloneFdPub_, threadFdPub, threadFd, (void *) &data, sizeof(data)); assert(ok); // Wait for the trusted process to fill out the thread state for us. char byte_message; int got = sys.read(threadFdPub, &byte_message, 1); assert(got == 1); assert(byte_message == 0); // Switch to seccomp mode. rc = sys.prctl(PR_SET_SECCOMP, 1); assert(rc == 0); } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/seq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] 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 seq.C /// @brief Subroutines for the PHY SEQ registers /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/seq.H> #include <lib/utils/scom.H> #include <lib/utils/c_str.H> #include <lib/utils/bit_count.H> #include <lib/eff_config/timing.H> using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; namespace mss { namespace seq { /// /// @brief PHY SEQ register exponent helper /// PHY SEQ fields is used as exponent of 2, to calculate the number of MEMINTCLKO clock cycles. /// For example, if TMOD_CYCLES[0:3] = 5, the internal timers use the value 2^5 = 32 MEMINTCLKO /// clock cycles. The maximum value per nibble is ‘A’h. This helper takes a calculated value and returns /// the 'best' exponent. /// @param[in] i_value a value for which to make an exponent /// @return uint64_t right-aligned value to stick in the field /// uint64_t exp_helper( const uint64_t i_value ) { // PHY exponents don't make much sense above this value so we short circuit if possible. constexpr uint64_t MAX_EXP = 0xA; if (i_value >= (1 << MAX_EXP)) { return 0xA; } // If the user passes in 0, let it past. if (i_value == 0) { return 0; } // Find the first bit set. The subtraction from 63 switches from a left-count to a right-count (e.g., 0 (left most // bit) is really bit 63 if you start on the right.) const uint64_t l_first_bit = 63 - first_bit_set(i_value); // If the input is greater than 2^first bit, add one to the first_bit so 2^first_bit >= input // (round up) return l_first_bit + (uint64_t(1 << l_first_bit) < i_value ? 1 : 0); } /// /// @brief reset SEQ_TIMING0 /// @param[in] i_target fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template<> fapi2::ReturnCode reset_timing0( const fapi2::Target<TARGET_TYPE_MCA>& i_target ) { typedef seqTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; // Table 5-324. SEQ Memory Timing Parameter 0 Register Bit Definition // TMOD_CYCLES max(tMRD, tMOD) // TRCD_CYCLES tRCD // TRP_CYCLES tRP // TRFC_CYCLES tRFC uint64_t l_tmod_cycles = 0; uint8_t l_trcd = 0; uint8_t l_trp = 0; uint16_t l_trfc_max = 0; l_tmod_cycles = exp_helper( std::max(mss::tmrd(), mss::tmod(i_target)) ); l_data.insertFromRight<TT::TMOD_CYCLES, TT::TMOD_CYCLES_LEN>(l_tmod_cycles); FAPI_TRY( mss::eff_dram_trcd(i_target, l_trcd) ); l_data.insertFromRight<TT::TRCD_CYCLES, TT::TRCD_CYCLES_LEN>( exp_helper(l_trcd) ); FAPI_TRY( mss::eff_dram_trp(i_target, l_trp) ); l_data.insertFromRight<TT::TRP_CYCLES, TT::TRP_CYCLES_LEN>( exp_helper(l_trp) ); // It's not really clear what to put here. We can have DIMM with different tRFC as they // don't have to be the same (3DS v. SPD for example.) So we'll take the maximum trfc we // find on the DIMM connected to this port. for (const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(i_target)) { uint16_t l_trfc = 0; FAPI_TRY( mss::trfc(d, l_trfc) ); l_trfc_max = std::max(l_trfc_max, l_trfc); } l_data.insertFromRight<TT::TRFC_CYCLES, TT::TRFC_CYCLES_LEN>( exp_helper(l_trfc_max) ); FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING0_REG, l_data) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief reset SEQ_TIMING1 /// @param[in] i_target fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template<> fapi2::ReturnCode reset_timing1( const fapi2::Target<TARGET_TYPE_MCA>& i_target ) { typedef seqTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; // Table 5-325. SEQ Memory Timing Parameter 1 Register // TZQINIT_CYCLES max(tZQINIT,tZQOPER) // TZQCS_CYCLES tZQCS // TWLDQSEN_CYCLES tWLDQSEN // TWRMRD_CYCLES tWLMRD uint64_t l_tzqint = std::max( mss::tzqinit(), mss::tzqoper() ); l_data.insertFromRight<TT::TZQINIT_CYCLES, TT::TZQINIT_CYCLES_LEN>( exp_helper(l_tzqint) ); l_data.insertFromRight<TT::TZQCS_CYCLES, TT::TZQCS_CYCLES_LEN>( exp_helper(mss::tzqcs()) ); l_data.insertFromRight<TT::TWLDQSEN_CYCLES, TT::TWLDQSEN_CYCLES_LEN>( exp_helper(mss::twldqsen()) ); l_data.insertFromRight<TT::TWRMRD_CYCLES, TT::TWRMRD_CYCLES_LEN>( exp_helper(mss::twlmrd()) ); return mss::putScom(i_target, TT::SEQ_TIMING1_REG, l_data); } /// /// @brief reset SEQ_TIMING2 /// @param[in] i_target fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template<> fapi2::ReturnCode reset_timing2( const fapi2::Target<TARGET_TYPE_MCA>& i_target ) { typedef seqTraits<TARGET_TYPE_MCA> TT; // Reset value of SEQ_TIMING2 is lucky 7's - we'll fix up the first nibble with ODT info fapi2::buffer<uint64_t> l_data(0x7777); // Table 5-327. SEQ Memory Timing Parameter 2 Register // TODTLON_OFF_CYCLES max(ODTLon, ODTLoff) uint8_t l_odtlon = 0; uint8_t l_odtloff = 0; uint64_t l_odt = 0; FAPI_TRY( mss::max_dodt_on(i_target, l_odtlon) ); FAPI_TRY( mss::max_dodt_off(i_target, l_odtloff) ); l_odt = std::max( l_odtlon, l_odtloff ); l_data.insertFromRight<TT::TODTLON_OFF_CYCLES, TT::TODTLON_OFF_CYCLES_LEN>( exp_helper(l_odt) ); FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING2_REG, l_data) ); fapi_try_exit: return fapi2::current_err; } } // close namespace seq } // close namespace mss <commit_msg>Fixed CL and timing bugs, unit test augmentations<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/seq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] 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 seq.C /// @brief Subroutines for the PHY SEQ registers /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/seq.H> #include <lib/utils/scom.H> #include <lib/utils/c_str.H> #include <lib/utils/bit_count.H> #include <lib/eff_config/timing.H> using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; namespace mss { namespace seq { /// /// @brief PHY SEQ register exponent helper /// PHY SEQ fields is used as exponent of 2, to calculate the number of MEMINTCLKO clock cycles. /// For example, if TMOD_CYCLES[0:3] = 5, the internal timers use the value 2^5 = 32 MEMINTCLKO /// clock cycles. The maximum value per nibble is ‘A’h. This helper takes a calculated value and returns /// the 'best' exponent. /// @param[in] i_value a value for which to make an exponent /// @return uint64_t right-aligned value to stick in the field /// uint64_t exp_helper( const uint64_t i_value ) { // PHY exponents don't make much sense above this value so we short circuit if possible. constexpr uint64_t MAX_EXP = 0xA; if (i_value >= (1 << MAX_EXP)) { return 0xA; } // If the user passes in 0, let it past. if (i_value == 0) { return 0; } // Find the first bit set. The subtraction from 63 switches from a left-count to a right-count (e.g., 0 (left most // bit) is really bit 63 if you start on the right.) const uint64_t l_first_bit = 63 - first_bit_set(i_value); // If the input is greater than 2^first bit, add one to the first_bit so 2^first_bit >= input // (round up) return l_first_bit + (uint64_t(1 << l_first_bit) < i_value ? 1 : 0); } /// /// @brief reset SEQ_TIMING0 /// @param[in] i_target fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template<> fapi2::ReturnCode reset_timing0( const fapi2::Target<TARGET_TYPE_MCA>& i_target ) { typedef seqTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; // Table 5-324. SEQ Memory Timing Parameter 0 Register Bit Definition // TMOD_CYCLES max(tMRD, tMOD) // TRCD_CYCLES tRCD // TRP_CYCLES tRP // TRFC_CYCLES tRFC uint64_t l_tmod_cycles = 0; uint8_t l_trcd = 0; uint8_t l_trp = 0; uint16_t l_trfc_max = 0; l_tmod_cycles = exp_helper( std::max(mss::tmrd(), mss::tmod(i_target)) ); l_data.insertFromRight<TT::TMOD_CYCLES, TT::TMOD_CYCLES_LEN>(l_tmod_cycles); FAPI_TRY( mss::eff_dram_trcd(i_target, l_trcd) ); l_data.insertFromRight<TT::TRCD_CYCLES, TT::TRCD_CYCLES_LEN>( exp_helper(l_trcd) ); FAPI_TRY( mss::eff_dram_trp(i_target, l_trp) ); l_data.insertFromRight<TT::TRP_CYCLES, TT::TRP_CYCLES_LEN>( exp_helper(l_trp) ); // It's not really clear what to put here. We can have DIMM with different tRFC as they // don't have to be the same (3DS v. SDP for example.) So we'll take the maximum trfc we // find on the DIMM connected to this port. for (const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(i_target)) { // tRFC is for non-3DS, tRFC_slr for 3DS is to the same logical rank, // and tRFC_dlr is to different logical ranks. Unclear which to use. uint16_t l_trfc = 0; uint8_t l_trfc_dlr = 0; // tRFC (or tRFC_slr) will retrieve a value for 3DS or non-3DS // tRFC_dlr is only set for 3DS (should be 0 otherwise) // so we opt to take the more aggressive timing, // means less chance of data being corrupted FAPI_TRY( mss::eff_dram_trfc(d, l_trfc) ); FAPI_TRY( mss::eff_dram_trfc_dlr(d, l_trfc_dlr) ); { // cast needed for template deduction of std::max() // HB doesn't support using std::min() with initializer lists const uint16_t l_trfc_3ds_min = std::min(l_trfc, static_cast<uint16_t>(l_trfc_dlr)); l_trfc_max = std::min( l_trfc_3ds_min, l_trfc_max); } } l_data.insertFromRight<TT::TRFC_CYCLES, TT::TRFC_CYCLES_LEN>( exp_helper(l_trfc_max) ); FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING0_REG, l_data) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief reset SEQ_TIMING1 /// @param[in] i_target fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template<> fapi2::ReturnCode reset_timing1( const fapi2::Target<TARGET_TYPE_MCA>& i_target ) { typedef seqTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; // Table 5-325. SEQ Memory Timing Parameter 1 Register // TZQINIT_CYCLES max(tZQINIT,tZQOPER) // TZQCS_CYCLES tZQCS // TWLDQSEN_CYCLES tWLDQSEN // TWRMRD_CYCLES tWLMRD uint64_t l_tzqint = std::max( mss::tzqinit(), mss::tzqoper() ); l_data.insertFromRight<TT::TZQINIT_CYCLES, TT::TZQINIT_CYCLES_LEN>( exp_helper(l_tzqint) ); l_data.insertFromRight<TT::TZQCS_CYCLES, TT::TZQCS_CYCLES_LEN>( exp_helper(mss::tzqcs()) ); l_data.insertFromRight<TT::TWLDQSEN_CYCLES, TT::TWLDQSEN_CYCLES_LEN>( exp_helper(mss::twldqsen()) ); l_data.insertFromRight<TT::TWRMRD_CYCLES, TT::TWRMRD_CYCLES_LEN>( exp_helper(mss::twlmrd()) ); return mss::putScom(i_target, TT::SEQ_TIMING1_REG, l_data); } /// /// @brief reset SEQ_TIMING2 /// @param[in] i_target fapi2 target of the port /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template<> fapi2::ReturnCode reset_timing2( const fapi2::Target<TARGET_TYPE_MCA>& i_target ) { typedef seqTraits<TARGET_TYPE_MCA> TT; // Reset value of SEQ_TIMING2 is lucky 7's - we'll fix up the first nibble with ODT info fapi2::buffer<uint64_t> l_data(0x7777); // Table 5-327. SEQ Memory Timing Parameter 2 Register // TODTLON_OFF_CYCLES max(ODTLon, ODTLoff) uint8_t l_odtlon = 0; uint8_t l_odtloff = 0; uint64_t l_odt = 0; FAPI_TRY( mss::max_dodt_on(i_target, l_odtlon) ); FAPI_TRY( mss::max_dodt_off(i_target, l_odtloff) ); l_odt = std::max( l_odtlon, l_odtloff ); l_data.insertFromRight<TT::TODTLON_OFF_CYCLES, TT::TODTLON_OFF_CYCLES_LEN>( exp_helper(l_odt) ); FAPI_TRY( mss::putScom(i_target, TT::SEQ_TIMING2_REG, l_data) ); fapi_try_exit: return fapi2::current_err; } } // close namespace seq } // close namespace mss <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/common/rcw_settings.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] 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 raw_cards.H /// @brief Raw card data structure /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef _MSS_RAW_CARDS_H_ #define _MSS_RAW_CARDS_H_ #include <fapi2.H> #include <cstdint> #include <vector> namespace mss { /// /// @brief raw card VBU settings /// @note contains RCD settings for hard-coded values /// that are not application specific. /// Application specific settings are dervied in eff_config struct rcw_settings { uint64_t iv_rc00; uint64_t iv_rc01; /// /// @brief default ctor /// rcw_settings() = default; /// /// @brief Equality operator /// @param[in] i_rhs the right-hand side of the == operation /// @return true iff both raw_cards are equal /// inline bool operator==(const rcw_settings& i_rhs) const { // Betting this is faster than all the conditionals ... return (memcmp(this, &i_rhs, sizeof(rcw_settings)) == 0); } /// /// @brief Logical not operator /// @param[in] i_rhs the right-hand side of the != operation /// @return true iff both raw_cards are not equal /// inline bool operator!=(const rcw_settings& i_rhs) const { // Betting this is faster than all the conditionals ... return !(*this == i_rhs); } /// /// @brief ctor /// @param[in] i_rc00 setting for register control word (RC00) /// @param[in] i_rc01 setting for register control word (RC01) /// constexpr rcw_settings( const uint64_t i_rc00, const uint64_t i_rc01) : iv_rc00(i_rc00), iv_rc01(i_rc01) {} /// /// @brief default dtor /// ~rcw_settings() = default; }; }// mss #endif //_MSS_RAW_CARDS_H_ <commit_msg>Remove mss::c_str dependency for SPD decoder for future reuse<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/common/rcw_settings.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] 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 raw_cards.H /// @brief Raw card data structure /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Stephen Glancy <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef _MSS_RAW_CARDS_H_ #define _MSS_RAW_CARDS_H_ #include <fapi2.H> #include <cstdint> #include <vector> namespace mss { /// /// @brief raw card VBU settings /// @note contains RCD settings for hard-coded values /// that are not application specific. /// Application specific settings are dervied in eff_config struct rcw_settings { uint64_t iv_rc00; uint64_t iv_rc01; /// /// @brief default ctor /// rcw_settings() = default; /// /// @brief Equality operator /// @param[in] i_rhs the right-hand side of the == operation /// @return true iff both raw_cards are equal /// inline bool operator==(const rcw_settings& i_rhs) const { // Betting this is faster than all the conditionals ... return (memcmp(this, &i_rhs, sizeof(rcw_settings)) == 0); } /// /// @brief Logical not operator /// @param[in] i_rhs the right-hand side of the != operation /// @return true iff both raw_cards are not equal /// inline bool operator!=(const rcw_settings& i_rhs) const { // Betting this is faster than all the conditionals ... return !(*this == i_rhs); } /// /// @brief ctor /// @param[in] i_rc00 setting for register control word (RC00) /// @param[in] i_rc01 setting for register control word (RC01) /// constexpr rcw_settings( const uint64_t i_rc00, const uint64_t i_rc01) : iv_rc00(i_rc00), iv_rc01(i_rc01) {} /// /// @brief default dtor /// ~rcw_settings() = default; }; }// mss #endif //_MSS_RAW_CARDS_H_ <|endoftext|>
<commit_before>#include <iostream> #include<stdlib.h> #include<map> using namespace std; void print_num(map<char,int>M) { int num=rand()%100; cout<<num<<endl; int count=0; map<char,int>:: iterator it; for(it=M.begin();it!=M.end();it++) { count+=it->second; if(num>0 && num<=count) cout<<it->first; } } int main() { map<char,int>M; M['A']=10; M['B']=20; M['C']=30; M['D']=40; print_num(M); return 0; } <commit_msg>Adding wtd rand<commit_after>#include <iostream> #include <stdlib.h> #include <map> using namespace std; void print_num(map<char,int>M) { int num = rand()%100; //45 // cout<<num<<endl; int ub=0; map<char,int>:: iterator it; int lb = 0; for(it=M.begin();it!=M.end();it++) { ub += it->second; if(num >= lb && num < ub) { cout<<it->first; return; } lb = ub; } } int main() { map<char,int>M; M['A']=10; M['B']=20; M['C']=30; M['D']=40; //int num=25; print_num(M); return 0; } <|endoftext|>
<commit_before>#ifndef __UHD_QUEUE_HPP__ #define __UHD_QUEUE_HPP__ #include <queue> #include <mutex> #include <condition_variable> namespace uhd { template <typename T> class Queue { public: Queue() {} void push(T &&value); void push(const T &value); T pop(); void clear(); bool empty(); size_t size(); private: std::mutex _lock; std::condition_variable _notify; std::queue<T> _queue; }; template <typename T> void Queue<T>::push(T &&value) { std::lock_guard<std::mutex> lg(_lock); _queue.push(std::move(value)); _notify.notify_one(); } template <typename T> T Queue<T>::pop() { std::unique_lock<std::mutex> lg(_lock); while (_queue.empty()) _notify.wait(lg); T value(std::move(_queue.front())); _queue.pop(); return value; } template <typename T> void Queue<T>::clear() { std::lock_guard<std::mutex> lg(_lock); while (!_queue.empty()) _queue.pop(); } template <typename T> bool Queue<T>::empty() { std::lock_guard<std::mutex> lg(_lock); return _queue.empty(); } template <typename T> size_t Queue<T>::size() { std::lock_guard<std::mutex> lg(_lock); return _queue.size(); } } #endif /** __UHD_QUEUE_HPP__ **/ <commit_msg>uhd_queue.hpp: add push(const T&)<commit_after>#ifndef __UHD_QUEUE_HPP__ #define __UHD_QUEUE_HPP__ #include <queue> #include <mutex> #include <condition_variable> namespace uhd { template <typename T> class Queue { public: Queue() {} void push(const T &value); void push(T &&value); T pop(); void clear(); bool empty(); size_t size(); private: std::mutex _lock; std::condition_variable _notify; std::queue<T> _queue; }; template <typename T> void Queue<T>::push(const T &value) { std::lock_guard<std::mutex> lg(_lock); _queue.push(value); _notify.notify_one(); } template <typename T> void Queue<T>::push(T &&value) { std::lock_guard<std::mutex> lg(_lock); _queue.push(std::move(value)); _notify.notify_one(); } template <typename T> T Queue<T>::pop() { std::unique_lock<std::mutex> lg(_lock); while (_queue.empty()) _notify.wait(lg); T value(std::move(_queue.front())); _queue.pop(); return value; } template <typename T> void Queue<T>::clear() { std::lock_guard<std::mutex> lg(_lock); while (!_queue.empty()) _queue.pop(); } template <typename T> bool Queue<T>::empty() { std::lock_guard<std::mutex> lg(_lock); return _queue.empty(); } template <typename T> size_t Queue<T>::size() { std::lock_guard<std::mutex> lg(_lock); return _queue.size(); } } #endif /** __UHD_QUEUE_HPP__ **/ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDijkstraGraphGeodesicPath.cxx Language: C++ Date: $Date$ Version: $Revision$ Made by Rasmus Paulsen email: rrp(at)imm.dtu.dk web: www.imm.dtu.dk/~rrp/VTK This class is not mature enough to enter the official VTK release. =========================================================================*/ #include "vtkDijkstraGraphGeodesicPath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkFloatArray.h" #include "vtkObjectFactory.h" #include "vtkExecutive.h" #include "vtkMath.h" #include "vtkIdList.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkPolyData.h" #include "vtkPoints.h" #include "vtkPointData.h" #include "vtkCellArray.h" vtkCxxRevisionMacro(vtkDijkstraGraphGeodesicPath, "1.2"); vtkStandardNewMacro(vtkDijkstraGraphGeodesicPath); //---------------------------------------------------------------------------- vtkDijkstraGraphGeodesicPath::vtkDijkstraGraphGeodesicPath() { this->IdList = vtkIdList::New(); this->d = vtkFloatArray::New(); this->pre = vtkIntArray::New(); this->f = vtkIntArray::New(); this->s = vtkIntArray::New(); this->H = vtkIntArray::New(); this->p = vtkIntArray::New(); this->Hsize = 0; this->StartVertex = 0; this->EndVertex = 0; this->StopWhenEndReached = 0; this->UseScalarWeights = 0; this->Adj = NULL; this->n = 0; this->AdjacencyGraphSize = 0; } //---------------------------------------------------------------------------- vtkDijkstraGraphGeodesicPath::~vtkDijkstraGraphGeodesicPath() { if (this->IdList) this->IdList->Delete(); if (this->d) this->d->Delete(); if (this->pre) this->pre->Delete(); if (this->f) this->f->Delete(); if (this->s) this->s->Delete(); if (this->H) this->H->Delete(); if (this->p) this->p->Delete(); DeleteAdjacency(); } //---------------------------------------------------------------------------- int vtkDijkstraGraphGeodesicPath::RequestData( vtkInformation * vtkNotUsed( request ), vtkInformationVector ** inputVector, vtkInformationVector * outputVector) { vtkInformation * inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkPolyData *input = vtkPolyData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input) { return 0; } vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input) { return 0; } this->Initialize(); this->ShortestPath(this->StartVertex, this->EndVertex); this->TraceShortestPath(input, output, this->StartVertex, this->EndVertex); return 1; } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::Initialize() { vtkPolyData *input = vtkPolyData::SafeDownCast( this->GetExecutive()->GetInputData(0, 0)); this->BuildAdjacency( input ); this->IdList->Reset(); this->n = input->GetNumberOfPoints(); this->d->SetNumberOfComponents(1); this->d->SetNumberOfTuples(this->n); this->pre->SetNumberOfComponents(1); this->pre->SetNumberOfTuples(this->n); this->f->SetNumberOfComponents(1); this->f->SetNumberOfTuples(this->n); this->s->SetNumberOfComponents(1); this->s->SetNumberOfTuples(this->n); this->p->SetNumberOfComponents(1); this->p->SetNumberOfTuples(this->n); // The heap has elements from 1 to n this->H->SetNumberOfComponents(1); this->H->SetNumberOfTuples(this->n+1); this->Hsize = 0; } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::DeleteAdjacency() { const int npoints = this->AdjacencyGraphSize; if (this->Adj) { for (int i = 0; i < npoints; i++) { this->Adj[i]->Delete(); } delete [] this->Adj; } this->Adj = NULL; } //---------------------------------------------------------------------------- // The edge cost function should be implemented as a callback function to // allow more advanced weighting double vtkDijkstraGraphGeodesicPath::EdgeCost( vtkPolyData *pd, vtkIdType u, vtkIdType v) { double p1[3]; pd->GetPoint(u,p1); double p2[3]; pd->GetPoint(v,p2); double w = sqrt(vtkMath::Distance2BetweenPoints(p1, p2)); if (this->UseScalarWeights) { // Note this edge cost is not symmetric! vtkFloatArray *scalars = (vtkFloatArray*)pd->GetPointData()->GetScalars(); // float s1 = scalars->GetValue(u); float s2 = scalars->GetValue(v); if (s2) { w /= (s2*s2); } } return w; } //---------------------------------------------------------------------------- // This is probably a horribly inefficient way to do it. void vtkDijkstraGraphGeodesicPath::BuildAdjacency(vtkPolyData *pd) { int i; int npoints = pd->GetNumberOfPoints(); int ncells = pd->GetNumberOfCells(); this->DeleteAdjacency(); this->Adj = new vtkIdList*[npoints]; // Remember size, so it can be deleted again this->AdjacencyGraphSize = npoints; for (i = 0; i < npoints; i++) { this->Adj[i] = vtkIdList::New(); } for (i = 0; i < ncells; i++) { // Possible types // VTK_VERTEX, VTK_POLY_VERTEX, VTK_LINE, // VTK_POLY_LINE,VTK_TRIANGLE, VTK_QUAD, // VTK_POLYGON, or VTK_TRIANGLE_STRIP. vtkIdType ctype = pd->GetCellType(i); // Until now only handle polys and triangles // TODO: All types if (ctype == VTK_POLYGON || ctype == VTK_TRIANGLE || ctype == VTK_LINE) { vtkIdType *pts; vtkIdType npts; pd->GetCellPoints (i, npts, pts); vtkIdType u = pts[0]; vtkIdType v = pts[npts-1]; Adj[u]->InsertUniqueId(v); Adj[v]->InsertUniqueId(u); for (int j = 0; j < npts-1; j++) { vtkIdType u1 = pts[j]; vtkIdType v1 = pts[j+1]; Adj[u1]->InsertUniqueId(v1); Adj[v1]->InsertUniqueId(u1); } } } } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::TraceShortestPath( vtkPolyData *inPd, vtkPolyData *outPd, vtkIdType startv, vtkIdType endv) { vtkPoints *points = vtkPoints::New(); vtkCellArray *lines = vtkCellArray::New(); // n is far to many. Adjusted later lines->InsertNextCell(this->n); // trace backward int npoints = 0; int v = endv; double pt[3]; vtkIdType id; while (v != startv) { IdList->InsertNextId(v); inPd->GetPoint(v,pt); id = points->InsertNextPoint(pt); lines->InsertCellPoint(id); npoints++; v = this->pre->GetValue(v); } this->IdList->InsertNextId(v); inPd->GetPoint(v,pt); id = points->InsertNextPoint(pt); lines->InsertCellPoint(id); npoints++; lines->UpdateCellCount(npoints); outPd->SetPoints(points); points->Delete(); outPd->SetLines(lines); lines->Delete(); } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::InitSingleSource(int startv) { for (int v = 0; v < this->n; v++) { // d will be updated with first visit of vertex this->d->SetValue(v, -1); this->pre->SetValue(v, -1); this->s->SetValue(v, 0); this->f->SetValue(v, 0); } this->d->SetValue(startv, 0); } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::Relax(int u, int v, double w) { if (this->d->GetValue(v) > this->d->GetValue(u) + w) { this->d->SetValue(v, this->d->GetValue(u) + w); this->pre->SetValue(v, u); this->HeapDecreaseKey(v); } } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::ShortestPath(int startv, int endv) { vtkPolyData *input = vtkPolyData::SafeDownCast( this->GetExecutive()->GetInputData(0, 0)); int i, u, v; this->InitSingleSource(startv); this->HeapInsert(startv); this->f->SetValue(startv, 1); int stop = 0; while ((u = this->HeapExtractMin()) >= 0 && !stop) { // u is now in s since the shortest path to u is determined this->s->SetValue(u, 1); // remove u from the front set this->f->SetValue(u, 0); if (u == endv && this->StopWhenEndReached) stop = 1; // Update all vertices v adjacent to u for (i = 0; i < this->Adj[u]->GetNumberOfIds(); i++) { v = this->Adj[u]->GetId(i); // s is the set of vertices with determined shortest path...do not use them again if (!this->s->GetValue(v)) { // Only relax edges where the end is not in s and edge is in the front set double w = this->EdgeCost(input, u, v); if (this->f->GetValue(v)) { Relax(u, v, w); } // add edge v to front set else { this->f->SetValue(v, 1); this->d->SetValue(v, this->d->GetValue(u) + w); // Set Predecessor of v to be u this->pre->SetValue(v, u); this->HeapInsert(v); } } } } } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::Heapify(int i) { // left node int l = i * 2; // right node int r = i * 2 + 1; int smallest = -1; // The value of element v is d(v) // the heap stores the vertex numbers if ( l <= this->Hsize && (this->d->GetValue(this->H->GetValue(l)) < this->d->GetValue(this->H->GetValue(i)))) { smallest = l; } else { smallest = i; } if ( r <= this->Hsize && (this->d->GetValue(this->H->GetValue(r)) < this->d->GetValue(this->H->GetValue(smallest)))) { smallest = r; } if (smallest != i) { int t = this->H->GetValue(i); this->H->SetValue(i, this->H->GetValue(smallest)); // where is H(i) this->p->SetValue(this->H->GetValue(i), i); // H and p is kinda inverse this->H->SetValue(smallest, t); this->p->SetValue(t, smallest); this->Heapify(smallest); } } //---------------------------------------------------------------------------- // Insert vertex v. Weight is given in d(v) // H has indices 1..n void vtkDijkstraGraphGeodesicPath::HeapInsert(int v) { if (this->Hsize >= this->H->GetNumberOfTuples()-1) return; this->Hsize++; int i = this->Hsize; while (i > 1 && (this->d->GetValue(this->H->GetValue(i/2)) > this->d->GetValue(v))) { this->H->SetValue(i, this->H->GetValue(i/2)); this->p->SetValue(this->H->GetValue(i), i); i /= 2; } // H and p is kinda inverse this->H->SetValue(i, v); this->p->SetValue(v, i); } //---------------------------------------------------------------------------- int vtkDijkstraGraphGeodesicPath::HeapExtractMin() { if (this->Hsize == 0) return -1; int minv = this->H->GetValue(1); this->p->SetValue(minv, -1); this->H->SetValue(1, this->H->GetValue(this->Hsize)); this->p->SetValue(this->H->GetValue(1), 1); this->Hsize--; this->Heapify(1); return minv; } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::HeapDecreaseKey(int v) { // where in H is vertex v int i = this->p->GetValue(v); if (i < 1 || i > this->Hsize) return; while (i > 1 && this->d->GetValue(this->H->GetValue(i/2)) > this->d->GetValue(v)) { this->H->SetValue(i, this->H->GetValue(i/2)); this->p->SetValue(this->H->GetValue(i), i); i /= 2; } // H and p is kinda inverse this->H->SetValue(i, v); this->p->SetValue(v, i); } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); // Add all members later } <commit_msg>COMP: try to get rid of the numerical issue on borland.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDijkstraGraphGeodesicPath.cxx Language: C++ Date: $Date$ Version: $Revision$ Made by Rasmus Paulsen email: rrp(at)imm.dtu.dk web: www.imm.dtu.dk/~rrp/VTK This class is not mature enough to enter the official VTK release. =========================================================================*/ #include "vtkDijkstraGraphGeodesicPath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkFloatArray.h" #include "vtkObjectFactory.h" #include "vtkExecutive.h" #include "vtkMath.h" #include "vtkIdList.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkPolyData.h" #include "vtkPoints.h" #include "vtkPointData.h" #include "vtkCellArray.h" vtkCxxRevisionMacro(vtkDijkstraGraphGeodesicPath, "1.3"); vtkStandardNewMacro(vtkDijkstraGraphGeodesicPath); //---------------------------------------------------------------------------- vtkDijkstraGraphGeodesicPath::vtkDijkstraGraphGeodesicPath() { this->IdList = vtkIdList::New(); this->d = vtkFloatArray::New(); this->pre = vtkIntArray::New(); this->f = vtkIntArray::New(); this->s = vtkIntArray::New(); this->H = vtkIntArray::New(); this->p = vtkIntArray::New(); this->Hsize = 0; this->StartVertex = 0; this->EndVertex = 0; this->StopWhenEndReached = 0; this->UseScalarWeights = 0; this->Adj = NULL; this->n = 0; this->AdjacencyGraphSize = 0; } //---------------------------------------------------------------------------- vtkDijkstraGraphGeodesicPath::~vtkDijkstraGraphGeodesicPath() { if (this->IdList) this->IdList->Delete(); if (this->d) this->d->Delete(); if (this->pre) this->pre->Delete(); if (this->f) this->f->Delete(); if (this->s) this->s->Delete(); if (this->H) this->H->Delete(); if (this->p) this->p->Delete(); DeleteAdjacency(); } //---------------------------------------------------------------------------- int vtkDijkstraGraphGeodesicPath::RequestData( vtkInformation * vtkNotUsed( request ), vtkInformationVector ** inputVector, vtkInformationVector * outputVector) { vtkInformation * inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkPolyData *input = vtkPolyData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input) { return 0; } vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input) { return 0; } this->Initialize(); this->ShortestPath(this->StartVertex, this->EndVertex); this->TraceShortestPath(input, output, this->StartVertex, this->EndVertex); return 1; } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::Initialize() { vtkPolyData *input = vtkPolyData::SafeDownCast( this->GetExecutive()->GetInputData(0, 0)); this->BuildAdjacency( input ); this->IdList->Reset(); this->n = input->GetNumberOfPoints(); this->d->SetNumberOfComponents(1); this->d->SetNumberOfTuples(this->n); this->pre->SetNumberOfComponents(1); this->pre->SetNumberOfTuples(this->n); this->f->SetNumberOfComponents(1); this->f->SetNumberOfTuples(this->n); this->s->SetNumberOfComponents(1); this->s->SetNumberOfTuples(this->n); this->p->SetNumberOfComponents(1); this->p->SetNumberOfTuples(this->n); // The heap has elements from 1 to n this->H->SetNumberOfComponents(1); this->H->SetNumberOfTuples(this->n+1); this->Hsize = 0; } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::DeleteAdjacency() { const int npoints = this->AdjacencyGraphSize; if (this->Adj) { for (int i = 0; i < npoints; i++) { this->Adj[i]->Delete(); } delete [] this->Adj; } this->Adj = NULL; } //---------------------------------------------------------------------------- // The edge cost function should be implemented as a callback function to // allow more advanced weighting double vtkDijkstraGraphGeodesicPath::EdgeCost( vtkPolyData *pd, vtkIdType u, vtkIdType v) { double p1[3]; pd->GetPoint(u,p1); double p2[3]; pd->GetPoint(v,p2); double w = sqrt(vtkMath::Distance2BetweenPoints(p1, p2)); if (this->UseScalarWeights) { // Note this edge cost is not symmetric! vtkFloatArray *scalars = (vtkFloatArray*)pd->GetPointData()->GetScalars(); // float s1 = scalars->GetValue(u); float s2 = scalars->GetValue(v); double wt = ((double)(s2))*((double)(s2)); if (wt != 0.0) { w /= wt; } } return w; } //---------------------------------------------------------------------------- // This is probably a horribly inefficient way to do it. void vtkDijkstraGraphGeodesicPath::BuildAdjacency(vtkPolyData *pd) { int i; int npoints = pd->GetNumberOfPoints(); int ncells = pd->GetNumberOfCells(); this->DeleteAdjacency(); this->Adj = new vtkIdList*[npoints]; // Remember size, so it can be deleted again this->AdjacencyGraphSize = npoints; for (i = 0; i < npoints; i++) { this->Adj[i] = vtkIdList::New(); } for (i = 0; i < ncells; i++) { // Possible types // VTK_VERTEX, VTK_POLY_VERTEX, VTK_LINE, // VTK_POLY_LINE,VTK_TRIANGLE, VTK_QUAD, // VTK_POLYGON, or VTK_TRIANGLE_STRIP. vtkIdType ctype = pd->GetCellType(i); // Until now only handle polys and triangles // TODO: All types if (ctype == VTK_POLYGON || ctype == VTK_TRIANGLE || ctype == VTK_LINE) { vtkIdType *pts; vtkIdType npts; pd->GetCellPoints (i, npts, pts); vtkIdType u = pts[0]; vtkIdType v = pts[npts-1]; Adj[u]->InsertUniqueId(v); Adj[v]->InsertUniqueId(u); for (int j = 0; j < npts-1; j++) { vtkIdType u1 = pts[j]; vtkIdType v1 = pts[j+1]; Adj[u1]->InsertUniqueId(v1); Adj[v1]->InsertUniqueId(u1); } } } } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::TraceShortestPath( vtkPolyData *inPd, vtkPolyData *outPd, vtkIdType startv, vtkIdType endv) { vtkPoints *points = vtkPoints::New(); vtkCellArray *lines = vtkCellArray::New(); // n is far to many. Adjusted later lines->InsertNextCell(this->n); // trace backward int npoints = 0; int v = endv; double pt[3]; vtkIdType id; while (v != startv) { IdList->InsertNextId(v); inPd->GetPoint(v,pt); id = points->InsertNextPoint(pt); lines->InsertCellPoint(id); npoints++; v = this->pre->GetValue(v); } this->IdList->InsertNextId(v); inPd->GetPoint(v,pt); id = points->InsertNextPoint(pt); lines->InsertCellPoint(id); npoints++; lines->UpdateCellCount(npoints); outPd->SetPoints(points); points->Delete(); outPd->SetLines(lines); lines->Delete(); } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::InitSingleSource(int startv) { for (int v = 0; v < this->n; v++) { // d will be updated with first visit of vertex this->d->SetValue(v, -1); this->pre->SetValue(v, -1); this->s->SetValue(v, 0); this->f->SetValue(v, 0); } this->d->SetValue(startv, 0); } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::Relax(int u, int v, double w) { if (this->d->GetValue(v) > this->d->GetValue(u) + w) { this->d->SetValue(v, this->d->GetValue(u) + w); this->pre->SetValue(v, u); this->HeapDecreaseKey(v); } } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::ShortestPath(int startv, int endv) { vtkPolyData *input = vtkPolyData::SafeDownCast( this->GetExecutive()->GetInputData(0, 0)); int i, u, v; this->InitSingleSource(startv); this->HeapInsert(startv); this->f->SetValue(startv, 1); int stop = 0; while ((u = this->HeapExtractMin()) >= 0 && !stop) { // u is now in s since the shortest path to u is determined this->s->SetValue(u, 1); // remove u from the front set this->f->SetValue(u, 0); if (u == endv && this->StopWhenEndReached) stop = 1; // Update all vertices v adjacent to u for (i = 0; i < this->Adj[u]->GetNumberOfIds(); i++) { v = this->Adj[u]->GetId(i); // s is the set of vertices with determined shortest path...do not use them again if (!this->s->GetValue(v)) { // Only relax edges where the end is not in s and edge is in the front set double w = this->EdgeCost(input, u, v); if (this->f->GetValue(v)) { Relax(u, v, w); } // add edge v to front set else { this->f->SetValue(v, 1); this->d->SetValue(v, this->d->GetValue(u) + w); // Set Predecessor of v to be u this->pre->SetValue(v, u); this->HeapInsert(v); } } } } } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::Heapify(int i) { // left node int l = i * 2; // right node int r = i * 2 + 1; int smallest = -1; // The value of element v is d(v) // the heap stores the vertex numbers if ( l <= this->Hsize && (this->d->GetValue(this->H->GetValue(l)) < this->d->GetValue(this->H->GetValue(i)))) { smallest = l; } else { smallest = i; } if ( r <= this->Hsize && (this->d->GetValue(this->H->GetValue(r)) < this->d->GetValue(this->H->GetValue(smallest)))) { smallest = r; } if (smallest != i) { int t = this->H->GetValue(i); this->H->SetValue(i, this->H->GetValue(smallest)); // where is H(i) this->p->SetValue(this->H->GetValue(i), i); // H and p is kinda inverse this->H->SetValue(smallest, t); this->p->SetValue(t, smallest); this->Heapify(smallest); } } //---------------------------------------------------------------------------- // Insert vertex v. Weight is given in d(v) // H has indices 1..n void vtkDijkstraGraphGeodesicPath::HeapInsert(int v) { if (this->Hsize >= this->H->GetNumberOfTuples()-1) return; this->Hsize++; int i = this->Hsize; while (i > 1 && (this->d->GetValue(this->H->GetValue(i/2)) > this->d->GetValue(v))) { this->H->SetValue(i, this->H->GetValue(i/2)); this->p->SetValue(this->H->GetValue(i), i); i /= 2; } // H and p is kinda inverse this->H->SetValue(i, v); this->p->SetValue(v, i); } //---------------------------------------------------------------------------- int vtkDijkstraGraphGeodesicPath::HeapExtractMin() { if (this->Hsize == 0) return -1; int minv = this->H->GetValue(1); this->p->SetValue(minv, -1); this->H->SetValue(1, this->H->GetValue(this->Hsize)); this->p->SetValue(this->H->GetValue(1), 1); this->Hsize--; this->Heapify(1); return minv; } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::HeapDecreaseKey(int v) { // where in H is vertex v int i = this->p->GetValue(v); if (i < 1 || i > this->Hsize) return; while (i > 1 && this->d->GetValue(this->H->GetValue(i/2)) > this->d->GetValue(v)) { this->H->SetValue(i, this->H->GetValue(i/2)); this->p->SetValue(this->H->GetValue(i), i); i /= 2; } // H and p is kinda inverse this->H->SetValue(i, v); this->p->SetValue(v, i); } //---------------------------------------------------------------------------- void vtkDijkstraGraphGeodesicPath::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); // Add all members later } <|endoftext|>
<commit_before>#include "user.h" #include "process.h" #include <shlwapi.h> #include <io.h> #include <stdio.h> #include <fcntl.h> #include <iostream> int wmain() { try { UserManager user_manager; JobbedProcessManager process; WCHAR szDirectory[MAX_PATH]; GetModuleFileName(nullptr, szDirectory, MAX_PATH); *(PathFindFileName(szDirectory) - 1) = '\0'; process.time(2).memory(65536 * 1024).processes(1).command(L"hello.exe").directory(szDirectory) .withLogin(user_manager.username(), user_manager.password()); process.spawn(); process.stdIn().close(); process.stdErr().close(); int ch, fd = _open_osfhandle((intptr_t) (HANDLE) process.stdOut(), _O_RDONLY); FILE *file = _fdopen(fd, "r"); while ((ch = fgetc(file)) != EOF) putchar(ch); } catch (WindowsException &e) { std::cout << e.what() << '\n'; } }<commit_msg>Prevent double close.<commit_after>#include "user.h" #include "process.h" #include <shlwapi.h> #include <io.h> #include <stdio.h> #include <fcntl.h> #include <iostream> int wmain() { try { UserManager user_manager; JobbedProcessManager process; WCHAR szDirectory[MAX_PATH]; GetModuleFileName(nullptr, szDirectory, MAX_PATH); *(PathFindFileName(szDirectory) - 1) = '\0'; process.time(2).memory(65536 * 1024).processes(1).command(L"hello.exe").directory(szDirectory) .withLogin(user_manager.username(), user_manager.password()); process.spawn(); process.stdIn().close(); process.stdErr().close(); int ch, fd = _open_osfhandle((intptr_t) process.stdOut().detach(), _O_RDONLY); FILE *file = _fdopen(fd, "r"); while ((ch = fgetc(file)) != EOF) putchar(ch); } catch (WindowsException &e) { std::cout << e.what() << '\n'; } }<|endoftext|>
<commit_before>/* * Copyright (C) 2008-2013 J-P Nurmi <[email protected]> * * This test is free, and not covered by LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. By using it you may give me some credits in your * program, but you don't have to. */ #include "messageformatter.h" #include "usermodel.h" #include "session.h" #include <QtTest/QtTest> #include <QtCore/QStringList> static const QString MSG_32_5("Vestibulum eu libero eget metus."); static const QString MSG_64_9("Phasellus enim dui, sodales sed tincidunt quis, ultricies metus."); static const QString MSG_128_19("Ut porttitor volutpat tristique. Aenean semper ligula eget nulla condimentum tempor in quis felis. Sed sem diam, tincidunt amet."); static const QString MSG_256_37("Vestibulum quis lorem velit, a varius augue. Suspendisse risus augue, ultricies at convallis in, elementum in velit. Fusce fermentum congue augue sit amet dapibus. Fusce ultrices urna ut tortor laoreet a aliquet elit lobortis. Suspendisse volutpat posuere."); static const QString MSG_512_75("Nam leo risus, accumsan a sagittis eget, posuere eu velit. Morbi mattis auctor risus, vel consequat massa pulvinar nec. Proin aliquam convallis elit nec egestas. Pellentesque accumsan placerat augue, id volutpat nibh dictum vel. Aenean venenatis varius feugiat. Nullam molestie, ipsum id dignissim vulputate, eros urna vestibulum massa, in vehicula lacus nisi vitae risus. Ut nunc nunc, venenatis a mattis auctor, dictum et sem. Nulla posuere libero ut tortor elementum egestas. Aliquam egestas suscipit posuere."); static const QStringList USERS_100 = QStringList() << "jpnurmi" << "Curabitur" << "nORMAL" << "leo" << "luctus" << "luctus" << "paraply" << "sapien" << "nope" << "vitae" << "where" << "alien" << "urna" << "turpis" << "rea_son" << "alone" << "velit" << "jipsu" << "rutrum" << "DiSCO" << "abort" << "venue" << "__duis__" << "eros" << "adam" << "hendrix" << "liber0" << "Jim" << "Leonardo" << "JiMi" << "justin" << "semper" << "fidelis" << "Excelsior" << "parachute" << "nam" << "nom" << "Lorem" << "risus" << "stereo" << "tv" << "what-ever" << "kill" << "savior" << "[haha]" << "null" << "nill" << "will" << "still" << "ill" << "fill" << "hill" << "bill" << "Lucas" << "metus" << "bitch" << "d0nut" << "perverT" << "br0tha" << "WHYZ" << "Amen" << "hero" << "another" << "other" << "augue" << "Vestibulum" << "quit" << "quis" << "Luis" << "luiz" << "Luigi" << "anus" << "formal" << "f00bar" << "sed" << "sodales" << "phasellus" << "port" << "porttitor" << "absolute" << "varius" << "Marius" << "access" << "ZzZzZz" << "dust" << "up" << "d0wn" << "l3ft" << "r1ght" << "n0ne" << "MeSsAgE" << "FoRmAtTeR" << "c00l" << "_[KiDDO]_" << "yes" << "no" << "never" << "tincidunt" << "ultricies" << "posuere"; class TestMessageFormatter : public MessageFormatter { friend class tst_MessageFormatter; }; class TestUserModel : public UserModel { friend class tst_MessageFormatter; public: TestUserModel(Session* session) : UserModel(session) { } }; class tst_MessageFormatter : public QObject { Q_OBJECT private slots: void testFormatHtml_data(); void testFormatHtml(); private: TestMessageFormatter formatter; }; Q_DECLARE_METATYPE(QStringList) void tst_MessageFormatter::testFormatHtml_data() { qRegisterMetaType<QStringList>(); QStringList USERS_UC; foreach (const QString& user, USERS_100) USERS_UC += user.toUpper(); QTest::addColumn<QString>("message"); QTest::addColumn<QStringList>("users"); QTest::newRow("empty") << QString() << QStringList(); QTest::newRow("32 chars / 5 words / 0 users") << MSG_32_5 << QStringList(); QTest::newRow("32 chars / 5 words / 25 users") << MSG_32_5 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("32 chars / 5 words / 50 users") << MSG_32_5 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("32 chars / 5 words / 75 users") << MSG_32_5 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("32 chars / 5 words / 100 users") << MSG_32_5 << USERS_100; QTest::newRow("32 chars / 5 words / 200 users") << MSG_32_5 << USERS_100 + USERS_UC; QTest::newRow("64 chars / 9 words / 0 users") << MSG_64_9 << QStringList(); QTest::newRow("64 chars / 9 words / 25 users") << MSG_64_9 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("64 chars / 9 words / 50 users") << MSG_64_9 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("64 chars / 9 words / 75 users") << MSG_64_9 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("64 chars / 9 words / 100 users") << MSG_64_9 << USERS_100; QTest::newRow("64 chars / 9 words / 200 users") << MSG_64_9 << USERS_100 + USERS_UC; QTest::newRow("128 chars / 19 words / 0 users") << MSG_128_19 << QStringList(); QTest::newRow("128 chars / 19 words / 25 users") << MSG_128_19 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("128 chars / 19 words / 50 users") << MSG_128_19 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("128 chars / 19 words / 75 users") << MSG_128_19 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("128 chars / 19 words / 100 users") << MSG_128_19 << USERS_100; QTest::newRow("128 chars / 19 words / 200 users") << MSG_128_19 << USERS_100 + USERS_UC; QTest::newRow("256 chars / 37 words / 0 users") << MSG_256_37 << QStringList(); QTest::newRow("256 chars / 37 words / 25 users") << MSG_256_37 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("256 chars / 37 words / 50 users") << MSG_256_37 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("256 chars / 37 words / 75 users") << MSG_256_37 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("256 chars / 37 words / 100 users") << MSG_256_37 << USERS_100; QTest::newRow("256 chars / 37 words / 200 users") << MSG_256_37 << USERS_100 + USERS_UC; QTest::newRow("512 chars / 75 words / 0 users") << MSG_512_75 << QStringList(); QTest::newRow("512 chars / 75 words / 25 users") << MSG_512_75 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("512 chars / 75 words / 50 users") << MSG_512_75 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("512 chars / 75 words / 75 users") << MSG_512_75 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("512 chars / 75 words / 100 users") << MSG_512_75 << USERS_100; QTest::newRow("512 chars / 75 words / 200 users") << MSG_512_75 << USERS_100 + USERS_UC; } void tst_MessageFormatter::testFormatHtml() { QFETCH(QString, message); QFETCH(QStringList, users); Session session; TestUserModel model(&session); model.addUsers(users); QCOMPARE(model.rowCount(), users.count()); IrcMessage dummy; formatter.formatMessage(&dummy, &model); QBENCHMARK { formatter.formatHtml(message); } } QTEST_MAIN(tst_MessageFormatter) #include "tst_messageformatter.moc" <commit_msg>Fix tst_messageformatter build failure<commit_after>/* * Copyright (C) 2008-2013 J-P Nurmi <[email protected]> * * This test is free, and not covered by LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. By using it you may give me some credits in your * program, but you don't have to. */ #include "messageformatter.h" #include "usermodel.h" #include "session.h" #include <QtTest/QtTest> #include <QtCore/QStringList> static const QString MSG_32_5("Vestibulum eu libero eget metus."); static const QString MSG_64_9("Phasellus enim dui, sodales sed tincidunt quis, ultricies metus."); static const QString MSG_128_19("Ut porttitor volutpat tristique. Aenean semper ligula eget nulla condimentum tempor in quis felis. Sed sem diam, tincidunt amet."); static const QString MSG_256_37("Vestibulum quis lorem velit, a varius augue. Suspendisse risus augue, ultricies at convallis in, elementum in velit. Fusce fermentum congue augue sit amet dapibus. Fusce ultrices urna ut tortor laoreet a aliquet elit lobortis. Suspendisse volutpat posuere."); static const QString MSG_512_75("Nam leo risus, accumsan a sagittis eget, posuere eu velit. Morbi mattis auctor risus, vel consequat massa pulvinar nec. Proin aliquam convallis elit nec egestas. Pellentesque accumsan placerat augue, id volutpat nibh dictum vel. Aenean venenatis varius feugiat. Nullam molestie, ipsum id dignissim vulputate, eros urna vestibulum massa, in vehicula lacus nisi vitae risus. Ut nunc nunc, venenatis a mattis auctor, dictum et sem. Nulla posuere libero ut tortor elementum egestas. Aliquam egestas suscipit posuere."); static const QStringList USERS_100 = QStringList() << "jpnurmi" << "Curabitur" << "nORMAL" << "leo" << "luctus" << "luctus" << "paraply" << "sapien" << "nope" << "vitae" << "where" << "alien" << "urna" << "turpis" << "rea_son" << "alone" << "velit" << "jipsu" << "rutrum" << "DiSCO" << "abort" << "venue" << "__duis__" << "eros" << "adam" << "hendrix" << "liber0" << "Jim" << "Leonardo" << "JiMi" << "justin" << "semper" << "fidelis" << "Excelsior" << "parachute" << "nam" << "nom" << "Lorem" << "risus" << "stereo" << "tv" << "what-ever" << "kill" << "savior" << "[haha]" << "null" << "nill" << "will" << "still" << "ill" << "fill" << "hill" << "bill" << "Lucas" << "metus" << "bitch" << "d0nut" << "perverT" << "br0tha" << "WHYZ" << "Amen" << "hero" << "another" << "other" << "augue" << "Vestibulum" << "quit" << "quis" << "Luis" << "luiz" << "Luigi" << "anus" << "formal" << "f00bar" << "sed" << "sodales" << "phasellus" << "port" << "porttitor" << "absolute" << "varius" << "Marius" << "access" << "ZzZzZz" << "dust" << "up" << "d0wn" << "l3ft" << "r1ght" << "n0ne" << "MeSsAgE" << "FoRmAtTeR" << "c00l" << "_[KiDDO]_" << "yes" << "no" << "never" << "tincidunt" << "ultricies" << "posuere"; class TestMessageFormatter : public MessageFormatter { friend class tst_MessageFormatter; }; class TestUserModel : public UserModel { friend class tst_MessageFormatter; public: TestUserModel(Session* session) : UserModel(session) { } }; class tst_MessageFormatter : public QObject { Q_OBJECT private slots: void testFormatHtml_data(); void testFormatHtml(); private: TestMessageFormatter formatter; }; Q_DECLARE_METATYPE(QStringList) void tst_MessageFormatter::testFormatHtml_data() { qRegisterMetaType<QStringList>(); QStringList USERS_UC; foreach (const QString& user, USERS_100) USERS_UC += user.toUpper(); QTest::addColumn<QString>("message"); QTest::addColumn<QStringList>("users"); QTest::newRow("empty") << QString() << QStringList(); QTest::newRow("32 chars / 5 words / 0 users") << MSG_32_5 << QStringList(); QTest::newRow("32 chars / 5 words / 25 users") << MSG_32_5 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("32 chars / 5 words / 50 users") << MSG_32_5 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("32 chars / 5 words / 75 users") << MSG_32_5 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("32 chars / 5 words / 100 users") << MSG_32_5 << USERS_100; QTest::newRow("32 chars / 5 words / 200 users") << MSG_32_5 << USERS_100 + USERS_UC; QTest::newRow("64 chars / 9 words / 0 users") << MSG_64_9 << QStringList(); QTest::newRow("64 chars / 9 words / 25 users") << MSG_64_9 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("64 chars / 9 words / 50 users") << MSG_64_9 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("64 chars / 9 words / 75 users") << MSG_64_9 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("64 chars / 9 words / 100 users") << MSG_64_9 << USERS_100; QTest::newRow("64 chars / 9 words / 200 users") << MSG_64_9 << USERS_100 + USERS_UC; QTest::newRow("128 chars / 19 words / 0 users") << MSG_128_19 << QStringList(); QTest::newRow("128 chars / 19 words / 25 users") << MSG_128_19 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("128 chars / 19 words / 50 users") << MSG_128_19 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("128 chars / 19 words / 75 users") << MSG_128_19 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("128 chars / 19 words / 100 users") << MSG_128_19 << USERS_100; QTest::newRow("128 chars / 19 words / 200 users") << MSG_128_19 << USERS_100 + USERS_UC; QTest::newRow("256 chars / 37 words / 0 users") << MSG_256_37 << QStringList(); QTest::newRow("256 chars / 37 words / 25 users") << MSG_256_37 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("256 chars / 37 words / 50 users") << MSG_256_37 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("256 chars / 37 words / 75 users") << MSG_256_37 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("256 chars / 37 words / 100 users") << MSG_256_37 << USERS_100; QTest::newRow("256 chars / 37 words / 200 users") << MSG_256_37 << USERS_100 + USERS_UC; QTest::newRow("512 chars / 75 words / 0 users") << MSG_512_75 << QStringList(); QTest::newRow("512 chars / 75 words / 25 users") << MSG_512_75 << QStringList(USERS_100.mid(0, 25)); QTest::newRow("512 chars / 75 words / 50 users") << MSG_512_75 << QStringList(USERS_100.mid(0, 50)); QTest::newRow("512 chars / 75 words / 75 users") << MSG_512_75 << QStringList(USERS_100.mid(0, 75)); QTest::newRow("512 chars / 75 words / 100 users") << MSG_512_75 << USERS_100; QTest::newRow("512 chars / 75 words / 200 users") << MSG_512_75 << USERS_100 + USERS_UC; } void tst_MessageFormatter::testFormatHtml() { QFETCH(QString, message); QFETCH(QStringList, users); Session session; TestUserModel model(&session); model.addUsers(users); QCOMPARE(model.rowCount(), users.count()); IrcMessage* dummy = new IrcMessage(&session); formatter.formatMessage(dummy, &model); QBENCHMARK { formatter.formatHtml(message); } } QTEST_MAIN(tst_MessageFormatter) #include "tst_messageformatter.moc" <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: propertyids.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2006-12-20 12:24:43 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ #ifndef _CONNECTIVITY_PROPERTYIDS_HXX_ #define _CONNECTIVITY_PROPERTYIDS_HXX_ // this define has to be set to split the names into different dll's or so's // every dll has his own set of property names #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _MAP_ #include <map> #endif namespace connectivity { namespace skeleton { class OPropertyMap { ::std::map<sal_Int32 , rtl_uString*> m_aPropertyMap; ::rtl::OUString fillValue(sal_Int32 _nIndex); public: OPropertyMap() { } ~OPropertyMap(); ::rtl::OUString getNameByIndex(sal_Int32 _nIndex) const; static OPropertyMap& getPropMap() { static OPropertyMap s_aPropMap; return s_aPropMap; } }; typedef const sal_Char* (*PVFN)(); struct UStringDescription { const sal_Char* pZeroTerminatedName; sal_Int32 nLength; UStringDescription(PVFN _fCharFkt); operator ::rtl::OUString() const { return ::rtl::OUString(pZeroTerminatedName,nLength,RTL_TEXTENCODING_ASCII_US); } ~UStringDescription(); private: UStringDescription(); }; } } //------------------------------------------------------------------------------ #define DECL_PROP1IMPL(varname, type) \ pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_##varname), PROPERTY_ID_##varname, ::cppu::UnoType< type >::get(), //------------------------------------------------------------------------------ #define DECL_PROP0(varname, type) \ DECL_PROP1IMPL(varname, type) 0) //------------------------------------------------------------------------------ #define DECL_BOOL_PROP1IMPL(varname) \ pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_##varname), PROPERTY_ID_##varname, ::getBooleanCppuType(), //------------------------------------------------------------------------------ #define DECL_BOOL_PROP0(varname) \ DECL_BOOL_PROP1IMPL(varname) 0) #define PROPERTY_ID_QUERYTIMEOUT 1 #define PROPERTY_ID_MAXFIELDSIZE 2 #define PROPERTY_ID_MAXROWS 3 #define PROPERTY_ID_CURSORNAME 4 #define PROPERTY_ID_RESULTSETCONCURRENCY 5 #define PROPERTY_ID_RESULTSETTYPE 6 #define PROPERTY_ID_FETCHDIRECTION 7 #define PROPERTY_ID_FETCHSIZE 8 #define PROPERTY_ID_ESCAPEPROCESSING 9 #define PROPERTY_ID_USEBOOKMARKS 10 // Column #define PROPERTY_ID_NAME 11 #define PROPERTY_ID_TYPE 12 #define PROPERTY_ID_TYPENAME 13 #define PROPERTY_ID_PRECISION 14 #define PROPERTY_ID_SCALE 15 #define PROPERTY_ID_ISNULLABLE 16 #define PROPERTY_ID_ISAUTOINCREMENT 17 #define PROPERTY_ID_ISROWVERSION 18 #define PROPERTY_ID_DESCRIPTION 19 #define PROPERTY_ID_DEFAULTVALUE 20 #define PROPERTY_ID_REFERENCEDTABLE 21 #define PROPERTY_ID_UPDATERULE 22 #define PROPERTY_ID_DELETERULE 23 #define PROPERTY_ID_CATALOG 24 #define PROPERTY_ID_ISUNIQUE 25 #define PROPERTY_ID_ISPRIMARYKEYINDEX 26 #define PROPERTY_ID_ISCLUSTERED 27 #define PROPERTY_ID_ISASCENDING 28 #define PROPERTY_ID_SCHEMANAME 29 #define PROPERTY_ID_CATALOGNAME 30 #define PROPERTY_ID_COMMAND 31 #define PROPERTY_ID_CHECKOPTION 32 #define PROPERTY_ID_PASSWORD 33 #define PROPERTY_ID_RELATEDCOLUMN 34 #define PROPERTY_ID_FUNCTION 35 #define PROPERTY_ID_TABLENAME 36 #define PROPERTY_ID_REALNAME 37 #define PROPERTY_ID_DBASEPRECISIONCHANGED 38 #define PROPERTY_ID_ISCURRENCY 39 #define PROPERTY_ID_ISBOOKMARKABLE 40 #define PROPERTY_ID_INVALID_INDEX 41 #define PROPERTY_ID_ERRORMSG_SEQUENCE 42 #define PROPERTY_ID_HY010 43 #define PROPERTY_ID_HY0000 44 #define PROPERTY_ID_DELIMITER 45 #define PROPERTY_ID_FORMATKEY 46 #define PROPERTY_ID_LOCALE 47 #define PROPERTY_ID_IM001 48 #define PROPERTY_ID_AUTOINCREMENTCREATION 49 #define PROPERTY_ID_PRIVILEGES 50 #endif // _CONNECTIVITY_PROPERTYIDS_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.5.90); FILE MERGED 2008/04/01 12:31:56 thb 1.5.90.1: #i85898# Stripping all external header guards<commit_after>/************************************************************************* * * $RCSfile: propertyids.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2008-04-10 16:38:35 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ #ifndef _CONNECTIVITY_PROPERTYIDS_HXX_ #define _CONNECTIVITY_PROPERTYIDS_HXX_ // this define has to be set to split the names into different dll's or so's // every dll has his own set of property names #include <rtl/ustring.hxx> #ifndef _MAP_ #include <map> #endif namespace connectivity { namespace skeleton { class OPropertyMap { ::std::map<sal_Int32 , rtl_uString*> m_aPropertyMap; ::rtl::OUString fillValue(sal_Int32 _nIndex); public: OPropertyMap() { } ~OPropertyMap(); ::rtl::OUString getNameByIndex(sal_Int32 _nIndex) const; static OPropertyMap& getPropMap() { static OPropertyMap s_aPropMap; return s_aPropMap; } }; typedef const sal_Char* (*PVFN)(); struct UStringDescription { const sal_Char* pZeroTerminatedName; sal_Int32 nLength; UStringDescription(PVFN _fCharFkt); operator ::rtl::OUString() const { return ::rtl::OUString(pZeroTerminatedName,nLength,RTL_TEXTENCODING_ASCII_US); } ~UStringDescription(); private: UStringDescription(); }; } } //------------------------------------------------------------------------------ #define DECL_PROP1IMPL(varname, type) \ pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_##varname), PROPERTY_ID_##varname, ::cppu::UnoType< type >::get(), //------------------------------------------------------------------------------ #define DECL_PROP0(varname, type) \ DECL_PROP1IMPL(varname, type) 0) //------------------------------------------------------------------------------ #define DECL_BOOL_PROP1IMPL(varname) \ pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_##varname), PROPERTY_ID_##varname, ::getBooleanCppuType(), //------------------------------------------------------------------------------ #define DECL_BOOL_PROP0(varname) \ DECL_BOOL_PROP1IMPL(varname) 0) #define PROPERTY_ID_QUERYTIMEOUT 1 #define PROPERTY_ID_MAXFIELDSIZE 2 #define PROPERTY_ID_MAXROWS 3 #define PROPERTY_ID_CURSORNAME 4 #define PROPERTY_ID_RESULTSETCONCURRENCY 5 #define PROPERTY_ID_RESULTSETTYPE 6 #define PROPERTY_ID_FETCHDIRECTION 7 #define PROPERTY_ID_FETCHSIZE 8 #define PROPERTY_ID_ESCAPEPROCESSING 9 #define PROPERTY_ID_USEBOOKMARKS 10 // Column #define PROPERTY_ID_NAME 11 #define PROPERTY_ID_TYPE 12 #define PROPERTY_ID_TYPENAME 13 #define PROPERTY_ID_PRECISION 14 #define PROPERTY_ID_SCALE 15 #define PROPERTY_ID_ISNULLABLE 16 #define PROPERTY_ID_ISAUTOINCREMENT 17 #define PROPERTY_ID_ISROWVERSION 18 #define PROPERTY_ID_DESCRIPTION 19 #define PROPERTY_ID_DEFAULTVALUE 20 #define PROPERTY_ID_REFERENCEDTABLE 21 #define PROPERTY_ID_UPDATERULE 22 #define PROPERTY_ID_DELETERULE 23 #define PROPERTY_ID_CATALOG 24 #define PROPERTY_ID_ISUNIQUE 25 #define PROPERTY_ID_ISPRIMARYKEYINDEX 26 #define PROPERTY_ID_ISCLUSTERED 27 #define PROPERTY_ID_ISASCENDING 28 #define PROPERTY_ID_SCHEMANAME 29 #define PROPERTY_ID_CATALOGNAME 30 #define PROPERTY_ID_COMMAND 31 #define PROPERTY_ID_CHECKOPTION 32 #define PROPERTY_ID_PASSWORD 33 #define PROPERTY_ID_RELATEDCOLUMN 34 #define PROPERTY_ID_FUNCTION 35 #define PROPERTY_ID_TABLENAME 36 #define PROPERTY_ID_REALNAME 37 #define PROPERTY_ID_DBASEPRECISIONCHANGED 38 #define PROPERTY_ID_ISCURRENCY 39 #define PROPERTY_ID_ISBOOKMARKABLE 40 #define PROPERTY_ID_INVALID_INDEX 41 #define PROPERTY_ID_ERRORMSG_SEQUENCE 42 #define PROPERTY_ID_HY010 43 #define PROPERTY_ID_HY0000 44 #define PROPERTY_ID_DELIMITER 45 #define PROPERTY_ID_FORMATKEY 46 #define PROPERTY_ID_LOCALE 47 #define PROPERTY_ID_IM001 48 #define PROPERTY_ID_AUTOINCREMENTCREATION 49 #define PROPERTY_ID_PRIVILEGES 50 #endif // _CONNECTIVITY_PROPERTYIDS_HXX_ <|endoftext|>
<commit_before> /************************/ /* Contour finder class */ /************************/ #include "nebulaContourFinder.h" void nebulaContourFinder::setup(){ // setup contour finder parameter GUI guiGrp.setName("Blob tracker"); guiGrp.add(enabled.set("enable",true)); guiGrp.add(minAreaRad.set("minimum area radius",1,0,240)); guiGrp.add(maxAreaRad.set("maximum area radius",100,0,240)); guiGrp.add(threshold.set("threshold",15,0,255)); guiGrp.add(erodeAmount.set("erode",1,0,10)); guiGrp.add(blurAmount.set("blur",10,0,100)); guiGrp.add(persistence.set("persistence", 15,0,200)); guiGrp.add(maxDistance.set("max distance",32,0,200)); guiGrp.add(showLabels.set("show label",true)); minAreaRad.addListener(this, &nebulaContourFinder::minAreaCb); maxAreaRad.addListener(this, &nebulaContourFinder::maxAreaCb); threshold.addListener(this, &nebulaContourFinder::thresholdCb); persistence.addListener(this, &nebulaContourFinder::persistenceCb); maxDistance.addListener(this, &nebulaContourFinder::maxDistanceCb); showLabels.addListener(this, &nebulaContourFinder::showLabelsCb); finder.setMinAreaRadius(minAreaRad); finder.setMaxAreaRadius(maxAreaRad); finder.setThreshold(threshold); // wait for half a frame before forgetting something finder.getTracker().setPersistence(persistence); // an object can move up to 32 pixels per frame finder.getTracker().setMaximumDistance(maxDistance); } void nebulaContourFinder::draw(int x, int y, int w, int h){ if(!enabled || blurred.size() == cv::Size(0,0)) return; ofxCv::RectTracker& tracker = finder.getTracker(); ofPushMatrix(); ofScale(w/blurred.cols, h/blurred.rows); ofTranslate(x,y); if(showLabels) { finder.draw(); for(int i = 0; i < finder.size(); i++) { ofPoint center = ofxCv::toOf(finder.getCenter(i)); ofPushMatrix(); ofTranslate(center.x, center.y); int label = finder.getLabel(i); string msg = ofToString(label) + ":" + ofToString(tracker.getAge(label)); ofDrawBitmapString(msg, 0, 0); ofDrawCircle(0,0,2); msg = ofToString(finder.getCentroid(i)); ofDrawBitmapString(msg, 0, 12); ofVec2f velocity = ofxCv::toOf(finder.getVelocity(i)); ofScale(5, 5); ofDrawLine(0, 0, velocity.x, velocity.y); ofPopMatrix(); } } else { for(int i = 0; i < finder.size(); i++) { unsigned int label = finder.getLabel(i); // only draw a line if this is not a new label if(tracker.existsPrevious(label)) { // use the label to pick a random color ofSeedRandom(label << 24); ofSetColor(ofColor::fromHsb(ofRandom(255), 255, 255)); // get the tracked object (cv::Rect) at current and previous position const cv::Rect& previous = tracker.getPrevious(label); const cv::Rect& current = tracker.getCurrent(label); // get the centers of the rectangles ofVec2f previousPosition(previous.x + previous.width / 2, previous.y + previous.height / 2); ofVec2f currentPosition(current.x + current.width / 2, current.y + current.height / 2); ofDrawLine(previousPosition, currentPosition); } } } ofTranslate(x,y); // this chunk of code visualizes the creation and destruction of labels const vector<unsigned int>& currentLabels = tracker.getCurrentLabels(); const vector<unsigned int>& previousLabels = tracker.getPreviousLabels(); const vector<unsigned int>& newLabels = tracker.getNewLabels(); const vector<unsigned int>& deadLabels = tracker.getDeadLabels(); ofSetColor(ofxCv::cyanPrint); for(int i = 0; i < currentLabels.size(); i++) { int j = currentLabels[i]; ofDrawLine(j, 0, j, 4); } ofSetColor(ofxCv::magentaPrint); for(int i = 0; i < previousLabels.size(); i++) { int j = previousLabels[i]; ofDrawLine(j, 4, j, 8); } ofSetColor(ofxCv::yellowPrint); for(int i = 0; i < newLabels.size(); i++) { int j = newLabels[i]; ofDrawLine(j, 8, j, 12); } ofSetColor(ofColor::white); for(int i = 0; i < deadLabels.size(); i++) { int j = deadLabels[i]; ofDrawLine(j, 12, j, 16); } ofPopMatrix(); ofPopStyle(); } void nebulaContourFinder::showLabelsCb(bool& flag){ if (!flag){ fbo.begin(); ofClear(0,0,0,0); // clear sceen before drawing fbo.end(); } } void nebulaContourFinder::minAreaCb(int& val){ finder.setMinAreaRadius(val); } void nebulaContourFinder::maxAreaCb(int& val){ finder.setMaxAreaRadius(val); } void nebulaContourFinder::thresholdCb(int& val){ finder.setThreshold(val); } void nebulaContourFinder::persistenceCb(int& val){ finder.getTracker().setPersistence(val); } void nebulaContourFinder::maxDistanceCb(int& val){ finder.getTracker().setMaximumDistance(val); } vector<ofPoint> nebulaContourFinder::getCentroids(){ vector<ofPoint> centroids; for (int i = 0; i < finder.size(); i++){ centroids.push_back(ofxCv::toOf(finder.getCentroid(i))); } return centroids; } <commit_msg>move comment<commit_after> /************************/ /* Contour finder class */ /************************/ #include "nebulaContourFinder.h" void nebulaContourFinder::setup(){ // setup contour finder parameter GUI guiGrp.setName("Blob tracker"); guiGrp.add(enabled.set("enable",true)); guiGrp.add(minAreaRad.set("minimum area radius",1,0,240)); guiGrp.add(maxAreaRad.set("maximum area radius",100,0,240)); guiGrp.add(threshold.set("threshold",15,0,255)); guiGrp.add(erodeAmount.set("erode",1,0,10)); guiGrp.add(blurAmount.set("blur",10,0,100)); // time to wait before forgetting something guiGrp.add(persistence.set("persistence", 15,0,200)); // this is the maximum distance a pixel can move between 2 frames guiGrp.add(maxDistance.set("max distance",32,0,200)); guiGrp.add(showLabels.set("show label",true)); minAreaRad.addListener(this, &nebulaContourFinder::minAreaCb); maxAreaRad.addListener(this, &nebulaContourFinder::maxAreaCb); threshold.addListener(this, &nebulaContourFinder::thresholdCb); persistence.addListener(this, &nebulaContourFinder::persistenceCb); maxDistance.addListener(this, &nebulaContourFinder::maxDistanceCb); showLabels.addListener(this, &nebulaContourFinder::showLabelsCb); finder.setMinAreaRadius(minAreaRad); finder.setMaxAreaRadius(maxAreaRad); finder.setThreshold(threshold); finder.getTracker().setPersistence(persistence); finder.getTracker().setMaximumDistance(maxDistance); } void nebulaContourFinder::draw(int x, int y, int w, int h){ if(!enabled || blurred.size() == cv::Size(0,0)) return; ofxCv::RectTracker& tracker = finder.getTracker(); ofPushMatrix(); ofScale(w/blurred.cols, h/blurred.rows); ofTranslate(x,y); if(showLabels) { finder.draw(); for(int i = 0; i < finder.size(); i++) { ofPoint center = ofxCv::toOf(finder.getCenter(i)); ofPushMatrix(); ofTranslate(center.x, center.y); int label = finder.getLabel(i); string msg = ofToString(label) + ":" + ofToString(tracker.getAge(label)); ofDrawBitmapString(msg, 0, 0); ofDrawCircle(0,0,2); msg = ofToString(finder.getCentroid(i)); ofDrawBitmapString(msg, 0, 12); ofVec2f velocity = ofxCv::toOf(finder.getVelocity(i)); ofScale(5, 5); ofDrawLine(0, 0, velocity.x, velocity.y); ofPopMatrix(); } } else { for(int i = 0; i < finder.size(); i++) { unsigned int label = finder.getLabel(i); // only draw a line if this is not a new label if(tracker.existsPrevious(label)) { // use the label to pick a random color ofSeedRandom(label << 24); ofSetColor(ofColor::fromHsb(ofRandom(255), 255, 255)); // get the tracked object (cv::Rect) at current and previous position const cv::Rect& previous = tracker.getPrevious(label); const cv::Rect& current = tracker.getCurrent(label); // get the centers of the rectangles ofVec2f previousPosition(previous.x + previous.width / 2, previous.y + previous.height / 2); ofVec2f currentPosition(current.x + current.width / 2, current.y + current.height / 2); ofDrawLine(previousPosition, currentPosition); } } } ofTranslate(x,y); // this chunk of code visualizes the creation and destruction of labels const vector<unsigned int>& currentLabels = tracker.getCurrentLabels(); const vector<unsigned int>& previousLabels = tracker.getPreviousLabels(); const vector<unsigned int>& newLabels = tracker.getNewLabels(); const vector<unsigned int>& deadLabels = tracker.getDeadLabels(); ofSetColor(ofxCv::cyanPrint); for(int i = 0; i < currentLabels.size(); i++) { int j = currentLabels[i]; ofDrawLine(j, 0, j, 4); } ofSetColor(ofxCv::magentaPrint); for(int i = 0; i < previousLabels.size(); i++) { int j = previousLabels[i]; ofDrawLine(j, 4, j, 8); } ofSetColor(ofxCv::yellowPrint); for(int i = 0; i < newLabels.size(); i++) { int j = newLabels[i]; ofDrawLine(j, 8, j, 12); } ofSetColor(ofColor::white); for(int i = 0; i < deadLabels.size(); i++) { int j = deadLabels[i]; ofDrawLine(j, 12, j, 16); } ofPopMatrix(); ofPopStyle(); } void nebulaContourFinder::showLabelsCb(bool& flag){ if (!flag){ fbo.begin(); ofClear(0,0,0,0); // clear sceen before drawing fbo.end(); } } void nebulaContourFinder::minAreaCb(int& val){ finder.setMinAreaRadius(val); } void nebulaContourFinder::maxAreaCb(int& val){ finder.setMaxAreaRadius(val); } void nebulaContourFinder::thresholdCb(int& val){ finder.setThreshold(val); } void nebulaContourFinder::persistenceCb(int& val){ finder.getTracker().setPersistence(val); } void nebulaContourFinder::maxDistanceCb(int& val){ finder.getTracker().setMaximumDistance(val); } vector<ofPoint> nebulaContourFinder::getCentroids(){ vector<ofPoint> centroids; for (int i = 0; i < finder.size(); i++){ centroids.push_back(ofxCv::toOf(finder.getCentroid(i))); } return centroids; } <|endoftext|>
<commit_before>/* * 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 * * 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. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <arrow-glib/array.hpp> #include <arrow-glib/uint32-array.h> G_BEGIN_DECLS /** * SECTION: uint32-array * @short_description: 32-bit unsigned integer array class * * #GArrowUInt32Array is a class for 32-bit unsigned integer array. It * can store zero or more 32-bit unsigned integer data. * * #GArrowUInt32Array is immutable. You need to use * #GArrowUInt32ArrayBuilder to create a new array. */ G_DEFINE_TYPE(GArrowUInt32Array, \ garrow_uint32_array, \ GARROW_TYPE_ARRAY) static void garrow_uint32_array_init(GArrowUInt32Array *object) { } static void garrow_uint32_array_class_init(GArrowUInt32ArrayClass *klass) { } /** * garrow_uint32_array_get_value: * @array: A #GArrowUInt32Array. * @i: The index of the target value. * * Returns: The i-th value. */ guint32 garrow_uint32_array_get_value(GArrowUInt32Array *array, gint64 i) { auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); return static_cast<arrow::UInt32Array *>(arrow_array.get())->Value(i); } G_END_DECLS <commit_msg>ARROW-793: [GLib] Fix indent<commit_after>/* * 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 * * 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. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <arrow-glib/array.hpp> #include <arrow-glib/uint32-array.h> G_BEGIN_DECLS /** * SECTION: uint32-array * @short_description: 32-bit unsigned integer array class * * #GArrowUInt32Array is a class for 32-bit unsigned integer array. It * can store zero or more 32-bit unsigned integer data. * * #GArrowUInt32Array is immutable. You need to use * #GArrowUInt32ArrayBuilder to create a new array. */ G_DEFINE_TYPE(GArrowUInt32Array, \ garrow_uint32_array, \ GARROW_TYPE_ARRAY) static void garrow_uint32_array_init(GArrowUInt32Array *object) { } static void garrow_uint32_array_class_init(GArrowUInt32ArrayClass *klass) { } /** * garrow_uint32_array_get_value: * @array: A #GArrowUInt32Array. * @i: The index of the target value. * * Returns: The i-th value. */ guint32 garrow_uint32_array_get_value(GArrowUInt32Array *array, gint64 i) { auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); return static_cast<arrow::UInt32Array *>(arrow_array.get())->Value(i); } G_END_DECLS <|endoftext|>
<commit_before>/***************************************************************************** * Project: BaBar detector at the SLAC PEP-II B-factory * Package: RooFitCore * File: $Id: RooBMixDecay.cc,v 1.8 2001/11/05 18:53:48 verkerke Exp $ * Authors: * WV, Wouter Verkerke, UC Santa Barbara, [email protected] * History: * 05-Jun-2001 WV Created initial version * * Copyright (C) 2001 University of California *****************************************************************************/ // -- CLASS DESCRIPTION [PDF] -- // #include <iostream.h> #include "RooFitCore/RooRealVar.hh" #include "RooFitModels/RooBMixDecay.hh" #include "RooFitCore/RooRandom.hh" ClassImp(RooBMixDecay) ; RooBMixDecay::RooBMixDecay(const char *name, const char *title, RooRealVar& t, RooAbsCategory& mixState, RooAbsCategory& tagFlav, RooAbsReal& tau, RooAbsReal& dm, RooAbsReal& mistag, RooAbsReal& delMistag, const RooResolutionModel& model, DecayType type) : RooConvolutedPdf(name,title,model,t), _mistag("mistag","Mistag rate",this,mistag), _mixState("mixState","Mixing state",this,mixState), _tagFlav("tagFlav","Flavour of tagged B0",this,tagFlav), _delMistag("delMistag","Delta mistag rate",this,delMistag), _type(type), _tau("tau","Mixing life time",this,tau), _dm("dm","Mixing frequency",this,dm), _t("_t","time",this,t), _genMixFrac(0) { // Constructor switch(type) { case SingleSided: _basisExp = declareBasis("exp(-@0/@1)",RooArgList(tau,dm)) ; _basisCos = declareBasis("exp(-@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ; break ; case Flipped: _basisExp = declareBasis("exp(@0)/@1)",RooArgList(tau,dm)) ; _basisCos = declareBasis("exp(@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ; break ; case DoubleSided: _basisExp = declareBasis("exp(-abs(@0)/@1)",RooArgList(tau,dm)) ; _basisCos = declareBasis("exp(-abs(@0)/@1)*cos(@0*@2)",RooArgList(tau,dm)) ; break ; } } RooBMixDecay::RooBMixDecay(const RooBMixDecay& other, const char* name) : RooConvolutedPdf(other,name), _mistag("mistag",this,other._mistag), _mixState("mixState",this,other._mixState), _tagFlav("tagFlav",this,other._tagFlav), _delMistag("delMistag",this,other._delMistag), _tau("tau",this,other._tau), _dm("dm",this,other._dm), _t("t",this,other._t), _basisExp(other._basisExp), _basisCos(other._basisCos), _type(other._type), _genMixFrac(other._genMixFrac), _genFlavFrac(other._genFlavFrac), _genFlavFracMix(other._genFlavFracMix), _genFlavFracUnmix(other._genFlavFracUnmix) { // Copy constructor } RooBMixDecay::~RooBMixDecay() { // Destructor } Double_t RooBMixDecay::coefficient(Int_t basisIndex) const { // Comp with tFit MC: must be (1 - tagFlav*...) if (basisIndex==_basisExp) { return (1 - _tagFlav*_delMistag) ; } if (basisIndex==_basisCos) { return _mixState*(1-2*_mistag) ; } return 0 ; } Int_t RooBMixDecay::getCoefAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const { if (matchArgs(allVars,analVars,_mixState,_tagFlav)) return 3 ; if (matchArgs(allVars,analVars,_mixState)) return 2 ; if (matchArgs(allVars,analVars,_tagFlav)) return 1 ; return 0 ; } Double_t RooBMixDecay::coefAnalyticalIntegral(Int_t basisIndex, Int_t code) const { switch(code) { // No integration case 0: return coefficient(basisIndex) ; // Integration over 'mixState' and 'tagFlav' case 3: if (basisIndex==_basisExp) { return 4.0 ; } if (basisIndex==_basisCos) { return 0.0 ; } // Integration over 'mixState' case 2: if (basisIndex==_basisExp) { return 2.0*coefficient(basisIndex) ; } if (basisIndex==_basisCos) { return 0.0 ; } // Integration over 'tagFlav' case 1: if (basisIndex==_basisExp) { return 2.0 ; } if (basisIndex==_basisCos) { return 2.0*coefficient(basisIndex) ; } default: assert(0) ; } return 0 ; } Int_t RooBMixDecay::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars) const { if (matchArgs(directVars,generateVars,_t,_mixState,_tagFlav)) return 4 ; if (matchArgs(directVars,generateVars,_t,_mixState)) return 3 ; if (matchArgs(directVars,generateVars,_t,_tagFlav)) return 2 ; if (matchArgs(directVars,generateVars,_t)) return 1 ; return 0 ; } void RooBMixDecay::initGenerator(Int_t code) { switch (code) { case 2: { // Calculate the fraction of mixed events to generate Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_mixState.arg())).getVal() ; _mixState = -1 ; // mixed Double_t mixInt = RooRealIntegral("mixInt","mix integral",*this,RooArgSet(_t.arg())).getVal() ; _genMixFrac = mixInt/sumInt ; break ; } case 3: { // Calculate the fraction of B0bar events to generate Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_tagFlav.arg())).getVal() ; _tagFlav = 1 ; // B0 Double_t flavInt = RooRealIntegral("flavInt","flav integral",*this,RooArgSet(_t.arg())).getVal() ; _genFlavFrac = flavInt/sumInt ; break ; } case 4: { // Calculate the fraction of mixed events to generate Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_mixState.arg(),_tagFlav.arg())).getVal() ; _mixState = -1 ; // mixed Double_t mixInt = RooRealIntegral("mixInt","mix integral",*this,RooArgSet(_t.arg(),_tagFlav.arg())).getVal() ; _genMixFrac = mixInt/sumInt ; // Calculate the fractio of B0bar tags for mixed and unmixed RooRealIntegral dtInt("mixInt","mix integral",*this,RooArgSet(_t.arg())) ; _mixState = -1 ; // Mixed _tagFlav = 1 ; // B0 _genFlavFracMix = dtInt.getVal() / mixInt ; _mixState = 1 ; // Unmixed _tagFlav = 1 ; // B0 _genFlavFracUnmix = dtInt.getVal() / (sumInt - mixInt) ; break ; } } } void RooBMixDecay::generateEvent(Int_t code) { // Generate mix-state dependent switch(code) { case 2: { Double_t rand = RooRandom::uniform() ; _mixState = (Int_t) ((rand<=_genMixFrac) ? -1 : 1) ; break ; } case 3: { Double_t rand = RooRandom::uniform() ; _tagFlav = (Int_t) ((rand<=_genFlavFrac) ? 1 : -1) ; break ; } case 4: { Double_t rand = RooRandom::uniform() ; _mixState = (Int_t) ((rand<=_genMixFrac) ? -1 : 1) ; rand = RooRandom::uniform() ; Double_t genFlavFrac = (_mixState==-1) ? _genFlavFracMix : _genFlavFracUnmix ; _tagFlav = (Int_t) ((rand<=genFlavFrac) ? 1 : -1) ; break ; } } // Generate delta-t dependent while(1) { Double_t rand = RooRandom::uniform() ; Double_t tval(0) ; switch(_type) { case SingleSided: tval = -_tau*log(rand); break ; case Flipped: tval= +_tau*log(rand); break ; case DoubleSided: tval = (rand<=0.5) ? -_tau*log(2*rand) : +_tau*log(2*(rand-0.5)) ; break ; } // Accept event if T is in generated range Double_t dil = fabs(1-2*_mistag) ; Double_t maxAcceptProb = 1 + fabs(_delMistag) + dil ; Double_t acceptProb = (1-_tagFlav*_delMistag) + _mixState*dil*cos(_dm*tval); Bool_t mixAccept = maxAcceptProb*RooRandom::uniform() < acceptProb ? kTRUE : kFALSE ; if (tval<_t.max() && tval>_t.min() && mixAccept) { _t = tval ; break ; } } } <commit_msg><commit_after>/***************************************************************************** * Project: BaBar detector at the SLAC PEP-II B-factory * Package: RooFitCore * File: $Id: RooBMixDecay.cc,v 1.9 2001/11/14 19:15:30 verkerke Exp $ * Authors: * WV, Wouter Verkerke, UC Santa Barbara, [email protected] * History: * 05-Jun-2001 WV Created initial version * * Copyright (C) 2001 University of California *****************************************************************************/ // -- CLASS DESCRIPTION [PDF] -- // #include <iostream.h> #include "RooFitCore/RooRealVar.hh" #include "RooFitModels/RooBMixDecay.hh" #include "RooFitCore/RooRandom.hh" ClassImp(RooBMixDecay) ; RooBMixDecay::RooBMixDecay(const char *name, const char *title, RooRealVar& t, RooAbsCategory& mixState, RooAbsCategory& tagFlav, RooAbsReal& tau, RooAbsReal& dm, RooAbsReal& mistag, RooAbsReal& delMistag, const RooResolutionModel& model, DecayType type) : RooConvolutedPdf(name,title,model,t), _mistag("mistag","Mistag rate",this,mistag), _mixState("mixState","Mixing state",this,mixState), _tagFlav("tagFlav","Flavour of tagged B0",this,tagFlav), _delMistag("delMistag","Delta mistag rate",this,delMistag), _type(type), _tau("tau","Mixing life time",this,tau), _dm("dm","Mixing frequency",this,dm), _t("_t","time",this,t), _genMixFrac(0) { // Constructor switch(type) { case SingleSided: _basisExp = declareBasis("exp(-@0/@1)",RooArgList(tau,dm)) ; _basisCos = declareBasis("exp(-@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ; break ; case Flipped: _basisExp = declareBasis("exp(@0)/@1)",RooArgList(tau,dm)) ; _basisCos = declareBasis("exp(@0/@1)*cos(@0*@2)",RooArgList(tau,dm)) ; break ; case DoubleSided: _basisExp = declareBasis("exp(-abs(@0)/@1)",RooArgList(tau,dm)) ; _basisCos = declareBasis("exp(-abs(@0)/@1)*cos(@0*@2)",RooArgList(tau,dm)) ; break ; } } RooBMixDecay::RooBMixDecay(const RooBMixDecay& other, const char* name) : RooConvolutedPdf(other,name), _mistag("mistag",this,other._mistag), _mixState("mixState",this,other._mixState), _tagFlav("tagFlav",this,other._tagFlav), _delMistag("delMistag",this,other._delMistag), _tau("tau",this,other._tau), _dm("dm",this,other._dm), _t("t",this,other._t), _basisExp(other._basisExp), _basisCos(other._basisCos), _type(other._type), _genMixFrac(other._genMixFrac), _genFlavFrac(other._genFlavFrac), _genFlavFracMix(other._genFlavFracMix), _genFlavFracUnmix(other._genFlavFracUnmix) { // Copy constructor } RooBMixDecay::~RooBMixDecay() { // Destructor } Double_t RooBMixDecay::coefficient(Int_t basisIndex) const { // Comp with tFit MC: must be (1 - tagFlav*...) if (basisIndex==_basisExp) { return (1 - _tagFlav*_delMistag) ; } if (basisIndex==_basisCos) { return _mixState*(1-2*_mistag) ; } return 0 ; } Int_t RooBMixDecay::getCoefAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const { // cout << "RooBMixDecay::getCoefAI " ; allVars.Print("1") ; if (matchArgs(allVars,analVars,_mixState,_tagFlav)) return 3 ; if (matchArgs(allVars,analVars,_mixState)) return 2 ; if (matchArgs(allVars,analVars,_tagFlav)) return 1 ; return 0 ; } Double_t RooBMixDecay::coefAnalyticalIntegral(Int_t basisIndex, Int_t code) const { switch(code) { // No integration case 0: return coefficient(basisIndex) ; // Integration over 'mixState' and 'tagFlav' case 3: if (basisIndex==_basisExp) { return 4.0 ; } if (basisIndex==_basisCos) { return 0.0 ; } // Integration over 'mixState' case 2: if (basisIndex==_basisExp) { return 2.0*coefficient(basisIndex) ; } if (basisIndex==_basisCos) { return 0.0 ; } // Integration over 'tagFlav' case 1: if (basisIndex==_basisExp) { return 2.0 ; } if (basisIndex==_basisCos) { return 2.0*coefficient(basisIndex) ; } default: assert(0) ; } return 0 ; } Int_t RooBMixDecay::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars) const { if (matchArgs(directVars,generateVars,_t,_mixState,_tagFlav)) return 4 ; if (matchArgs(directVars,generateVars,_t,_mixState)) return 3 ; if (matchArgs(directVars,generateVars,_t,_tagFlav)) return 2 ; if (matchArgs(directVars,generateVars,_t)) return 1 ; return 0 ; } void RooBMixDecay::initGenerator(Int_t code) { switch (code) { case 2: { // Calculate the fraction of B0bar events to generate Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_tagFlav.arg())).getVal() ; _tagFlav = 1 ; // B0 Double_t flavInt = RooRealIntegral("flavInt","flav integral",*this,RooArgSet(_t.arg())).getVal() ; _genFlavFrac = flavInt/sumInt ; break ; } case 3: { // Calculate the fraction of mixed events to generate Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_mixState.arg())).getVal() ; _mixState = -1 ; // mixed Double_t mixInt = RooRealIntegral("mixInt","mix integral",*this,RooArgSet(_t.arg())).getVal() ; _genMixFrac = mixInt/sumInt ; break ; } case 4: { // Calculate the fraction of mixed events to generate Double_t sumInt = RooRealIntegral("sumInt","sum integral",*this,RooArgSet(_t.arg(),_mixState.arg(),_tagFlav.arg())).getVal() ; _mixState = -1 ; // mixed Double_t mixInt = RooRealIntegral("mixInt","mix integral",*this,RooArgSet(_t.arg(),_tagFlav.arg())).getVal() ; _genMixFrac = mixInt/sumInt ; // Calculate the fractio of B0bar tags for mixed and unmixed RooRealIntegral dtInt("mixInt","mix integral",*this,RooArgSet(_t.arg())) ; _mixState = -1 ; // Mixed _tagFlav = 1 ; // B0 _genFlavFracMix = dtInt.getVal() / mixInt ; _mixState = 1 ; // Unmixed _tagFlav = 1 ; // B0 _genFlavFracUnmix = dtInt.getVal() / (sumInt - mixInt) ; break ; } } } void RooBMixDecay::generateEvent(Int_t code) { // Generate mix-state dependent switch(code) { case 2: { Double_t rand = RooRandom::uniform() ; _tagFlav = (Int_t) ((rand<=_genFlavFrac) ? 1 : -1) ; break ; } case 3: { Double_t rand = RooRandom::uniform() ; _mixState = (Int_t) ((rand<=_genMixFrac) ? -1 : 1) ; break ; } case 4: { Double_t rand = RooRandom::uniform() ; _mixState = (Int_t) ((rand<=_genMixFrac) ? -1 : 1) ; rand = RooRandom::uniform() ; Double_t genFlavFrac = (_mixState==-1) ? _genFlavFracMix : _genFlavFracUnmix ; _tagFlav = (Int_t) ((rand<=genFlavFrac) ? 1 : -1) ; break ; } } // Generate delta-t dependent while(1) { Double_t rand = RooRandom::uniform() ; Double_t tval(0) ; switch(_type) { case SingleSided: tval = -_tau*log(rand); break ; case Flipped: tval= +_tau*log(rand); break ; case DoubleSided: tval = (rand<=0.5) ? -_tau*log(2*rand) : +_tau*log(2*(rand-0.5)) ; break ; } // Accept event if T is in generated range Double_t dil = fabs(1-2*_mistag) ; Double_t maxAcceptProb = 1 + fabs(_delMistag) + dil ; Double_t acceptProb = (1-_tagFlav*_delMistag) + _mixState*dil*cos(_dm*tval); Bool_t mixAccept = maxAcceptProb*RooRandom::uniform() < acceptProb ? kTRUE : kFALSE ; if (tval<_t.max() && tval>_t.min() && mixAccept) { _t = tval ; break ; } } } <|endoftext|>
<commit_before><commit_msg>Changes tab dragging code to continue iterating through windows if window's rect contains the point but the window region doesn't. This is necessary as some apps create a window the size of the desktop and set a window region on it. Without this check we don't allow docking when these apps are running.<commit_after><|endoftext|>
<commit_before>#ifndef K3_RUNTIME_QUEUE_H #define K3_RUNTIME_QUEUE_H #include <list> #include <map> #include <memory> #include <queue> #include <tuple> #include <boost/lockfree/queue.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/lockable_adapter.hpp> #include <boost/thread/externally_locked.hpp> #include <Common.hpp> namespace K3 { // using namespace std; using namespace boost; using std::shared_ptr; using mutex = boost::mutex; //------------- // Queue types. template<typename Value> class MsgQueue { public: virtual bool push(Value& v) = 0; virtual bool pop(Value& v) = 0; virtual bool empty() = 0; virtual size_t size() = 0; }; template<typename Value> class LockfreeMsgQueue : public MsgQueue<Value> { public: LockfreeMsgQueue() {} bool empty() { return queue.empty(); } bool push(Value& v) { ++qSize; return queue.push(v); } bool pop(Value& v) { --qSize; return queue.pop(v); } size_t size() { return qSize; } protected: boost::lockfree::queue<Value> queue; size_t qSize; // TODO: synchronize. }; template<typename Value> class LockingMsgQueue : public MsgQueue<Value>, public basic_lockable_adapter<mutex> { public: typedef basic_lockable_adapter<mutex> qlockable; LockingMsgQueue () : qlockable(), queue(*this) {} bool empty() { strict_lock<LockingMsgQueue> guard(*this); return queue.get(guard).empty(); } bool push(Value& v) { strict_lock<LockingMsgQueue> guard(*this); ++qSize; queue.get(guard).push(v); return true; } bool pop(Value& v) { strict_lock<LockingMsgQueue> guard(*this); bool r = false; if ( !queue.get(guard).empty() ) { --qSize; v = queue.get(guard).front(); queue.get(guard).pop(); r = true; } return r; } size_t size() { return qSize; } protected: externally_locked<std::queue<Value>, LockingMsgQueue> queue; size_t qSize; // TODO: synchronize }; //------------------ // Queue containers. class MessageQueues : public virtual LogMT { public: MessageQueues() : LogMT("queue") {} virtual void enqueue(Message m) = 0; // TODO: use a ref / rvalue ref to avoid copying virtual shared_ptr<Message> dequeue() = 0; virtual size_t size() = 0; }; template<typename QueueIndex, typename Queue> class IndexedMessageQueues : public MessageQueues { public: IndexedMessageQueues() : LogMT("IndexedMessageQueues") {} // TODO: use a ref / rvalue ref to avoid copying void enqueue(Message m) { if ( validTarget(m) ) { enqueue(m, queue(m)); } else { BOOST_LOG(*this) << "Invalid message target: " << addressAsString(m.address()) << ":" << m.id(); } } // TODO: fair queueing policy. shared_ptr<Message> dequeue() { shared_ptr<Message> r; tuple<QueueIndex, shared_ptr<Queue> > idxQ = nonEmptyQueue(); if ( get<1>(idxQ) ) { r = dequeue(idxQ); } else { BOOST_LOG(*this) << "Invalid non-empty queue on dequeue"; } return r; } protected: virtual bool validTarget(Message& m) = 0; virtual shared_ptr<Queue> queue(Message& m) = 0; virtual tuple<QueueIndex, shared_ptr<Queue> > nonEmptyQueue() = 0; virtual void enqueue(Message& m, shared_ptr<Queue> q) = 0; virtual shared_ptr<Message> dequeue(const tuple<QueueIndex, shared_ptr<Queue> >& q) = 0; }; class SinglePeerQueue : public IndexedMessageQueues<Address, MsgQueue<tuple<Identifier, Value> > > { public: typedef Address QueueKey; //typedef LockfreeMsgQueue<tuple<Identifier, Value> > Queue; typedef LockingMsgQueue<tuple<Identifier, Value> > Queue; typedef tuple<QueueKey, shared_ptr<Queue> > PeerMessages; SinglePeerQueue() : LogMT("SinglePeerQueue") {} SinglePeerQueue(Address addr) : LogMT("SinglePeerQueue"), peerMsgs(addr, shared_ptr<Queue>(new Queue())) {} size_t size() { return get<1>(peerMsgs)->size(); } protected: typedef MsgQueue<tuple<Identifier, Value> > BaseQueue; PeerMessages peerMsgs; bool validTarget(Message& m) { return m.address() == get<0>(peerMsgs); } shared_ptr<BaseQueue> queue(Message& m) { return dynamic_pointer_cast<BaseQueue, Queue>(get<1>(peerMsgs)); } tuple<QueueKey, shared_ptr<BaseQueue> > nonEmptyQueue() { shared_ptr<Queue> r = get<1>(peerMsgs); shared_ptr<BaseQueue> br = r->empty()? shared_ptr<BaseQueue>() : dynamic_pointer_cast<BaseQueue, Queue>(r); return make_tuple(get<0>(peerMsgs), br); } void enqueue(Message& m, shared_ptr<BaseQueue> q) { tuple<Identifier, Value> entry = make_tuple(m.id(), m.contents()); if ( !(q && q->push(entry)) ) { BOOST_LOG(*this) << "Invalid destination queue during enqueue"; } } shared_ptr<Message> dequeue(const tuple<QueueKey, shared_ptr<BaseQueue> >& idxQ) { shared_ptr<Message> r; tuple<Identifier, Value> entry; shared_ptr<BaseQueue> q = get<1>(idxQ); if ( q && q->pop(entry) ) { const Address& addr = get<0>(idxQ); const Identifier& id = get<0>(entry); const Value& v = get<1>(entry); r = shared_ptr<Message>(new Message(addr, id, v)); } else { BOOST_LOG(*this) << "Invalid source queue during dequeue"; } return r; } }; // TODO: for dynamic changes to the queues container, use a shared lock class MultiPeerQueue : public IndexedMessageQueues<Address, MsgQueue<tuple<Identifier, Value> > > { public: typedef Address QueueKey; //typedef LockfreeMsgQueue<tuple<Identifier, Value> > Queue; typedef LockingMsgQueue<tuple<Identifier, Value> > Queue; typedef map<QueueKey, shared_ptr<Queue> > MultiPeerMessages; MultiPeerQueue() : LogMT("MultiPeerQueue") {} MultiPeerQueue(const list<Address>& addresses) : LogMT("MultiPeerQueue") { for ( auto x : addresses ) { multiPeerMsgs.insert(make_pair(x, shared_ptr<Queue>(new Queue()))); } } size_t size() { size_t r = 0; for ( auto x : multiPeerMsgs ) { r += x.second? x.second->size() : 0; } return r; } protected: typedef MsgQueue<tuple<Identifier, Value> > BaseQueue; MultiPeerMessages multiPeerMsgs; bool validTarget(Message& m) { return multiPeerMsgs.find(m.address()) != multiPeerMsgs.end(); } shared_ptr<BaseQueue> queue(Message& m) { return dynamic_pointer_cast<BaseQueue, Queue>(multiPeerMsgs[m.address()]); } tuple<QueueKey, shared_ptr<BaseQueue> > nonEmptyQueue() { tuple<QueueKey, shared_ptr<BaseQueue> > r; MultiPeerMessages::iterator it = find_if(multiPeerMsgs.begin(), multiPeerMsgs.end(), [](MultiPeerMessages::value_type& x){ return x.second->empty(); }); if ( it != multiPeerMsgs.end() ) { r = make_tuple(it->first, dynamic_pointer_cast<BaseQueue, Queue>(it->second)); } return r; } void enqueue(Message& m, shared_ptr<BaseQueue> q) { tuple<Identifier, Value> entry = make_tuple(m.id(), m.contents()); if ( !(q && q->push(entry)) ) { BOOST_LOG(*this) << "Invalid destination queue during enqueue"; } } shared_ptr<Message> dequeue(const tuple<QueueKey, shared_ptr<BaseQueue> >& idxQ) { shared_ptr<Message> r; tuple<Identifier, Value> entry; shared_ptr<BaseQueue> q = get<1>(idxQ); if ( q && q->pop(entry) ) { const Address& addr = get<0>(idxQ); const Identifier& id = get<0>(entry); const Value& v = get<1>(entry); r = shared_ptr<Message >(new Message(addr, id, v)); } else { BOOST_LOG(*this) << "Invalid source queue during dequeue"; } return r; } }; // TODO: for dynamic changes to the queues container, use a shared lock class MultiTriggerQueue : public IndexedMessageQueues<tuple<Address, Identifier>, MsgQueue<Value> > { public: typedef tuple<Address, Identifier> QueueKey; //typedef LockfreeMsgQueue<Value> Queue; typedef LockingMsgQueue<Value> Queue; typedef map<QueueKey, shared_ptr<Queue> > MultiTriggerMessages; MultiTriggerQueue() : LogMT("MultiTriggerQueue") {} MultiTriggerQueue(const list<Address>& addresses, const list<Identifier>& triggerIds) : LogMT("MultiTriggerQueue") { for ( auto addr : addresses ) { for ( auto id : triggerIds ) { multiTriggerMsgs.insert( make_pair(make_tuple(addr, id), shared_ptr<Queue>(new Queue()))); } } } size_t size() { size_t r = 0; for ( auto x : multiTriggerMsgs ) { r += x.second? x.second->size() : 0; } return r; } protected: typedef MsgQueue<Value> BaseQueue; MultiTriggerMessages multiTriggerMsgs; bool validTarget(Message& m) { return multiTriggerMsgs.find(make_tuple(m.address(), m.id())) != multiTriggerMsgs.end(); } shared_ptr<BaseQueue> queue(Message& m) { return dynamic_pointer_cast<BaseQueue, Queue>( multiTriggerMsgs[make_tuple(m.address(), m.id())]); } tuple<QueueKey, shared_ptr<BaseQueue> > nonEmptyQueue() { tuple<QueueKey, shared_ptr<BaseQueue> > r; MultiTriggerMessages::iterator it = find_if(multiTriggerMsgs.begin(), multiTriggerMsgs.end(), [](MultiTriggerMessages::value_type& x) { return x.second->empty(); }); if ( it != multiTriggerMsgs.end() ) { r = make_tuple(it->first, dynamic_pointer_cast<BaseQueue, Queue>(it->second)); } return r; } void enqueue(Message& m, shared_ptr<BaseQueue> q) { if ( !(q && q->push(m.contents())) ) { BOOST_LOG(*this) << "Invalid destination queue during enqueue"; } } shared_ptr<Message > dequeue(const tuple<QueueKey, shared_ptr<BaseQueue> >& idxQ) { shared_ptr<Message > r; Value entry; shared_ptr<BaseQueue> q = get<1>(idxQ); if ( q && q->pop(entry) ) { const Address& addr = get<0>(get<0>(idxQ)); const Identifier& id = get<1>(get<0>(idxQ)); r = shared_ptr<Message >(new Message(addr, id, entry)); } else { BOOST_LOG(*this) << "Invalid source queue during dequeue"; } return r; } }; //-------------------- // Queue constructors. shared_ptr<MessageQueues> simpleQueues(Address addr) { return shared_ptr<MessageQueues>(new SinglePeerQueue(addr)); } shared_ptr<MessageQueues> perPeerQueues(const list<Address>& addresses) { return shared_ptr<MessageQueues>(new MultiPeerQueue(addresses)); } shared_ptr<MessageQueues> perTriggerQueues(const list<Address>& addresses, const list<Identifier>& triggerIds) { return shared_ptr<MessageQueues>(new MultiTriggerQueue(addresses, triggerIds)); } } #endif <commit_msg>Fixed MessageQueues' enqueue arg to be a reference rather than a copy<commit_after>#ifndef K3_RUNTIME_QUEUE_H #define K3_RUNTIME_QUEUE_H #include <list> #include <map> #include <memory> #include <queue> #include <tuple> #include <boost/lockfree/queue.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/lockable_adapter.hpp> #include <boost/thread/externally_locked.hpp> #include <Common.hpp> namespace K3 { // using namespace std; using namespace boost; using std::shared_ptr; using mutex = boost::mutex; //------------- // Queue types. // TODO: r-ref overloads for push and pop template<typename Value> class MsgQueue { public: virtual bool push(Value& v) = 0; virtual bool pop(Value& v) = 0; virtual bool empty() = 0; virtual size_t size() = 0; }; // TODO: r-ref overloads for push and pop template<typename Value> class LockfreeMsgQueue : public MsgQueue<Value> { public: LockfreeMsgQueue() {} bool empty() { return queue.empty(); } bool push(Value& v) { ++qSize; return queue.push(v); } bool pop(Value& v) { --qSize; return queue.pop(v); } size_t size() { return qSize; } protected: boost::lockfree::queue<Value> queue; size_t qSize; // TODO: synchronize. }; // TODO: r-ref overloads for push and pop template<typename Value> class LockingMsgQueue : public MsgQueue<Value>, public basic_lockable_adapter<mutex> { public: typedef basic_lockable_adapter<mutex> qlockable; LockingMsgQueue () : qlockable(), queue(*this) {} bool empty() { strict_lock<LockingMsgQueue> guard(*this); return queue.get(guard).empty(); } bool push(Value& v) { strict_lock<LockingMsgQueue> guard(*this); ++qSize; queue.get(guard).push(v); return true; } bool pop(Value& v) { strict_lock<LockingMsgQueue> guard(*this); bool r = false; if ( !queue.get(guard).empty() ) { --qSize; v = queue.get(guard).front(); queue.get(guard).pop(); r = true; } return r; } size_t size() { return qSize; } protected: externally_locked<std::queue<Value>, LockingMsgQueue> queue; size_t qSize; // TODO: synchronize }; //------------------ // Queue containers. // TODO: r-ref overload for enqueue class MessageQueues : public virtual LogMT { public: MessageQueues() : LogMT("queue") {} virtual void enqueue(Message& m) = 0; virtual shared_ptr<Message> dequeue() = 0; virtual size_t size() = 0; }; // TODO: r-ref overload for enqueue template<typename QueueIndex, typename Queue> class IndexedMessageQueues : public MessageQueues { public: IndexedMessageQueues() : LogMT("IndexedMessageQueues") {} void enqueue(Message& m) { if ( validTarget(m) ) { enqueue(m, queue(m)); } else { BOOST_LOG(*this) << "Invalid message target: " << addressAsString(m.address()) << ":" << m.id(); } } // TODO: fair queueing policy. shared_ptr<Message> dequeue() { shared_ptr<Message> r; tuple<QueueIndex, shared_ptr<Queue> > idxQ = nonEmptyQueue(); if ( get<1>(idxQ) ) { r = dequeue(idxQ); } else { BOOST_LOG(*this) << "Invalid non-empty queue on dequeue"; } return r; } protected: virtual bool validTarget(Message& m) = 0; virtual shared_ptr<Queue> queue(Message& m) = 0; virtual tuple<QueueIndex, shared_ptr<Queue> > nonEmptyQueue() = 0; virtual void enqueue(Message& m, shared_ptr<Queue> q) = 0; virtual shared_ptr<Message> dequeue(const tuple<QueueIndex, shared_ptr<Queue> >& q) = 0; }; class SinglePeerQueue : public IndexedMessageQueues<Address, MsgQueue<tuple<Identifier, Value> > > { public: typedef Address QueueKey; //typedef LockfreeMsgQueue<tuple<Identifier, Value> > Queue; typedef LockingMsgQueue<tuple<Identifier, Value> > Queue; typedef tuple<QueueKey, shared_ptr<Queue> > PeerMessages; SinglePeerQueue() : LogMT("SinglePeerQueue") {} SinglePeerQueue(Address addr) : LogMT("SinglePeerQueue"), peerMsgs(addr, shared_ptr<Queue>(new Queue())) {} size_t size() { return get<1>(peerMsgs)->size(); } protected: typedef MsgQueue<tuple<Identifier, Value> > BaseQueue; PeerMessages peerMsgs; bool validTarget(Message& m) { return m.address() == get<0>(peerMsgs); } shared_ptr<BaseQueue> queue(Message& m) { return dynamic_pointer_cast<BaseQueue, Queue>(get<1>(peerMsgs)); } tuple<QueueKey, shared_ptr<BaseQueue> > nonEmptyQueue() { shared_ptr<Queue> r = get<1>(peerMsgs); shared_ptr<BaseQueue> br = r->empty()? shared_ptr<BaseQueue>() : dynamic_pointer_cast<BaseQueue, Queue>(r); return make_tuple(get<0>(peerMsgs), br); } void enqueue(Message& m, shared_ptr<BaseQueue> q) { tuple<Identifier, Value> entry = make_tuple(m.id(), m.contents()); if ( !(q && q->push(entry)) ) { BOOST_LOG(*this) << "Invalid destination queue during enqueue"; } } shared_ptr<Message> dequeue(const tuple<QueueKey, shared_ptr<BaseQueue> >& idxQ) { shared_ptr<Message> r; tuple<Identifier, Value> entry; shared_ptr<BaseQueue> q = get<1>(idxQ); if ( q && q->pop(entry) ) { const Address& addr = get<0>(idxQ); const Identifier& id = get<0>(entry); const Value& v = get<1>(entry); r = shared_ptr<Message>(new Message(addr, id, v)); } else { BOOST_LOG(*this) << "Invalid source queue during dequeue"; } return r; } }; // TODO: r-ref overload for enqueue // TODO: for dynamic changes to the queues container, use a shared lock class MultiPeerQueue : public IndexedMessageQueues<Address, MsgQueue<tuple<Identifier, Value> > > { public: typedef Address QueueKey; //typedef LockfreeMsgQueue<tuple<Identifier, Value> > Queue; typedef LockingMsgQueue<tuple<Identifier, Value> > Queue; typedef map<QueueKey, shared_ptr<Queue> > MultiPeerMessages; MultiPeerQueue() : LogMT("MultiPeerQueue") {} MultiPeerQueue(const list<Address>& addresses) : LogMT("MultiPeerQueue") { for ( auto x : addresses ) { multiPeerMsgs.insert(make_pair(x, shared_ptr<Queue>(new Queue()))); } } size_t size() { size_t r = 0; for ( auto x : multiPeerMsgs ) { r += x.second? x.second->size() : 0; } return r; } protected: typedef MsgQueue<tuple<Identifier, Value> > BaseQueue; MultiPeerMessages multiPeerMsgs; bool validTarget(Message& m) { return multiPeerMsgs.find(m.address()) != multiPeerMsgs.end(); } shared_ptr<BaseQueue> queue(Message& m) { return dynamic_pointer_cast<BaseQueue, Queue>(multiPeerMsgs[m.address()]); } tuple<QueueKey, shared_ptr<BaseQueue> > nonEmptyQueue() { tuple<QueueKey, shared_ptr<BaseQueue> > r; MultiPeerMessages::iterator it = find_if(multiPeerMsgs.begin(), multiPeerMsgs.end(), [](MultiPeerMessages::value_type& x){ return x.second->empty(); }); if ( it != multiPeerMsgs.end() ) { r = make_tuple(it->first, dynamic_pointer_cast<BaseQueue, Queue>(it->second)); } return r; } void enqueue(Message& m, shared_ptr<BaseQueue> q) { tuple<Identifier, Value> entry = make_tuple(m.id(), m.contents()); if ( !(q && q->push(entry)) ) { BOOST_LOG(*this) << "Invalid destination queue during enqueue"; } } shared_ptr<Message> dequeue(const tuple<QueueKey, shared_ptr<BaseQueue> >& idxQ) { shared_ptr<Message> r; tuple<Identifier, Value> entry; shared_ptr<BaseQueue> q = get<1>(idxQ); if ( q && q->pop(entry) ) { const Address& addr = get<0>(idxQ); const Identifier& id = get<0>(entry); const Value& v = get<1>(entry); r = shared_ptr<Message >(new Message(addr, id, v)); } else { BOOST_LOG(*this) << "Invalid source queue during dequeue"; } return r; } }; // TODO: r-ref overload for enqueue // TODO: for dynamic changes to the queues container, use a shared lock class MultiTriggerQueue : public IndexedMessageQueues<tuple<Address, Identifier>, MsgQueue<Value> > { public: typedef tuple<Address, Identifier> QueueKey; //typedef LockfreeMsgQueue<Value> Queue; typedef LockingMsgQueue<Value> Queue; typedef map<QueueKey, shared_ptr<Queue> > MultiTriggerMessages; MultiTriggerQueue() : LogMT("MultiTriggerQueue") {} MultiTriggerQueue(const list<Address>& addresses, const list<Identifier>& triggerIds) : LogMT("MultiTriggerQueue") { for ( auto addr : addresses ) { for ( auto id : triggerIds ) { multiTriggerMsgs.insert( make_pair(make_tuple(addr, id), shared_ptr<Queue>(new Queue()))); } } } size_t size() { size_t r = 0; for ( auto x : multiTriggerMsgs ) { r += x.second? x.second->size() : 0; } return r; } protected: typedef MsgQueue<Value> BaseQueue; MultiTriggerMessages multiTriggerMsgs; bool validTarget(Message& m) { return multiTriggerMsgs.find(make_tuple(m.address(), m.id())) != multiTriggerMsgs.end(); } shared_ptr<BaseQueue> queue(Message& m) { return dynamic_pointer_cast<BaseQueue, Queue>( multiTriggerMsgs[make_tuple(m.address(), m.id())]); } tuple<QueueKey, shared_ptr<BaseQueue> > nonEmptyQueue() { tuple<QueueKey, shared_ptr<BaseQueue> > r; MultiTriggerMessages::iterator it = find_if(multiTriggerMsgs.begin(), multiTriggerMsgs.end(), [](MultiTriggerMessages::value_type& x) { return x.second->empty(); }); if ( it != multiTriggerMsgs.end() ) { r = make_tuple(it->first, dynamic_pointer_cast<BaseQueue, Queue>(it->second)); } return r; } void enqueue(Message& m, shared_ptr<BaseQueue> q) { if ( !(q && q->push(m.contents())) ) { BOOST_LOG(*this) << "Invalid destination queue during enqueue"; } } shared_ptr<Message > dequeue(const tuple<QueueKey, shared_ptr<BaseQueue> >& idxQ) { shared_ptr<Message > r; Value entry; shared_ptr<BaseQueue> q = get<1>(idxQ); if ( q && q->pop(entry) ) { const Address& addr = get<0>(get<0>(idxQ)); const Identifier& id = get<1>(get<0>(idxQ)); r = shared_ptr<Message >(new Message(addr, id, entry)); } else { BOOST_LOG(*this) << "Invalid source queue during dequeue"; } return r; } }; //-------------------- // Queue constructors. shared_ptr<MessageQueues> simpleQueues(Address addr) { return shared_ptr<MessageQueues>(new SinglePeerQueue(addr)); } shared_ptr<MessageQueues> perPeerQueues(const list<Address>& addresses) { return shared_ptr<MessageQueues>(new MultiPeerQueue(addresses)); } shared_ptr<MessageQueues> perTriggerQueues(const list<Address>& addresses, const list<Identifier>& triggerIds) { return shared_ptr<MessageQueues>(new MultiTriggerQueue(addresses, triggerIds)); } } #endif <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "EC_Light.h" #include "ModuleInterface.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include "Entity.h" #include "OgreConversionUtils.h" #include "XMLUtilities.h" #include "RexNetworkUtils.h" #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("EC_Light") #include <Ogre.h> #include <QDomDocument> using namespace RexTypes; using namespace OgreRenderer; EC_Light::EC_Light(Foundation::ModuleInterface *module) : Foundation::ComponentInterface(module->GetFramework()), light_(0), attached_(false), typeAttr_(this, "light type", LT_Point), directionAttr_(this, "direction", Vector3df(0.0f, 0.0f, 1.0f)), diffColorAttr_(this, "diffuse color", Color(1.0f, 1.0f, 1.0f)), specColorAttr_(this, "specular color", Color(0.0f, 0.0f, 0.0f)), castShadowsAttr_(this, "cast shadows", false), rangeAttr_(this, "light range", 10.0f), constAttenAttr_(this, "constant atten", 1.0f), linearAttenAttr_(this, "linear atten", 0.0f), quadraAttenAttr_(this, "quadratic atten", 0.0f), innerAngleAttr_(this, "light inner angle", 30.0f), outerAngleAttr_(this, "light outer angle", 40.0f) { static AttributeMetadata typeAttrData; static bool metadataInitialized = false; if(!metadataInitialized) { typeAttrData.enums[LT_Point] = "Point"; typeAttrData.enums[LT_Spot] = "Spot"; typeAttrData.enums[LT_Directional] = "Directional"; metadataInitialized = true; } typeAttr_.SetMetadata(&typeAttrData); boost::shared_ptr<Renderer> renderer = module->GetFramework()->GetServiceManager()->GetService <Renderer>(Foundation::Service::ST_Renderer).lock(); if (!renderer) return; Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); light_ = scene_mgr->createLight(renderer->GetUniqueObjectName()); QObject::connect(this, SIGNAL(OnChanged()), this, SLOT(UpdateOgreLight())); } EC_Light::~EC_Light() { if (!GetFramework()) return; boost::shared_ptr<Renderer> renderer = GetFramework()->GetServiceManager()->GetService <Renderer>(Foundation::Service::ST_Renderer).lock(); if (!renderer) return; if (light_) { DetachLight(); Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); scene_mgr->destroyLight(light_); light_ = 0; } } void EC_Light::SetPlaceable(Foundation::ComponentPtr placeable) { if (dynamic_cast<EC_OgrePlaceable*>(placeable.get()) == 0) { LogError("Attempted to set a placeable which is not a placeable"); return; } if (placeable_ == placeable) return; DetachLight(); placeable_ = placeable; AttachLight(); } void EC_Light::AttachLight() { if ((placeable_) && (!attached_)) { EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get()); Ogre::SceneNode* node = placeable->GetSceneNode(); node->attachObject(light_); attached_ = true; } } void EC_Light::DetachLight() { if ((placeable_) && (attached_)) { EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get()); Ogre::SceneNode* node = placeable->GetSceneNode(); node->detachObject(light_); attached_ = false; } } void EC_Light::UpdateOgreLight() { // Now the true hack: because we don't (yet) store EC links/references, we hope to find a valid placeable from the entity, and to set it if (parent_entity_) { Foundation::ComponentPtr placeable = parent_entity_->GetComponent(EC_OgrePlaceable::TypeNameStatic()); if (placeable) SetPlaceable(placeable); else LogError("No EC_OgrePlaceable in entity, EC_Light could not attach itself to scenenode"); } else LogError("Parent entity not set, EC_Light could not auto-set placeable"); Ogre::Light::LightTypes ogre_type = Ogre::Light::LT_POINT; switch (typeAttr_.Get()) { case LT_Spot: ogre_type = Ogre::Light::LT_SPOTLIGHT; break; case LT_Directional: ogre_type = Ogre::Light::LT_DIRECTIONAL; break; } try { light_->setType(ogre_type); light_->setDirection(ToOgreVector3(directionAttr_.Get())); light_->setDiffuseColour(ToOgreColor(diffColorAttr_.Get())); light_->setSpecularColour(ToOgreColor(specColorAttr_.Get())); light_->setAttenuation(rangeAttr_.Get(), constAttenAttr_.Get(), linearAttenAttr_.Get(), quadraAttenAttr_.Get()); // Note: Ogre throws exception if we try to set this when light is not spotlight if (typeAttr_.Get() == LT_Spot) light_->setSpotlightRange(Ogre::Degree(innerAngleAttr_.Get()), Ogre::Degree(outerAngleAttr_.Get())); } catch (Ogre::Exception& e) { LogError("Exception while setting EC_Light parameters to Ogre: " + std::string(e.what())); } } <commit_msg>Better EC_Light default values so it looks nicer when added in comp editor. New default values courtesy of Manaluusuas ogre/math brain.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "EC_Light.h" #include "ModuleInterface.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include "Entity.h" #include "OgreConversionUtils.h" #include "XMLUtilities.h" #include "RexNetworkUtils.h" #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("EC_Light") #include <Ogre.h> #include <QDomDocument> using namespace RexTypes; using namespace OgreRenderer; EC_Light::EC_Light(Foundation::ModuleInterface *module) : Foundation::ComponentInterface(module->GetFramework()), light_(0), attached_(false), typeAttr_(this, "light type", LT_Point), directionAttr_(this, "direction", Vector3df(0.0f, 0.0f, 1.0f)), diffColorAttr_(this, "diffuse color", Color(1.0f, 1.0f, 1.0f)), specColorAttr_(this, "specular color", Color(0.0f, 0.0f, 0.0f)), castShadowsAttr_(this, "cast shadows", false), rangeAttr_(this, "light range", 100.0f), constAttenAttr_(this, "constant atten", 0.0f), linearAttenAttr_(this, "linear atten", 0.01f), quadraAttenAttr_(this, "quadratic atten", 0.01f), innerAngleAttr_(this, "light inner angle", 30.0f), outerAngleAttr_(this, "light outer angle", 40.0f) { static AttributeMetadata typeAttrData; static bool metadataInitialized = false; if(!metadataInitialized) { typeAttrData.enums[LT_Point] = "Point"; typeAttrData.enums[LT_Spot] = "Spot"; typeAttrData.enums[LT_Directional] = "Directional"; metadataInitialized = true; } typeAttr_.SetMetadata(&typeAttrData); boost::shared_ptr<Renderer> renderer = module->GetFramework()->GetServiceManager()->GetService <Renderer>(Foundation::Service::ST_Renderer).lock(); if (!renderer) return; Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); light_ = scene_mgr->createLight(renderer->GetUniqueObjectName()); QObject::connect(this, SIGNAL(OnChanged()), this, SLOT(UpdateOgreLight())); } EC_Light::~EC_Light() { if (!GetFramework()) return; boost::shared_ptr<Renderer> renderer = GetFramework()->GetServiceManager()->GetService <Renderer>(Foundation::Service::ST_Renderer).lock(); if (!renderer) return; if (light_) { DetachLight(); Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); scene_mgr->destroyLight(light_); light_ = 0; } } void EC_Light::SetPlaceable(Foundation::ComponentPtr placeable) { if (dynamic_cast<EC_OgrePlaceable*>(placeable.get()) == 0) { LogError("Attempted to set a placeable which is not a placeable"); return; } if (placeable_ == placeable) return; DetachLight(); placeable_ = placeable; AttachLight(); } void EC_Light::AttachLight() { if ((placeable_) && (!attached_)) { EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get()); Ogre::SceneNode* node = placeable->GetSceneNode(); node->attachObject(light_); attached_ = true; } } void EC_Light::DetachLight() { if ((placeable_) && (attached_)) { EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get()); Ogre::SceneNode* node = placeable->GetSceneNode(); node->detachObject(light_); attached_ = false; } } void EC_Light::UpdateOgreLight() { // Now the true hack: because we don't (yet) store EC links/references, we hope to find a valid placeable from the entity, and to set it if (parent_entity_) { Foundation::ComponentPtr placeable = parent_entity_->GetComponent(EC_OgrePlaceable::TypeNameStatic()); if (placeable) SetPlaceable(placeable); else LogError("No EC_OgrePlaceable in entity, EC_Light could not attach itself to scenenode"); } else LogError("Parent entity not set, EC_Light could not auto-set placeable"); Ogre::Light::LightTypes ogre_type = Ogre::Light::LT_POINT; switch (typeAttr_.Get()) { case LT_Spot: ogre_type = Ogre::Light::LT_SPOTLIGHT; break; case LT_Directional: ogre_type = Ogre::Light::LT_DIRECTIONAL; break; } try { light_->setType(ogre_type); light_->setDirection(ToOgreVector3(directionAttr_.Get())); light_->setDiffuseColour(ToOgreColor(diffColorAttr_.Get())); light_->setSpecularColour(ToOgreColor(specColorAttr_.Get())); light_->setAttenuation(rangeAttr_.Get(), constAttenAttr_.Get(), linearAttenAttr_.Get(), quadraAttenAttr_.Get()); // Note: Ogre throws exception if we try to set this when light is not spotlight if (typeAttr_.Get() == LT_Spot) light_->setSpotlightRange(Ogre::Degree(innerAngleAttr_.Get()), Ogre::Degree(outerAngleAttr_.Get())); } catch (Ogre::Exception& e) { LogError("Exception while setting EC_Light parameters to Ogre: " + std::string(e.what())); } } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // All code is property of Dictator Developers Inc // Contact at [email protected] for permission to use // Or to discuss ideas // (c) 2018 // Systems/CaravanTrade.cpp // When a Caravan is at the end of a route, perform the trade and turn around #include "../Core/typedef.h" #include "Systems.h" #include "../ECS/System.h" #include "../ECS/ECS.h" #include <algorithm> void CaravanTrade::ProgramInit() {} void CaravanTrade::SetupGameplay() {} enum class TradeType { PREFER_EXCHANGE, HIGHEST_AVAILABLE }; void PerformTrade( ECS_Core::Components::C_ResourceInventory& caravanInventory, ECS_Core::Components::C_ResourceInventory& buildingInventory, ECS_Core::Manager& manager, TradeType tradeType) { using namespace ECS_Core; // Drop off everything but some food for (auto&& resource : caravanInventory.m_collectedYields) { auto amountToMove = resource.first == Components::Yields::FOOD ? (resource.second > 100 ? (resource.second - 100) : 0) : resource.second; buildingInventory.m_collectedYields[resource.first] += amountToMove; resource.second -= amountToMove; } // Then take the most available yields in the inventory of the base, preferring those not carried back this way std::vector<std::pair<ECS_Core::Components::YieldType, f64>> heldResources; for (auto&& resource : buildingInventory.m_collectedYields) { heldResources.push_back(resource); } if (tradeType == TradeType::PREFER_EXCHANGE) { std::sort( heldResources.begin(), heldResources.end(), [&caravanInventory](auto& left, auto& right) -> bool { if (caravanInventory.m_collectedYields.count(left.first) && !caravanInventory.m_collectedYields.count(right.first)) { return false; } if (!caravanInventory.m_collectedYields.count(left.first) && caravanInventory.m_collectedYields.count(right.first)) { return true; } if (left.second < right.second) return false; if (left.second > right.second) return true; return left.first < right.first; }); } else { std::sort( heldResources.begin(), heldResources.end(), [](auto& left, auto& right) -> bool { if (left.second < right.second) return false; if (left.second > right.second) return true; return left.first < right.first; }); } // Reset inventory auto remainingFood = caravanInventory.m_collectedYields[Components::Yields::FOOD]; caravanInventory.m_collectedYields.clear(); auto foodToTake = min<f64>(100 - remainingFood, buildingInventory.m_collectedYields[Components::Yields::FOOD]); buildingInventory.m_collectedYields[Components::Yields::FOOD] -= foodToTake; caravanInventory.m_collectedYields[Components::Yields::FOOD] = remainingFood + foodToTake; auto resourcesMoved{ 0 }; for (auto&& resource : heldResources) { if (resource.second <= 100) continue; caravanInventory.m_collectedYields[resource.first] = 100; buildingInventory.m_collectedYields[resource.first] -= 100; if (++resourcesMoved >= 3) { break; } } } void CaravanTrade::Operate(GameLoopPhase phase, const timeuS& frameDuration) { using namespace ECS_Core; switch (phase) { case GameLoopPhase::ACTION_RESPONSE: m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_CaravanUnit>([&manager = m_managerRef]( const ecs::EntityIndex&, const Components::C_TilePosition& position, Components::C_MovingUnit& mover, Components::C_ResourceInventory& inventory, const Components::C_Population&, Components::C_CaravanPath& path) { if (position.m_position == path.m_basePath.m_path.front().m_tile && path.m_isReturning) { // Trade with home base and turn around if (!mover.m_currentMovement || !std::holds_alternative<Components::MoveToPoint>(*mover.m_currentMovement)) { return ecs::IterationBehavior::CONTINUE; } if (!manager.hasComponent<Components::C_ResourceInventory>(path.m_originBuildingHandle)) { return ecs::IterationBehavior::CONTINUE; } auto& baseInventory = manager.getComponent<Components::C_ResourceInventory>(path.m_originBuildingHandle); PerformTrade(inventory, baseInventory, manager, TradeType::HIGHEST_AVAILABLE); auto& moveToPoint = std::get<Components::MoveToPoint>(*mover.m_currentMovement); std::reverse(moveToPoint.m_path.begin(), moveToPoint.m_path.end()); moveToPoint.m_currentPathIndex = 0; moveToPoint.m_currentMovementProgress = 0; moveToPoint.m_targetPosition = moveToPoint.m_path.back().m_tile; path.m_isReturning = false; } else if (position.m_position == path.m_basePath.m_path.back().m_tile && !path.m_isReturning) { // Trade with target and turn around if (!mover.m_currentMovement || !std::holds_alternative<Components::MoveToPoint>(*mover.m_currentMovement)) { return ecs::IterationBehavior::CONTINUE; } if (!manager.hasComponent<Components::C_ResourceInventory>(path.m_targetBuildingHandle)) { return ecs::IterationBehavior::CONTINUE; } PerformTrade(inventory, manager.getComponent<Components::C_ResourceInventory>(path.m_targetBuildingHandle), manager, TradeType::PREFER_EXCHANGE); auto& moveToPoint = std::get<Components::MoveToPoint>(*mover.m_currentMovement); std::reverse(moveToPoint.m_path.begin(), moveToPoint.m_path.end()); moveToPoint.m_currentPathIndex = 0; moveToPoint.m_currentMovementProgress = 0; moveToPoint.m_targetPosition = moveToPoint.m_path.back().m_tile; path.m_isReturning = true; } return ecs::IterationBehavior::CONTINUE; }); break; case GameLoopPhase::PREPARATION: case GameLoopPhase::INPUT: case GameLoopPhase::ACTION: case GameLoopPhase::RENDER: case GameLoopPhase::CLEANUP: return; } } bool CaravanTrade::ShouldExit() { return false; } DEFINE_SYSTEM_INSTANTIATION(CaravanTrade);<commit_msg>No more food hole on caravans<commit_after>//----------------------------------------------------------------------------- // All code is property of Dictator Developers Inc // Contact at [email protected] for permission to use // Or to discuss ideas // (c) 2018 // Systems/CaravanTrade.cpp // When a Caravan is at the end of a route, perform the trade and turn around #include "../Core/typedef.h" #include "Systems.h" #include "../ECS/System.h" #include "../ECS/ECS.h" #include <algorithm> void CaravanTrade::ProgramInit() {} void CaravanTrade::SetupGameplay() {} enum class TradeType { PREFER_EXCHANGE, HIGHEST_AVAILABLE }; void PerformTrade( ECS_Core::Components::C_ResourceInventory& caravanInventory, ECS_Core::Components::C_ResourceInventory& buildingInventory, ECS_Core::Manager& manager, TradeType tradeType) { using namespace ECS_Core; // Drop off everything but some food for (auto&& resource : caravanInventory.m_collectedYields) { auto amountToMove = resource.first == Components::Yields::FOOD ? (resource.second > 100 ? (resource.second - 100) : 0) : resource.second; buildingInventory.m_collectedYields[resource.first] += amountToMove; resource.second -= amountToMove; } // Then take the most available yields in the inventory of the base, preferring those not carried back this way std::vector<std::pair<ECS_Core::Components::YieldType, f64>> heldResources; for (auto&& resource : buildingInventory.m_collectedYields) { heldResources.push_back(resource); } if (tradeType == TradeType::PREFER_EXCHANGE) { std::sort( heldResources.begin(), heldResources.end(), [&caravanInventory](auto& left, auto& right) -> bool { if (caravanInventory.m_collectedYields.count(left.first) && !caravanInventory.m_collectedYields.count(right.first)) { return false; } if (!caravanInventory.m_collectedYields.count(left.first) && caravanInventory.m_collectedYields.count(right.first)) { return true; } if (left.second < right.second) return false; if (left.second > right.second) return true; return left.first < right.first; }); } else { std::sort( heldResources.begin(), heldResources.end(), [](auto& left, auto& right) -> bool { if (left.second < right.second) return false; if (left.second > right.second) return true; return left.first < right.first; }); } // Reset inventory auto remainingFood = caravanInventory.m_collectedYields[Components::Yields::FOOD]; caravanInventory.m_collectedYields.clear(); auto foodToTake = min<f64>(100 - remainingFood, buildingInventory.m_collectedYields[Components::Yields::FOOD]); buildingInventory.m_collectedYields[Components::Yields::FOOD] -= foodToTake; caravanInventory.m_collectedYields[Components::Yields::FOOD] = remainingFood + foodToTake; auto resourcesMoved{ 0 }; for (auto&& resource : heldResources) { if (resource.second <= 100) continue; caravanInventory.m_collectedYields[resource.first] += 100; buildingInventory.m_collectedYields[resource.first] -= 100; if (++resourcesMoved >= 3) { break; } } } void CaravanTrade::Operate(GameLoopPhase phase, const timeuS& frameDuration) { using namespace ECS_Core; switch (phase) { case GameLoopPhase::ACTION_RESPONSE: m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_CaravanUnit>([&manager = m_managerRef]( const ecs::EntityIndex&, const Components::C_TilePosition& position, Components::C_MovingUnit& mover, Components::C_ResourceInventory& inventory, const Components::C_Population&, Components::C_CaravanPath& path) { if (position.m_position == path.m_basePath.m_path.front().m_tile && path.m_isReturning) { // Trade with home base and turn around if (!mover.m_currentMovement || !std::holds_alternative<Components::MoveToPoint>(*mover.m_currentMovement)) { return ecs::IterationBehavior::CONTINUE; } if (!manager.hasComponent<Components::C_ResourceInventory>(path.m_originBuildingHandle)) { return ecs::IterationBehavior::CONTINUE; } auto& baseInventory = manager.getComponent<Components::C_ResourceInventory>(path.m_originBuildingHandle); PerformTrade(inventory, baseInventory, manager, TradeType::HIGHEST_AVAILABLE); auto& moveToPoint = std::get<Components::MoveToPoint>(*mover.m_currentMovement); std::reverse(moveToPoint.m_path.begin(), moveToPoint.m_path.end()); moveToPoint.m_currentPathIndex = 0; moveToPoint.m_currentMovementProgress = 0; moveToPoint.m_targetPosition = moveToPoint.m_path.back().m_tile; path.m_isReturning = false; } else if (position.m_position == path.m_basePath.m_path.back().m_tile && !path.m_isReturning) { // Trade with target and turn around if (!mover.m_currentMovement || !std::holds_alternative<Components::MoveToPoint>(*mover.m_currentMovement)) { return ecs::IterationBehavior::CONTINUE; } if (!manager.hasComponent<Components::C_ResourceInventory>(path.m_targetBuildingHandle)) { return ecs::IterationBehavior::CONTINUE; } PerformTrade(inventory, manager.getComponent<Components::C_ResourceInventory>(path.m_targetBuildingHandle), manager, TradeType::PREFER_EXCHANGE); auto& moveToPoint = std::get<Components::MoveToPoint>(*mover.m_currentMovement); std::reverse(moveToPoint.m_path.begin(), moveToPoint.m_path.end()); moveToPoint.m_currentPathIndex = 0; moveToPoint.m_currentMovementProgress = 0; moveToPoint.m_targetPosition = moveToPoint.m_path.back().m_tile; path.m_isReturning = true; } return ecs::IterationBehavior::CONTINUE; }); break; case GameLoopPhase::PREPARATION: case GameLoopPhase::INPUT: case GameLoopPhase::ACTION: case GameLoopPhase::RENDER: case GameLoopPhase::CLEANUP: return; } } bool CaravanTrade::ShouldExit() { return false; } DEFINE_SYSTEM_INSTANTIATION(CaravanTrade);<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: npwrap.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-03-29 13:06:21 $ * * 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): _______________________________________ * * ************************************************************************/ #include <errno.h> #include <dlfcn.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <plugin/unx/plugcon.hxx> PluginConnector* pConnector = NULL; int nAppArguments = 0; char** pAppArguments = NULL; Display* pAppDisplay = NULL; extern void* pPluginLib; extern NPError (*pNP_Shutdown)(); void LoadAdditionalLibs(const char*); XtAppContext app_context; Widget topLevel = NULL, topBox = NULL; int wakeup_fd[2] = { 0, 0 }; static bool bPluginAppQuit = false; static long GlobalConnectionLostHdl( void* pInst, void* pArg ) { medDebug( 1, "pluginapp exiting due to connection lost\n" ); write( wakeup_fd[1], "xxxx", 4 ); return 0; } extern "C" { static int plugin_x_error_handler( Display*, XErrorEvent* ) { return 0; } static void ThreadEventHandler( XtPointer client_data, int* source, XtInputId* id ) { char buf[256]; // clear pipe int len, nLast = -1; while( (len = read( wakeup_fd[0], buf, sizeof( buf ) ) ) > 0 ) nLast = len-1; if( ! bPluginAppQuit ) { if( ( nLast == -1 || buf[nLast] != 'x' ) && pConnector ) pConnector->CallWorkHandler(); else { // it seems you can use XtRemoveInput only // safely from within the callback // why is that ? medDebug( 1, "removing wakeup pipe\n" ); XtRemoveInput( *id ); XtAppSetExitFlag( app_context ); bPluginAppQuit = true; delete pConnector; pConnector = NULL; } } } } IMPL_LINK( PluginConnector, NewMessageHdl, Mediator*, pMediator ) { medDebug( 1, "new message handler\n" ); write( wakeup_fd[1], "cccc", 4 ); return 0; } Widget createSubWidget( char* pPluginText, Widget shell, XLIB_Window aParentWindow ) { Widget newWidget = XtVaCreateManagedWidget( #if defined USE_MOTIF "drawingArea", xmDrawingAreaWidgetClass, #else "", labelWidgetClass, #endif shell, XtNwidth, 200, XtNheight, 200, NULL ); XtRealizeWidget( shell ); medDebug( 1, "Reparenting new widget %x to %x\n", XtWindow( newWidget ), aParentWindow ); XReparentWindow( pAppDisplay, XtWindow( shell ), aParentWindow, 0, 0 ); XtMapWidget( shell ); XtMapWidget( newWidget ); XRaiseWindow( pAppDisplay, XtWindow( shell ) ); XSync( pAppDisplay, False ); return newWidget; } void* CreateNewShell( void** pShellReturn, XLIB_Window aParentWindow ) { XLIB_String n, c; XtGetApplicationNameAndClass(pAppDisplay, &n, &c); Widget newShell = XtVaAppCreateShell( "pane", c, topLevelShellWidgetClass, pAppDisplay, XtNwidth, 200, XtNheight, 200, XtNoverrideRedirect, True, NULL ); *pShellReturn = newShell; char pText[1024]; sprintf( pText, "starting plugin %s ...", pAppArguments[2] ); Widget newWidget = createSubWidget( pText, newShell, aParentWindow ); return newWidget; } // Unix specific implementation static void CheckPlugin( const char* pPath ) { rtl_TextEncoding aEncoding = osl_getThreadTextEncoding(); void *pLib = dlopen( pPath, RTLD_LAZY ); if( ! pLib ) { medDebug( 1, "could not dlopen( %s ) (%s)\n", pPath, dlerror() ); return; } char*(*pNP_GetMIMEDescription)() = (char*(*)()) dlsym( pLib, "NP_GetMIMEDescription" ); if( pNP_GetMIMEDescription ) printf( "%s\n", pNP_GetMIMEDescription() ); else medDebug( 1, "could not dlsym NP_GetMIMEDescription (%s)\n", dlerror() ); dlclose( pLib ); } #if OSL_DEBUG_LEVEL > 1 && defined LINUX #include <execinfo.h> #endif extern "C" { static void signal_handler( int nSig ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "caught signal %d, exiting\n", nSig ); #ifdef LINUX void* pStack[64]; int nStackLevels = backtrace( pStack, sizeof(pStack)/sizeof(pStack[0]) ); backtrace_symbols_fd( pStack, nStackLevels, STDERR_FILENO ); #endif #endif if( pConnector ) { // ensure that a read on the other side will wakeup delete pConnector; pConnector = NULL; } _exit(nSig); } } int main( int argc, char **argv) { struct sigaction aSigAction; aSigAction.sa_handler = signal_handler; sigemptyset( &aSigAction.sa_mask ); aSigAction.sa_flags = SA_NOCLDSTOP; sigaction( SIGSEGV, &aSigAction, NULL ); sigaction( SIGBUS, &aSigAction, NULL ); sigaction( SIGABRT, &aSigAction, NULL ); sigaction( SIGTERM, &aSigAction, NULL ); sigaction( SIGILL, &aSigAction, NULL ); int nArg = (argc < 3) ? 1 : 2; char* pBaseName = argv[nArg] + strlen(argv[nArg]); while( pBaseName > argv[nArg] && pBaseName[-1] != '/' ) pBaseName--; LoadAdditionalLibs( pBaseName ); if( argc < 3 ) { CheckPlugin(argv[1]); exit(0); } nAppArguments = argc; pAppArguments = argv; XSetErrorHandler( plugin_x_error_handler ); if( pipe( wakeup_fd ) ) { medDebug( 1, "could not pipe()\n" ); return 1; } // initialize 'wakeup' pipe. int flags; // set close-on-exec descriptor flag. if ((flags = fcntl (wakeup_fd[0], F_GETFD)) != -1) { flags |= FD_CLOEXEC; fcntl (wakeup_fd[0], F_SETFD, flags); } if ((flags = fcntl (wakeup_fd[1], F_GETFD)) != -1) { flags |= FD_CLOEXEC; fcntl (wakeup_fd[1], F_SETFD, flags); } // set non-blocking I/O flag. if ((flags = fcntl (wakeup_fd[0], F_GETFL)) != -1) { flags |= O_NONBLOCK; fcntl (wakeup_fd[0], F_SETFL, flags); } if ((flags = fcntl (wakeup_fd[1], F_GETFL)) != -1) { flags |= O_NONBLOCK; fcntl (wakeup_fd[1], F_SETFL, flags); } pPluginLib = dlopen( argv[2], RTLD_LAZY ); if( ! pPluginLib ) { medDebug( 1, "dlopen on %s failed because of:\n\t%s\n", argv[2], dlerror() ); exit(255); } int nSocket = atol( argv[1] ); pConnector = new PluginConnector( nSocket ); pConnector->SetConnectionLostHdl( Link( NULL, GlobalConnectionLostHdl ) ); XtSetLanguageProc( NULL, NULL, NULL ); topLevel = XtVaOpenApplication( &app_context, /* Application context */ "SOPlugin", /* Application class */ NULL, 0, /* command line option list */ &argc, argv, /* command line args */ NULL, /* for missing app-defaults file */ topLevelShellWidgetClass, XtNoverrideRedirect, True, NULL); /* terminate varargs list */ pAppDisplay = XtDisplay( topLevel ); XtAppAddInput( app_context, wakeup_fd[0], (XtPointer)XtInputReadMask, ThreadEventHandler, NULL ); /* * Create windows for widgets and map them. */ INT32 nWindow; sscanf( argv[3], "%d", &nWindow ); char pText[1024]; sprintf( pText, "starting plugin %s ...", pAppArguments[2] ); topBox = createSubWidget( pText, topLevel, (XLIB_Window)nWindow ); // send that we are ready to go MediatorMessage* pMessage = pConnector->Transact( "init req", 8, NULL ); delete pMessage; #if OSL_DEBUG_LEVEL > 3 int nPID = getpid(); int nChild = fork(); if( nChild == 0 ) { char pidbuf[16]; char* pArgs[] = { "xterm", "-sl", "2000", "-sb", "-e", "gdb", "pluginapp.bin", pidbuf, NULL }; sprintf( pidbuf, "%d", nPID ); execvp( pArgs[0], pArgs ); _exit(255); } else sleep( 10 ); #endif /* * Loop for events. */ // for some reason XtAppSetExitFlag won't quit the application // in ThreadEventHandler most of times; Xt will hang in select // (hat is in XtAppNextEvent). Have our own mainloop instead // of XtAppMainLoop do { XtAppProcessEvent( app_context, XtIMAll ); } while( ! XtAppGetExitFlag( app_context ) && ! bPluginAppQuit ); medDebug( 1, "left plugin app main loop\n" ); pNP_Shutdown(); medDebug( 1, "NP_Shutdown done\n" ); dlclose( pPluginLib ); medDebug( 1, "plugin close\n" ); close( wakeup_fd[0] ); close( wakeup_fd[1] ); return 0; } #ifdef GCC extern "C" { void __pure_virtual() {} void* __builtin_new( int nBytes ) { return malloc(nBytes); } void* __builtin_vec_new( int nBytes ) { return malloc(nBytes); } void __builtin_delete( char* pMem ) { free(pMem); } void __builtin_vec_delete( char* pMem ) { free(pMem); } } #endif <commit_msg>INTEGRATION: CWS hr16 (1.10.52); FILE MERGED 2005/06/13 16:35:16 hr 1.10.52.1: #i47959#: fix gcc-4.0 warning<commit_after>/************************************************************************* * * $RCSfile: npwrap.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-06-21 10:31:46 $ * * 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): _______________________________________ * * ************************************************************************/ #include <errno.h> #include <dlfcn.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <plugin/unx/plugcon.hxx> PluginConnector* pConnector = NULL; int nAppArguments = 0; char** pAppArguments = NULL; Display* pAppDisplay = NULL; extern void* pPluginLib; extern NPError (*pNP_Shutdown)(); void LoadAdditionalLibs(const char*); XtAppContext app_context; Widget topLevel = NULL, topBox = NULL; int wakeup_fd[2] = { 0, 0 }; static bool bPluginAppQuit = false; static long GlobalConnectionLostHdl( void* pInst, void* pArg ) { medDebug( 1, "pluginapp exiting due to connection lost\n" ); write( wakeup_fd[1], "xxxx", 4 ); return 0; } extern "C" { static int plugin_x_error_handler( Display*, XErrorEvent* ) { return 0; } static void ThreadEventHandler( XtPointer client_data, int* source, XtInputId* id ) { char buf[256]; // clear pipe int len, nLast = -1; while( (len = read( wakeup_fd[0], buf, sizeof( buf ) ) ) > 0 ) nLast = len-1; if( ! bPluginAppQuit ) { if( ( nLast == -1 || buf[nLast] != 'x' ) && pConnector ) pConnector->CallWorkHandler(); else { // it seems you can use XtRemoveInput only // safely from within the callback // why is that ? medDebug( 1, "removing wakeup pipe\n" ); XtRemoveInput( *id ); XtAppSetExitFlag( app_context ); bPluginAppQuit = true; delete pConnector; pConnector = NULL; } } } } IMPL_LINK( PluginConnector, NewMessageHdl, Mediator*, pMediator ) { medDebug( 1, "new message handler\n" ); write( wakeup_fd[1], "cccc", 4 ); return 0; } Widget createSubWidget( char* pPluginText, Widget shell, XLIB_Window aParentWindow ) { Widget newWidget = XtVaCreateManagedWidget( #if defined USE_MOTIF "drawingArea", xmDrawingAreaWidgetClass, #else "", labelWidgetClass, #endif shell, XtNwidth, 200, XtNheight, 200, (char *)NULL ); XtRealizeWidget( shell ); medDebug( 1, "Reparenting new widget %x to %x\n", XtWindow( newWidget ), aParentWindow ); XReparentWindow( pAppDisplay, XtWindow( shell ), aParentWindow, 0, 0 ); XtMapWidget( shell ); XtMapWidget( newWidget ); XRaiseWindow( pAppDisplay, XtWindow( shell ) ); XSync( pAppDisplay, False ); return newWidget; } void* CreateNewShell( void** pShellReturn, XLIB_Window aParentWindow ) { XLIB_String n, c; XtGetApplicationNameAndClass(pAppDisplay, &n, &c); Widget newShell = XtVaAppCreateShell( "pane", c, topLevelShellWidgetClass, pAppDisplay, XtNwidth, 200, XtNheight, 200, XtNoverrideRedirect, True, (char *)NULL ); *pShellReturn = newShell; char pText[1024]; sprintf( pText, "starting plugin %s ...", pAppArguments[2] ); Widget newWidget = createSubWidget( pText, newShell, aParentWindow ); return newWidget; } // Unix specific implementation static void CheckPlugin( const char* pPath ) { rtl_TextEncoding aEncoding = osl_getThreadTextEncoding(); void *pLib = dlopen( pPath, RTLD_LAZY ); if( ! pLib ) { medDebug( 1, "could not dlopen( %s ) (%s)\n", pPath, dlerror() ); return; } char*(*pNP_GetMIMEDescription)() = (char*(*)()) dlsym( pLib, "NP_GetMIMEDescription" ); if( pNP_GetMIMEDescription ) printf( "%s\n", pNP_GetMIMEDescription() ); else medDebug( 1, "could not dlsym NP_GetMIMEDescription (%s)\n", dlerror() ); dlclose( pLib ); } #if OSL_DEBUG_LEVEL > 1 && defined LINUX #include <execinfo.h> #endif extern "C" { static void signal_handler( int nSig ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "caught signal %d, exiting\n", nSig ); #ifdef LINUX void* pStack[64]; int nStackLevels = backtrace( pStack, sizeof(pStack)/sizeof(pStack[0]) ); backtrace_symbols_fd( pStack, nStackLevels, STDERR_FILENO ); #endif #endif if( pConnector ) { // ensure that a read on the other side will wakeup delete pConnector; pConnector = NULL; } _exit(nSig); } } int main( int argc, char **argv) { struct sigaction aSigAction; aSigAction.sa_handler = signal_handler; sigemptyset( &aSigAction.sa_mask ); aSigAction.sa_flags = SA_NOCLDSTOP; sigaction( SIGSEGV, &aSigAction, NULL ); sigaction( SIGBUS, &aSigAction, NULL ); sigaction( SIGABRT, &aSigAction, NULL ); sigaction( SIGTERM, &aSigAction, NULL ); sigaction( SIGILL, &aSigAction, NULL ); int nArg = (argc < 3) ? 1 : 2; char* pBaseName = argv[nArg] + strlen(argv[nArg]); while( pBaseName > argv[nArg] && pBaseName[-1] != '/' ) pBaseName--; LoadAdditionalLibs( pBaseName ); if( argc < 3 ) { CheckPlugin(argv[1]); exit(0); } nAppArguments = argc; pAppArguments = argv; XSetErrorHandler( plugin_x_error_handler ); if( pipe( wakeup_fd ) ) { medDebug( 1, "could not pipe()\n" ); return 1; } // initialize 'wakeup' pipe. int flags; // set close-on-exec descriptor flag. if ((flags = fcntl (wakeup_fd[0], F_GETFD)) != -1) { flags |= FD_CLOEXEC; fcntl (wakeup_fd[0], F_SETFD, flags); } if ((flags = fcntl (wakeup_fd[1], F_GETFD)) != -1) { flags |= FD_CLOEXEC; fcntl (wakeup_fd[1], F_SETFD, flags); } // set non-blocking I/O flag. if ((flags = fcntl (wakeup_fd[0], F_GETFL)) != -1) { flags |= O_NONBLOCK; fcntl (wakeup_fd[0], F_SETFL, flags); } if ((flags = fcntl (wakeup_fd[1], F_GETFL)) != -1) { flags |= O_NONBLOCK; fcntl (wakeup_fd[1], F_SETFL, flags); } pPluginLib = dlopen( argv[2], RTLD_LAZY ); if( ! pPluginLib ) { medDebug( 1, "dlopen on %s failed because of:\n\t%s\n", argv[2], dlerror() ); exit(255); } int nSocket = atol( argv[1] ); pConnector = new PluginConnector( nSocket ); pConnector->SetConnectionLostHdl( Link( NULL, GlobalConnectionLostHdl ) ); XtSetLanguageProc( NULL, NULL, NULL ); topLevel = XtVaOpenApplication( &app_context, /* Application context */ "SOPlugin", /* Application class */ NULL, 0, /* command line option list */ &argc, argv, /* command line args */ NULL, /* for missing app-defaults file */ topLevelShellWidgetClass, XtNoverrideRedirect, True, (char *)NULL); /* terminate varargs list */ pAppDisplay = XtDisplay( topLevel ); XtAppAddInput( app_context, wakeup_fd[0], (XtPointer)XtInputReadMask, ThreadEventHandler, NULL ); /* * Create windows for widgets and map them. */ INT32 nWindow; sscanf( argv[3], "%d", &nWindow ); char pText[1024]; sprintf( pText, "starting plugin %s ...", pAppArguments[2] ); topBox = createSubWidget( pText, topLevel, (XLIB_Window)nWindow ); // send that we are ready to go MediatorMessage* pMessage = pConnector->Transact( "init req", 8, NULL ); delete pMessage; #if OSL_DEBUG_LEVEL > 3 int nPID = getpid(); int nChild = fork(); if( nChild == 0 ) { char pidbuf[16]; char* pArgs[] = { "xterm", "-sl", "2000", "-sb", "-e", "gdb", "pluginapp.bin", pidbuf, NULL }; sprintf( pidbuf, "%d", nPID ); execvp( pArgs[0], pArgs ); _exit(255); } else sleep( 10 ); #endif /* * Loop for events. */ // for some reason XtAppSetExitFlag won't quit the application // in ThreadEventHandler most of times; Xt will hang in select // (hat is in XtAppNextEvent). Have our own mainloop instead // of XtAppMainLoop do { XtAppProcessEvent( app_context, XtIMAll ); } while( ! XtAppGetExitFlag( app_context ) && ! bPluginAppQuit ); medDebug( 1, "left plugin app main loop\n" ); pNP_Shutdown(); medDebug( 1, "NP_Shutdown done\n" ); dlclose( pPluginLib ); medDebug( 1, "plugin close\n" ); close( wakeup_fd[0] ); close( wakeup_fd[1] ); return 0; } #ifdef GCC extern "C" { void __pure_virtual() {} void* __builtin_new( int nBytes ) { return malloc(nBytes); } void* __builtin_vec_new( int nBytes ) { return malloc(nBytes); } void __builtin_delete( char* pMem ) { free(pMem); } void __builtin_vec_delete( char* pMem ) { free(pMem); } } #endif <|endoftext|>
<commit_before><commit_msg>Fix a crash when using negotiate HTTP auth.<commit_after><|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Maarten Ballintijn 21/06/2004 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TParameter TParameter <AParamType> . Named parameter, streamable and storable. */ #include "TParameter.h" templateClassImp(TParameter) <commit_msg>Fix doxygen errors<commit_after>// @(#)root/base:$Id$ // Author: Maarten Ballintijn 21/06/2004 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TParameter Named parameter, streamable and storable. */ #include "TParameter.h" templateClassImp(TParameter) <|endoftext|>
<commit_before>#include "PythonInteractor.h" #include "Scene.h" #include <SofaPython/PythonCommon.h> #include <SofaPython/PythonEnvironment.h> #include <SofaPython/ScriptEnvironment.h> #include <SofaPython/PythonMacros.h> #include <SofaPython/PythonScriptController.h> #include <SofaPython/PythonScriptFunction.h> #include <qqml.h> #include <QDebug> #include <QSequentialIterable> #include <vector> PythonInteractor::PythonInteractor(QObject *parent) : QObject(parent), QQmlParserStatus(), myScene(0), myPythonScriptControllers() { connect(this, &PythonInteractor::sceneChanged, this, &PythonInteractor::handleSceneChanged); } PythonInteractor::~PythonInteractor() { } void PythonInteractor::classBegin() { } void PythonInteractor::componentComplete() { if(!myScene) setScene(qobject_cast<Scene*>(parent())); } void PythonInteractor::setScene(Scene* newScene) { if(newScene == myScene) return; myScene = newScene; sceneChanged(newScene); } void PythonInteractor::handleSceneChanged(Scene* scene) { if(scene) { if(scene->isReady()) retrievePythonScriptControllers(); connect(scene, &Scene::loaded, this, &PythonInteractor::retrievePythonScriptControllers); } } void PythonInteractor::retrievePythonScriptControllers() { myPythonScriptControllers.clear(); if(!myScene || !myScene->isReady()) return; std::vector<PythonScriptController*> pythonScriptControllers; myScene->sofaSimulation()->GetRoot()->get<PythonScriptController>(&pythonScriptControllers, sofa::core::objectmodel::BaseContext::SearchDown); for(size_t i = 0; i < pythonScriptControllers.size(); ++i) myPythonScriptControllers.insert(pythonScriptControllers[i]->m_classname.getValue().c_str(), pythonScriptControllers[i]); } static PyObject* PythonBuildValueHelper(const QVariant& parameter) { PyObject* value = 0; if(!parameter.isNull()) { switch(parameter.type()) { case QVariant::Bool: value = Py_BuildValue("b", parameter.toBool()); break; case QVariant::Int: value = Py_BuildValue("i", parameter.toInt()); break; case QVariant::UInt: value = Py_BuildValue("I", parameter.toUInt()); break; case QVariant::Double: value = Py_BuildValue("d", parameter.toDouble()); break; case QVariant::String: value = Py_BuildValue("s", parameter.toString().toLatin1().constData()); break; default: value = Py_BuildValue(""); qDebug() << "ERROR: buildPythonParameterHelper, type not supported:" << parameter.typeName(); break; } } return value; } static PyObject* PythonBuildTupleHelper(const QVariant& parameter) { PyObject* tuple = 0; if(!parameter.isNull()) { if(parameter.canConvert<QVariantList>()) { QSequentialIterable parameterIterable = parameter.value<QSequentialIterable>(); tuple = PyTuple_New(parameterIterable.size()); int count = 0; for(const QVariant& i : parameterIterable) PyTuple_SetItem(tuple, count++, PythonBuildValueHelper(i)); } else { tuple = PyTuple_New(1); PyTuple_SetItem(tuple, 0, PythonBuildValueHelper(parameter)); } } return tuple; } static QVariant ExtractPythonValueHelper(PyObject* parameter) { QVariant value; if(parameter) { if(PyBool_Check(parameter)) value = (Py_False != parameter); else if(PyInt_Check(parameter)) value = (int)PyInt_AsLong(parameter); else if(PyFloat_Check(parameter)) value = PyFloat_AsDouble(parameter); else if(PyString_Check(parameter)) value = PyString_AsString(parameter); } return value; } static QVariant ExtractPythonTupleHelper(PyObject* parameter) { QVariant value; if(!parameter) return value; if(PyTuple_Check(parameter) || PyList_Check(parameter)) { QVariantList tuple; PyObject *iterator = PyObject_GetIter(parameter); PyObject *item; if(!iterator) { qDebug() << "ERROR: Python tuple/list is empty"; return value; } while(item = PyIter_Next(iterator)) { tuple.append(ExtractPythonValueHelper(item)); Py_DECREF(item); } Py_DECREF(iterator); if(PyErr_Occurred()) qDebug() << "ERROR: during python tuple/list iteration"; return tuple; } value = ExtractPythonValueHelper(parameter); return value; } QVariant PythonInteractor::call(const QString& pythonClassName, const QString& funcName, const QVariant& parameter) { QVariant result; if(!myScene) { qDebug() << "ERROR: cannot call Python function on a null scene"; return result; } if(!myScene->isReady()) { qDebug() << "ERROR: cannot call Python function on a scene that is still loading"; return result; } if(pythonClassName.isEmpty()) { qDebug() << "ERROR: cannot call Python function without a valid python class name"; return result; } if(funcName.isEmpty()) { qDebug() << "ERROR: cannot call Python function without a valid python function name"; return result; } auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName); if(myPythonScriptControllers.end() == pythonScriptControllerIterator) { qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName; if(myPythonScriptControllers.isEmpty()) { qDebug() << "There is no PythonScriptController"; } else { qDebug() << "Known PythonScriptController(s):"; for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys()) qDebug() << "-" << pythonScriptControllerName; } return result; } PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value(); if(pythonScriptController) { PyObject* pyCallableObject = PyObject_GetAttrString(pythonScriptController->scriptControllerInstance(), funcName.toLatin1().constData()); if(!pyCallableObject) { qDebug() << "ERROR: cannot call Python function without a valid python class and function name"; } else { PythonScriptFunction pythonScriptFunction(pyCallableObject, true); PythonScriptFunctionParameter pythonScriptParameter(PythonBuildTupleHelper(parameter), true); PythonScriptFunctionResult pythonScriptResult; pythonScriptFunction(&pythonScriptParameter, &pythonScriptResult); result = ExtractPythonTupleHelper(pythonScriptResult.data()); } } return result; } void PythonInteractor::sendEvent(const QString& pythonClassName, const QString& eventName, const QVariant& parameter) { if(!myScene) { qDebug() << "ERROR: cannot send Python event on a null scene"; return; } if(!myScene->isReady()) { qDebug() << "ERROR: cannot send Python event on a scene that is still loading"; return; } auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName); if(myPythonScriptControllers.end() == pythonScriptControllerIterator) { qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName; if(myPythonScriptControllers.isEmpty()) { qDebug() << "There is no PythonScriptController"; } else { qDebug() << "Known PythonScriptController(s):"; for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys()) qDebug() << "-" << pythonScriptControllerName; } return; } PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value(); PyObject* pyParameter = PythonBuildValueHelper(parameter); if(!pyParameter) pyParameter = Py_BuildValue(""); sofa::core::objectmodel::PythonScriptEvent pythonScriptEvent(myScene->sofaSimulation()->GetRoot(), eventName.toLatin1().constData(), pyParameter); pythonScriptController->handleEvent(&pythonScriptEvent); } void PythonInteractor::sendEventToAll(const QString& eventName, const QVariant& parameter) { for(const QString& pythonClassName : myPythonScriptControllers.keys()) sendEvent(pythonClassName, eventName, parameter); } <commit_msg>UPDATE: PythonInteractor can now handle inner list/tuple (i.e. list inside list, tuple inside tuple, etc.) for function parameters and return values<commit_after>#include "PythonInteractor.h" #include "Scene.h" #include <SofaPython/PythonCommon.h> #include <SofaPython/PythonEnvironment.h> #include <SofaPython/ScriptEnvironment.h> #include <SofaPython/PythonMacros.h> #include <SofaPython/PythonScriptController.h> #include <SofaPython/PythonScriptFunction.h> #include <qqml.h> #include <QDebug> #include <QSequentialIterable> #include <vector> PythonInteractor::PythonInteractor(QObject *parent) : QObject(parent), QQmlParserStatus(), myScene(0), myPythonScriptControllers() { connect(this, &PythonInteractor::sceneChanged, this, &PythonInteractor::handleSceneChanged); } PythonInteractor::~PythonInteractor() { } void PythonInteractor::classBegin() { } void PythonInteractor::componentComplete() { if(!myScene) setScene(qobject_cast<Scene*>(parent())); } void PythonInteractor::setScene(Scene* newScene) { if(newScene == myScene) return; myScene = newScene; sceneChanged(newScene); } void PythonInteractor::handleSceneChanged(Scene* scene) { if(scene) { if(scene->isReady()) retrievePythonScriptControllers(); connect(scene, &Scene::loaded, this, &PythonInteractor::retrievePythonScriptControllers); } } void PythonInteractor::retrievePythonScriptControllers() { myPythonScriptControllers.clear(); if(!myScene || !myScene->isReady()) return; std::vector<PythonScriptController*> pythonScriptControllers; myScene->sofaSimulation()->GetRoot()->get<PythonScriptController>(&pythonScriptControllers, sofa::core::objectmodel::BaseContext::SearchDown); for(size_t i = 0; i < pythonScriptControllers.size(); ++i) myPythonScriptControllers.insert(pythonScriptControllers[i]->m_classname.getValue().c_str(), pythonScriptControllers[i]); } static PyObject* PythonBuildValueHelper(const QVariant& parameter) { PyObject* value = 0; if(!parameter.isNull()) { switch(parameter.type()) { case QVariant::Bool: value = Py_BuildValue("b", parameter.toBool()); break; case QVariant::Int: value = Py_BuildValue("i", parameter.toInt()); break; case QVariant::UInt: value = Py_BuildValue("I", parameter.toUInt()); break; case QVariant::Double: value = Py_BuildValue("d", parameter.toDouble()); break; case QVariant::String: value = Py_BuildValue("s", parameter.toString().toLatin1().constData()); break; default: value = Py_BuildValue(""); qDebug() << "ERROR: buildPythonParameterHelper, type not supported:" << parameter.typeName(); break; } } return value; } static PyObject* PythonBuildTupleHelper(const QVariant& parameter, bool mustBeTuple) { PyObject* tuple = 0; if(!parameter.isNull()) { if(parameter.canConvert<QVariantList>()) { QSequentialIterable parameterIterable = parameter.value<QSequentialIterable>(); tuple = PyTuple_New(parameterIterable.size()); int count = 0; for(const QVariant& i : parameterIterable) PyTuple_SetItem(tuple, count++, PythonBuildTupleHelper(i, false)); } else { if(mustBeTuple) { tuple = PyTuple_New(1); PyTuple_SetItem(tuple, 0, PythonBuildValueHelper(parameter)); } else { tuple = PythonBuildValueHelper(parameter); } } } return tuple; } static QVariant ExtractPythonValueHelper(PyObject* parameter) { QVariant value; if(parameter) { if(PyBool_Check(parameter)) value = (Py_False != parameter); else if(PyInt_Check(parameter)) value = (int)PyInt_AsLong(parameter); else if(PyFloat_Check(parameter)) value = PyFloat_AsDouble(parameter); else if(PyString_Check(parameter)) value = PyString_AsString(parameter); } return value; } static QVariant ExtractPythonTupleHelper(PyObject* parameter) { QVariant value; if(!parameter) return value; if(PyTuple_Check(parameter) || PyList_Check(parameter)) { QVariantList tuple; if(PyList_Check(parameter)) qDebug() << "length:" << PyList_Size(parameter); else qDebug() << "length:" << PyTuple_Size(parameter); PyObject *iterator = PyObject_GetIter(parameter); PyObject *item; if(!iterator) { qDebug() << "ERROR: Python tuple/list is empty"; return value; } while(item = PyIter_Next(iterator)) { tuple.append(ExtractPythonTupleHelper(item)); Py_DECREF(item); } Py_DECREF(iterator); if(PyErr_Occurred()) qDebug() << "ERROR: during python tuple/list iteration"; return tuple; } value = ExtractPythonValueHelper(parameter); return value; } QVariant PythonInteractor::call(const QString& pythonClassName, const QString& funcName, const QVariant& parameter) { QVariant result; if(!myScene) { qDebug() << "ERROR: cannot call Python function on a null scene"; return result; } if(!myScene->isReady()) { qDebug() << "ERROR: cannot call Python function on a scene that is still loading"; return result; } if(pythonClassName.isEmpty()) { qDebug() << "ERROR: cannot call Python function without a valid python class name"; return result; } if(funcName.isEmpty()) { qDebug() << "ERROR: cannot call Python function without a valid python function name"; return result; } auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName); if(myPythonScriptControllers.end() == pythonScriptControllerIterator) { qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName; if(myPythonScriptControllers.isEmpty()) { qDebug() << "There is no PythonScriptController"; } else { qDebug() << "Known PythonScriptController(s):"; for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys()) qDebug() << "-" << pythonScriptControllerName; } return result; } PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value(); if(pythonScriptController) { PyObject* pyCallableObject = PyObject_GetAttrString(pythonScriptController->scriptControllerInstance(), funcName.toLatin1().constData()); if(!pyCallableObject) { qDebug() << "ERROR: cannot call Python function without a valid python class and function name"; } else { PythonScriptFunction pythonScriptFunction(pyCallableObject, true); PythonScriptFunctionParameter pythonScriptParameter(PythonBuildTupleHelper(parameter, true), true); PythonScriptFunctionResult pythonScriptResult; pythonScriptFunction(&pythonScriptParameter, &pythonScriptResult); result = ExtractPythonTupleHelper(pythonScriptResult.data()); } } return result; } void PythonInteractor::sendEvent(const QString& pythonClassName, const QString& eventName, const QVariant& parameter) { if(!myScene) { qDebug() << "ERROR: cannot send Python event on a null scene"; return; } if(!myScene->isReady()) { qDebug() << "ERROR: cannot send Python event on a scene that is still loading"; return; } auto pythonScriptControllerIterator = myPythonScriptControllers.find(pythonClassName); if(myPythonScriptControllers.end() == pythonScriptControllerIterator) { qDebug() << "ERROR: cannot send Python event on an unknown script controller:" << pythonClassName; if(myPythonScriptControllers.isEmpty()) { qDebug() << "There is no PythonScriptController"; } else { qDebug() << "Known PythonScriptController(s):"; for(const QString& pythonScriptControllerName : myPythonScriptControllers.keys()) qDebug() << "-" << pythonScriptControllerName; } return; } PythonScriptController* pythonScriptController = pythonScriptControllerIterator.value(); PyObject* pyParameter = PythonBuildValueHelper(parameter); if(!pyParameter) pyParameter = Py_BuildValue(""); sofa::core::objectmodel::PythonScriptEvent pythonScriptEvent(myScene->sofaSimulation()->GetRoot(), eventName.toLatin1().constData(), pyParameter); pythonScriptController->handleEvent(&pythonScriptEvent); } void PythonInteractor::sendEventToAll(const QString& eventName, const QVariant& parameter) { for(const QString& pythonClassName : myPythonScriptControllers.keys()) sendEvent(pythonClassName, eventName, parameter); } <|endoftext|>
<commit_before>#ifndef _YAHTTP_URL_HPP #define _YAHTTP_URL_HPP 1 #include <sstream> #include <string> #include "utility.hpp" #ifndef YAHTTP_MAX_URL_LENGTH #define YAHTTP_MAX_URL_LENGTH 2048 #endif namespace YaHTTP { /*! URL parser and container */ class URL { private: bool parseSchema(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return false; // no data if ( (pos1 = url.find_first_of(":",pos)) == std::string::npos ) return false; // schema is mandatory protocol = url.substr(pos, pos1-pos); if (protocol == "http") port = 80; if (protocol == "https") port = 443; pos = pos1+1; // after : if (url.compare(pos, 2, "//") == 0) { pathless = false; // if this is true we put rest into parameters pos += 2; } return true; }; //<! parse schema/protocol part bool parseHost(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return true; // no data if ( (pos1 = url.find_first_of("/", pos)) == std::string::npos ) { host = url.substr(pos); path = "/"; pos = url.size(); } else { host = url.substr(pos, pos1-pos); pos = pos1; } if ( (pos1 = host.find_first_of(":")) != std::string::npos ) { std::istringstream tmp(host.substr(pos1+1)); tmp >> port; host = host.substr(0, pos1); } return true; }; //<! parse host and port bool parseUserPass(const std::string& url, size_t &pos) { size_t pos1,pos2; if (pos >= url.size()) return true; // no data if ( (pos1 = url.find_first_of("@",pos)) == std::string::npos ) return true; // no userinfo pos2 = url.find_first_of(":",pos); if (pos2 != std::string::npos) { // comes with password username = url.substr(pos, pos2 - pos); password = url.substr(pos2+1, pos1 - pos2 - 1); password = Utility::decodeURL(password); } else { username = url.substr(pos+1, pos1 - pos); } pos = pos1+1; username = Utility::decodeURL(username); return true; }; //<! parse possible username and password bool parsePath(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return true; // no data if (url[pos] != '/') return false; // not an url if ( (pos1 = url.find_first_of("?", pos)) == std::string::npos ) { path = url.substr(pos); pos = url.size(); } else { path = url.substr(pos, pos1-pos); pos = pos1; } return true; }; //<! parse path component bool parseParameters(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return true; // no data if (url[pos] == '#') return true; // anchor starts here if (url[pos] != '?') return false; // not a parameter if ( (pos1 = url.find_first_of("#", pos)) == std::string::npos ) { parameters = url.substr(pos+1);; pos = url.size(); } else { parameters = url.substr(pos+1, pos1-pos-1); pos = pos1; } if (parameters.size()>0 && *(parameters.end()-1) == '&') parameters.resize(parameters.size()-1); return true; }; //<! parse url parameters bool parseAnchor(const std::string& url, size_t &pos) { if (pos >= url.size()) return true; // no data if (url[pos] != '#') return false; // not anchor anchor = url.substr(pos+1); return true; }; //<! parse anchor void initialize() { protocol = ""; host = ""; port = 0; username = ""; password = ""; path = ""; parameters = ""; anchor =""; pathless = true; }; //<! initialize to empty URL public: std::string to_string() const { std::string tmp; std::ostringstream oss; if (protocol.empty() == false) { oss << protocol << ":"; if (host.empty() == false) { oss << "//"; } } if (username.empty() == false) { if (password.empty() == false) oss << Utility::encodeURL(username) << ":" << Utility::encodeURL(password) << "@"; else oss << Utility::encodeURL(username) << "@"; } if (host.empty() == false) oss << host; if (!(protocol == "http" && port == 80) && !(protocol == "https" && port == 443) && port > 0) oss << ":" << port; oss << path; if (parameters.empty() == false) { if (!pathless) oss << "?"; oss << parameters; } if (anchor.empty() == false) oss << "#" << anchor; return oss.str(); }; //<! convert this URL to string std::string protocol; //<! schema/protocol std::string host; //<! host int port; //<! port std::string username; //<! username std::string password; //<! password std::string path; //<! path std::string parameters; //<! url parameters std::string anchor; //<! anchor bool pathless; //<! whether this url has no path URL() { initialize(); }; //<! construct empty url URL(const std::string& url) { parse(url); }; //<! calls parse with url URL(const char *url) { parse(std::string(url)); }; //<! calls parse with url bool parse(const std::string& url) { // setup initialize(); if (url.size() > YAHTTP_MAX_URL_LENGTH) return false; size_t pos = 0; if (*(url.begin()) != '/') { // full url? if (parseSchema(url, pos) == false) return false; if (pathless) { parameters = url.substr(pos); return true; } if (parseUserPass(url, pos) == false) return false; if (parseHost(url, pos) == false) return false; } if (parsePath(url, pos) == false) return false; if (parseParameters(url, pos) == false) return false; return parseAnchor(url, pos); }; //<! parse various formats of urls ranging from http://example.com/foo?bar=baz into data:base64:d089swt64wt... friend std::ostream & operator<<(std::ostream& os, const URL& url) { os<<url.to_string(); return os; }; }; }; #endif <commit_msg>Fix off-by-one in username parsing<commit_after>#ifndef _YAHTTP_URL_HPP #define _YAHTTP_URL_HPP 1 #include <sstream> #include <string> #include "utility.hpp" #ifndef YAHTTP_MAX_URL_LENGTH #define YAHTTP_MAX_URL_LENGTH 2048 #endif namespace YaHTTP { /*! URL parser and container */ class URL { private: bool parseSchema(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return false; // no data if ( (pos1 = url.find_first_of(":",pos)) == std::string::npos ) return false; // schema is mandatory protocol = url.substr(pos, pos1-pos); if (protocol == "http") port = 80; if (protocol == "https") port = 443; pos = pos1+1; // after : if (url.compare(pos, 2, "//") == 0) { pathless = false; // if this is true we put rest into parameters pos += 2; } return true; }; //<! parse schema/protocol part bool parseHost(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return true; // no data if ( (pos1 = url.find_first_of("/", pos)) == std::string::npos ) { host = url.substr(pos); path = "/"; pos = url.size(); } else { host = url.substr(pos, pos1-pos); pos = pos1; } if ( (pos1 = host.find_first_of(":")) != std::string::npos ) { std::istringstream tmp(host.substr(pos1+1)); tmp >> port; host = host.substr(0, pos1); } return true; }; //<! parse host and port bool parseUserPass(const std::string& url, size_t &pos) { size_t pos1,pos2; if (pos >= url.size()) return true; // no data if ( (pos1 = url.find_first_of("@",pos)) == std::string::npos ) return true; // no userinfo pos2 = url.find_first_of(":",pos); if (pos2 != std::string::npos) { // comes with password username = url.substr(pos, pos2 - pos); password = url.substr(pos2+1, pos1 - pos2 - 1); password = Utility::decodeURL(password); } else { username = url.substr(pos, pos1 - pos); } pos = pos1+1; username = Utility::decodeURL(username); return true; }; //<! parse possible username and password bool parsePath(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return true; // no data if (url[pos] != '/') return false; // not an url if ( (pos1 = url.find_first_of("?", pos)) == std::string::npos ) { path = url.substr(pos); pos = url.size(); } else { path = url.substr(pos, pos1-pos); pos = pos1; } return true; }; //<! parse path component bool parseParameters(const std::string& url, size_t &pos) { size_t pos1; if (pos >= url.size()) return true; // no data if (url[pos] == '#') return true; // anchor starts here if (url[pos] != '?') return false; // not a parameter if ( (pos1 = url.find_first_of("#", pos)) == std::string::npos ) { parameters = url.substr(pos+1);; pos = url.size(); } else { parameters = url.substr(pos+1, pos1-pos-1); pos = pos1; } if (parameters.size()>0 && *(parameters.end()-1) == '&') parameters.resize(parameters.size()-1); return true; }; //<! parse url parameters bool parseAnchor(const std::string& url, size_t &pos) { if (pos >= url.size()) return true; // no data if (url[pos] != '#') return false; // not anchor anchor = url.substr(pos+1); return true; }; //<! parse anchor void initialize() { protocol = ""; host = ""; port = 0; username = ""; password = ""; path = ""; parameters = ""; anchor =""; pathless = true; }; //<! initialize to empty URL public: std::string to_string() const { std::string tmp; std::ostringstream oss; if (protocol.empty() == false) { oss << protocol << ":"; if (host.empty() == false) { oss << "//"; } } if (username.empty() == false) { if (password.empty() == false) oss << Utility::encodeURL(username) << ":" << Utility::encodeURL(password) << "@"; else oss << Utility::encodeURL(username) << "@"; } if (host.empty() == false) oss << host; if (!(protocol == "http" && port == 80) && !(protocol == "https" && port == 443) && port > 0) oss << ":" << port; oss << path; if (parameters.empty() == false) { if (!pathless) oss << "?"; oss << parameters; } if (anchor.empty() == false) oss << "#" << anchor; return oss.str(); }; //<! convert this URL to string std::string protocol; //<! schema/protocol std::string host; //<! host int port; //<! port std::string username; //<! username std::string password; //<! password std::string path; //<! path std::string parameters; //<! url parameters std::string anchor; //<! anchor bool pathless; //<! whether this url has no path URL() { initialize(); }; //<! construct empty url URL(const std::string& url) { parse(url); }; //<! calls parse with url URL(const char *url) { parse(std::string(url)); }; //<! calls parse with url bool parse(const std::string& url) { // setup initialize(); if (url.size() > YAHTTP_MAX_URL_LENGTH) return false; size_t pos = 0; if (*(url.begin()) != '/') { // full url? if (parseSchema(url, pos) == false) return false; if (pathless) { parameters = url.substr(pos); return true; } if (parseUserPass(url, pos) == false) return false; if (parseHost(url, pos) == false) return false; } if (parsePath(url, pos) == false) return false; if (parseParameters(url, pos) == false) return false; return parseAnchor(url, pos); }; //<! parse various formats of urls ranging from http://example.com/foo?bar=baz into data:base64:d089swt64wt... friend std::ostream & operator<<(std::ostream& os, const URL& url) { os<<url.to_string(); return os; }; }; }; #endif <|endoftext|>
<commit_before><commit_msg>fix ppc build<commit_after><|endoftext|>
<commit_before>/* Copyright (C) 2014 Sadman Kazi, Wojciech Swiderski, Serge Babayan, Shan Phylim This file is part of MyoPad. MyoPad is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyoPad 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 MyoPad. If not, see <http://www.gnu.org/licenses/>. */ //the main #include "filter.h" #include "kinematics.h" #include <time.h> #include <GL\glew.h> #include <GL\freeglut.h> //constant values const int DIM = 3, FPS = 48, WHITE = 0, BLACK = 1, RED = 2, BLUE = 3, GREEN = 4; const float xThresh = 0.005f, yThresh = 0.01f; const int WIDTH = 1600, HEIGHT = 900; const float scaleA = 1.0, scaleV = 1.0, scaleS = 1.0, armLength = 2.0; //stores the armlength of the person using the program bool first = true; void draw(float x, float y, float tipSize, int textColor, float pX, float pY, float cursorY, float yCursor, bool notSpread, bool erase) { //sets up the color for clearing the screen //glClearColor(1.0f, 1.0f, 1.0f, 0); //glClear(GL_COLOR_BUFFER_BIT); //sets up the screen coordinates switch (textColor) { case WHITE: glColor3ub(255, 255, 255); break; case BLACK: glColor3ub(0, 0, 0); break; case RED: glColor3ub(255, 0, 0); break; case BLUE: glColor3ub(0, 0, 255); break; case GREEN: glColor3ub(0, 255, 0); break; default: glColor3ub(0, 0, 0); break; } if (notSpread && !first && !erase && fabs(pX - x) < 0.5f && fabs(pY - y) < 0.5f) { glPointSize(tipSize); glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(pX, pY); //drawing point on the screen glEnd(); } else if (erase) { glPointSize(tipSize); glBegin(GL_POINTS); glVertex2f(x, y); glEnd(); } first = false; glPointSize(5.0f); glBegin(GL_POINTS); //clear the cursor glColor3ub(255, 255, 255); glVertex2f(pX, cursorY); //print new cursor glColor3ub(0, 0, 255); glVertex2f(x, yCursor); glEnd(); glutSwapBuffers(); glReadBuffer(GL_FRONT); glDrawBuffer(GL_BACK); glCopyPixels(0, 0, WIDTH, HEIGHT, GL_COLOR); } int main(int argc, char** argv) { //int timeInt = 1000000 / FPS; //for storing the accelerometer data and the position vector data float tipSize = 2.5f, xScale = 2.0f, yScale = 4.0f; int textColor = BLACK; //set up the GUI glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize(WIDTH, HEIGHT); glutCreateWindow("MyoPad"); glClearColor(1.0f, 1.0f, 1.0f, 0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-30, 30, -30, 30, -30, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); bool erase = false; bool write = true; // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. myo::Hub hub("com.myohack.myopad"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForAnyMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForAnyMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. Filter collector; //Kinematic accToPos(DIM, scaleA, scaleV, scaleS); //adds the integral class //sets the precision for floating points std::cout.precision(2); bool check = false; hub.addListener(&collector); int currentTime = clock(); hub.run(1000 / FPS); float x = -1 * xScale * collector.roll - 25.0f; float y = -1 * yScale * collector.pitch + 20.0f; //up is positive float xi = x; float yi = y; float pastX = 0.0, pastY = 0.0, cursorY = 0.0; // loop keeps running and mapping the coordinates on the window while (true) { if (x < xi) { if (y < yi) { x = 19.9f; y += 10.0f; first = true; } else x = xi; } if (x < 20.0f) { //gets 48 packets of data every second hub.run(1000 / FPS); if (collector.currentPose.toString() == "waveIn") x -= 0.15f; //moves the cursor oto the left else if (collector.currentPose.toString() == "waveOut") x += 0.15f; //moves the cursor to the right if (collector.currentPose.toString() == "fist") { textColor = WHITE; tipSize = 100.0f; //for the eraser erase = true; }else{ textColor = BLACK; tipSize = 2.5f; } std::cout << collector.currentPose.toString() << " " << tipSize; /*else if (collector.currentPose.toString() == "waveOut") { textColor++; if (textColor > 4) textColor = WHITE; }*/ std::cout << '\r'; if (!(collector.currentPose.toString() == "fingersSpread" || collector.currentPose.toString() == "waveOut" || collector.currentPose.toString() == "waveIn")) { check = true; } draw(x + collector.roll * xScale, y + collector.yaw * yScale, tipSize, textColor, pastX, pastY, cursorY, y - 5.0f, check, erase); //draw(pastX, pastY, 5.0f, WHITE); //draw(x - 7.5f, y - 5.0f, 5.0f, BLUE); pastX = x + collector.roll * xScale; pastY = y + collector.yaw * yScale; cursorY = y - 5.0f; if (!erase) x += 0.01f; check = false; erase = false; //print the position //std::cout << collector.roll << " " << collector.yaw; } else { first = true; y -= 10.0f; x = xi; //switches the position of x to its initial position } } } // If a standard exception occurred, we print out its message and exit. catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } return 0; }<commit_msg>Update main.cpp<commit_after>/* Copyright (C) 2016 Abhinav Narayanan This file is part of MyoPad. MyoPad is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyoPad 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 MyoPad. If not, see <http://www.gnu.org/licenses/>. */ //the main #include "filter.h" #include "kinematics.h" #include <time.h> #include <GL\glew.h> #include <GL\freeglut.h> //constant values const int DIM = 3, FPS = 48, WHITE = 0, BLACK = 1, RED = 2, BLUE = 3, GREEN = 4; const float xThresh = 0.005f, yThresh = 0.01f; const int WIDTH = 1600, HEIGHT = 900; const float scaleA = 1.0, scaleV = 1.0, scaleS = 1.0, armLength = 2.0; //stores the armlength of the person using the program bool first = true; void draw(float x, float y, float tipSize, int textColor, float pX, float pY, float cursorY, float yCursor, bool notSpread, bool erase) { //sets up the color for clearing the screen //glClearColor(1.0f, 1.0f, 1.0f, 0); //glClear(GL_COLOR_BUFFER_BIT); //sets up the screen coordinates switch (textColor) { case WHITE: glColor3ub(255, 255, 255); break; case BLACK: glColor3ub(0, 0, 0); break; case RED: glColor3ub(255, 0, 0); break; case BLUE: glColor3ub(0, 0, 255); break; case GREEN: glColor3ub(0, 255, 0); break; default: glColor3ub(0, 0, 0); break; } if (notSpread && !first && !erase && fabs(pX - x) < 0.5f && fabs(pY - y) < 0.5f) { glPointSize(tipSize); glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(pX, pY); //drawing point on the screen glEnd(); } else if (erase) { glPointSize(tipSize); glBegin(GL_POINTS); glVertex2f(x, y); glEnd(); } first = false; glPointSize(5.0f); glBegin(GL_POINTS); //clear the cursor glColor3ub(255, 255, 255); glVertex2f(pX, cursorY); //print new cursor glColor3ub(0, 0, 255); glVertex2f(x, yCursor); glEnd(); glutSwapBuffers(); glReadBuffer(GL_FRONT); glDrawBuffer(GL_BACK); glCopyPixels(0, 0, WIDTH, HEIGHT, GL_COLOR); } int main(int argc, char** argv) { //int timeInt = 1000000 / FPS; //for storing the accelerometer data and the position vector data float tipSize = 2.5f, xScale = 2.0f, yScale = 4.0f; int textColor = BLACK; //set up the GUI glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize(WIDTH, HEIGHT); glutCreateWindow("MyoPad"); glClearColor(1.0f, 1.0f, 1.0f, 0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-30, 30, -30, 30, -30, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); bool erase = false; bool write = true; // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. myo::Hub hub("com.myohack.myopad"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForAnyMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForAnyMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. Filter collector; //Kinematic accToPos(DIM, scaleA, scaleV, scaleS); //adds the integral class //sets the precision for floating points std::cout.precision(2); bool check = false; hub.addListener(&collector); int currentTime = clock(); hub.run(1000 / FPS); float x = -1 * xScale * collector.roll - 25.0f; float y = -1 * yScale * collector.pitch + 20.0f; //up is positive float xi = x; float yi = y; float pastX = 0.0, pastY = 0.0, cursorY = 0.0; // loop keeps running and mapping the coordinates on the window while (true) { if (x < xi) { if (y < yi) { x = 19.9f; y += 10.0f; first = true; } else x = xi; } if (x < 20.0f) { //gets 48 packets of data every second hub.run(1000 / FPS); if (collector.currentPose.toString() == "waveIn") x -= 0.15f; //moves the cursor oto the left else if (collector.currentPose.toString() == "waveOut") x += 0.15f; //moves the cursor to the right if (collector.currentPose.toString() == "fist") { textColor = WHITE; tipSize = 100.0f; //for the eraser erase = true; }else{ textColor = BLACK; tipSize = 2.5f; } std::cout << collector.currentPose.toString() << " " << tipSize; /*else if (collector.currentPose.toString() == "waveOut") { textColor++; if (textColor > 4) textColor = WHITE; }*/ std::cout << '\r'; if (!(collector.currentPose.toString() == "fingersSpread" || collector.currentPose.toString() == "waveOut" || collector.currentPose.toString() == "waveIn")) { check = true; } draw(x + collector.roll * xScale, y + collector.yaw * yScale, tipSize, textColor, pastX, pastY, cursorY, y - 5.0f, check, erase); //draw(pastX, pastY, 5.0f, WHITE); //draw(x - 7.5f, y - 5.0f, 5.0f, BLUE); pastX = x + collector.roll * xScale; pastY = y + collector.yaw * yScale; cursorY = y - 5.0f; if (!erase) x += 0.01f; check = false; erase = false; //print the position //std::cout << collector.roll << " " << collector.yaw; } else { first = true; y -= 10.0f; x = xi; //switches the position of x to its initial position } } } // If a standard exception occurred, we print out its message and exit. catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } return 0; } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mSelf = self; msPropertyName = strPropertyName; mstrRelationValue = strRelationValue; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const std::string& NFCProperty::GetRelationValue() const { return mstrRelationValue; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetRelationValue(const std::string& strRelationValue) { mstrRelationValue = strRelationValue; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = GetString(); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString(const std::string& strData) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } bool NFCProperty::DeSerialization() { bool bRet = false; const TDATA_TYPE eType = GetType(); if (eType == TDATA_STRING) { NFCDataList xDataList; const std::string& strData = mxData->GetString(); xDataList.Split(strData.c_str(), ";"); for (int i = 0; i < xDataList.GetCount(); ++i) { if (nullptr == mxEmbeddedList) { mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>()); } else { mxEmbeddedList->ClearAll(); } if(xDataList.String(i).empty()) { NFASSERT(0, strData, __FILE__, __FUNCTION__); } mxEmbeddedList->Add(xDataList.String(i)); } if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0) { std::string strTemData; for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData)) { NFCDataList xTemDataList; xTemDataList.Split(strTemData.c_str(), ","); if (xTemDataList.GetCount() > 0) { if (xTemDataList.GetCount() != 2) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } const std::string& strKey = xTemDataList.String(0); const std::string& strValue = xTemDataList.String(0); if (strKey.empty() || strValue.empty()) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } if (nullptr == mxEmbeddedMap) { mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>()); } else { mxEmbeddedMap->ClearAll(); } mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue))); } } bRet = true; } } return bRet; } const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const { return this->mxEmbeddedList; } const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const { return this->mxEmbeddedMap; } <commit_msg>fixed for split<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mSelf = self; msPropertyName = strPropertyName; mstrRelationValue = strRelationValue; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const std::string& NFCProperty::GetRelationValue() const { return mstrRelationValue; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetRelationValue(const std::string& strRelationValue) { mstrRelationValue = strRelationValue; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = GetString(); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString(const std::string& strData) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } bool NFCProperty::DeSerialization() { bool bRet = false; const TDATA_TYPE eType = GetType(); if (eType == TDATA_STRING && mxData && !mxData->IsNullValue()) { NFCDataList xDataList; const std::string& strData = mxData->GetString(); xDataList.Split(strData.c_str(), ";"); if (xDataList.GetCount() > 0) { if (nullptr == mxEmbeddedList) { mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>()); } else { mxEmbeddedList->ClearAll(); } } for (int i = 0; i < xDataList.GetCount(); ++i) { if(xDataList.String(i).empty()) { NFASSERT(0, strData, __FILE__, __FUNCTION__); } mxEmbeddedList->Add(xDataList.String(i)); } if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0) { if (nullptr == mxEmbeddedMap) { mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>()); } else { mxEmbeddedMap->ClearAll(); } std::string strTemData; for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData)) { NFCDataList xTemDataList; xTemDataList.Split(strTemData.c_str(), ","); if (xTemDataList.GetCount() > 0) { if (mxEmbeddedList->Count() == 1 && xTemDataList.GetCount() == 1) { return bRet; } if (xTemDataList.GetCount() != 2) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } const std::string& strKey = xTemDataList.String(0); const std::string& strValue = xTemDataList.String(0); if (strKey.empty() || strValue.empty()) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue))); } } bRet = true; } } return bRet; } const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const { return this->mxEmbeddedList; } const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const { return this->mxEmbeddedMap; } <|endoftext|>
<commit_before>#include "search_engine.hpp" #include "categories_holder.hpp" #include "geometry_utils.hpp" #include "search_query.hpp" #include "search_string_utils.hpp" #include "storage/country_info_getter.hpp" #include "indexer/classificator.hpp" #include "indexer/scales.hpp" #include "platform/platform.hpp" #include "geometry/distance_on_sphere.hpp" #include "geometry/mercator.hpp" #include "base/logging.hpp" #include "base/scope_guard.hpp" #include "base/stl_add.hpp" #include "std/algorithm.hpp" #include "std/bind.hpp" #include "std/map.hpp" #include "std/vector.hpp" #include "3party/Alohalytics/src/alohalytics.h" namespace search { namespace { int const kResultsCount = 30; class InitSuggestions { using TSuggestMap = map<pair<strings::UniString, int8_t>, uint8_t>; TSuggestMap m_suggests; public: void operator()(CategoriesHolder::Category::Name const & name) { if (name.m_prefixLengthToSuggest != CategoriesHolder::Category::EMPTY_PREFIX_LENGTH) { strings::UniString const uniName = NormalizeAndSimplifyString(name.m_name); uint8_t & score = m_suggests[make_pair(uniName, name.m_locale)]; if (score == 0 || score > name.m_prefixLengthToSuggest) score = name.m_prefixLengthToSuggest; } } void GetSuggests(vector<Suggest> & suggests) const { suggests.reserve(suggests.size() + m_suggests.size()); for (auto const & s : m_suggests) suggests.emplace_back(s.first.first, s.second, s.first.second); } }; void SendStatistics(SearchParams const & params, m2::RectD const & viewport, Results const & res) { size_t const kMaxNumResultsToSend = 10; size_t const numResultsToSend = min(kMaxNumResultsToSend, res.GetCount()); string resultString = strings::to_string(numResultsToSend); for (size_t i = 0; i < numResultsToSend; ++i) resultString.append("\t" + res.GetResult(i).ToStringForStats()); string posX, posY; if (params.IsValidPosition()) { posX = strings::to_string(MercatorBounds::LonToX(params.m_lon)); posY = strings::to_string(MercatorBounds::LatToY(params.m_lat)); } alohalytics::TStringMap const stats = { {"posX", posX}, {"posY", posY}, {"viewportMinX", strings::to_string(viewport.minX())}, {"viewportMinY", strings::to_string(viewport.minY())}, {"viewportMaxX", strings::to_string(viewport.maxX())}, {"viewportMaxY", strings::to_string(viewport.maxY())}, {"query", params.m_query}, {"results", resultString}, }; alohalytics::LogEvent("searchEmitResultsAndCoords", stats); } } // namespace QueryHandle::QueryHandle() : m_query(nullptr), m_cancelled(false) {} void QueryHandle::Cancel() { lock_guard<mutex> lock(m_mu); m_cancelled = true; if (m_query) m_query->Cancel(); } void QueryHandle::Attach(Query & query) { lock_guard<mutex> lock(m_mu); m_query = &query; if (m_cancelled) m_query->Cancel(); } void QueryHandle::Detach() { lock_guard<mutex> lock(m_mu); m_query = nullptr; } Engine::Engine(Index & index, Reader * categoriesR, storage::CountryInfoGetter const & infoGetter, string const & locale, unique_ptr<SearchQueryFactory> && factory) : m_categories(categoriesR), m_factory(move(factory)), m_shutdown(false) { InitSuggestions doInit; m_categories.ForEachName(bind<void>(ref(doInit), _1)); doInit.GetSuggests(m_suggests); m_query = m_factory->BuildSearchQuery(index, m_categories, m_suggests, infoGetter); m_query->SetPreferredLocale(locale); m_thread = threads::SimpleThread(&Engine::MainLoop, this); } Engine::~Engine() { { lock_guard<mutex> lock(m_mu); m_shutdown = true; m_cv.notify_one(); } m_thread.join(); } weak_ptr<QueryHandle> Engine::Search(SearchParams const & params, m2::RectD const & viewport) { shared_ptr<QueryHandle> handle(new QueryHandle()); PostTask(bind(&Engine::DoSearch, this, params, viewport, handle)); return handle; } void Engine::SetSupportOldFormat(bool support) { PostTask(bind(&Engine::DoSupportOldFormat, this, support)); } void Engine::ClearCaches() { PostTask(bind(&Engine::DoClearCaches, this)); } bool Engine::GetNameByType(uint32_t type, int8_t locale, string & name) const { uint8_t level = ftype::GetLevel(type); ASSERT_GREATER(level, 0, ()); while (true) { if (m_categories.GetNameByType(type, locale, name)) return true; if (--level == 0) break; ftype::TruncValue(type, level); } return false; } void Engine::SetRankPivot(SearchParams const & params, m2::RectD const & viewport, bool viewportSearch) { if (!viewportSearch && params.IsValidPosition()) { m2::PointD const pos = MercatorBounds::FromLatLon(params.m_lat, params.m_lon); if (m2::Inflate(viewport, viewport.SizeX() / 4.0, viewport.SizeY() / 4.0).IsPointInside(pos)) { m_query->SetRankPivot(pos); return; } } m_query->SetRankPivot(viewport.Center()); } void Engine::EmitResults(SearchParams const & params, Results const & res) { params.m_callback(res); } void Engine::MainLoop() { while (true) { unique_lock<mutex> lock(m_mu); m_cv.wait(lock, [this]() { return m_shutdown || !m_tasks.empty(); }); if (m_shutdown) break; function<void()> task(move(m_tasks.front())); m_tasks.pop(); lock.unlock(); task(); } } void Engine::PostTask(function<void()> && task) { lock_guard<mutex> lock(m_mu); m_tasks.push(move(task)); m_cv.notify_one(); } void Engine::DoSearch(SearchParams const & params, m2::RectD const & viewport, shared_ptr<QueryHandle> handle) { bool const viewportSearch = params.GetMode() == Mode::Viewport; // Initialize query. m_query->Init(viewportSearch); handle->Attach(*m_query); MY_SCOPE_GUARD(detach, [&handle] { handle->Detach(); }); // Early exit when query is cancelled. if (m_query->IsCancelled()) { params.m_callback(Results::GetEndMarker(true /* isCancelled */)); return; } SetRankPivot(params, viewport, viewportSearch); if (params.IsValidPosition()) m_query->SetPosition(MercatorBounds::FromLatLon(params.m_lat, params.m_lon)); else m_query->SetPosition(viewport.Center()); m_query->SetMode(params.GetMode()); // This flag is needed for consistency with old search algorithm // only. It will gone away when we will remove old search code. m_query->SetSearchInWorld(true); m_query->SetInputLocale(params.m_inputLocale); ASSERT(!params.m_query.empty(), ()); m_query->SetQuery(params.m_query); Results res; m_query->SearchCoordinates(res); try { if (viewportSearch) { m_query->SetViewport(viewport, true /* forceUpdate */); m_query->SearchViewportPoints(res); } else { m_query->SetViewport(viewport, params.IsSearchAroundPosition() /* forceUpdate */); m_query->Search(res, kResultsCount); } EmitResults(params, res); } catch (Query::CancelException const &) { LOG(LDEBUG, ("Search has been cancelled.")); } if (!viewportSearch && !m_query->IsCancelled()) SendStatistics(params, viewport, res); // Emit finish marker to client. params.m_callback(Results::GetEndMarker(m_query->IsCancelled())); } void Engine::DoSupportOldFormat(bool support) { m_query->SupportOldFormat(support); } void Engine::DoClearCaches() { m_query->ClearCaches(); } } // namespace search <commit_msg>Review fixes.<commit_after>#include "search_engine.hpp" #include "categories_holder.hpp" #include "geometry_utils.hpp" #include "search_query.hpp" #include "search_string_utils.hpp" #include "storage/country_info_getter.hpp" #include "indexer/classificator.hpp" #include "indexer/scales.hpp" #include "platform/platform.hpp" #include "geometry/distance_on_sphere.hpp" #include "geometry/mercator.hpp" #include "base/logging.hpp" #include "base/scope_guard.hpp" #include "base/stl_add.hpp" #include "std/algorithm.hpp" #include "std/bind.hpp" #include "std/map.hpp" #include "std/vector.hpp" #include "3party/Alohalytics/src/alohalytics.h" namespace search { namespace { int const kResultsCount = 30; class InitSuggestions { using TSuggestMap = map<pair<strings::UniString, int8_t>, uint8_t>; TSuggestMap m_suggests; public: void operator()(CategoriesHolder::Category::Name const & name) { if (name.m_prefixLengthToSuggest != CategoriesHolder::Category::EMPTY_PREFIX_LENGTH) { strings::UniString const uniName = NormalizeAndSimplifyString(name.m_name); uint8_t & score = m_suggests[make_pair(uniName, name.m_locale)]; if (score == 0 || score > name.m_prefixLengthToSuggest) score = name.m_prefixLengthToSuggest; } } void GetSuggests(vector<Suggest> & suggests) const { suggests.reserve(suggests.size() + m_suggests.size()); for (auto const & s : m_suggests) suggests.emplace_back(s.first.first, s.second, s.first.second); } }; void SendStatistics(SearchParams const & params, m2::RectD const & viewport, Results const & res) { size_t const kMaxNumResultsToSend = 10; size_t const numResultsToSend = min(kMaxNumResultsToSend, res.GetCount()); string resultString = strings::to_string(numResultsToSend); for (size_t i = 0; i < numResultsToSend; ++i) resultString.append("\t" + res.GetResult(i).ToStringForStats()); string posX, posY; if (params.IsValidPosition()) { posX = strings::to_string(MercatorBounds::LonToX(params.m_lon)); posY = strings::to_string(MercatorBounds::LatToY(params.m_lat)); } alohalytics::TStringMap const stats = { {"posX", posX}, {"posY", posY}, {"viewportMinX", strings::to_string(viewport.minX())}, {"viewportMinY", strings::to_string(viewport.minY())}, {"viewportMaxX", strings::to_string(viewport.maxX())}, {"viewportMaxY", strings::to_string(viewport.maxY())}, {"query", params.m_query}, {"results", resultString}, }; alohalytics::LogEvent("searchEmitResultsAndCoords", stats); } } // namespace QueryHandle::QueryHandle() : m_query(nullptr), m_cancelled(false) {} void QueryHandle::Cancel() { lock_guard<mutex> lock(m_mu); m_cancelled = true; if (m_query) m_query->Cancel(); } void QueryHandle::Attach(Query & query) { lock_guard<mutex> lock(m_mu); m_query = &query; if (m_cancelled) m_query->Cancel(); } void QueryHandle::Detach() { lock_guard<mutex> lock(m_mu); m_query = nullptr; } Engine::Engine(Index & index, Reader * categoriesR, storage::CountryInfoGetter const & infoGetter, string const & locale, unique_ptr<SearchQueryFactory> && factory) : m_categories(categoriesR), m_factory(move(factory)), m_shutdown(false) { InitSuggestions doInit; m_categories.ForEachName(bind<void>(ref(doInit), _1)); doInit.GetSuggests(m_suggests); m_query = m_factory->BuildSearchQuery(index, m_categories, m_suggests, infoGetter); m_query->SetPreferredLocale(locale); m_thread = threads::SimpleThread(&Engine::MainLoop, this); } Engine::~Engine() { { lock_guard<mutex> lock(m_mu); m_shutdown = true; m_cv.notify_one(); } m_thread.join(); } weak_ptr<QueryHandle> Engine::Search(SearchParams const & params, m2::RectD const & viewport) { shared_ptr<QueryHandle> handle(new QueryHandle()); PostTask(bind(&Engine::DoSearch, this, params, viewport, handle)); return handle; } void Engine::SetSupportOldFormat(bool support) { PostTask(bind(&Engine::DoSupportOldFormat, this, support)); } void Engine::ClearCaches() { PostTask(bind(&Engine::DoClearCaches, this)); } bool Engine::GetNameByType(uint32_t type, int8_t locale, string & name) const { uint8_t level = ftype::GetLevel(type); ASSERT_GREATER(level, 0, ()); while (true) { if (m_categories.GetNameByType(type, locale, name)) return true; if (--level == 0) break; ftype::TruncValue(type, level); } return false; } void Engine::SetRankPivot(SearchParams const & params, m2::RectD const & viewport, bool viewportSearch) { if (!viewportSearch && params.IsValidPosition()) { m2::PointD const pos = MercatorBounds::FromLatLon(params.m_lat, params.m_lon); if (m2::Inflate(viewport, viewport.SizeX() / 4.0, viewport.SizeY() / 4.0).IsPointInside(pos)) { m_query->SetRankPivot(pos); return; } } m_query->SetRankPivot(viewport.Center()); } void Engine::EmitResults(SearchParams const & params, Results const & res) { params.m_callback(res); } void Engine::MainLoop() { while (true) { unique_lock<mutex> lock(m_mu); m_cv.wait(lock, [this]() { return m_shutdown || !m_tasks.empty(); }); if (m_shutdown) break; function<void()> task(move(m_tasks.front())); m_tasks.pop(); lock.unlock(); task(); } } void Engine::PostTask(function<void()> && task) { lock_guard<mutex> lock(m_mu); m_tasks.push(move(task)); m_cv.notify_one(); } void Engine::DoSearch(SearchParams const & params, m2::RectD const & viewport, shared_ptr<QueryHandle> handle) { bool const viewportSearch = params.GetMode() == Mode::Viewport; // Initialize query. m_query->Init(viewportSearch); handle->Attach(*m_query); MY_SCOPE_GUARD(detach, [&handle] { handle->Detach(); }); // Early exit when query is cancelled. if (m_query->IsCancelled()) { params.m_callback(Results::GetEndMarker(true /* isCancelled */)); return; } SetRankPivot(params, viewport, viewportSearch); if (params.IsValidPosition()) m_query->SetPosition(MercatorBounds::FromLatLon(params.m_lat, params.m_lon)); else m_query->SetPosition(viewport.Center()); m_query->SetMode(params.GetMode()); // This flag is needed for consistency with old search algorithm // only. It will be gone when we remove old search code. m_query->SetSearchInWorld(true); m_query->SetInputLocale(params.m_inputLocale); ASSERT(!params.m_query.empty(), ()); m_query->SetQuery(params.m_query); Results res; m_query->SearchCoordinates(res); try { if (viewportSearch) { m_query->SetViewport(viewport, true /* forceUpdate */); m_query->SearchViewportPoints(res); } else { m_query->SetViewport(viewport, params.IsSearchAroundPosition() /* forceUpdate */); m_query->Search(res, kResultsCount); } EmitResults(params, res); } catch (Query::CancelException const &) { LOG(LDEBUG, ("Search has been cancelled.")); } if (!viewportSearch && !m_query->IsCancelled()) SendStatistics(params, viewport, res); // Emit finish marker to client. params.m_callback(Results::GetEndMarker(m_query->IsCancelled())); } void Engine::DoSupportOldFormat(bool support) { m_query->SupportOldFormat(support); } void Engine::DoClearCaches() { m_query->ClearCaches(); } } // namespace search <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery 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 University of Wisconsin - Madison 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. */ //---------------------------------------------------------------------------// /*! * \brief DTK_LibmeshNodalShapeFunction.hpp * \author Stuart R. Slattery * \brief Nodal shape function implementation for Libmesh mesh. */ //---------------------------------------------------------------------------// #ifndef LIBMESHDTKADAPTERS_LIBMESHNODALSHAPEFUNCTION #define LIBMESHDTKADAPTERS_LIBMESHNODALSHAPEFUNCTION #include "DTK_LibmeshEntityExtraData.hpp" #include <DTK_EntityShapeFunction.hpp> #include <DTK_Types.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_Array.hpp> #include <libmesh/mesh_base.h> #include <libmesh/system.h> namespace DataTransferKit { //---------------------------------------------------------------------------// /*! \class LibmeshNodalShapeFunction \brief Nodal shape function implementation for Libmesh mesh. LibmeshNodalShapeFunction provides a shape function for node-centered quantities with shape functions evaluated in an element supported by nodes. The node ids serve as the dof ids for these shape functions. A corresponding DOF vector indexed via node ids should be produced to match this shape function. LibmeshDOFVector provides services to construct these vectors. */ //---------------------------------------------------------------------------// class LibmeshNodalShapeFunction : public DataTransferKit::EntityShapeFunction { public: /*! * \brief Constructor. */ LibmeshNodalShapeFunction( const Teuchos::RCP<libMesh::MeshBase>& libmesh_mesh, const Teuchos::RCP<libMesh::System>& libmesh_system ); /*! * \brief Given an entity, get the ids of its support locations. * \param entity Get the support locations for this entity. * \param support_ids Return the ids of the degrees of freedom in the parallel * vector space supporting the entities. */ void entitySupportIds( const DataTransferKit::Entity& entity, Teuchos::Array<DataTransferKit::SupportId>& support_ids ) const; /*! * \brief Given an entity and a reference point, evaluate the shape * function of the entity at that point. * \param entity Evaluate the shape function of this entity. * \param reference_point Evaluate the shape function at this point * given in reference coordinates. * \param values Entity shape function evaluated at the reference * point. */ void evaluateValue( const DataTransferKit::Entity& entity, const Teuchos::ArrayView<const double>& reference_point, Teuchos::Array<double> & values ) const; /*! * \brief Given an entity and a reference point, evaluate the gradient of * the shape function of the entity at that point. * \param entity Evaluate the shape function of this entity. * \param reference_point Evaluate the shape function at this point * given in reference coordinates. * \param gradients Entity shape function gradients evaluated at the * reference point. Return these ordered with respect to those return by * getDOFIds() such that gradients[N][D] gives the gradient value of the * Nth DOF in the Dth spatial dimension. */ void evaluateGradient( const DataTransferKit::Entity& entity, const Teuchos::ArrayView<const double>& reference_point, Teuchos::Array<Teuchos::Array<double> >& gradients ) const; private: // Extract the libmesh geom object. template<class LibmeshGeom> Teuchos::Ptr<LibmeshGeom> extractGeom( const DataTransferKit::Entity& entity ) const; private: // Libmesh mesh. Teuchos::RCP<libMesh::MeshBase> d_libmesh_mesh; // Libmesh system. Teuchos::RCP<libMesh::System> d_libmesh_system; }; //---------------------------------------------------------------------------// // Template functions. //---------------------------------------------------------------------------// // Extract the libmesh geom object. template<class LibmeshGeom> Teuchos::Ptr<LibmeshGeom> LibmeshNodalShapeFunction::extractGeom( const DataTransferKit::Entity& entity ) const { return Teuchos::rcp_dynamic_cast<LibmeshEntityExtraData<LibmeshGeom> >( entity.extraData())->d_libmesh_geom; } //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// #endif // end LIBMESHDTKADPATERS_LIBMESHNODALSHAPEFUNCTION //---------------------------------------------------------------------------// // end DTK_LibmeshNodalShapeFunction.hpp //---------------------------------------------------------------------------// <commit_msg>Update DTK_LibmeshNodalShapeFunction.hpp<commit_after>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery 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 University of Wisconsin - Madison 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. */ //---------------------------------------------------------------------------// /*! * \brief DTK_LibmeshNodalShapeFunction.hpp * \author Stuart R. Slattery * \brief Nodal shape function implementation for Libmesh mesh. */ //---------------------------------------------------------------------------// #ifndef LIBMESHDTKADAPTERS_LIBMESHNODALSHAPEFUNCTION #define LIBMESHDTKADAPTERS_LIBMESHNODALSHAPEFUNCTION #include "DTK_LibmeshEntityExtraData.hpp" #include <DTK_EntityShapeFunction.hpp> #include <DTK_Types.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_Array.hpp> #include <libmesh/mesh_base.h> #include <libmesh/system.h> namespace DataTransferKit { //---------------------------------------------------------------------------// /*! \class LibmeshNodalShapeFunction \brief Nodal shape function implementation for Libmesh mesh. LibmeshNodalShapeFunction provides a shape function for node-centered quantities with shape functions evaluated in an element supported by nodes. The node ids serve as the dof ids for these shape functions. A corresponding DOF vector indexed via node ids should be produced to match this shape function. LibmeshDOFVector provides services to construct these vectors. */ //---------------------------------------------------------------------------// class LibmeshNodalShapeFunction : public EntityShapeFunction { public: /*! * \brief Constructor. */ LibmeshNodalShapeFunction( const Teuchos::RCP<libMesh::MeshBase>& libmesh_mesh, const Teuchos::RCP<libMesh::System>& libmesh_system ); /*! * \brief Given an entity, get the ids of its support locations. * \param entity Get the support locations for this entity. * \param support_ids Return the ids of the degrees of freedom in the parallel * vector space supporting the entities. */ void entitySupportIds( const Entity& entity, Teuchos::Array<SupportId>& support_ids ) const; /*! * \brief Given an entity and a reference point, evaluate the shape * function of the entity at that point. * \param entity Evaluate the shape function of this entity. * \param reference_point Evaluate the shape function at this point * given in reference coordinates. * \param values Entity shape function evaluated at the reference * point. */ void evaluateValue( const Entity& entity, const Teuchos::ArrayView<const double>& reference_point, Teuchos::Array<double> & values ) const; /*! * \brief Given an entity and a reference point, evaluate the gradient of * the shape function of the entity at that point. * \param entity Evaluate the shape function of this entity. * \param reference_point Evaluate the shape function at this point * given in reference coordinates. * \param gradients Entity shape function gradients evaluated at the * reference point. Return these ordered with respect to those return by * getDOFIds() such that gradients[N][D] gives the gradient value of the * Nth DOF in the Dth spatial dimension. */ void evaluateGradient( const Entity& entity, const Teuchos::ArrayView<const double>& reference_point, Teuchos::Array<Teuchos::Array<double> >& gradients ) const; private: // Extract the libmesh geom object. template<class LibmeshGeom> Teuchos::Ptr<LibmeshGeom> extractGeom( const Entity& entity ) const; private: // Libmesh mesh. Teuchos::RCP<libMesh::MeshBase> d_libmesh_mesh; // Libmesh system. Teuchos::RCP<libMesh::System> d_libmesh_system; }; //---------------------------------------------------------------------------// // Template functions. //---------------------------------------------------------------------------// // Extract the libmesh geom object. template<class LibmeshGeom> Teuchos::Ptr<LibmeshGeom> LibmeshNodalShapeFunction::extractGeom( const Entity& entity ) const { return Teuchos::rcp_dynamic_cast<LibmeshEntityExtraData<LibmeshGeom> >( entity.extraData())->d_libmesh_geom; } //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// #endif // end LIBMESHDTKADPATERS_LIBMESHNODALSHAPEFUNCTION //---------------------------------------------------------------------------// // end DTK_LibmeshNodalShapeFunction.hpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mSelf = self; msPropertyName = strPropertyName; mstrRelationValue = strRelationValue; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const std::string& NFCProperty::GetRelationValue() const { return mstrRelationValue; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetRelationValue(const std::string& strRelationValue) { mstrRelationValue = strRelationValue; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = GetString(); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString(const std::string& strData) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } bool NFCProperty::DeSerialization() { bool bRet = false; const TDATA_TYPE eType = GetType(); if(eType == TDATA_STRING) { NFCDataList xDataList(); const std::string& strData = mxData->GetString(); xDataList.Split(strData.c_str(), ";") for(int i = 0; i < xDataList.GetCount(); ++i) { if(nullptr == mxEmbeddedList) { mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>()); } else { mxEmbeddedList->ClearAll(); } if(xDataList.String(i).empty()) { NFASSERT(0, strData, __FILE__, __FUNCTION__); } mxEmbeddedList->Add(xDataList.String(i)); } if(nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0) { std::string strTemData; for(bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData)) { NFCDataList xTemDataList(); xTemDataList.Split(strTemData.c_str(), ",") if(xTemDataList.GetCount() > 0) { if (xTemDataList.GetCount() != 2) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } const std::string& strKey = xTemDataList.String(0); const std::string& strValue = xTemDataList.String(0); if(strKey.empty() || strValue.empty()) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } if(nullptr == mxEmbeddedMap) { mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>()); } else { mxEmbeddedMap->ClearAll(); } mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue))) } } bRet = true; } } return bRet; } const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const { return this->mxEmbeddedList; } const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const { return this->mxEmbeddedMap; } <commit_msg>fixed for compile<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mSelf = self; msPropertyName = strPropertyName; mstrRelationValue = strRelationValue; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const std::string& NFCProperty::GetRelationValue() const { return mstrRelationValue; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetRelationValue(const std::string& strRelationValue) { mstrRelationValue = strRelationValue; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = GetString(); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString(const std::string& strData) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } bool NFCProperty::DeSerialization() { bool bRet = false; const TDATA_TYPE eType = GetType(); if(eType == TDATA_STRING) { NFCDataList xDataList; const std::string& strData = mxData->GetString(); xDataList.Split(strData.c_str(), ";") for(int i = 0; i < xDataList.GetCount(); ++i) { if(nullptr == mxEmbeddedList) { mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>()); } else { mxEmbeddedList->ClearAll(); } if(xDataList.String(i).empty()) { NFASSERT(0, strData, __FILE__, __FUNCTION__); } mxEmbeddedList->Add(xDataList.String(i)); } if(nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0) { std::string strTemData; for(bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData)) { NFCDataList xTemDataList; xTemDataList.Split(strTemData.c_str(), ",") if(xTemDataList.GetCount() > 0) { if (xTemDataList.GetCount() != 2) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } const std::string& strKey = xTemDataList.String(0); const std::string& strValue = xTemDataList.String(0); if(strKey.empty() || strValue.empty()) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } if(nullptr == mxEmbeddedMap) { mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>()); } else { mxEmbeddedMap->ClearAll(); } mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue))) } } bRet = true; } } return bRet; } const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const { return this->mxEmbeddedList; } const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const { return this->mxEmbeddedMap; } <|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 "ui/views/widget/desktop_aura/x11_whole_screen_move_loop.h" #include <X11/Xlib.h> // Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class. #undef RootWindow #include "base/debug/stack_trace.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_x11.h" #include "base/run_loop.h" #include "ui/aura/env.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/x/x11_util.h" #include "ui/events/event.h" #include "ui/gfx/point_conversions.h" #include "ui/gfx/screen.h" #include "ui/views/controls/image_view.h" #include "ui/views/widget/widget.h" namespace views { namespace { class ScopedCapturer { public: explicit ScopedCapturer(aura::WindowTreeHost* host) : host_(host) { host_->SetCapture(); } ~ScopedCapturer() { host_->ReleaseCapture(); } private: aura::WindowTreeHost* host_; DISALLOW_COPY_AND_ASSIGN(ScopedCapturer); }; } // namespace X11WholeScreenMoveLoop::X11WholeScreenMoveLoop( X11WholeScreenMoveLoopDelegate* delegate) : delegate_(delegate), in_move_loop_(false), should_reset_mouse_flags_(false), grab_input_window_(None) { } X11WholeScreenMoveLoop::~X11WholeScreenMoveLoop() {} //////////////////////////////////////////////////////////////////////////////// // DesktopWindowTreeHostLinux, MessagePumpDispatcher implementation: bool X11WholeScreenMoveLoop::Dispatch(const base::NativeEvent& event) { XEvent* xev = event; // Note: the escape key is handled in the tab drag controller, which has // keyboard focus even though we took pointer grab. switch (xev->type) { case MotionNotify: { if (drag_widget_.get()) { gfx::Screen* screen = gfx::Screen::GetNativeScreen(); gfx::Point location = gfx::ToFlooredPoint( screen->GetCursorScreenPoint() - drag_offset_); drag_widget_->SetBounds(gfx::Rect(location, drag_image_.size())); } delegate_->OnMouseMovement(&xev->xmotion); break; } case ButtonRelease: { if (xev->xbutton.button == Button1) { // Assume that drags are being done with the left mouse button. Only // break the drag if the left mouse button was released. delegate_->OnMouseReleased(); } break; } } return true; } //////////////////////////////////////////////////////////////////////////////// // DesktopWindowTreeHostLinux, aura::client::WindowMoveClient implementation: bool X11WholeScreenMoveLoop::RunMoveLoop(aura::Window* source, gfx::NativeCursor cursor) { // Start a capture on the host, so that it continues to receive events during // the drag. ScopedCapturer capturer(source->GetDispatcher()->host()); DCHECK(!in_move_loop_); // Can only handle one nested loop at a time. in_move_loop_ = true; XDisplay* display = gfx::GetXDisplay(); grab_input_window_ = CreateDragInputWindow(display); if (!drag_image_.isNull()) CreateDragImageWindow(); base::MessagePumpX11::Current()->AddDispatcherForWindow( this, grab_input_window_); if (!GrabPointerWithCursor(cursor)) return false; // We are handling a mouse drag outside of the aura::RootWindow system. We // must manually make aura think that the mouse button is pressed so that we // don't draw extraneous tooltips. aura::Env* env = aura::Env::GetInstance(); if (!env->IsMouseButtonDown()) { env->set_mouse_button_flags(ui::EF_LEFT_MOUSE_BUTTON); should_reset_mouse_flags_ = true; } base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); base::MessageLoop::ScopedNestableTaskAllower allow_nested(loop); base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); run_loop.Run(); return true; } void X11WholeScreenMoveLoop::UpdateCursor(gfx::NativeCursor cursor) { DCHECK(in_move_loop_); GrabPointerWithCursor(cursor); } void X11WholeScreenMoveLoop::EndMoveLoop() { if (!in_move_loop_) return; // We undo our emulated mouse click from RunMoveLoop(); if (should_reset_mouse_flags_) { aura::Env::GetInstance()->set_mouse_button_flags(0); should_reset_mouse_flags_ = false; } // TODO(erg): Is this ungrab the cause of having to click to give input focus // on drawn out windows? Not ungrabbing here screws the X server until I kill // the chrome process. // Ungrab before we let go of the window. XDisplay* display = gfx::GetXDisplay(); XUngrabPointer(display, CurrentTime); base::MessagePumpX11::Current()->RemoveDispatcherForWindow( grab_input_window_); drag_widget_.reset(); delegate_->OnMoveLoopEnded(); XDestroyWindow(display, grab_input_window_); in_move_loop_ = false; quit_closure_.Run(); } void X11WholeScreenMoveLoop::SetDragImage(const gfx::ImageSkia& image, gfx::Vector2dF offset) { drag_image_ = image; drag_offset_ = offset; // Reset the Y offset, so that the drag-image is always just below the cursor, // so that it is possible to see where the cursor is going. drag_offset_.set_y(0.f); } bool X11WholeScreenMoveLoop::GrabPointerWithCursor(gfx::NativeCursor cursor) { XDisplay* display = gfx::GetXDisplay(); XGrabServer(display); XUngrabPointer(display, CurrentTime); int ret = XGrabPointer( display, grab_input_window_, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, None, cursor.platform(), CurrentTime); XUngrabServer(display); if (ret != GrabSuccess) { DLOG(ERROR) << "Grabbing new tab for dragging failed: " << ui::GetX11ErrorString(display, ret); return false; } return true; } Window X11WholeScreenMoveLoop::CreateDragInputWindow(XDisplay* display) { // Creates an invisible, InputOnly toplevel window. This window will receive // all mouse movement for drags. It turns out that normal windows doing a // grab doesn't redirect pointer motion events if the pointer isn't over the // grabbing window. But InputOnly windows are able to grab everything. This // is what GTK+ does, and I found a patch to KDE that did something similar. unsigned long attribute_mask = CWEventMask | CWOverrideRedirect; XSetWindowAttributes swa; memset(&swa, 0, sizeof(swa)); swa.event_mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; swa.override_redirect = True; Window window = XCreateWindow(display, DefaultRootWindow(display), -100, -100, 10, 10, 0, CopyFromParent, InputOnly, CopyFromParent, attribute_mask, &swa); XMapRaised(display, window); base::MessagePumpX11::Current()->BlockUntilWindowMapped(window); return window; } void X11WholeScreenMoveLoop::CreateDragImageWindow() { Widget* widget = new Widget; Widget::InitParams params(Widget::InitParams::TYPE_DRAG); params.opacity = Widget::InitParams::OPAQUE_WINDOW; params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.accept_events = false; gfx::Point location = gfx::ToFlooredPoint( gfx::Screen::GetNativeScreen()->GetCursorScreenPoint() - drag_offset_); params.bounds = gfx::Rect(location, drag_image_.size()); widget->set_focus_on_creation(false); widget->set_frame_type(Widget::FRAME_TYPE_FORCE_NATIVE); widget->Init(params); widget->GetNativeWindow()->SetName("DragWindow"); ImageView* image = new ImageView(); image->SetImage(drag_image_); image->SetBounds(0, 0, drag_image_.width(), drag_image_.height()); widget->SetContentsView(image); widget->Show(); widget->GetNativeWindow()->layer()->SetFillsBoundsOpaquely(false); drag_widget_.reset(widget); } } // namespace views <commit_msg>linux_aura: Don't update cursor while shutting down the move loop.<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 "ui/views/widget/desktop_aura/x11_whole_screen_move_loop.h" #include <X11/Xlib.h> // Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class. #undef RootWindow #include "base/debug/stack_trace.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_x11.h" #include "base/run_loop.h" #include "ui/aura/env.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/x/x11_util.h" #include "ui/events/event.h" #include "ui/gfx/point_conversions.h" #include "ui/gfx/screen.h" #include "ui/views/controls/image_view.h" #include "ui/views/widget/widget.h" namespace views { namespace { class ScopedCapturer { public: explicit ScopedCapturer(aura::WindowTreeHost* host) : host_(host) { host_->SetCapture(); } ~ScopedCapturer() { host_->ReleaseCapture(); } private: aura::WindowTreeHost* host_; DISALLOW_COPY_AND_ASSIGN(ScopedCapturer); }; } // namespace X11WholeScreenMoveLoop::X11WholeScreenMoveLoop( X11WholeScreenMoveLoopDelegate* delegate) : delegate_(delegate), in_move_loop_(false), should_reset_mouse_flags_(false), grab_input_window_(None) { } X11WholeScreenMoveLoop::~X11WholeScreenMoveLoop() {} //////////////////////////////////////////////////////////////////////////////// // DesktopWindowTreeHostLinux, MessagePumpDispatcher implementation: bool X11WholeScreenMoveLoop::Dispatch(const base::NativeEvent& event) { XEvent* xev = event; // Note: the escape key is handled in the tab drag controller, which has // keyboard focus even though we took pointer grab. switch (xev->type) { case MotionNotify: { if (drag_widget_.get()) { gfx::Screen* screen = gfx::Screen::GetNativeScreen(); gfx::Point location = gfx::ToFlooredPoint( screen->GetCursorScreenPoint() - drag_offset_); drag_widget_->SetBounds(gfx::Rect(location, drag_image_.size())); } delegate_->OnMouseMovement(&xev->xmotion); break; } case ButtonRelease: { if (xev->xbutton.button == Button1) { // Assume that drags are being done with the left mouse button. Only // break the drag if the left mouse button was released. delegate_->OnMouseReleased(); } break; } } return true; } //////////////////////////////////////////////////////////////////////////////// // DesktopWindowTreeHostLinux, aura::client::WindowMoveClient implementation: bool X11WholeScreenMoveLoop::RunMoveLoop(aura::Window* source, gfx::NativeCursor cursor) { // Start a capture on the host, so that it continues to receive events during // the drag. ScopedCapturer capturer(source->GetDispatcher()->host()); DCHECK(!in_move_loop_); // Can only handle one nested loop at a time. in_move_loop_ = true; XDisplay* display = gfx::GetXDisplay(); grab_input_window_ = CreateDragInputWindow(display); if (!drag_image_.isNull()) CreateDragImageWindow(); base::MessagePumpX11::Current()->AddDispatcherForWindow( this, grab_input_window_); if (!GrabPointerWithCursor(cursor)) return false; // We are handling a mouse drag outside of the aura::RootWindow system. We // must manually make aura think that the mouse button is pressed so that we // don't draw extraneous tooltips. aura::Env* env = aura::Env::GetInstance(); if (!env->IsMouseButtonDown()) { env->set_mouse_button_flags(ui::EF_LEFT_MOUSE_BUTTON); should_reset_mouse_flags_ = true; } base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); base::MessageLoop::ScopedNestableTaskAllower allow_nested(loop); base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); run_loop.Run(); return true; } void X11WholeScreenMoveLoop::UpdateCursor(gfx::NativeCursor cursor) { if (in_move_loop_) { // If we're still in the move loop, regrab the pointer with the updated // cursor. Note: we can be called from handling an XdndStatus message after // EndMoveLoop() was called, but before we return from the nested RunLoop. GrabPointerWithCursor(cursor); } } void X11WholeScreenMoveLoop::EndMoveLoop() { if (!in_move_loop_) return; // We undo our emulated mouse click from RunMoveLoop(); if (should_reset_mouse_flags_) { aura::Env::GetInstance()->set_mouse_button_flags(0); should_reset_mouse_flags_ = false; } // TODO(erg): Is this ungrab the cause of having to click to give input focus // on drawn out windows? Not ungrabbing here screws the X server until I kill // the chrome process. // Ungrab before we let go of the window. XDisplay* display = gfx::GetXDisplay(); XUngrabPointer(display, CurrentTime); base::MessagePumpX11::Current()->RemoveDispatcherForWindow( grab_input_window_); drag_widget_.reset(); delegate_->OnMoveLoopEnded(); XDestroyWindow(display, grab_input_window_); in_move_loop_ = false; quit_closure_.Run(); } void X11WholeScreenMoveLoop::SetDragImage(const gfx::ImageSkia& image, gfx::Vector2dF offset) { drag_image_ = image; drag_offset_ = offset; // Reset the Y offset, so that the drag-image is always just below the cursor, // so that it is possible to see where the cursor is going. drag_offset_.set_y(0.f); } bool X11WholeScreenMoveLoop::GrabPointerWithCursor(gfx::NativeCursor cursor) { XDisplay* display = gfx::GetXDisplay(); XGrabServer(display); XUngrabPointer(display, CurrentTime); int ret = XGrabPointer( display, grab_input_window_, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, None, cursor.platform(), CurrentTime); XUngrabServer(display); if (ret != GrabSuccess) { DLOG(ERROR) << "Grabbing new tab for dragging failed: " << ui::GetX11ErrorString(display, ret); return false; } return true; } Window X11WholeScreenMoveLoop::CreateDragInputWindow(XDisplay* display) { // Creates an invisible, InputOnly toplevel window. This window will receive // all mouse movement for drags. It turns out that normal windows doing a // grab doesn't redirect pointer motion events if the pointer isn't over the // grabbing window. But InputOnly windows are able to grab everything. This // is what GTK+ does, and I found a patch to KDE that did something similar. unsigned long attribute_mask = CWEventMask | CWOverrideRedirect; XSetWindowAttributes swa; memset(&swa, 0, sizeof(swa)); swa.event_mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; swa.override_redirect = True; Window window = XCreateWindow(display, DefaultRootWindow(display), -100, -100, 10, 10, 0, CopyFromParent, InputOnly, CopyFromParent, attribute_mask, &swa); XMapRaised(display, window); base::MessagePumpX11::Current()->BlockUntilWindowMapped(window); return window; } void X11WholeScreenMoveLoop::CreateDragImageWindow() { Widget* widget = new Widget; Widget::InitParams params(Widget::InitParams::TYPE_DRAG); params.opacity = Widget::InitParams::OPAQUE_WINDOW; params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.accept_events = false; gfx::Point location = gfx::ToFlooredPoint( gfx::Screen::GetNativeScreen()->GetCursorScreenPoint() - drag_offset_); params.bounds = gfx::Rect(location, drag_image_.size()); widget->set_focus_on_creation(false); widget->set_frame_type(Widget::FRAME_TYPE_FORCE_NATIVE); widget->Init(params); widget->GetNativeWindow()->SetName("DragWindow"); ImageView* image = new ImageView(); image->SetImage(drag_image_); image->SetBounds(0, 0, drag_image_.width(), drag_image_.height()); widget->SetContentsView(image); widget->Show(); widget->GetNativeWindow()->layer()->SetFillsBoundsOpaquely(false); drag_widget_.reset(widget); } } // namespace views <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2010 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real Copyright (C) 2017 Roman Lebedev 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 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 "decompressors/SamsungV2Decompressor.h" #include "common/Common.h" // for uint32, ushort16, int32 #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpMSB32.h" // for BitPumpMSB32 #include "io/ByteStream.h" // for ByteStream #include <algorithm> // for max #include <cassert> // for assert #include <type_traits> // for underlying_type, underlyin... namespace rawspeed { // Seriously Samsung just use lossless jpeg already, it compresses better too :) // Thanks to Michael Reichmann (Luminous Landscape) for putting Pedro Côrte-Real // in contact and Loring von Palleske (Samsung) for pointing to the open-source // code of Samsung's DNG converter at http://opensource.samsung.com/ enum struct SamsungV2Decompressor::OptFlags : uint32 { NONE = 0U, // no flags SKIP = 1U << 0U, // Skip checking if we need differences from previous line MV = 1U << 1U, // Simplify motion vector definition QP = 1U << 2U, // Don't scale the diff values // all possible flags ALL = SKIP | MV | QP, }; constexpr SamsungV2Decompressor::OptFlags operator|(SamsungV2Decompressor::OptFlags lhs, SamsungV2Decompressor::OptFlags rhs) { return static_cast<SamsungV2Decompressor::OptFlags>( static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( lhs) | static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( rhs)); } constexpr bool operator&(SamsungV2Decompressor::OptFlags lhs, SamsungV2Decompressor::OptFlags rhs) { return SamsungV2Decompressor::OptFlags::NONE != static_cast<SamsungV2Decompressor::OptFlags>( static_cast< std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( lhs) & static_cast< std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( rhs)); } SamsungV2Decompressor::SamsungV2Decompressor(const RawImage& image, const ByteStream& bs, int bit) : AbstractSamsungDecompressor(image), bits(bit) { BitPumpMSB32 startpump(bs); // Process the initial metadata bits, we only really use initVal, width and // height (the last two match the TIFF values anyway) startpump.getBits(16); // NLCVersion startpump.getBits(4); // ImgFormat bitDepth = startpump.getBits(4) + 1; startpump.getBits(4); // NumBlkInRCUnit startpump.getBits(4); // CompressionRatio width = startpump.getBits(16); height = startpump.getBits(16); startpump.getBits(16); // TileWidth startpump.getBits(4); // reserved // The format includes an optimization code that sets 3 flags to change the // decoding parameters const uint32 optflags = startpump.getBits(4); if (optflags > static_cast<uint32>(OptFlags::ALL)) ThrowRDE("Invalid opt flags %x", optflags); _flags = static_cast<OptFlags>(optflags); startpump.getBits(8); // OverlapWidth startpump.getBits(8); // reserved startpump.getBits(8); // Inc startpump.getBits(2); // reserved initVal = startpump.getBits(14); if (width == 0 || height == 0 || width % 16 != 0 || width > 6496 || height > 4336) ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height); if (width != static_cast<uint32>(mRaw->dim.x) || height != static_cast<uint32>(mRaw->dim.y)) ThrowRDE("EXIF image dimensions do not match dimensions from raw header"); data = startpump.getStream(startpump.getRemainSize()); } void SamsungV2Decompressor::decompress() { switch (_flags) { case OptFlags::NONE: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::NONE>(row); break; case OptFlags::ALL: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::ALL>(row); break; case OptFlags::SKIP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::SKIP>(row); break; case OptFlags::MV: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::MV>(row); break; case OptFlags::QP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::QP>(row); break; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch" case OptFlags::SKIP | OptFlags::MV: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::SKIP | OptFlags::MV>(row); break; case OptFlags::SKIP | OptFlags::QP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::SKIP | OptFlags::QP>(row); break; case OptFlags::MV | OptFlags::QP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::MV | OptFlags::QP>(row); break; #pragma GCC diagnostic pop default: __builtin_unreachable(); } } template <SamsungV2Decompressor::OptFlags optflags> void SamsungV2Decompressor::decompressRow(uint32 row) { // The format is relatively straightforward. Each line gets encoded as a set // of differences from pixels from another line. Pixels are grouped in blocks // of 16 (8 green, 8 red or blue). Each block is encoded in three sections. // First 1 or 4 bits to specify which reference pixels to use, then a section // that specifies for each pixel the number of bits in the difference, then // the actual difference bits // Align pump to 16byte boundary const auto line_offset = data.getPosition(); if ((line_offset & 0xf) != 0) data.skipBytes(16 - (line_offset & 0xf)); BitPumpMSB32 pump(data); auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, row)); ushort16* img_up = reinterpret_cast<ushort16*>( mRaw->getData(0, std::max(0, static_cast<int>(row) - 1))); ushort16* img_up2 = reinterpret_cast<ushort16*>( mRaw->getData(0, std::max(0, static_cast<int>(row) - 2))); // Initialize the motion and diff modes at the start of the line uint32 motion = 7; // By default we are not scaling values at all int32 scale = 0; uint32 diffBitsMode[3][2] = {{0}}; for (auto& i : diffBitsMode) i[0] = i[1] = (row == 0 || row == 1) ? 7 : 4; assert(width >= 16); for (uint32 col = 0; col < width; col += 16) { if (!(optflags & OptFlags::QP) && !(col & 63)) { int32 scalevals[] = {0, -2, 2}; uint32 i = pump.getBits(2); scale = i < 3 ? scale + scalevals[i] : pump.getBits(12); } // First we figure out which reference pixels mode we're in if (optflags & OptFlags::MV) motion = pump.getBits(1) ? 3 : 7; else if (!pump.getBits(1)) motion = pump.getBits(3); if ((row == 0 || row == 1) && (motion != 7)) ThrowRDE("At start of image and motion isn't 7. File corrupted?"); if (motion == 7) { // The base case, just set all pixels to the previous ones on the same // line If we're at the left edge we just start at the initial value for (uint32 i = 0; i < 16; i++) img[i] = (col == 0) ? initVal : *(img + i - 2); } else { // The complex case, we now need to actually lookup one or two lines // above if (row < 2) ThrowRDE( "Got a previous line lookup on first two lines. File corrupted?"); int32 motionOffset[7] = {-4, -2, -2, 0, 0, 2, 4}; int32 motionDoAverage[7] = {0, 0, 1, 0, 1, 0, 0}; int32 slideOffset = motionOffset[motion]; int32 doAverage = motionDoAverage[motion]; for (uint32 i = 0; i < 16; i++) { ushort16* refpixel; if ((row + i) & 0x1) // Red or blue pixels use same color two lines up refpixel = img_up2 + i + slideOffset; else // Green pixel N uses Green pixel N from row above (top left or // top right) refpixel = img_up + i + slideOffset + (((i % 2) != 0) ? -1 : 1); // In some cases we use as reference interpolation of this pixel and // the next if (doAverage) img[i] = (*refpixel + *(refpixel + 2) + 1) >> 1; else img[i] = *refpixel; } } // Figure out how many difference bits we have to read for each pixel uint32 diffBits[4] = {0}; if (optflags & OptFlags::SKIP || !pump.getBits(1)) { uint32 flags[4]; for (unsigned int& flag : flags) flag = pump.getBits(2); for (uint32 i = 0; i < 4; i++) { // The color is 0-Green 1-Blue 2-Red uint32 colornum = (row % 2 != 0) ? i >> 1 : ((i >> 1) + 2) % 3; assert(flags[i] <= 3); switch (flags[i]) { case 0: diffBits[i] = diffBitsMode[colornum][0]; break; case 1: diffBits[i] = diffBitsMode[colornum][0] + 1; break; case 2: diffBits[i] = diffBitsMode[colornum][0] - 1; break; case 3: diffBits[i] = pump.getBits(4); break; default: __builtin_unreachable(); } diffBitsMode[colornum][0] = diffBitsMode[colornum][1]; diffBitsMode[colornum][1] = diffBits[i]; if (diffBits[i] > bitDepth + 1) ThrowRDE("Too many difference bits. File corrupted?"); } } // Actually read the differences and write them to the pixels for (uint32 i = 0; i < 16; i++) { uint32 len = diffBits[i >> 2]; int32 diff = pump.getBits(len); // If the first bit is 1 we need to turn this into a negative number if (len != 0 && diff >> (len - 1)) diff -= (1 << len); ushort16* value = nullptr; // Apply the diff to pixels 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 if (row % 2) value = &img[((i & 0x7) << 1) + 1 - (i >> 3)]; else value = &img[((i & 0x7) << 1) + (i >> 3)]; diff = diff * (scale * 2 + 1) + scale; *value = clampBits(static_cast<int>(*value) + diff, bits); } img += 16; img_up += 16; img_up2 += 16; } data.skipBytes(pump.getBufferPosition()); } } // namespace rawspeed <commit_msg>SamsungV2Decompressor::decompressRow(): "complex case": first 16 pix: check<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2010 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real Copyright (C) 2017 Roman Lebedev 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 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 "decompressors/SamsungV2Decompressor.h" #include "common/Common.h" // for uint32, ushort16, int32 #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpMSB32.h" // for BitPumpMSB32 #include "io/ByteStream.h" // for ByteStream #include <algorithm> // for max #include <cassert> // for assert #include <type_traits> // for underlying_type, underlyin... namespace rawspeed { // Seriously Samsung just use lossless jpeg already, it compresses better too :) // Thanks to Michael Reichmann (Luminous Landscape) for putting Pedro Côrte-Real // in contact and Loring von Palleske (Samsung) for pointing to the open-source // code of Samsung's DNG converter at http://opensource.samsung.com/ enum struct SamsungV2Decompressor::OptFlags : uint32 { NONE = 0U, // no flags SKIP = 1U << 0U, // Skip checking if we need differences from previous line MV = 1U << 1U, // Simplify motion vector definition QP = 1U << 2U, // Don't scale the diff values // all possible flags ALL = SKIP | MV | QP, }; constexpr SamsungV2Decompressor::OptFlags operator|(SamsungV2Decompressor::OptFlags lhs, SamsungV2Decompressor::OptFlags rhs) { return static_cast<SamsungV2Decompressor::OptFlags>( static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( lhs) | static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( rhs)); } constexpr bool operator&(SamsungV2Decompressor::OptFlags lhs, SamsungV2Decompressor::OptFlags rhs) { return SamsungV2Decompressor::OptFlags::NONE != static_cast<SamsungV2Decompressor::OptFlags>( static_cast< std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( lhs) & static_cast< std::underlying_type<SamsungV2Decompressor::OptFlags>::type>( rhs)); } SamsungV2Decompressor::SamsungV2Decompressor(const RawImage& image, const ByteStream& bs, int bit) : AbstractSamsungDecompressor(image), bits(bit) { BitPumpMSB32 startpump(bs); // Process the initial metadata bits, we only really use initVal, width and // height (the last two match the TIFF values anyway) startpump.getBits(16); // NLCVersion startpump.getBits(4); // ImgFormat bitDepth = startpump.getBits(4) + 1; startpump.getBits(4); // NumBlkInRCUnit startpump.getBits(4); // CompressionRatio width = startpump.getBits(16); height = startpump.getBits(16); startpump.getBits(16); // TileWidth startpump.getBits(4); // reserved // The format includes an optimization code that sets 3 flags to change the // decoding parameters const uint32 optflags = startpump.getBits(4); if (optflags > static_cast<uint32>(OptFlags::ALL)) ThrowRDE("Invalid opt flags %x", optflags); _flags = static_cast<OptFlags>(optflags); startpump.getBits(8); // OverlapWidth startpump.getBits(8); // reserved startpump.getBits(8); // Inc startpump.getBits(2); // reserved initVal = startpump.getBits(14); if (width == 0 || height == 0 || width % 16 != 0 || width > 6496 || height > 4336) ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height); if (width != static_cast<uint32>(mRaw->dim.x) || height != static_cast<uint32>(mRaw->dim.y)) ThrowRDE("EXIF image dimensions do not match dimensions from raw header"); data = startpump.getStream(startpump.getRemainSize()); } void SamsungV2Decompressor::decompress() { switch (_flags) { case OptFlags::NONE: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::NONE>(row); break; case OptFlags::ALL: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::ALL>(row); break; case OptFlags::SKIP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::SKIP>(row); break; case OptFlags::MV: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::MV>(row); break; case OptFlags::QP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::QP>(row); break; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch" case OptFlags::SKIP | OptFlags::MV: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::SKIP | OptFlags::MV>(row); break; case OptFlags::SKIP | OptFlags::QP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::SKIP | OptFlags::QP>(row); break; case OptFlags::MV | OptFlags::QP: for (uint32 row = 0; row < height; row++) decompressRow<OptFlags::MV | OptFlags::QP>(row); break; #pragma GCC diagnostic pop default: __builtin_unreachable(); } } template <SamsungV2Decompressor::OptFlags optflags> void SamsungV2Decompressor::decompressRow(uint32 row) { // The format is relatively straightforward. Each line gets encoded as a set // of differences from pixels from another line. Pixels are grouped in blocks // of 16 (8 green, 8 red or blue). Each block is encoded in three sections. // First 1 or 4 bits to specify which reference pixels to use, then a section // that specifies for each pixel the number of bits in the difference, then // the actual difference bits // Align pump to 16byte boundary const auto line_offset = data.getPosition(); if ((line_offset & 0xf) != 0) data.skipBytes(16 - (line_offset & 0xf)); BitPumpMSB32 pump(data); auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, row)); ushort16* img_up = reinterpret_cast<ushort16*>( mRaw->getData(0, std::max(0, static_cast<int>(row) - 1))); ushort16* img_up2 = reinterpret_cast<ushort16*>( mRaw->getData(0, std::max(0, static_cast<int>(row) - 2))); // Initialize the motion and diff modes at the start of the line uint32 motion = 7; // By default we are not scaling values at all int32 scale = 0; uint32 diffBitsMode[3][2] = {{0}}; for (auto& i : diffBitsMode) i[0] = i[1] = (row == 0 || row == 1) ? 7 : 4; assert(width >= 16); for (uint32 col = 0; col < width; col += 16) { if (!(optflags & OptFlags::QP) && !(col & 63)) { int32 scalevals[] = {0, -2, 2}; uint32 i = pump.getBits(2); scale = i < 3 ? scale + scalevals[i] : pump.getBits(12); } // First we figure out which reference pixels mode we're in if (optflags & OptFlags::MV) motion = pump.getBits(1) ? 3 : 7; else if (!pump.getBits(1)) motion = pump.getBits(3); if ((row == 0 || row == 1) && (motion != 7)) ThrowRDE("At start of image and motion isn't 7. File corrupted?"); if (motion == 7) { // The base case, just set all pixels to the previous ones on the same // line If we're at the left edge we just start at the initial value for (uint32 i = 0; i < 16; i++) img[i] = (col == 0) ? initVal : *(img + i - 2); } else { // The complex case, we now need to actually lookup one or two lines // above if (row < 2) ThrowRDE( "Got a previous line lookup on first two lines. File corrupted?"); int32 motionOffset[7] = {-4, -2, -2, 0, 0, 2, 4}; int32 motionDoAverage[7] = {0, 0, 1, 0, 1, 0, 0}; int32 slideOffset = motionOffset[motion]; int32 doAverage = motionDoAverage[motion]; for (uint32 i = 0; i < 16; i++) { ushort16* refpixel; if ((row + i) & 0x1) { // Red or blue pixels use same color two lines up refpixel = img_up2 + i + slideOffset; if (col == 0 && img_up2 > refpixel) ThrowRDE("Bad motion %u at the beginning of the row", motion); } else { // Green pixel N uses Green pixel N from row above // (top left or top right) refpixel = img_up + i + slideOffset + (((i % 2) != 0) ? -1 : 1); if (col == 0 && img_up > refpixel) ThrowRDE("Bad motion %u at the beginning of the row", motion); } // In some cases we use as reference interpolation of this pixel and // the next if (doAverage) img[i] = (*refpixel + *(refpixel + 2) + 1) >> 1; else img[i] = *refpixel; } } // Figure out how many difference bits we have to read for each pixel uint32 diffBits[4] = {0}; if (optflags & OptFlags::SKIP || !pump.getBits(1)) { uint32 flags[4]; for (unsigned int& flag : flags) flag = pump.getBits(2); for (uint32 i = 0; i < 4; i++) { // The color is 0-Green 1-Blue 2-Red uint32 colornum = (row % 2 != 0) ? i >> 1 : ((i >> 1) + 2) % 3; assert(flags[i] <= 3); switch (flags[i]) { case 0: diffBits[i] = diffBitsMode[colornum][0]; break; case 1: diffBits[i] = diffBitsMode[colornum][0] + 1; break; case 2: diffBits[i] = diffBitsMode[colornum][0] - 1; break; case 3: diffBits[i] = pump.getBits(4); break; default: __builtin_unreachable(); } diffBitsMode[colornum][0] = diffBitsMode[colornum][1]; diffBitsMode[colornum][1] = diffBits[i]; if (diffBits[i] > bitDepth + 1) ThrowRDE("Too many difference bits. File corrupted?"); } } // Actually read the differences and write them to the pixels for (uint32 i = 0; i < 16; i++) { uint32 len = diffBits[i >> 2]; int32 diff = pump.getBits(len); // If the first bit is 1 we need to turn this into a negative number if (len != 0 && diff >> (len - 1)) diff -= (1 << len); ushort16* value = nullptr; // Apply the diff to pixels 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 if (row % 2) value = &img[((i & 0x7) << 1) + 1 - (i >> 3)]; else value = &img[((i & 0x7) << 1) + (i >> 3)]; diff = diff * (scale * 2 + 1) + scale; *value = clampBits(static_cast<int>(*value) + diff, bits); } img += 16; img_up += 16; img_up2 += 16; } data.skipBytes(pump.getBufferPosition()); } } // namespace rawspeed <|endoftext|>
<commit_before><commit_msg>forgot to stage part of the patch<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 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 "base/at_exit.h" #include "base/message_loop.h" #include "base/scoped_nsautorelease_pool.h" #include "gpu/command_buffer/common/command_buffer_mock.h" #include "gpu/command_buffer/service/context_group.h" #include "gpu/command_buffer/service/gpu_processor.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/gles2_cmd_decoder_mock.h" #include "gpu/command_buffer/service/mocks.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gmock/include/gmock/gmock.h" using testing::_; using testing::DoAll; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::SetArgumentPointee; using testing::StrictMock; namespace gpu { const size_t kRingBufferSize = 1024; const size_t kRingBufferEntries = kRingBufferSize / sizeof(CommandBufferEntry); class GPUProcessorTest : public testing::Test { protected: virtual void SetUp() { shared_memory_.reset(new ::base::SharedMemory); shared_memory_->Create(std::wstring(), false, false, kRingBufferSize); shared_memory_->Map(kRingBufferSize); buffer_ = static_cast<int32*>(shared_memory_->memory()); shared_memory_buffer_.ptr = buffer_; shared_memory_buffer_.size = kRingBufferSize; memset(buffer_, 0, kRingBufferSize); command_buffer_.reset(new MockCommandBuffer); ON_CALL(*command_buffer_.get(), GetRingBuffer()) .WillByDefault(Return(shared_memory_buffer_)); CommandBuffer::State default_state; default_state.size = kRingBufferEntries; ON_CALL(*command_buffer_.get(), GetState()) .WillByDefault(Return(default_state)); async_api_.reset(new StrictMock<AsyncAPIMock>); decoder_ = new gles2::MockGLES2Decoder(&group_); parser_ = new CommandParser(buffer_, kRingBufferEntries, 0, kRingBufferEntries, 0, async_api_.get()); processor_.reset(new GPUProcessor(command_buffer_.get(), decoder_, parser_, 2)); } virtual void TearDown() { // Ensure that any unexpected tasks posted by the GPU processor are executed // in order to fail the test. MessageLoop::current()->RunAllPending(); } error::Error GetError() { return command_buffer_->GetState().error; } base::ScopedNSAutoreleasePool autorelease_pool_; base::AtExitManager at_exit_manager; MessageLoop message_loop; scoped_ptr<MockCommandBuffer> command_buffer_; scoped_ptr<base::SharedMemory> shared_memory_; Buffer shared_memory_buffer_; int32* buffer_; gles2::ContextGroup group_; gles2::MockGLES2Decoder* decoder_; CommandParser* parser_; scoped_ptr<AsyncAPIMock> async_api_; scoped_ptr<GPUProcessor> processor_; }; TEST_F(GPUProcessorTest, ProcessorDoesNothingIfRingBufferIsEmpty) { CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessesOneCommand) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; CommandBuffer::State state; state.put_offset = 2; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(2)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessesTwoCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; CommandBuffer::State state; state.put_offset = 3; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessorSetsTheGLContext) { EXPECT_CALL(*decoder_, MakeCurrent()) .WillOnce(Return(true)); CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, PostsTaskToFinishRemainingCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; header[3].command = 9; header[3].size = 1; CommandBuffer::State state; state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); processor_->ProcessCommands(); // ProcessCommands is called a second time when the pending task is run. state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(9, 0, &buffer_[3])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(4)); MessageLoop::current()->RunAllPending(); } TEST_F(GPUProcessorTest, SetsErrorCodeOnCommandBuffer) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 1; CommandBuffer::State state; state.put_offset = 1; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 0, &buffer_[0])) .WillOnce(Return( error::kUnknownCommand)); EXPECT_CALL(*command_buffer_, SetParseError(error::kUnknownCommand)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessCommandsDoesNothingAfterError) { CommandBuffer::State state; state.error = error::kGenericError; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, CanGetAddressOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(&buffer_[0], processor_->GetSharedMemoryBuffer(7).ptr); } ACTION_P2(SetPointee, address, value) { *address = value; } TEST_F(GPUProcessorTest, CanGetSizeOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(kRingBufferSize, processor_->GetSharedMemoryBuffer(7).size); } TEST_F(GPUProcessorTest, SetTokenForwardsToCommandBuffer) { EXPECT_CALL(*command_buffer_, SetToken(7)); processor_->set_token(7); } } // namespace gpu <commit_msg>Disable the ProcessorDoesNothingIfRingBufferIsEmpty because it crashes gpu_unittests.<commit_after>// Copyright (c) 2009 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 "base/at_exit.h" #include "base/message_loop.h" #include "base/scoped_nsautorelease_pool.h" #include "gpu/command_buffer/common/command_buffer_mock.h" #include "gpu/command_buffer/service/context_group.h" #include "gpu/command_buffer/service/gpu_processor.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/gles2_cmd_decoder_mock.h" #include "gpu/command_buffer/service/mocks.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gmock/include/gmock/gmock.h" using testing::_; using testing::DoAll; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::SetArgumentPointee; using testing::StrictMock; namespace gpu { const size_t kRingBufferSize = 1024; const size_t kRingBufferEntries = kRingBufferSize / sizeof(CommandBufferEntry); class GPUProcessorTest : public testing::Test { protected: virtual void SetUp() { shared_memory_.reset(new ::base::SharedMemory); shared_memory_->Create(std::wstring(), false, false, kRingBufferSize); shared_memory_->Map(kRingBufferSize); buffer_ = static_cast<int32*>(shared_memory_->memory()); shared_memory_buffer_.ptr = buffer_; shared_memory_buffer_.size = kRingBufferSize; memset(buffer_, 0, kRingBufferSize); command_buffer_.reset(new MockCommandBuffer); ON_CALL(*command_buffer_.get(), GetRingBuffer()) .WillByDefault(Return(shared_memory_buffer_)); CommandBuffer::State default_state; default_state.size = kRingBufferEntries; ON_CALL(*command_buffer_.get(), GetState()) .WillByDefault(Return(default_state)); async_api_.reset(new StrictMock<AsyncAPIMock>); decoder_ = new gles2::MockGLES2Decoder(&group_); parser_ = new CommandParser(buffer_, kRingBufferEntries, 0, kRingBufferEntries, 0, async_api_.get()); processor_.reset(new GPUProcessor(command_buffer_.get(), decoder_, parser_, 2)); } virtual void TearDown() { // Ensure that any unexpected tasks posted by the GPU processor are executed // in order to fail the test. MessageLoop::current()->RunAllPending(); } error::Error GetError() { return command_buffer_->GetState().error; } base::ScopedNSAutoreleasePool autorelease_pool_; base::AtExitManager at_exit_manager; MessageLoop message_loop; scoped_ptr<MockCommandBuffer> command_buffer_; scoped_ptr<base::SharedMemory> shared_memory_; Buffer shared_memory_buffer_; int32* buffer_; gles2::ContextGroup group_; gles2::MockGLES2Decoder* decoder_; CommandParser* parser_; scoped_ptr<AsyncAPIMock> async_api_; scoped_ptr<GPUProcessor> processor_; }; // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_ProcessorDoesNothingIfRingBufferIsEmpty) { CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessesOneCommand) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; CommandBuffer::State state; state.put_offset = 2; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(2)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessesTwoCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; CommandBuffer::State state; state.put_offset = 3; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessorSetsTheGLContext) { EXPECT_CALL(*decoder_, MakeCurrent()) .WillOnce(Return(true)); CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, PostsTaskToFinishRemainingCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; header[3].command = 9; header[3].size = 1; CommandBuffer::State state; state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); processor_->ProcessCommands(); // ProcessCommands is called a second time when the pending task is run. state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(9, 0, &buffer_[3])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(4)); MessageLoop::current()->RunAllPending(); } TEST_F(GPUProcessorTest, SetsErrorCodeOnCommandBuffer) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 1; CommandBuffer::State state; state.put_offset = 1; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 0, &buffer_[0])) .WillOnce(Return( error::kUnknownCommand)); EXPECT_CALL(*command_buffer_, SetParseError(error::kUnknownCommand)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessCommandsDoesNothingAfterError) { CommandBuffer::State state; state.error = error::kGenericError; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, CanGetAddressOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(&buffer_[0], processor_->GetSharedMemoryBuffer(7).ptr); } ACTION_P2(SetPointee, address, value) { *address = value; } TEST_F(GPUProcessorTest, CanGetSizeOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(kRingBufferSize, processor_->GetSharedMemoryBuffer(7).size); } TEST_F(GPUProcessorTest, SetTokenForwardsToCommandBuffer) { EXPECT_CALL(*command_buffer_, SetToken(7)); processor_->set_token(7); } } // namespace gpu <|endoftext|>
<commit_before><commit_msg>Number representation class templates have a default zero.<commit_after><|endoftext|>
<commit_before>#include <cassert> #include "AnnLocator.h" using namespace cigma; // --------------------------------------------------------------------------- AnnLocator::AnnLocator() { nnk = 8; epsilon = 0; npts = 0; ndim2 = 0; dataPoints = 0; kdtree = 0; nnIdx = 0; nnDists = 0; locatorType = NULL_LOCATOR; } AnnLocator::~AnnLocator() { if (kdtree != 0) delete kdtree; if (dataPoints != 0) { annDeallocPts(dataPoints); dataPoints = 0; } if (nnIdx != 0) { delete [] nnIdx; nnIdx = 0; } if (nnDists != 0) { delete [] nnDists; nnDists = 0; } } // --------------------------------------------------------------------------- void AnnLocator::initialize(MeshPart *meshPart) { assert(nnk > 0); npts = meshPart->nel; ndim = meshPart->nsd; ndim2 = ndim * 2; assert(npts > 0); assert(ndim > 0); dataPoints = annAllocPts(npts, ndim); queryPoint = annAllocPt(ndim2); nnIdx = new ANNidx[nnk]; nnDists = new ANNdist[nnk]; int i,j; double minpt[ndim]; double maxpt[ndim]; for (i = 0; i < npts; i++) { ANNpoint pt = dataPoints[i]; meshPart->select_cell(i); meshPart->cell->bbox(minpt, maxpt); for (j = 0; j < ndim; j++) { pt[ndim*0 + j] = minpt[j]; pt[ndim*1 + j] = maxpt[j]; } } kdtree = new ANNkd_tree(dataPoints, npts, ndim2); locatorType = CELL_LOCATOR; } // --------------------------------------------------------------------------- void AnnLocator::initialize(Points *points) { assert(nnk > 0); npts = points->n_points(); ndim = points->n_dim(); assert(npts > 0); assert(ndim > 0); // XXX watch out for when you change the ANNpoint type to floaT assert(sizeof(ANNcoord) == sizeof(double)); //dataPoints = (ANNpointArray)(points->data); // questionable cast.. dataPoints = annAllocPts(npts, ndim); queryPoint = annAllocPt(ndim); int i,j; for (i = 0; i < npts; i++) { ANNpoint pt = dataPoints[i]; for (j = 0; j < ndim; j++) { pt[j] = points->data[ndim*i + j]; } } nnIdx = new ANNidx[nnk]; nnDists = new ANNdist[nnk]; kdtree = new ANNkd_tree(dataPoints, npts, ndim); locatorType = POINT_LOCATOR; } // --------------------------------------------------------------------------- void AnnLocator::search(double *point) { for (int i = 0; i < ndim; i++) { queryPoint[ndim*0 + i] = point[i]; queryPoint[ndim*1 + i] = point[i]; } kdtree->annkSearch(queryPoint, nnk, nnIdx, nnDists, epsilon); } // --------------------------------------------------------------------------- <commit_msg>Ooops..big typo! Fixes broken locator searches.<commit_after>#include <cassert> #include "AnnLocator.h" using namespace cigma; // --------------------------------------------------------------------------- AnnLocator::AnnLocator() { nnk = 8; epsilon = 0; npts = 0; ndim2 = 0; dataPoints = 0; kdtree = 0; nnIdx = 0; nnDists = 0; locatorType = NULL_LOCATOR; } AnnLocator::~AnnLocator() { if (kdtree != 0) delete kdtree; if (dataPoints != 0) { annDeallocPts(dataPoints); dataPoints = 0; } if (nnIdx != 0) { delete [] nnIdx; nnIdx = 0; } if (nnDists != 0) { delete [] nnDists; nnDists = 0; } } // --------------------------------------------------------------------------- void AnnLocator::initialize(MeshPart *meshPart) { assert(nnk > 0); npts = meshPart->nel; ndim = meshPart->nsd; ndim2 = ndim * 2; assert(npts > 0); assert(ndim > 0); dataPoints = annAllocPts(npts, ndim2); queryPoint = annAllocPt(ndim2); nnIdx = new ANNidx[nnk]; nnDists = new ANNdist[nnk]; int i,j; double minpt[ndim]; double maxpt[ndim]; for (i = 0; i < npts; i++) { ANNpoint pt = dataPoints[i]; meshPart->select_cell(i); meshPart->cell->bbox(minpt, maxpt); for (j = 0; j < ndim; j++) { pt[ndim*0 + j] = minpt[j]; pt[ndim*1 + j] = maxpt[j]; } } kdtree = new ANNkd_tree(dataPoints, npts, ndim2); locatorType = CELL_LOCATOR; } // --------------------------------------------------------------------------- void AnnLocator::initialize(Points *points) { assert(nnk > 0); npts = points->n_points(); ndim = points->n_dim(); assert(npts > 0); assert(ndim > 0); // XXX watch out for when you change the ANNpoint type to floaT assert(sizeof(ANNcoord) == sizeof(double)); //dataPoints = (ANNpointArray)(points->data); // questionable cast.. dataPoints = annAllocPts(npts, ndim); queryPoint = annAllocPt(ndim); int i,j; for (i = 0; i < npts; i++) { ANNpoint pt = dataPoints[i]; for (j = 0; j < ndim; j++) { pt[j] = points->data[ndim*i + j]; } } nnIdx = new ANNidx[nnk]; nnDists = new ANNdist[nnk]; kdtree = new ANNkd_tree(dataPoints, npts, ndim); locatorType = POINT_LOCATOR; } // --------------------------------------------------------------------------- void AnnLocator::search(double *point) { for (int i = 0; i < ndim; i++) { queryPoint[ndim*0 + i] = point[i]; queryPoint[ndim*1 + i] = point[i]; } kdtree->annkSearch(queryPoint, nnk, nnIdx, nnDists, epsilon); } // --------------------------------------------------------------------------- <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX24T ファースト・サンプル @n ・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "RX24T/system.hpp" #include "RX600/port.hpp" namespace { void wait_delay_(uint32_t n) { // とりあえず無駄ループ for(uint32_t i = 0; i < n; ++i) { asm("nop"); } } } int main(int argc, char** argv); int main(int argc, char** argv) { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MEMWAIT = 0b10; // 80MHz 動作 wait 設定 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); device::SYSTEM::OPCCR = 0; // 高速モード選択 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); // clock osc 10MHz device::SYSTEM::MOSCWTCR = 9; // 4ms wait // メインクロック・ドライブ能力設定、内部発信 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop"); device::SYSTEM::PLLCR.STC = 0b001111; // PLL input: 1, PLL 8 倍(80MHz) device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop"); device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2) // 1/4 (80/4=20) | device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (80/2=40) | device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60) device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 uint32_t wait = 1000000; device::PORT0::PDR.B0 = 1; // output while(1) { wait_delay_(wait); device::PORT0::PODR.B0 = 0; wait_delay_(wait); device::PORT0::PODR.B0 = 1; } } <commit_msg>remove: project refine<commit_after><|endoftext|>
<commit_before>/* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* 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 */ // <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1> // // LibMesh provides interfaces to both Triangle and TetGen for generating // Delaunay triangulations and tetrahedralizations in two and three dimensions // (respectively). // Local header files #include "mesh.h" #include "mesh_triangle_interface.h" #include "mesh_generation.h" #include "elem.h" #include "mesh_tetgen_interface.h" #include "node.h" #include "face_tri3.h" #include "mesh_triangle_holes.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Major functions called by main void triangulate_domain(); void tetrahedralize_domain(); // Helper routine for tetrahedralize_domain(). Adds the points and elements // of a convex hull generated by TetGen to the input mesh void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit); // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); std::cout << "Triangulating an L-shaped domain with holes" << std::endl; // 1.) 2D triangulation of L-shaped domain with three holes of different shape triangulate_domain(); libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl; // 2.) 3D tetrahedralization of rectangular domain with hole. tetrahedralize_domain(); return 0; } void triangulate_domain() { #ifdef LIBMESH_HAVE_TRIANGLE // Use typedefs for slightly less typing. typedef TriangleInterface::Hole Hole; typedef TriangleInterface::PolygonHole PolygonHole; typedef TriangleInterface::ArbitraryHole ArbitraryHole; // Libmesh mesh that will eventually be created. Mesh mesh(2); // The points which make up the L-shape: mesh.add_point(Point( 0. , 0.)); mesh.add_point(Point( 0. , -1.)); mesh.add_point(Point(-1. , -1.)); mesh.add_point(Point(-1. , 1.)); mesh.add_point(Point( 1. , 1.)); mesh.add_point(Point( 1. , 0.)); // Declare the TriangleInterface object. This is where // we can set parameters of the triangulation and where the // actual triangulate function lives. TriangleInterface t(mesh); // Customize the variables for the triangulation t.desired_area() = .01; // A Planar Straight Line Graph (PSLG) is essentially a list // of segments which have to exist in the final triangulation. // For an L-shaped domain, Triangle will compute the convex // hull of boundary points if we do not specify the PSLG. // The PSLG algorithm is also required for triangulating domains // containing holes t.triangulation_type() = TriangleInterface::PSLG; // Turn on/off Laplacian mesh smoothing after generation. // By default this is on. t.smooth_after_generating() = true; // Define holes... // hole_1 is a circle (discretized by 50 points) PolygonHole hole_1(Point(-0.5, 0.5), // center 0.25, // radius 50); // n. points // hole_2 is itself a triangle PolygonHole hole_2(Point(0.5, 0.5), // center 0.1, // radius 3); // n. points // hole_3 is an ellipse of 100 points which we define here Point ellipse_center(-0.5, -0.5); const unsigned int n_ellipse_points=100; std::vector<Point> ellipse_points(n_ellipse_points); const Real dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points), a = .1, b = .2; for (unsigned int i=0; i<n_ellipse_points; ++i) ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta), ellipse_center(1)+b*sin(i*dtheta)); ArbitraryHole hole_3(ellipse_center, ellipse_points); // Create the vector of Hole*'s ... std::vector<Hole*> holes; holes.push_back(&hole_1); holes.push_back(&hole_2); holes.push_back(&hole_3); // ... and attach it to the triangulator object t.attach_hole_list(&holes); // Triangulate! t.triangulate(); // Write the result to file mesh.write("delaunay_l_shaped_hole.e"); #endif // LIBMESH_HAVE_TRIANGLE } void tetrahedralize_domain() { #ifdef LIBMESH_HAVE_TETGEN // The algorithm is broken up into several steps: // 1.) A convex hull is constructed for a rectangular hole. // 2.) A convex hull is constructed for the domain exterior. // 3.) Neighbor information is updated so TetGen knows there is a convex hull // 4.) A vector of hole points is created. // 5.) The domain is tetrahedralized, the mesh is written out, etc. // The mesh we will eventually generate Mesh mesh(3); // Lower and Upper bounding box limits for a rectangular hole within the unit cube. Point hole_lower_limit(0.2, 0.2, 0.4); Point hole_upper_limit(0.8, 0.8, 0.6); // 1.) Construct a convex hull for the hole add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit); // 2.) Generate elements comprising the outer boundary of the domain. add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.)); // 3.) Update neighbor information so that TetGen can verify there is a convex hull. mesh.find_neighbors(); // 4.) Set up vector of hole points std::vector<Point> hole(1); hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) ); // 5.) Set parameters and tetrahedralize the domain // 0 means "use TetGen default value" Real quality_constraint = 2.0; // The volume constraint determines the max-allowed tetrahedral // volume in the Mesh. TetGen will split cells which are larger than // this size Real volume_constraint = 0.001; // Construct the Delaunay tetrahedralization TetGenMeshInterface t(mesh); t.triangulate_conformingDelaunayMesh_carvehole(hole, quality_constraint, volume_constraint); // Find neighbors, etc in preparation for writing out the Mesh mesh.prepare_for_use(); // Finally, write out the result mesh.write("hole_3D.e"); #endif // LIBMESH_HAVE_TETGEN } void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit) { #ifdef LIBMESH_HAVE_TETGEN Mesh cube_mesh(3); unsigned n_elem = 1; MeshTools::Generation::build_cube(cube_mesh, n_elem,n_elem,n_elem, // n. elements in each direction lower_limit(0), upper_limit(0), lower_limit(1), upper_limit(1), lower_limit(2), upper_limit(2), HEX8); // The pointset_convexhull() algorithm will ignore the Hex8s // in the Mesh, and just construct the triangulation // of the convex hull. TetGenMeshInterface t(cube_mesh); t.pointset_convexhull(); // Now add all nodes from the boundary of the cube_mesh to the input mesh. // Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted // with a dummy value, later to be assigned a value by the input mesh. std::map<unsigned,unsigned> node_id_map; typedef std::map<unsigned,unsigned>::iterator iterator; { MeshBase::element_iterator it = cube_mesh.elements_begin(); const MeshBase::element_iterator end = cube_mesh.elements_end(); for ( ; it != end; ++it) { Elem* elem = *it; for (unsigned s=0; s<elem->n_sides(); ++s) if (elem->neighbor(s) == NULL) { // Add the node IDs of this side to the set AutoPtr<Elem> side = elem->side(s); for (unsigned n=0; n<side->n_nodes(); ++n) node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) ); } } } // For each node in the map, insert it into the input mesh and keep // track of the ID assigned. for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it) { // Id of the node in the cube mesh unsigned id = (*it).first; // Pointer to node in the cube mesh Node* old_node = cube_mesh.node_ptr(id); // Add geometric point to input mesh Node* new_node = mesh.add_point ( *old_node ); // Track ID value of new_node in map (*it).second = new_node->id(); } // With the points added and the map data structure in place, we are // ready to add each TRI3 element of the cube_mesh to the input Mesh // with proper node assignments { MeshBase::element_iterator el = cube_mesh.elements_begin(); const MeshBase::element_iterator end_el = cube_mesh.elements_end(); for (; el != end_el; ++el) { Elem* old_elem = *el; if (old_elem->type() == TRI3) { Elem* new_elem = mesh.add_elem(new Tri3); // Assign nodes in new elements. Since this is an example, // we'll do it in several steps. for (unsigned i=0; i<old_elem->n_nodes(); ++i) { // Locate old node ID in the map iterator it = node_id_map.find(old_elem->node(i)); // Check for not found if (it == node_id_map.end()) { libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl; libmesh_error(); } // Mapping to node ID in input mesh unsigned new_node_id = (*it).second; // Node pointer assigned from input mesh new_elem->set_node(i) = mesh.node_ptr(new_node_id); } } } } #endif // LIBMESH_HAVE_TETGEN } <commit_msg>Use SerialMesh with tetgen until I can track down the (not recent!) ParallelMesh regression there<commit_after>/* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* 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 */ // <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1> // // LibMesh provides interfaces to both Triangle and TetGen for generating // Delaunay triangulations and tetrahedralizations in two and three dimensions // (respectively). // Local header files #include "elem.h" #include "face_tri3.h" #include "mesh.h" #include "mesh_generation.h" #include "mesh_tetgen_interface.h" #include "mesh_triangle_holes.h" #include "mesh_triangle_interface.h" #include "node.h" #include "serial_mesh.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Major functions called by main void triangulate_domain(); void tetrahedralize_domain(); // Helper routine for tetrahedralize_domain(). Adds the points and elements // of a convex hull generated by TetGen to the input mesh void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit); // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); std::cout << "Triangulating an L-shaped domain with holes" << std::endl; // 1.) 2D triangulation of L-shaped domain with three holes of different shape triangulate_domain(); libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl; // 2.) 3D tetrahedralization of rectangular domain with hole. tetrahedralize_domain(); return 0; } void triangulate_domain() { #ifdef LIBMESH_HAVE_TRIANGLE // Use typedefs for slightly less typing. typedef TriangleInterface::Hole Hole; typedef TriangleInterface::PolygonHole PolygonHole; typedef TriangleInterface::ArbitraryHole ArbitraryHole; // Libmesh mesh that will eventually be created. Mesh mesh(2); // The points which make up the L-shape: mesh.add_point(Point( 0. , 0.)); mesh.add_point(Point( 0. , -1.)); mesh.add_point(Point(-1. , -1.)); mesh.add_point(Point(-1. , 1.)); mesh.add_point(Point( 1. , 1.)); mesh.add_point(Point( 1. , 0.)); // Declare the TriangleInterface object. This is where // we can set parameters of the triangulation and where the // actual triangulate function lives. TriangleInterface t(mesh); // Customize the variables for the triangulation t.desired_area() = .01; // A Planar Straight Line Graph (PSLG) is essentially a list // of segments which have to exist in the final triangulation. // For an L-shaped domain, Triangle will compute the convex // hull of boundary points if we do not specify the PSLG. // The PSLG algorithm is also required for triangulating domains // containing holes t.triangulation_type() = TriangleInterface::PSLG; // Turn on/off Laplacian mesh smoothing after generation. // By default this is on. t.smooth_after_generating() = true; // Define holes... // hole_1 is a circle (discretized by 50 points) PolygonHole hole_1(Point(-0.5, 0.5), // center 0.25, // radius 50); // n. points // hole_2 is itself a triangle PolygonHole hole_2(Point(0.5, 0.5), // center 0.1, // radius 3); // n. points // hole_3 is an ellipse of 100 points which we define here Point ellipse_center(-0.5, -0.5); const unsigned int n_ellipse_points=100; std::vector<Point> ellipse_points(n_ellipse_points); const Real dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points), a = .1, b = .2; for (unsigned int i=0; i<n_ellipse_points; ++i) ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta), ellipse_center(1)+b*sin(i*dtheta)); ArbitraryHole hole_3(ellipse_center, ellipse_points); // Create the vector of Hole*'s ... std::vector<Hole*> holes; holes.push_back(&hole_1); holes.push_back(&hole_2); holes.push_back(&hole_3); // ... and attach it to the triangulator object t.attach_hole_list(&holes); // Triangulate! t.triangulate(); // Write the result to file mesh.write("delaunay_l_shaped_hole.e"); #endif // LIBMESH_HAVE_TRIANGLE } void tetrahedralize_domain() { #ifdef LIBMESH_HAVE_TETGEN // The algorithm is broken up into several steps: // 1.) A convex hull is constructed for a rectangular hole. // 2.) A convex hull is constructed for the domain exterior. // 3.) Neighbor information is updated so TetGen knows there is a convex hull // 4.) A vector of hole points is created. // 5.) The domain is tetrahedralized, the mesh is written out, etc. // The mesh we will eventually generate SerialMesh mesh(3); // Lower and Upper bounding box limits for a rectangular hole within the unit cube. Point hole_lower_limit(0.2, 0.2, 0.4); Point hole_upper_limit(0.8, 0.8, 0.6); // 1.) Construct a convex hull for the hole add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit); // 2.) Generate elements comprising the outer boundary of the domain. add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.)); // 3.) Update neighbor information so that TetGen can verify there is a convex hull. mesh.find_neighbors(); // 4.) Set up vector of hole points std::vector<Point> hole(1); hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) ); // 5.) Set parameters and tetrahedralize the domain // 0 means "use TetGen default value" Real quality_constraint = 2.0; // The volume constraint determines the max-allowed tetrahedral // volume in the Mesh. TetGen will split cells which are larger than // this size Real volume_constraint = 0.001; // Construct the Delaunay tetrahedralization TetGenMeshInterface t(mesh); t.triangulate_conformingDelaunayMesh_carvehole(hole, quality_constraint, volume_constraint); // Find neighbors, etc in preparation for writing out the Mesh mesh.prepare_for_use(); // Finally, write out the result mesh.write("hole_3D.e"); #endif // LIBMESH_HAVE_TETGEN } void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit) { #ifdef LIBMESH_HAVE_TETGEN Mesh cube_mesh(3); unsigned n_elem = 1; MeshTools::Generation::build_cube(cube_mesh, n_elem,n_elem,n_elem, // n. elements in each direction lower_limit(0), upper_limit(0), lower_limit(1), upper_limit(1), lower_limit(2), upper_limit(2), HEX8); // The pointset_convexhull() algorithm will ignore the Hex8s // in the Mesh, and just construct the triangulation // of the convex hull. TetGenMeshInterface t(cube_mesh); t.pointset_convexhull(); // Now add all nodes from the boundary of the cube_mesh to the input mesh. // Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted // with a dummy value, later to be assigned a value by the input mesh. std::map<unsigned,unsigned> node_id_map; typedef std::map<unsigned,unsigned>::iterator iterator; { MeshBase::element_iterator it = cube_mesh.elements_begin(); const MeshBase::element_iterator end = cube_mesh.elements_end(); for ( ; it != end; ++it) { Elem* elem = *it; for (unsigned s=0; s<elem->n_sides(); ++s) if (elem->neighbor(s) == NULL) { // Add the node IDs of this side to the set AutoPtr<Elem> side = elem->side(s); for (unsigned n=0; n<side->n_nodes(); ++n) node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) ); } } } // For each node in the map, insert it into the input mesh and keep // track of the ID assigned. for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it) { // Id of the node in the cube mesh unsigned id = (*it).first; // Pointer to node in the cube mesh Node* old_node = cube_mesh.node_ptr(id); // Add geometric point to input mesh Node* new_node = mesh.add_point ( *old_node ); // Track ID value of new_node in map (*it).second = new_node->id(); } // With the points added and the map data structure in place, we are // ready to add each TRI3 element of the cube_mesh to the input Mesh // with proper node assignments { MeshBase::element_iterator el = cube_mesh.elements_begin(); const MeshBase::element_iterator end_el = cube_mesh.elements_end(); for (; el != end_el; ++el) { Elem* old_elem = *el; if (old_elem->type() == TRI3) { Elem* new_elem = mesh.add_elem(new Tri3); // Assign nodes in new elements. Since this is an example, // we'll do it in several steps. for (unsigned i=0; i<old_elem->n_nodes(); ++i) { // Locate old node ID in the map iterator it = node_id_map.find(old_elem->node(i)); // Check for not found if (it == node_id_map.end()) { libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl; libmesh_error(); } // Mapping to node ID in input mesh unsigned new_node_id = (*it).second; // Node pointer assigned from input mesh new_elem->set_node(i) = mesh.node_ptr(new_node_id); } } } } #endif // LIBMESH_HAVE_TETGEN } <|endoftext|>
<commit_before>// // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // // Developed by Minigraph // // Author: James Stanard // #include "pch.h" #include "CommandListManager.h" CommandQueue::CommandQueue(D3D12_COMMAND_LIST_TYPE Type) : m_Type(Type), m_CommandQueue(nullptr), m_pFence(nullptr), m_NextFenceValue((uint64_t)Type << 56 | 1), m_LastCompletedFenceValue((uint64_t)Type << 56), m_AllocatorPool(Type) { } CommandQueue::~CommandQueue() { Shutdown(); } void CommandQueue::Shutdown() { if (m_CommandQueue == nullptr) return; m_AllocatorPool.Shutdown(); CloseHandle(m_FenceEventHandle); m_pFence->Release(); m_pFence = nullptr; m_CommandQueue->Release(); m_CommandQueue = nullptr; } CommandListManager::CommandListManager() : m_Device(nullptr), m_GraphicsQueue(D3D12_COMMAND_LIST_TYPE_DIRECT), m_ComputeQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE), m_CopyQueue(D3D12_COMMAND_LIST_TYPE_COPY) { } CommandListManager::~CommandListManager() { Shutdown(); } void CommandListManager::Shutdown() { m_GraphicsQueue.Shutdown(); m_ComputeQueue.Shutdown(); m_CopyQueue.Shutdown(); } void CommandQueue::Create(ID3D12Device* pDevice) { ASSERT(pDevice != nullptr); ASSERT(!IsReady()); ASSERT(m_AllocatorPool.Size() == 0); D3D12_COMMAND_QUEUE_DESC QueueDesc = {}; QueueDesc.Type = m_Type; QueueDesc.NodeMask = 1; pDevice->CreateCommandQueue(&QueueDesc, MY_IID_PPV_ARGS(&m_CommandQueue)); m_CommandQueue->SetName(L"CommandListManager::m_CommandQueue"); ASSERT_SUCCEEDED(pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, MY_IID_PPV_ARGS(&m_pFence))); m_pFence->SetName(L"CommandListManager::m_pFence"); m_pFence->Signal((uint64_t)m_Type << 56); m_FenceEventHandle = CreateEvent(nullptr, false, false, nullptr); ASSERT(m_FenceEventHandle != INVALID_HANDLE_VALUE); m_AllocatorPool.Create(pDevice); ASSERT(IsReady()); } void CommandListManager::Create(ID3D12Device* pDevice) { ASSERT(pDevice != nullptr); m_Device = pDevice; m_GraphicsQueue.Create(pDevice); m_ComputeQueue.Create(pDevice); m_CopyQueue.Create(pDevice); } void CommandListManager::CreateNewCommandList( D3D12_COMMAND_LIST_TYPE Type, ID3D12GraphicsCommandList** List, ID3D12CommandAllocator** Allocator ) { ASSERT(Type != D3D12_COMMAND_LIST_TYPE_BUNDLE, "Bundles are not yet supported"); switch (Type) { case D3D12_COMMAND_LIST_TYPE_DIRECT: *Allocator = m_GraphicsQueue.RequestAllocator(); break; case D3D12_COMMAND_LIST_TYPE_BUNDLE: break; case D3D12_COMMAND_LIST_TYPE_COMPUTE: *Allocator = m_ComputeQueue.RequestAllocator(); break; case D3D12_COMMAND_LIST_TYPE_COPY: *Allocator = m_CopyQueue.RequestAllocator(); break; } ASSERT_SUCCEEDED( m_Device->CreateCommandList(1, Type, *Allocator, nullptr, MY_IID_PPV_ARGS(List)) ); (*List)->SetName(L"CommandList"); } uint64_t CommandQueue::ExecuteCommandList( ID3D12CommandList* List ) { std::lock_guard<std::mutex> LockGuard(m_FenceMutex); ASSERT_SUCCEEDED(((ID3D12GraphicsCommandList*)List)->Close()); // Kickoff the command list m_CommandQueue->ExecuteCommandLists(1, &List); // Signal the next fence value (with the GPU) m_CommandQueue->Signal(m_pFence, m_NextFenceValue); // And increment the fence value. return m_NextFenceValue++; } uint64_t CommandQueue::IncrementFence(void) { std::lock_guard<std::mutex> LockGuard(m_FenceMutex); m_CommandQueue->Signal(m_pFence, m_NextFenceValue); return m_NextFenceValue++; } bool CommandQueue::IsFenceComplete(uint64_t FenceValue) { // Avoid querying the fence value by testing against the last one seen. // The max() is to protect against an unlikely race condition that could cause the last // completed fence value to regress. if (FenceValue > m_LastCompletedFenceValue) m_LastCompletedFenceValue = std::max(m_LastCompletedFenceValue, m_pFence->GetCompletedValue()); return FenceValue <= m_LastCompletedFenceValue; } namespace Graphics { extern CommandListManager g_CommandManager; } void CommandQueue::StallForFence(uint64_t FenceValue) { CommandQueue& Producer = Graphics::g_CommandManager.GetQueue((D3D12_COMMAND_LIST_TYPE)(FenceValue >> 56)); m_CommandQueue->Wait(Producer.m_pFence, FenceValue); } void CommandQueue::StallForProducer(CommandQueue& Producer) { ASSERT(Producer.m_NextFenceValue > 0); m_CommandQueue->Wait(Producer.m_pFence, Producer.m_NextFenceValue - 1); } void CommandQueue::WaitForFence(uint64_t FenceValue) { if (IsFenceComplete(FenceValue)) return; // TODO: Think about how this might affect a multi-threaded situation. Suppose thread A // wants to wait for fence 100, then thread B comes along and wants to wait for 99. If // the fence can only have one event set on completion, then thread B has to wait for // 100 before it knows 99 is ready. Maybe insert sequential events? { std::lock_guard<std::mutex> LockGuard(m_EventMutex); m_pFence->SetEventOnCompletion(FenceValue, m_FenceEventHandle); WaitForSingleObject(m_FenceEventHandle, INFINITE); m_LastCompletedFenceValue = FenceValue; } } void CommandListManager::WaitForFence(uint64_t FenceValue) { CommandQueue& Producer = Graphics::g_CommandManager.GetQueue((D3D12_COMMAND_LIST_TYPE)(FenceValue >> 56)); Producer.WaitForFence(FenceValue); } ID3D12CommandAllocator* CommandQueue::RequestAllocator() { uint64_t CompletedFence = m_pFence->GetCompletedValue(); return m_AllocatorPool.RequestAllocator(CompletedFence); } void CommandQueue::DiscardAllocator(uint64_t FenceValue, ID3D12CommandAllocator* Allocator) { m_AllocatorPool.DiscardAllocator(FenceValue, Allocator); } <commit_msg>Fixed a bug with CreateEvent() error handling.<commit_after>// // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // // Developed by Minigraph // // Author: James Stanard // #include "pch.h" #include "CommandListManager.h" CommandQueue::CommandQueue(D3D12_COMMAND_LIST_TYPE Type) : m_Type(Type), m_CommandQueue(nullptr), m_pFence(nullptr), m_NextFenceValue((uint64_t)Type << 56 | 1), m_LastCompletedFenceValue((uint64_t)Type << 56), m_AllocatorPool(Type) { } CommandQueue::~CommandQueue() { Shutdown(); } void CommandQueue::Shutdown() { if (m_CommandQueue == nullptr) return; m_AllocatorPool.Shutdown(); CloseHandle(m_FenceEventHandle); m_pFence->Release(); m_pFence = nullptr; m_CommandQueue->Release(); m_CommandQueue = nullptr; } CommandListManager::CommandListManager() : m_Device(nullptr), m_GraphicsQueue(D3D12_COMMAND_LIST_TYPE_DIRECT), m_ComputeQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE), m_CopyQueue(D3D12_COMMAND_LIST_TYPE_COPY) { } CommandListManager::~CommandListManager() { Shutdown(); } void CommandListManager::Shutdown() { m_GraphicsQueue.Shutdown(); m_ComputeQueue.Shutdown(); m_CopyQueue.Shutdown(); } void CommandQueue::Create(ID3D12Device* pDevice) { ASSERT(pDevice != nullptr); ASSERT(!IsReady()); ASSERT(m_AllocatorPool.Size() == 0); D3D12_COMMAND_QUEUE_DESC QueueDesc = {}; QueueDesc.Type = m_Type; QueueDesc.NodeMask = 1; pDevice->CreateCommandQueue(&QueueDesc, MY_IID_PPV_ARGS(&m_CommandQueue)); m_CommandQueue->SetName(L"CommandListManager::m_CommandQueue"); ASSERT_SUCCEEDED(pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, MY_IID_PPV_ARGS(&m_pFence))); m_pFence->SetName(L"CommandListManager::m_pFence"); m_pFence->Signal((uint64_t)m_Type << 56); m_FenceEventHandle = CreateEvent(nullptr, false, false, nullptr); ASSERT(m_FenceEventHandle != NULL); m_AllocatorPool.Create(pDevice); ASSERT(IsReady()); } void CommandListManager::Create(ID3D12Device* pDevice) { ASSERT(pDevice != nullptr); m_Device = pDevice; m_GraphicsQueue.Create(pDevice); m_ComputeQueue.Create(pDevice); m_CopyQueue.Create(pDevice); } void CommandListManager::CreateNewCommandList( D3D12_COMMAND_LIST_TYPE Type, ID3D12GraphicsCommandList** List, ID3D12CommandAllocator** Allocator ) { ASSERT(Type != D3D12_COMMAND_LIST_TYPE_BUNDLE, "Bundles are not yet supported"); switch (Type) { case D3D12_COMMAND_LIST_TYPE_DIRECT: *Allocator = m_GraphicsQueue.RequestAllocator(); break; case D3D12_COMMAND_LIST_TYPE_BUNDLE: break; case D3D12_COMMAND_LIST_TYPE_COMPUTE: *Allocator = m_ComputeQueue.RequestAllocator(); break; case D3D12_COMMAND_LIST_TYPE_COPY: *Allocator = m_CopyQueue.RequestAllocator(); break; } ASSERT_SUCCEEDED( m_Device->CreateCommandList(1, Type, *Allocator, nullptr, MY_IID_PPV_ARGS(List)) ); (*List)->SetName(L"CommandList"); } uint64_t CommandQueue::ExecuteCommandList( ID3D12CommandList* List ) { std::lock_guard<std::mutex> LockGuard(m_FenceMutex); ASSERT_SUCCEEDED(((ID3D12GraphicsCommandList*)List)->Close()); // Kickoff the command list m_CommandQueue->ExecuteCommandLists(1, &List); // Signal the next fence value (with the GPU) m_CommandQueue->Signal(m_pFence, m_NextFenceValue); // And increment the fence value. return m_NextFenceValue++; } uint64_t CommandQueue::IncrementFence(void) { std::lock_guard<std::mutex> LockGuard(m_FenceMutex); m_CommandQueue->Signal(m_pFence, m_NextFenceValue); return m_NextFenceValue++; } bool CommandQueue::IsFenceComplete(uint64_t FenceValue) { // Avoid querying the fence value by testing against the last one seen. // The max() is to protect against an unlikely race condition that could cause the last // completed fence value to regress. if (FenceValue > m_LastCompletedFenceValue) m_LastCompletedFenceValue = std::max(m_LastCompletedFenceValue, m_pFence->GetCompletedValue()); return FenceValue <= m_LastCompletedFenceValue; } namespace Graphics { extern CommandListManager g_CommandManager; } void CommandQueue::StallForFence(uint64_t FenceValue) { CommandQueue& Producer = Graphics::g_CommandManager.GetQueue((D3D12_COMMAND_LIST_TYPE)(FenceValue >> 56)); m_CommandQueue->Wait(Producer.m_pFence, FenceValue); } void CommandQueue::StallForProducer(CommandQueue& Producer) { ASSERT(Producer.m_NextFenceValue > 0); m_CommandQueue->Wait(Producer.m_pFence, Producer.m_NextFenceValue - 1); } void CommandQueue::WaitForFence(uint64_t FenceValue) { if (IsFenceComplete(FenceValue)) return; // TODO: Think about how this might affect a multi-threaded situation. Suppose thread A // wants to wait for fence 100, then thread B comes along and wants to wait for 99. If // the fence can only have one event set on completion, then thread B has to wait for // 100 before it knows 99 is ready. Maybe insert sequential events? { std::lock_guard<std::mutex> LockGuard(m_EventMutex); m_pFence->SetEventOnCompletion(FenceValue, m_FenceEventHandle); WaitForSingleObject(m_FenceEventHandle, INFINITE); m_LastCompletedFenceValue = FenceValue; } } void CommandListManager::WaitForFence(uint64_t FenceValue) { CommandQueue& Producer = Graphics::g_CommandManager.GetQueue((D3D12_COMMAND_LIST_TYPE)(FenceValue >> 56)); Producer.WaitForFence(FenceValue); } ID3D12CommandAllocator* CommandQueue::RequestAllocator() { uint64_t CompletedFence = m_pFence->GetCompletedValue(); return m_AllocatorPool.RequestAllocator(CompletedFence); } void CommandQueue::DiscardAllocator(uint64_t FenceValue, ID3D12CommandAllocator* Allocator) { m_AllocatorPool.DiscardAllocator(FenceValue, Allocator); } <|endoftext|>
<commit_before>#include "umundo/core.h" #include <iostream> #include <stdio.h> using namespace umundo; static int receives = 0; static Monitor monitor; class TestDiscoverer : public ResultSet<NodeStub> { public: TestDiscoverer() { } void added(shared_ptr<NodeStub> node) { printf("node added!\n"); assert(node->getIP().size() >= 7); receives++; UMUNDO_SIGNAL(monitor); } void removed(shared_ptr<NodeStub> node) { } void changed(shared_ptr<NodeStub> node) { } }; class TestDiscoverable : public Node { public: TestDiscoverable(string domain) : Node(domain) { } }; int main(int argc, char** argv, char** envp) { // setenv("UMUNDO_LOGLEVEL", "4", 1); string hostId = Host::getHostId(); std::cout << "HostId:" << hostId << std::endl; TestDiscoverer* testDiscoverer = new TestDiscoverer(); shared_ptr<NodeQuery> query = shared_ptr<NodeQuery>(new NodeQuery(hostId + "fooDomain", testDiscoverer)); Discovery::browse(query); TestDiscoverable* testDiscoverable = new TestDiscoverable(hostId + "fooDomain"); Discovery::add(testDiscoverable); while(receives < 1) UMUNDO_WAIT(monitor); // test node / publisher / subscriber churn for (int i = 0; i < 2; i++) { Node* node1 = new Node(hostId); Node* node2 = new Node(hostId); for (int j = 0; j < 2; j++) { Subscriber* sub1 = new Subscriber("foo", NULL); Subscriber* sub2 = new Subscriber("foo", NULL); Subscriber* sub3 = new Subscriber("foo", NULL); Publisher* pub = new Publisher("foo"); int subs = 0; (void)subs; node1->addPublisher(pub); subs = pub->waitForSubscribers(0); assert(subs == 0); node2->addSubscriber(sub1); subs = pub->waitForSubscribers(1); assert(subs == 1); node2->addSubscriber(sub2); subs = pub->waitForSubscribers(2); assert(subs == 2); node2->addSubscriber(sub3); subs = pub->waitForSubscribers(3); assert(subs == 3); node2->removeSubscriber(sub1); Thread::sleepMs(50); subs = pub->waitForSubscribers(0); assert(subs == 2); node2->removeSubscriber(sub2); Thread::sleepMs(50); subs = pub->waitForSubscribers(0); assert(subs == 1); node2->removeSubscriber(sub3); Thread::sleepMs(50); subs = pub->waitForSubscribers(0); assert(subs == 0); node2->removeSubscriber(sub1); node2->removeSubscriber(sub2); node2->removeSubscriber(sub3); node1->removePublisher(pub); delete sub1; delete sub2; delete sub3; delete pub; } delete node1; delete node2; } } <commit_msg>some more test output<commit_after>#include "umundo/core.h" #include <iostream> #include <stdio.h> using namespace umundo; static int receives = 0; static Monitor monitor; class TestDiscoverer : public ResultSet<NodeStub> { public: TestDiscoverer() { } void added(shared_ptr<NodeStub> node) { printf("node added!\n"); assert(node->getIP().size() >= 7); receives++; UMUNDO_SIGNAL(monitor); } void removed(shared_ptr<NodeStub> node) { } void changed(shared_ptr<NodeStub> node) { } }; class TestDiscoverable : public Node { public: TestDiscoverable(string domain) : Node(domain) { } }; int main(int argc, char** argv, char** envp) { // setenv("UMUNDO_LOGLEVEL", "4", 1); string hostId = Host::getHostId(); std::cout << "HostId:" << hostId << std::endl; TestDiscoverer* testDiscoverer = new TestDiscoverer(); shared_ptr<NodeQuery> query = shared_ptr<NodeQuery>(new NodeQuery(hostId + "fooDomain", testDiscoverer)); Discovery::browse(query); TestDiscoverable* testDiscoverable = new TestDiscoverable(hostId + "fooDomain"); Discovery::add(testDiscoverable); while(receives < 1) UMUNDO_WAIT(monitor); std::cout << "Successfully found node via discovery" << std::endl; // test node / publisher / subscriber churn for (int i = 0; i < 2; i++) { Node* node1 = new Node(hostId); Node* node2 = new Node(hostId); for (int j = 0; j < 2; j++) { Subscriber* sub1 = new Subscriber("foo", NULL); Subscriber* sub2 = new Subscriber("foo", NULL); Subscriber* sub3 = new Subscriber("foo", NULL); Publisher* pub = new Publisher("foo"); int subs = 0; (void)subs; node1->addPublisher(pub); subs = pub->waitForSubscribers(0); assert(subs == 0); node2->addSubscriber(sub1); std::cout << "Waiting for 1st subscriber" << std::endl; subs = pub->waitForSubscribers(1); assert(subs == 1); node2->addSubscriber(sub2); std::cout << "Waiting for 2nd subscriber" << std::endl; subs = pub->waitForSubscribers(2); assert(subs == 2); node2->addSubscriber(sub3); std::cout << "Waiting for 3rd subscriber" << std::endl; subs = pub->waitForSubscribers(3); assert(subs == 3); node2->removeSubscriber(sub1); Thread::sleepMs(50); std::cout << "Removed 1st subscriber" << std::endl; subs = pub->waitForSubscribers(0); assert(subs == 2); node2->removeSubscriber(sub2); std::cout << "Removed 2nd subscriber" << std::endl; Thread::sleepMs(50); subs = pub->waitForSubscribers(0); assert(subs == 1); node2->removeSubscriber(sub3); std::cout << "Removed 3rd subscriber" << std::endl; Thread::sleepMs(50); subs = pub->waitForSubscribers(0); assert(subs == 0); std::cout << "Successfully connected subscribers to publishers" << std::endl; node2->removeSubscriber(sub1); node2->removeSubscriber(sub2); node2->removeSubscriber(sub3); node1->removePublisher(pub); delete sub1; delete sub2; delete sub3; delete pub; } delete node1; delete node2; } } <|endoftext|>
<commit_before>#include "firestore/src/include/firebase/firestore.h" #include <cassert> #include <map> #include "app/meta/move.h" #include "app/src/assert.h" #include "app/src/cleanup_notifier.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" #include "app/src/util.h" #include "firestore/src/common/futures.h" #if defined(__ANDROID__) #include "firestore/src/android/firestore_android.h" #elif defined(FIRESTORE_STUB_BUILD) #include "firestore/src/stub/firestore_stub.h" #else #include "firestore/src/ios/firestore_ios.h" #endif // defined(__ANDROID__) namespace firebase { namespace firestore { DEFINE_FIREBASE_VERSION_STRING(FirebaseFirestore); namespace { Mutex g_firestores_lock; // NOLINT std::map<App*, Firestore*>* g_firestores = nullptr; // Ensures that the cache is initialized. // Prerequisite: `g_firestores_lock` must be locked before calling this // function. std::map<App*, Firestore*>* FirestoreCache() { if (!g_firestores) { g_firestores = new std::map<App*, Firestore*>(); } return g_firestores; } // Prerequisite: `g_firestores_lock` must be locked before calling this // function. Firestore* FindFirestoreInCache(App* app, InitResult* init_result_out) { auto* cache = FirestoreCache(); auto found = cache->find(app); if (found != cache->end()) { if (init_result_out) *init_result_out = kInitResultSuccess; return found->second; } return nullptr; } InitResult CheckInitialized(const FirestoreInternal& firestore) { if (!firestore.initialized()) { return kInitResultFailedMissingDependency; } return kInitResultSuccess; } } // namespace Firestore* Firestore::GetInstance(App* app, InitResult* init_result_out) { FIREBASE_ASSERT_MESSAGE(app != nullptr, "Provided firebase::App must not be null."); MutexLock lock(g_firestores_lock); Firestore* from_cache = FindFirestoreInCache(app, init_result_out); if (from_cache) { return from_cache; } return AddFirestoreToCache(new Firestore(app), init_result_out); } Firestore* Firestore::GetInstance(InitResult* init_result_out) { App* app = App::GetInstance(); FIREBASE_ASSERT_MESSAGE(app, "You must call firebase::App.Create first."); return Firestore::GetInstance(app, init_result_out); } Firestore* Firestore::CreateFirestore(App* app, FirestoreInternal* internal, InitResult* init_result_out) { FIREBASE_ASSERT_MESSAGE(app != nullptr, "Provided firebase::App must not be null."); FIREBASE_ASSERT_MESSAGE(internal != nullptr, "Provided FirestoreInternal must not be null."); MutexLock lock(g_firestores_lock); Firestore* from_cache = FindFirestoreInCache(app, init_result_out); FIREBASE_ASSERT_MESSAGE(from_cache == nullptr, "Firestore must not be created already"); return AddFirestoreToCache(new Firestore(internal), init_result_out); } Firestore* Firestore::AddFirestoreToCache(Firestore* firestore, InitResult* init_result_out) { InitResult init_result = CheckInitialized(*firestore->internal_); if (init_result_out) { *init_result_out = init_result; } if (init_result != kInitResultSuccess) { delete firestore; return nullptr; } // Once we remove STLPort support, change this back to `emplace`. FirestoreCache()->insert(std::make_pair(firestore->app(), firestore)); return firestore; } Firestore::Firestore(::firebase::App* app) : Firestore{new FirestoreInternal{app}} {} Firestore::Firestore(FirestoreInternal* internal) // TODO(zxu): use make_unique once it is supported for our build here. : internal_(internal) { if (internal_->initialized()) { CleanupNotifier* app_notifier = CleanupNotifier::FindByOwner(app()); assert(app_notifier); app_notifier->RegisterObject(this, [](void* object) { Firestore* firestore = reinterpret_cast<Firestore*>(object); LogWarning( "Firestore object 0x%08x should be deleted before the App 0x%08x it " "depends upon.", static_cast<int>(reinterpret_cast<intptr_t>(firestore)), static_cast<int>(reinterpret_cast<intptr_t>(firestore->app()))); firestore->DeleteInternal(); }); } } Firestore::~Firestore() { DeleteInternal(); } void Firestore::DeleteInternal() { MutexLock lock(g_firestores_lock); if (!internal_) return; App* my_app = app(); // Only need to unregister if internal_ is initialized. if (internal_->initialized()) { CleanupNotifier* app_notifier = CleanupNotifier::FindByOwner(my_app); assert(app_notifier); app_notifier->UnregisterObject(this); } // Force cleanup to happen first. internal_->cleanup().CleanupAll(); delete internal_; internal_ = nullptr; // If a Firestore is explicitly deleted, remove it from our cache. FirestoreCache()->erase(my_app); // If it's the last one, delete the map. if (g_firestores->empty()) { delete g_firestores; g_firestores = nullptr; } } const App* Firestore::app() const { if (!internal_) return {}; return internal_->app(); } App* Firestore::app() { if (!internal_) return {}; return internal_->app(); } CollectionReference Firestore::Collection(const char* collection_path) const { FIREBASE_ASSERT_MESSAGE(collection_path != nullptr, "Provided collection path must not be null"); if (!internal_) return {}; return internal_->Collection(collection_path); } CollectionReference Firestore::Collection( const std::string& collection_path) const { return Collection(collection_path.c_str()); } DocumentReference Firestore::Document(const char* document_path) const { if (!internal_) return {}; return internal_->Document(document_path); } DocumentReference Firestore::Document(const std::string& document_path) const { return Document(document_path.c_str()); } Query Firestore::CollectionGroup(const std::string& collection_id) const { if (!internal_) return {}; return internal_->CollectionGroup(collection_id.c_str()); } Settings Firestore::settings() const { if (!internal_) return {}; return internal_->settings(); } void Firestore::set_settings(const Settings& settings) { if (!internal_) return; internal_->set_settings(settings); } WriteBatch Firestore::batch() const { if (!internal_) return {}; return internal_->batch(); } Future<void> Firestore::RunTransaction(TransactionFunction* update) { if (!internal_) return FailedFuture<void>(); return internal_->RunTransaction(update); } #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> Firestore::RunTransaction( std::function<Error(Transaction*, std::string*)> update) { FIREBASE_ASSERT_MESSAGE(update, "invalid update parameter is passed in."); if (!internal_) return FailedFuture<void>(); return internal_->RunTransaction(firebase::Move(update)); } #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> Firestore::RunTransactionLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->RunTransactionLastResult(); } Future<void> Firestore::DisableNetwork() { if (!internal_) return FailedFuture<void>(); return internal_->DisableNetwork(); } Future<void> Firestore::DisableNetworkLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->DisableNetworkLastResult(); } Future<void> Firestore::EnableNetwork() { if (!internal_) return FailedFuture<void>(); return internal_->EnableNetwork(); } Future<void> Firestore::EnableNetworkLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->EnableNetworkLastResult(); } Future<void> Firestore::Terminate() { if (!internal_) return FailedFuture<void>(); FirestoreCache()->erase(app()); return internal_->Terminate(); } Future<void> Firestore::TerminateLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->TerminateLastResult(); } Future<void> Firestore::WaitForPendingWrites() { if (!internal_) return FailedFuture<void>(); return internal_->WaitForPendingWrites(); } Future<void> Firestore::WaitForPendingWritesLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->WaitForPendingWritesLastResult(); } Future<void> Firestore::ClearPersistence() { if (!internal_) return FailedFuture<void>(); return internal_->ClearPersistence(); } Future<void> Firestore::ClearPersistenceLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->ClearPersistenceLastResult(); } } // namespace firestore } // namespace firebase <commit_msg>Enable iOS/Android integration tests as part of presubmit check_tests.<commit_after>#include "firestore/src/include/firebase/firestore.h" #include <cassert> #include <map> #include "app/meta/move.h" #include "app/src/assert.h" #include "app/src/cleanup_notifier.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" #include "app/src/util.h" #include "firestore/src/common/futures.h" #if defined(__ANDROID__) #include "firestore/src/android/firestore_android.h" #elif defined(FIRESTORE_STUB_BUILD) #include "firestore/src/stub/firestore_stub.h" #else #include "firestore/src/ios/firestore_ios.h" #endif // defined(__ANDROID__) namespace firebase { namespace firestore { DEFINE_FIREBASE_VERSION_STRING(FirebaseFirestore); namespace { Mutex g_firestores_lock; // NOLINT std::map<App*, Firestore*>* g_firestores = nullptr; // Ensures that the cache is initialized. // Prerequisite: `g_firestores_lock` must be locked before calling this // function. std::map<App*, Firestore*>* FirestoreCache() { if (!g_firestores) { g_firestores = new std::map<App*, Firestore*>(); } return g_firestores; } // Prerequisite: `g_firestores_lock` must be locked before calling this // function. Firestore* FindFirestoreInCache(App* app, InitResult* init_result_out) { auto* cache = FirestoreCache(); auto found = cache->find(app); if (found != cache->end()) { if (init_result_out) *init_result_out = kInitResultSuccess; return found->second; } return nullptr; } InitResult CheckInitialized(const FirestoreInternal& firestore) { if (!firestore.initialized()) { return kInitResultFailedMissingDependency; } return kInitResultSuccess; } } // namespace Firestore* Firestore::GetInstance(App* app, InitResult* init_result_out) { FIREBASE_ASSERT_MESSAGE(app != nullptr, "Provided firebase::App must not be null."); MutexLock lock(g_firestores_lock); Firestore* from_cache = FindFirestoreInCache(app, init_result_out); if (from_cache) { return from_cache; } return AddFirestoreToCache(new Firestore(app), init_result_out); } Firestore* Firestore::GetInstance(InitResult* init_result_out) { App* app = App::GetInstance(); FIREBASE_ASSERT_MESSAGE(app, "You must call firebase::App.Create first."); return Firestore::GetInstance(app, init_result_out); } Firestore* Firestore::CreateFirestore(App* app, FirestoreInternal* internal, InitResult* init_result_out) { FIREBASE_ASSERT_MESSAGE(app != nullptr, "Provided firebase::App must not be null."); FIREBASE_ASSERT_MESSAGE(internal != nullptr, "Provided FirestoreInternal must not be null."); MutexLock lock(g_firestores_lock); Firestore* from_cache = FindFirestoreInCache(app, init_result_out); FIREBASE_ASSERT_MESSAGE(from_cache == nullptr, "Firestore must not be created already"); return AddFirestoreToCache(new Firestore(internal), init_result_out); } Firestore* Firestore::AddFirestoreToCache(Firestore* firestore, InitResult* init_result_out) { InitResult init_result = CheckInitialized(*firestore->internal_); if (init_result_out) { *init_result_out = init_result; } if (init_result != kInitResultSuccess) { delete firestore; return nullptr; } // Once we remove STLPort support, change this back to `emplace`. FirestoreCache()->insert(std::make_pair(firestore->app(), firestore)); return firestore; } Firestore::Firestore(::firebase::App* app) : Firestore{new FirestoreInternal{app}} {} Firestore::Firestore(FirestoreInternal* internal) // TODO(wuandy): use make_unique once it is supported for our build here. : internal_(internal) { if (internal_->initialized()) { CleanupNotifier* app_notifier = CleanupNotifier::FindByOwner(app()); assert(app_notifier); app_notifier->RegisterObject(this, [](void* object) { Firestore* firestore = reinterpret_cast<Firestore*>(object); LogWarning( "Firestore object 0x%08x should be deleted before the App 0x%08x it " "depends upon.", static_cast<int>(reinterpret_cast<intptr_t>(firestore)), static_cast<int>(reinterpret_cast<intptr_t>(firestore->app()))); firestore->DeleteInternal(); }); } } Firestore::~Firestore() { DeleteInternal(); } void Firestore::DeleteInternal() { MutexLock lock(g_firestores_lock); if (!internal_) return; App* my_app = app(); // Only need to unregister if internal_ is initialized. if (internal_->initialized()) { CleanupNotifier* app_notifier = CleanupNotifier::FindByOwner(my_app); assert(app_notifier); app_notifier->UnregisterObject(this); } // Force cleanup to happen first. internal_->cleanup().CleanupAll(); delete internal_; internal_ = nullptr; // If a Firestore is explicitly deleted, remove it from our cache. FirestoreCache()->erase(my_app); // If it's the last one, delete the map. if (g_firestores->empty()) { delete g_firestores; g_firestores = nullptr; } } const App* Firestore::app() const { if (!internal_) return {}; return internal_->app(); } App* Firestore::app() { if (!internal_) return {}; return internal_->app(); } CollectionReference Firestore::Collection(const char* collection_path) const { FIREBASE_ASSERT_MESSAGE(collection_path != nullptr, "Provided collection path must not be null"); if (!internal_) return {}; return internal_->Collection(collection_path); } CollectionReference Firestore::Collection( const std::string& collection_path) const { return Collection(collection_path.c_str()); } DocumentReference Firestore::Document(const char* document_path) const { if (!internal_) return {}; return internal_->Document(document_path); } DocumentReference Firestore::Document(const std::string& document_path) const { return Document(document_path.c_str()); } Query Firestore::CollectionGroup(const std::string& collection_id) const { if (!internal_) return {}; return internal_->CollectionGroup(collection_id.c_str()); } Settings Firestore::settings() const { if (!internal_) return {}; return internal_->settings(); } void Firestore::set_settings(const Settings& settings) { if (!internal_) return; internal_->set_settings(settings); } WriteBatch Firestore::batch() const { if (!internal_) return {}; return internal_->batch(); } Future<void> Firestore::RunTransaction(TransactionFunction* update) { if (!internal_) return FailedFuture<void>(); return internal_->RunTransaction(update); } #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> Firestore::RunTransaction( std::function<Error(Transaction*, std::string*)> update) { FIREBASE_ASSERT_MESSAGE(update, "invalid update parameter is passed in."); if (!internal_) return FailedFuture<void>(); return internal_->RunTransaction(firebase::Move(update)); } #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> Firestore::RunTransactionLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->RunTransactionLastResult(); } Future<void> Firestore::DisableNetwork() { if (!internal_) return FailedFuture<void>(); return internal_->DisableNetwork(); } Future<void> Firestore::DisableNetworkLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->DisableNetworkLastResult(); } Future<void> Firestore::EnableNetwork() { if (!internal_) return FailedFuture<void>(); return internal_->EnableNetwork(); } Future<void> Firestore::EnableNetworkLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->EnableNetworkLastResult(); } Future<void> Firestore::Terminate() { if (!internal_) return FailedFuture<void>(); FirestoreCache()->erase(app()); return internal_->Terminate(); } Future<void> Firestore::TerminateLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->TerminateLastResult(); } Future<void> Firestore::WaitForPendingWrites() { if (!internal_) return FailedFuture<void>(); return internal_->WaitForPendingWrites(); } Future<void> Firestore::WaitForPendingWritesLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->WaitForPendingWritesLastResult(); } Future<void> Firestore::ClearPersistence() { if (!internal_) return FailedFuture<void>(); return internal_->ClearPersistence(); } Future<void> Firestore::ClearPersistenceLastResult() { if (!internal_) return FailedFuture<void>(); return internal_->ClearPersistenceLastResult(); } } // namespace firestore } // namespace firebase <|endoftext|>
<commit_before>#include <fstream> #include <stdexcept> #include "Geometry.h" #include "spruce.hh" using std::string; using std::istringstream; using std::ifstream; using Eigen::Vector3i; using Eigen::Vector3d; using Eigen::RowVectorXd; using Eigen::Matrix3Xd; using Eigen::Matrix3Xi; namespace DrakeShapes { const int Geometry::NUM_BBOX_POINTS = 8; const int Sphere::NUM_POINTS = 1; const int Capsule::NUM_POINTS = 2; std::string ShapeToString(Shape ss) { switch (ss) { case UNKNOWN: return "UNKNOWN"; case BOX: return "BOX"; case SPHERE: return "SPHERE"; case CYLINDER: return "CYLINDER"; case MESH: return "MESH"; case MESH_POINTS: return "MESH_POINTS"; case CAPSULE: return "CAPSULE"; } return "UNDEFINED"; } Geometry::Geometry() : shape(UNKNOWN) {} Geometry::Geometry(const Geometry &other) { shape = other.getShape(); } Geometry::Geometry(Shape shape) : shape(shape) {} Shape Geometry::getShape() const { return shape; } Geometry *Geometry::clone() const { return new Geometry(*this); } void Geometry::getPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(double x_half_width, double y_half_width, double z_half_width, Eigen::Matrix3Xd &points) const { // Return axis-aligned bounding-box vertices points.resize(3, NUM_BBOX_POINTS); RowVectorXd cx(NUM_BBOX_POINTS), cy(NUM_BBOX_POINTS), cz(NUM_BBOX_POINTS); cx << -1, 1, 1, -1, -1, 1, 1, -1; cy << 1, 1, 1, 1, -1, -1, -1, -1; cz << 1, 1, -1, -1, -1, -1, 1, 1; cx = cx * x_half_width; cy = cy * y_half_width; cz = cz * z_half_width; points << cx, cy, cz; } std::ostream &operator<<(std::ostream &out, const Geometry &gg) { out << ShapeToString(gg.getShape()) << ", " << gg.NUM_BBOX_POINTS; return out; } Sphere::Sphere(double radius) : Geometry(SPHERE), radius(radius) {} Sphere *Sphere::clone() const { return new Sphere(*this); } void Sphere::getPoints(Matrix3Xd &points) const { points = Matrix3Xd::Zero(3, NUM_POINTS); } void Sphere::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, radius, points); } void Sphere::getTerrainContactPoints(Matrix3Xd &points) const { if (radius < 1e-6) getPoints(points); else points = Matrix3Xd(); } std::ostream &operator<<(std::ostream &out, const Sphere &ss) { out << static_cast<const Geometry &>(ss) << ", " << ss.radius << ", " << ss.NUM_POINTS; return out; } Box::Box(const Eigen::Vector3d &size) : Geometry(BOX), size(size) {} Box *Box::clone() const { return new Box(*this); } void Box::getPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(size(0) / 2.0, size(1) / 2.0, size(2) / 2.0, points); } void Box::getBoundingBoxPoints(Matrix3Xd &points) const { getPoints(points); } void Box::getTerrainContactPoints(Matrix3Xd &points) const { getPoints(points); } std::ostream &operator<<(std::ostream &out, const Box &bb) { out << static_cast<const Geometry &>(bb) << ", " << bb.size.transpose(); return out; } Cylinder::Cylinder(double radius, double length) : Geometry(CYLINDER), radius(radius), length(length) {} Cylinder *Cylinder::clone() const { return new Cylinder(*this); } void Cylinder::getPoints(Matrix3Xd &points) const { static bool warnOnce = true; if (warnOnce) { std::cerr << "Warning: DrakeShapes::Cylinder::getPoints(): """ "This method returns the vertices of the cylinder''s bounding-box." << std::endl; warnOnce = false; } getBoundingBoxPoints(points); } void Cylinder::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, length / 2.0, points); } std::ostream &operator<<(std::ostream &out, const Cylinder &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Capsule::Capsule(double radius, double length) : Geometry(CAPSULE), radius(radius), length(length) {} Capsule *Capsule::clone() const { return new Capsule(*this); } void Capsule::getPoints(Matrix3Xd &points) const { // Return segment end-points points.resize(Eigen::NoChange, NUM_POINTS); RowVectorXd cx = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cy = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cz = RowVectorXd::Zero(NUM_POINTS); cz << length / 2.0, -length / 2.0; points << cx, cy, cz; } void Capsule::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, (length / 2.0 + radius), points); } std::ostream &operator<<(std::ostream &out, const Capsule &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Mesh::Mesh(const string &filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename) {} Mesh::Mesh(const string &filename, const string &resolved_filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename), resolved_filename(resolved_filename) {} bool Mesh::extractMeshVertices(Matrix3Xd &vertex_coordinates) const { if (resolved_filename.empty()) { return false; } spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); ifstream file; if (ext.compare(".obj") == 0) { file.open(spath.getStr().c_str(), ifstream::in); } else { spath.setExtension(".obj"); if (spath.exists()) { // try changing the extension to obj and loading. file.open(spath.getStr().c_str(), ifstream::in); } } if (!file.is_open()) { std::cerr << "Warning: Mesh " << spath.getStr() << " ignored because it does not have extension .obj (nor can I find " "a juxtaposed file with a .obj extension)" << std::endl; return false; } string line; // Count the number of vertices and resize vertex_coordinates. int num_vertices = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { ++num_vertices; } } vertex_coordinates.resize(3, num_vertices); file.clear(); file.seekg(0, file.beg); double d; int j = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { int i = 0; while (iss >> d) { vertex_coordinates(i++, j) = d; } ++j; } } return true; } bool Mesh::ReadMeshConnectivities(Matrix3Xi& connectivities) const { if (resolved_filename.empty()) return false; spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); FILE* file; if (ext.compare(".obj") == 0) { file = fopen(spath.getStr().c_str(),"r"); } else { spath.setExtension(".obj"); if (spath.exists()) { // try changing the extension to obj and loading. file = fopen(spath.getStr().c_str(),"r"); } } if (!file) { throw std::logic_error( "Could not open mesh file \""+spath.getStr() + "\"."); } // Count the number of triangles and resize connectivities. int num_triangles = 0; char *line = NULL; size_t len = 0; ssize_t read; char key[128]; while ((read = getline(&line, &len, file)) != -1) { sscanf(line,"%s",key); if (strcmp(key, "f") == 0) ++num_triangles; } // Allocate memory. connectivities.resize(3, num_triangles); // Read triangles. rewind(file); int itri = 0; int ignored_entry; int tri[3]; while(true) { // Get first word in the line. if(fscanf(file, "%s", key) == EOF) break; if (strcmp(key, "f") == 0) { int matches = fscanf(file, "%d//%d %d//%d %d//%d\n", tri + 0, &ignored_entry, tri + 1, &ignored_entry, tri + 2, &ignored_entry); if(matches != 6) throw std::logic_error( "File \""+filename+"\" cannot be parsed. Format not supported."); connectivities.col(itri++) = Vector3i(tri[0]-1,tri[1]-1,tri[2]-1); if(itri>num_triangles) throw(std::logic_error("Number of triangles exceeded previous count.")); } } // while fclose(file); return true; } Mesh *Mesh::clone() const { return new Mesh(*this); } void Mesh::getPoints(Eigen::Matrix3Xd &point_matrix) const { extractMeshVertices(point_matrix); } void Mesh::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Matrix3Xd mesh_vertices; extractMeshVertices(mesh_vertices); Vector3d min_pos = mesh_vertices.rowwise().minCoeff(); Vector3d max_pos = mesh_vertices.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } std::ostream &operator<<(std::ostream &out, const Mesh &mm) { out << static_cast<const Geometry &>(mm) << ", " << mm.scale << ", " << mm.filename << ", " << mm.resolved_filename << ", " << mm.root_dir; return out; } MeshPoints::MeshPoints(const Eigen::Matrix3Xd &points) : Geometry(MESH_POINTS), points(points) {} MeshPoints *MeshPoints::clone() const { return new MeshPoints(*this); } void MeshPoints::getPoints(Eigen::Matrix3Xd &point_matrix) const { point_matrix = points; } void MeshPoints::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Vector3d min_pos = points.rowwise().minCoeff(); Vector3d max_pos = points.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } std::ostream &operator<<(std::ostream &out, const MeshPoints &mp) { out << static_cast<const Geometry &>(mp) << ",\n" << mp.points; return out; } } // namespace DrakeShapes <commit_msg>Adds comments, cleans lint, etc in Mesh::ReadMeshConnectivities<commit_after>#include <fstream> #include <stdexcept> #include "Geometry.h" #include "spruce.hh" using std::string; using std::istringstream; using std::ifstream; using Eigen::Vector3i; using Eigen::Vector3d; using Eigen::RowVectorXd; using Eigen::Matrix3Xd; using Eigen::Matrix3Xi; namespace DrakeShapes { const int Geometry::NUM_BBOX_POINTS = 8; const int Sphere::NUM_POINTS = 1; const int Capsule::NUM_POINTS = 2; std::string ShapeToString(Shape ss) { switch (ss) { case UNKNOWN: return "UNKNOWN"; case BOX: return "BOX"; case SPHERE: return "SPHERE"; case CYLINDER: return "CYLINDER"; case MESH: return "MESH"; case MESH_POINTS: return "MESH_POINTS"; case CAPSULE: return "CAPSULE"; } return "UNDEFINED"; } Geometry::Geometry() : shape(UNKNOWN) {} Geometry::Geometry(const Geometry &other) { shape = other.getShape(); } Geometry::Geometry(Shape shape) : shape(shape) {} Shape Geometry::getShape() const { return shape; } Geometry *Geometry::clone() const { return new Geometry(*this); } void Geometry::getPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(double x_half_width, double y_half_width, double z_half_width, Eigen::Matrix3Xd &points) const { // Return axis-aligned bounding-box vertices points.resize(3, NUM_BBOX_POINTS); RowVectorXd cx(NUM_BBOX_POINTS), cy(NUM_BBOX_POINTS), cz(NUM_BBOX_POINTS); cx << -1, 1, 1, -1, -1, 1, 1, -1; cy << 1, 1, 1, 1, -1, -1, -1, -1; cz << 1, 1, -1, -1, -1, -1, 1, 1; cx = cx * x_half_width; cy = cy * y_half_width; cz = cz * z_half_width; points << cx, cy, cz; } std::ostream &operator<<(std::ostream &out, const Geometry &gg) { out << ShapeToString(gg.getShape()) << ", " << gg.NUM_BBOX_POINTS; return out; } Sphere::Sphere(double radius) : Geometry(SPHERE), radius(radius) {} Sphere *Sphere::clone() const { return new Sphere(*this); } void Sphere::getPoints(Matrix3Xd &points) const { points = Matrix3Xd::Zero(3, NUM_POINTS); } void Sphere::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, radius, points); } void Sphere::getTerrainContactPoints(Matrix3Xd &points) const { if (radius < 1e-6) getPoints(points); else points = Matrix3Xd(); } std::ostream &operator<<(std::ostream &out, const Sphere &ss) { out << static_cast<const Geometry &>(ss) << ", " << ss.radius << ", " << ss.NUM_POINTS; return out; } Box::Box(const Eigen::Vector3d &size) : Geometry(BOX), size(size) {} Box *Box::clone() const { return new Box(*this); } void Box::getPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(size(0) / 2.0, size(1) / 2.0, size(2) / 2.0, points); } void Box::getBoundingBoxPoints(Matrix3Xd &points) const { getPoints(points); } void Box::getTerrainContactPoints(Matrix3Xd &points) const { getPoints(points); } std::ostream &operator<<(std::ostream &out, const Box &bb) { out << static_cast<const Geometry &>(bb) << ", " << bb.size.transpose(); return out; } Cylinder::Cylinder(double radius, double length) : Geometry(CYLINDER), radius(radius), length(length) {} Cylinder *Cylinder::clone() const { return new Cylinder(*this); } void Cylinder::getPoints(Matrix3Xd &points) const { static bool warnOnce = true; if (warnOnce) { std::cerr << "Warning: DrakeShapes::Cylinder::getPoints(): """ "This method returns the vertices of the cylinder''s bounding-box." << std::endl; warnOnce = false; } getBoundingBoxPoints(points); } void Cylinder::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, length / 2.0, points); } std::ostream &operator<<(std::ostream &out, const Cylinder &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Capsule::Capsule(double radius, double length) : Geometry(CAPSULE), radius(radius), length(length) {} Capsule *Capsule::clone() const { return new Capsule(*this); } void Capsule::getPoints(Matrix3Xd &points) const { // Return segment end-points points.resize(Eigen::NoChange, NUM_POINTS); RowVectorXd cx = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cy = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cz = RowVectorXd::Zero(NUM_POINTS); cz << length / 2.0, -length / 2.0; points << cx, cy, cz; } void Capsule::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, (length / 2.0 + radius), points); } std::ostream &operator<<(std::ostream &out, const Capsule &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Mesh::Mesh(const string &filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename) {} Mesh::Mesh(const string &filename, const string &resolved_filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename), resolved_filename(resolved_filename) {} bool Mesh::extractMeshVertices(Matrix3Xd &vertex_coordinates) const { if (resolved_filename.empty()) { return false; } spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); ifstream file; if (ext.compare(".obj") == 0) { file.open(spath.getStr().c_str(), ifstream::in); } else { spath.setExtension(".obj"); if (spath.exists()) { // try changing the extension to obj and loading. file.open(spath.getStr().c_str(), ifstream::in); } } if (!file.is_open()) { std::cerr << "Warning: Mesh " << spath.getStr() << " ignored because it does not have extension .obj (nor can I find " "a juxtaposed file with a .obj extension)" << std::endl; return false; } string line; // Count the number of vertices and resize vertex_coordinates. int num_vertices = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { ++num_vertices; } } vertex_coordinates.resize(3, num_vertices); file.clear(); file.seekg(0, file.beg); double d; int j = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { int i = 0; while (iss >> d) { vertex_coordinates(i++, j) = d; } ++j; } } return true; } bool Mesh::ReadMeshConnectivities(Matrix3Xi& connectivities) const { if (resolved_filename.empty()) return false; spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); FILE* file; if (ext.compare(".obj") == 0) { file = fopen(spath.getStr().c_str(), "r"); if (!file) throw std::runtime_error( "Could not open mesh file \"" + spath.getStr() + "\"."); } else { // Tries to change the extension to obj and load. spath.setExtension(".obj"); if (spath.exists()) { file = fopen(spath.getStr().c_str(), "r"); if (!file) throw std::runtime_error( "Could not open mesh file \"" + spath.getStr() + "\"."); } else { throw std::runtime_error( "Could not find and obj file mesh file in the same directory as \"" + spath.getStr() + "\"."); } } // Counts the number of triangles and resizes connectivities. int num_triangles = 0; char *line = NULL; size_t len = 0; ssize_t read; char key[128]; while ((read = getline(&line, &len, file)) != -1) { sscanf(line, "%s", key); if (strcmp(key, "f") == 0) ++num_triangles; } // Allocates memory. connectivities.resize(3, num_triangles); // Reads triangles. // This simple parser assumes connectivities are in the obj format variant in // which indexes for both triangles and normals are provided. // TODO(amcastro-tri): use a library to parse obj files instead. rewind(file); int itri = 0; int ignored_entry; int tri[3]; while (true) { // Get first word in the line. if (fscanf(file, "%s", key) == EOF) break; if (strcmp(key, "f") == 0) { int matches = fscanf(file, "%d//%d %d//%d %d//%d\n", tri + 0, &ignored_entry, tri + 1, &ignored_entry, tri + 2, &ignored_entry); if (matches != 6) throw std::logic_error( "File \""+filename+"\" cannot be parsed. Format not supported."); connectivities.col(itri++) = Vector3i(tri[0]-1, tri[1]-1, tri[2]-1); if (itri > num_triangles) throw(std::logic_error("Number of triangles exceeded previous count.")); } } // while fclose(file); return true; } Mesh *Mesh::clone() const { return new Mesh(*this); } void Mesh::getPoints(Eigen::Matrix3Xd &point_matrix) const { extractMeshVertices(point_matrix); } void Mesh::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Matrix3Xd mesh_vertices; extractMeshVertices(mesh_vertices); Vector3d min_pos = mesh_vertices.rowwise().minCoeff(); Vector3d max_pos = mesh_vertices.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } std::ostream &operator<<(std::ostream &out, const Mesh &mm) { out << static_cast<const Geometry &>(mm) << ", " << mm.scale << ", " << mm.filename << ", " << mm.resolved_filename << ", " << mm.root_dir; return out; } MeshPoints::MeshPoints(const Eigen::Matrix3Xd &points) : Geometry(MESH_POINTS), points(points) {} MeshPoints *MeshPoints::clone() const { return new MeshPoints(*this); } void MeshPoints::getPoints(Eigen::Matrix3Xd &point_matrix) const { point_matrix = points; } void MeshPoints::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Vector3d min_pos = points.rowwise().minCoeff(); Vector3d max_pos = points.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } std::ostream &operator<<(std::ostream &out, const MeshPoints &mp) { out << static_cast<const Geometry &>(mp) << ",\n" << mp.points; return out; } } // namespace DrakeShapes <|endoftext|>
<commit_before>// BaseDisplay.hh for Fluxbox Window Manager // Copyright (c) 2001 - 2002 Henrik Kinnunen ([email protected]) // // BaseDisplay.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes ([email protected]) // // 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. // $Id: BaseDisplay.hh,v 1.28 2002/08/30 13:09:24 fluxgen Exp $ #ifndef BASEDISPLAY_HH #define BASEDISPLAY_HH #include "NotCopyable.hh" #include "EventHandler.hh" #include <X11/Xlib.h> #ifdef XINERAMA extern "C" { #include <X11/extensions/Xinerama.h> } #endif // XINERAMA #include <list> #include <vector> // forward declaration class ScreenInfo; #define PropBlackboxHintsElements (5) #define PropBlackboxAttributesElements (8) /// obsolete void bexec(const char *command, char *displaystring); /** Singleton class to manage display connection */ class BaseDisplay:private NotCopyable, FbTk::EventHandler<XEvent> { public: BaseDisplay(const char *app_name, const char *display_name = 0); virtual ~BaseDisplay(); static BaseDisplay *instance(); /** obsolete @see FluxboxWindow */ enum Attrib { ATTRIB_SHADED = 0x01, ATTRIB_MAXHORIZ = 0x02, ATTRIB_MAXVERT = 0x04, ATTRIB_OMNIPRESENT = 0x08, ATTRIB_WORKSPACE = 0x10, ATTRIB_STACK = 0x20, ATTRIB_DECORATION = 0x40 }; typedef struct _blackbox_hints { unsigned long flags, attrib, workspace, stack; int decoration; } BlackboxHints; typedef struct _blackbox_attributes { unsigned long flags, attrib, workspace, stack; int premax_x, premax_y; unsigned int premax_w, premax_h; } BlackboxAttributes; inline ScreenInfo *getScreenInfo(int s) { return screenInfoList[s]; } inline bool hasShapeExtensions() const { return shape.extensions; } inline bool doShutdown() const { return m_shutdown; } inline bool isStartup() const { return m_startup; } static Display *getXDisplay() { return s_display; } inline const char *getXDisplayName() const { return m_display_name; } inline const char *getApplicationName() const { return m_app_name; } inline int getNumberOfScreens() const { return number_of_screens; } inline int getShapeEventBase() const { return shape.event_basep; } inline void shutdown() { m_shutdown = true; } inline void run() { m_startup = m_shutdown = false; } bool validateWindow(Window); void grab(); void ungrab(); void eventLoop(); private: struct shape { Bool extensions; int event_basep, error_basep; } shape; bool m_startup, m_shutdown; static Display *s_display; typedef std::vector<ScreenInfo *> ScreenInfoList; ScreenInfoList screenInfoList; const char *m_display_name, *m_app_name; int number_of_screens, m_server_grabs; static BaseDisplay *s_singleton; }; class ScreenInfo { public: ScreenInfo(BaseDisplay *bdisp, int screen_num); ~ScreenInfo(); inline BaseDisplay *getBaseDisplay() { return basedisplay; } inline Visual *getVisual() { return visual; } inline const Window &getRootWindow() const { return root_window; } inline const Colormap &colormap() const { return m_colormap; } inline int getDepth() const { return depth; } inline int getScreenNumber() const { return screen_number; } inline unsigned int getWidth() const { return width; } inline unsigned int getHeight() const { return height; } #ifdef XINERAMA inline bool hasXinerama() const { return m_hasXinerama; } inline int getNumHeads() const { return xineramaNumHeads; } unsigned int getHead(int x, int y) const; unsigned int getCurrHead() const; unsigned int getHeadWidth(unsigned int head) const; unsigned int getHeadHeight(unsigned int head) const; int getHeadX(unsigned int head) const; int getHeadY(unsigned int head) const; #endif // XINERAMA private: BaseDisplay *basedisplay; Visual *visual; Window root_window; Colormap m_colormap; int depth, screen_number; unsigned int width, height; #ifdef XINERAMA bool m_hasXinerama; int xineramaMajor, xineramaMinor, xineramaNumHeads, xineramaLastHead; XineramaScreenInfo *xineramaInfos; #endif // XINERAMA }; #endif // BASEDISPLAY_HH <commit_msg>const and ref<commit_after>// BaseDisplay.hh for Fluxbox Window Manager // Copyright (c) 2001 - 2002 Henrik Kinnunen ([email protected]) // // BaseDisplay.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes ([email protected]) // // 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. // $Id: BaseDisplay.hh,v 1.29 2002/09/08 19:12:33 fluxgen Exp $ #ifndef BASEDISPLAY_HH #define BASEDISPLAY_HH #include "NotCopyable.hh" #include "EventHandler.hh" #include <X11/Xlib.h> #ifdef XINERAMA extern "C" { #include <X11/extensions/Xinerama.h> } #endif // XINERAMA #include <list> #include <vector> // forward declaration class ScreenInfo; #define PropBlackboxHintsElements (5) #define PropBlackboxAttributesElements (8) /// obsolete void bexec(const char *command, char *displaystring); /** Singleton class to manage display connection */ class BaseDisplay:private NotCopyable, FbTk::EventHandler<XEvent> { public: BaseDisplay(const char *app_name, const char *display_name = 0); virtual ~BaseDisplay(); static BaseDisplay *instance(); /** obsolete @see FluxboxWindow */ enum Attrib { ATTRIB_SHADED = 0x01, ATTRIB_MAXHORIZ = 0x02, ATTRIB_MAXVERT = 0x04, ATTRIB_OMNIPRESENT = 0x08, ATTRIB_WORKSPACE = 0x10, ATTRIB_STACK = 0x20, ATTRIB_DECORATION = 0x40 }; typedef struct _blackbox_hints { unsigned long flags, attrib, workspace, stack; int decoration; } BlackboxHints; typedef struct _blackbox_attributes { unsigned long flags, attrib, workspace, stack; int premax_x, premax_y; unsigned int premax_w, premax_h; } BlackboxAttributes; inline ScreenInfo *getScreenInfo(int s) { return screenInfoList[s]; } inline bool hasShapeExtensions() const { return shape.extensions; } inline bool doShutdown() const { return m_shutdown; } inline bool isStartup() const { return m_startup; } static Display *getXDisplay() { return s_display; } inline const char *getXDisplayName() const { return m_display_name; } inline const char *getApplicationName() const { return m_app_name; } inline int getNumberOfScreens() const { return number_of_screens; } inline int getShapeEventBase() const { return shape.event_basep; } inline void shutdown() { m_shutdown = true; } inline void run() { m_startup = m_shutdown = false; } bool validateWindow(Window); void grab(); void ungrab(); void eventLoop(); private: struct shape { Bool extensions; int event_basep, error_basep; } shape; bool m_startup, m_shutdown; static Display *s_display; typedef std::vector<ScreenInfo *> ScreenInfoList; ScreenInfoList screenInfoList; const char *m_display_name, *m_app_name; int number_of_screens, m_server_grabs; static BaseDisplay *s_singleton; }; class ScreenInfo { public: ScreenInfo(BaseDisplay *bdisp, int screen_num); ~ScreenInfo(); inline BaseDisplay *getBaseDisplay() { return basedisplay; } inline Visual *getVisual() const { return visual; } inline Window getRootWindow() const { return root_window; } inline Colormap colormap() const { return m_colormap; } inline int getDepth() const { return depth; } inline int getScreenNumber() const { return screen_number; } inline unsigned int getWidth() const { return width; } inline unsigned int getHeight() const { return height; } #ifdef XINERAMA inline bool hasXinerama() const { return m_hasXinerama; } inline int getNumHeads() const { return xineramaNumHeads; } unsigned int getHead(int x, int y) const; unsigned int getCurrHead() const; unsigned int getHeadWidth(unsigned int head) const; unsigned int getHeadHeight(unsigned int head) const; int getHeadX(unsigned int head) const; int getHeadY(unsigned int head) const; #endif // XINERAMA private: BaseDisplay *basedisplay; Visual *visual; Window root_window; Colormap m_colormap; int depth, screen_number; unsigned int width, height; #ifdef XINERAMA bool m_hasXinerama; int xineramaMajor, xineramaMinor, xineramaNumHeads, xineramaLastHead; XineramaScreenInfo *xineramaInfos; #endif // XINERAMA }; #endif // BASEDISPLAY_HH <|endoftext|>
<commit_before>#include <cstdio> int main(){ int j, n, p[5], i[5], pi = 0, ii = 0; while(scanf("%d", &n) != EOF){ if (n % 2 == 0){ p[pi] = n; pi++; } else { i[ii] = n; ii++; } if (pi == 5){ for (j = 0; j <= 4; j++) printf("par[%d] = %d\n", j, p[j]); for (j = 0; j <= 4; j++) p[j] = NULL; pi = 0; } if (ii == 5){ for (j = 0; j <= 4; j++) printf("impar[%d] = %d\n", j, i[j]); for (j = 0; j <= 4; j++) i[j] = NULL; ii = 0; } } for (j = 0; j <= 4; j++){ if (i[j] == NULL) break; printf("impar[%d] = %d\n", j, i[j]); } for (j = 0; j <= 4; j++){ if (p[j] == NULL) break; printf("par[%d] = %d\n", j, p[j]); } return 0; } <commit_msg>Refatorando 1179.<commit_after>#include <cstdio> int main(){ int j, n, p[5], i[5], pi = 0, ii = 0; while(scanf("%d", &n) != EOF){ if (n % 2 == 0){ p[pi] = n; pi++; } else { i[ii] = n; ii++; } if (pi == 5){ for (j = 0; j <= 4; j++){ printf("par[%d] = %d\n", j, p[j]); p[j] = NULL; } pi = 0; } if (ii == 5){ for (j = 0; j <= 4; j++){ printf("impar[%d] = %d\n", j, i[j]); i[j] = NULL; } ii = 0; } } for (j = 0; j <= 4; j++){ if (i[j] == NULL) break; printf("impar[%d] = %d\n", j, i[j]); } for (j = 0; j <= 4; j++){ if (p[j] == NULL) break; printf("par[%d] = %d\n", j, p[j]); } return 0; } <|endoftext|>
<commit_before>// testForces.cpp // Author: Ajay Seth /* * Copyright (c) 2005-2010, Stanford University. All rights reserved. * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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. */ //========================================================================================================== // testJoints builds OpenSim models using the OpenSim API and builds an equivalent // Simbody system using the Simbody API for each test case. A test fails if the // OpenSim and Simbody final states of the simulation are not equivelent (norm-err // less than 10x integration error tolerance) // // Tests Include: // 1. PointToPointSpring // 2. BusingForce // 3. ElasticFoundationForce // // Add tests here as Forces are added to OpenSim // //========================================================================================================== #include <OpenSim/OpenSim.h> using namespace OpenSim; using namespace SimTK; using namespace std; #define ASSERT(cond) {if (!(cond)) throw(exception());} #define ASSERT_EQUAL(expected, found, tolerance) {double tol = std::max((tolerance), std::abs((expected)*(tolerance))); if ((found)<(expected)-(tol) || (found)>(expected)+(tol)) throw(exception());} //========================================================================================================== // Common Parameters for the simulations are just global. const static double integ_accuracy = 1.0e-4; const static double duration = 1.0; const static Vec3 gravity_vec = Vec3(0, -9.8065, 0); //========================================================================================================== static int counter=0; //========================================================================================================== // Test Cases //========================================================================================================== int testSpringMass() { double mass = 1; double stiffness = 10; double restlength = 1.0; double h0 = 0; double start_h = 0.5; double ball_radius = 0.25; double omega = sqrt(stiffness/mass); double dh = mass*gravity_vec(1)/stiffness; // Setup OpenSim model Model *osimModel = new Model; osimModel->setName("SpringMass"); //OpenSim bodies OpenSim::Body& ground = osimModel->getGroundBody(); OpenSim::Body ball("ball", mass ,Vec3(0), mass*SimTK::Inertia::sphere(0.1)); ball.addDisplayGeometry("sphere.vtp"); ball.scale(Vec3(ball_radius), false); // Add joints SliderJoint slider("", ground, Vec3(0), Vec3(0,0,Pi/2), ball, Vec3(0), Vec3(0,0,Pi/2)); double positionRange[2] = {-10, 10}; // Rename coordinates for a slider joint CoordinateSet &slider_coords = slider.getCoordinateSet(); slider_coords[0].setName("ball_h"); slider_coords[0].setRange(positionRange); slider_coords[0].setMotionType(Coordinate::Translational); osimModel->addBody(&ball); // BAD: have to set memoryOwner to false or program will crash when this test is complete. osimModel->updBodySet().setMemoryOwner(false); osimModel->setGravity(gravity_vec); PointToPointSpring spring("ground", Vec3(0,restlength,0), "ball", Vec3(0), stiffness, restlength); osimModel->addForce(&spring); //osimModel->print("SpringMassModel.osim"); // Create the force reporter ForceReporter* reporter = new ForceReporter(osimModel); osimModel->addAnalysis(reporter); SimTK::State osim_state = osimModel->initSystem(); slider_coords[0].setValue(osim_state, start_h); osimModel->getSystem().realize(osim_state, Stage::Position ); //========================================================================================================== // Compute the force and torque at the specified times. RungeKuttaMersonIntegrator integrator(osimModel->getSystem() ); integrator.setAccuracy(1e-6); Manager manager(*osimModel, integrator); manager.setInitialTime(0.0); double final_t = 2.0; double nsteps = 10; double dt = final_t/nsteps; for(int i = 1; i <=nsteps; i++){ manager.setFinalTime(dt*i); manager.integrate(osim_state); osimModel->getSystem().realize(osim_state, Stage::Acceleration); Vec3 pos; osimModel->updSimbodyEngine().getPosition(osim_state, ball, Vec3(0), pos); double height = (start_h-dh)*cos(omega*osim_state.getTime())+dh; ASSERT_EQUAL(height, pos(1), 1e-5); //Now check that the force reported by spring Array<double> model_force = spring.getRecordValues(osim_state); // get the forces applied to the ground and ball double analytical_force = -stiffness*height; // analytical force corresponds in direction to the force on the ball Y index = 7 ASSERT_EQUAL(analytical_force, model_force[7], 1e-4); manager.setInitialTime(dt*i); } // Save the forces //reporter->getForceStorage().print("spring_mass_forces.mot"); // Before exiting lets see if copying the spring works PointToPointSpring *copyOfSpring = (PointToPointSpring *)spring.copy(); bool isEqual = (*copyOfSpring == spring); ASSERT(isEqual); return 0; } int testBushingForce() { double mass = 1; double stiffness = 10; double restlength = 0.0; double h0 = 0; double start_h = 0.5; double ball_radius = 0.25; double omega = sqrt(stiffness/mass); double dh = mass*gravity_vec(1)/stiffness; // Setup OpenSim model Model *osimModel = new Model; osimModel->setName("BushingTest"); //OpenSim bodies OpenSim::Body& ground = osimModel->getGroundBody(); OpenSim::Body ball("ball", mass ,Vec3(0), mass*SimTK::Inertia::sphere(0.1)); ball.addDisplayGeometry("sphere.vtp"); ball.scale(Vec3(ball_radius), false); // Add joints SliderJoint slider("", ground, Vec3(0), Vec3(0,0,Pi/2), ball, Vec3(0), Vec3(0,0,Pi/2)); double positionRange[2] = {-10, 10}; // Rename coordinates for a slider joint CoordinateSet &slider_coords = slider.getCoordinateSet(); slider_coords[0].setName("ball_h"); slider_coords[0].setRange(positionRange); slider_coords[0].setMotionType(Coordinate::Translational); osimModel->addBody(&ball); // BAD: have to set memoryOwner to false or program will crash when this test is complete. osimModel->updBodySet().setMemoryOwner(false); Vec3 rotStiffness(0); Vec3 transStiffness(stiffness); Vec3 rotDamping(0); Vec3 transDamping(0); osimModel->setGravity(gravity_vec); BushingForce spring("ground", Vec3(0), Vec3(0), "ball", Vec3(0), Vec3(0), transStiffness, rotStiffness, transDamping, rotDamping); osimModel->addForce(&spring); osimModel->print("BushingForceModel.osim"); // Create the force reporter ForceReporter* reporter = new ForceReporter(osimModel); osimModel->addAnalysis(reporter); SimTK::State &osim_state = osimModel->initSystem(); slider_coords[0].setValue(osim_state, start_h); osimModel->getSystem().realize(osim_state, Stage::Position ); //========================================================================================================== // Compute the force and torque at the specified times. RungeKuttaMersonIntegrator integrator(osimModel->getSystem() ); integrator.setAccuracy(1e-6); Manager manager(*osimModel, integrator); manager.setInitialTime(0.0); double final_t = 2.0; double nsteps = 10; double dt = final_t/nsteps; for(int i = 1; i <=nsteps; i++){ manager.setFinalTime(dt*i); manager.integrate(osim_state); osimModel->getSystem().realize(osim_state, Stage::Acceleration); Vec3 pos; osimModel->updSimbodyEngine().getPosition(osim_state, ball, Vec3(0), pos); double height = (start_h-dh)*cos(omega*osim_state.getTime())+dh; ASSERT_EQUAL(height, pos(1), 1e-4); //Now check that the force reported by spring Array<double> model_force = spring.getRecordValues(osim_state); // get the forces applied to the ground and ball double analytical_force = -stiffness*height; // analytical force corresponds in direction to the force on the ball Y index = 7 ASSERT_EQUAL(analytical_force, model_force[7], 1e-4); manager.setInitialTime(dt*i); } manager.getStateStorage().print("bushing_model_states.sto"); // Save the forces reporter->getForceStorage().print("bushing_forces.mot"); // Before exiting lets see if copying the spring works BushingForce *copyOfSpring = (BushingForce *)spring.copy(); bool isEqual = (*copyOfSpring == spring); ASSERT(isEqual); return 0; } // Test our wraapping of elastic foundation in OpenSim // Simple simulation of bouncing ball with dissipation should generate contact // forces that settle to ball weight. int testElasticFoundation() { double start_h = 0.5; // Setup OpenSim model Model *osimModel = new Model("BouncingBallModel.osim"); // Create the force reporter ForceReporter* reporter = new ForceReporter(osimModel); osimModel->addAnalysis(reporter); SimTK::State osim_state = osimModel->initSystem(); osimModel->getCoordinateSet()[4].setValue(osim_state, start_h); osimModel->getSystem().realize(osim_state, Stage::Position ); const OpenSim::Body &ball = osimModel->getBodySet().get("ball"); //========================================================================================================== // Compute the force and torque at the specified times. RungeKuttaMersonIntegrator integrator(osimModel->getSystem() ); integrator.setAccuracy(1e-6); Manager manager(*osimModel, integrator); manager.setInitialTime(0.0); double final_t = 2.0; manager.setFinalTime(final_t); manager.integrate(osim_state); //make sure we can access dynamic variables osimModel->getSystem().realize(osim_state, Stage::Acceleration); // Print out the motion for visualizing/debugging //manager.getStateStorage().print("bouncing_ball_states.sto"); // Save the forces //reporter->getForceStorage().print("elastic_contact_forces.mot"); // Bouncing ball should have settled to rest on groun due to dissipation // In that case the force generated by contact should be identically body weight // in vertical and zero else where. OpenSim::ElasticFoundationForce &contact = (OpenSim::ElasticFoundationForce &)osimModel->getForceSet().get("contact"); Array<double> contact_force = contact.getRecordValues(osim_state); ASSERT_EQUAL(contact_force[0], 0.0, 1e-4); // no horizontal force on the ball ASSERT_EQUAL(contact_force[1], -ball.getMass()*gravity_vec[1], 1e-3); // vertical is weight ASSERT_EQUAL(contact_force[2], 0.0, 1e-4); // no horizontal force on the ball ASSERT_EQUAL(contact_force[3], 0.0, 1e-4); // no torque on the ball ASSERT_EQUAL(contact_force[4], 0.0, 1e-4); // no torque on the ball ASSERT_EQUAL(contact_force[5], 0.0, 1e-4); // no torque on the ball // Before exiting lets see if copying the spring works OpenSim::ElasticFoundationForce *copyOfForce = (OpenSim::ElasticFoundationForce *)contact.copy(); bool isEqual = (*copyOfForce == contact); if(!isEqual){ contact.print("originalForce.xml"); copyOfForce->print("copyOfForce.xml"); } ASSERT(isEqual); return 0; } int main() { testSpringMass(); cout << "spring passed" << endl; testBushingForce(); cout << "bushing passed" << endl; testElasticFoundation(); cout << "elastic foundation force passed" << endl; return 0; } <commit_msg>Dissipation on bouncing ball test case for ElasticFoundationForce force was updated to reflect SimTK side changes to underlying equations.<commit_after>// testForces.cpp // Author: Ajay Seth /* * Copyright (c) 2005-2010, Stanford University. All rights reserved. * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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. */ //========================================================================================================== // testJoints builds OpenSim models using the OpenSim API and builds an equivalent // Simbody system using the Simbody API for each test case. A test fails if the // OpenSim and Simbody final states of the simulation are not equivelent (norm-err // less than 10x integration error tolerance) // // Tests Include: // 1. PointToPointSpring // 2. BusingForce // 3. ElasticFoundationForce // // Add tests here as Forces are added to OpenSim // //========================================================================================================== #include <OpenSim/OpenSim.h> using namespace OpenSim; using namespace SimTK; using namespace std; #define ASSERT(cond) {if (!(cond)) throw(exception());} #define ASSERT_EQUAL(expected, found, tolerance) {double tol = std::max((tolerance), std::abs((expected)*(tolerance))); if ((found)<(expected)-(tol) || (found)>(expected)+(tol)) throw(exception());} //========================================================================================================== // Common Parameters for the simulations are just global. const static double integ_accuracy = 1.0e-4; const static double duration = 1.0; const static Vec3 gravity_vec = Vec3(0, -9.8065, 0); //========================================================================================================== static int counter=0; //========================================================================================================== // Test Cases //========================================================================================================== int testSpringMass() { double mass = 1; double stiffness = 10; double restlength = 1.0; double h0 = 0; double start_h = 0.5; double ball_radius = 0.25; double omega = sqrt(stiffness/mass); double dh = mass*gravity_vec(1)/stiffness; // Setup OpenSim model Model *osimModel = new Model; osimModel->setName("SpringMass"); //OpenSim bodies OpenSim::Body& ground = osimModel->getGroundBody(); OpenSim::Body ball("ball", mass ,Vec3(0), mass*SimTK::Inertia::sphere(0.1)); ball.addDisplayGeometry("sphere.vtp"); ball.scale(Vec3(ball_radius), false); // Add joints SliderJoint slider("", ground, Vec3(0), Vec3(0,0,Pi/2), ball, Vec3(0), Vec3(0,0,Pi/2)); double positionRange[2] = {-10, 10}; // Rename coordinates for a slider joint CoordinateSet &slider_coords = slider.getCoordinateSet(); slider_coords[0].setName("ball_h"); slider_coords[0].setRange(positionRange); slider_coords[0].setMotionType(Coordinate::Translational); osimModel->addBody(&ball); // BAD: have to set memoryOwner to false or program will crash when this test is complete. osimModel->updBodySet().setMemoryOwner(false); osimModel->setGravity(gravity_vec); PointToPointSpring spring("ground", Vec3(0,restlength,0), "ball", Vec3(0), stiffness, restlength); osimModel->addForce(&spring); //osimModel->print("SpringMassModel.osim"); // Create the force reporter ForceReporter* reporter = new ForceReporter(osimModel); osimModel->addAnalysis(reporter); SimTK::State osim_state = osimModel->initSystem(); slider_coords[0].setValue(osim_state, start_h); osimModel->getSystem().realize(osim_state, Stage::Position ); //========================================================================================================== // Compute the force and torque at the specified times. RungeKuttaMersonIntegrator integrator(osimModel->getSystem() ); integrator.setAccuracy(1e-6); Manager manager(*osimModel, integrator); manager.setInitialTime(0.0); double final_t = 2.0; double nsteps = 10; double dt = final_t/nsteps; for(int i = 1; i <=nsteps; i++){ manager.setFinalTime(dt*i); manager.integrate(osim_state); osimModel->getSystem().realize(osim_state, Stage::Acceleration); Vec3 pos; osimModel->updSimbodyEngine().getPosition(osim_state, ball, Vec3(0), pos); double height = (start_h-dh)*cos(omega*osim_state.getTime())+dh; ASSERT_EQUAL(height, pos(1), 1e-5); //Now check that the force reported by spring Array<double> model_force = spring.getRecordValues(osim_state); // get the forces applied to the ground and ball double analytical_force = -stiffness*height; // analytical force corresponds in direction to the force on the ball Y index = 7 ASSERT_EQUAL(analytical_force, model_force[7], 1e-4); manager.setInitialTime(dt*i); } // Save the forces //reporter->getForceStorage().print("spring_mass_forces.mot"); // Before exiting lets see if copying the spring works PointToPointSpring *copyOfSpring = (PointToPointSpring *)spring.copy(); bool isEqual = (*copyOfSpring == spring); ASSERT(isEqual); return 0; } int testBushingForce() { double mass = 1; double stiffness = 10; double restlength = 0.0; double h0 = 0; double start_h = 0.5; double ball_radius = 0.25; double omega = sqrt(stiffness/mass); double dh = mass*gravity_vec(1)/stiffness; // Setup OpenSim model Model *osimModel = new Model; osimModel->setName("BushingTest"); //OpenSim bodies OpenSim::Body& ground = osimModel->getGroundBody(); OpenSim::Body ball("ball", mass ,Vec3(0), mass*SimTK::Inertia::sphere(0.1)); ball.addDisplayGeometry("sphere.vtp"); ball.scale(Vec3(ball_radius), false); // Add joints SliderJoint slider("", ground, Vec3(0), Vec3(0,0,Pi/2), ball, Vec3(0), Vec3(0,0,Pi/2)); double positionRange[2] = {-10, 10}; // Rename coordinates for a slider joint CoordinateSet &slider_coords = slider.getCoordinateSet(); slider_coords[0].setName("ball_h"); slider_coords[0].setRange(positionRange); slider_coords[0].setMotionType(Coordinate::Translational); osimModel->addBody(&ball); // BAD: have to set memoryOwner to false or program will crash when this test is complete. osimModel->updBodySet().setMemoryOwner(false); Vec3 rotStiffness(0); Vec3 transStiffness(stiffness); Vec3 rotDamping(0); Vec3 transDamping(0); osimModel->setGravity(gravity_vec); BushingForce spring("ground", Vec3(0), Vec3(0), "ball", Vec3(0), Vec3(0), transStiffness, rotStiffness, transDamping, rotDamping); osimModel->addForce(&spring); osimModel->print("BushingForceModel.osim"); // Create the force reporter ForceReporter* reporter = new ForceReporter(osimModel); osimModel->addAnalysis(reporter); SimTK::State &osim_state = osimModel->initSystem(); slider_coords[0].setValue(osim_state, start_h); osimModel->getSystem().realize(osim_state, Stage::Position ); //========================================================================================================== // Compute the force and torque at the specified times. RungeKuttaMersonIntegrator integrator(osimModel->getSystem() ); integrator.setAccuracy(1e-6); Manager manager(*osimModel, integrator); manager.setInitialTime(0.0); double final_t = 2.0; double nsteps = 10; double dt = final_t/nsteps; for(int i = 1; i <=nsteps; i++){ manager.setFinalTime(dt*i); manager.integrate(osim_state); osimModel->getSystem().realize(osim_state, Stage::Acceleration); Vec3 pos; osimModel->updSimbodyEngine().getPosition(osim_state, ball, Vec3(0), pos); double height = (start_h-dh)*cos(omega*osim_state.getTime())+dh; ASSERT_EQUAL(height, pos(1), 1e-4); //Now check that the force reported by spring Array<double> model_force = spring.getRecordValues(osim_state); // get the forces applied to the ground and ball double analytical_force = -stiffness*height; // analytical force corresponds in direction to the force on the ball Y index = 7 ASSERT_EQUAL(analytical_force, model_force[7], 1e-4); manager.setInitialTime(dt*i); } manager.getStateStorage().print("bushing_model_states.sto"); // Save the forces reporter->getForceStorage().print("bushing_forces.mot"); // Before exiting lets see if copying the spring works BushingForce *copyOfSpring = (BushingForce *)spring.copy(); bool isEqual = (*copyOfSpring == spring); ASSERT(isEqual); return 0; } // Test our wraapping of elastic foundation in OpenSim // Simple simulation of bouncing ball with dissipation should generate contact // forces that settle to ball weight. int testElasticFoundation() { double start_h = 0.5; // Setup OpenSim model Model *osimModel = new Model("BouncingBallModel.osim"); // Create the force reporter ForceReporter* reporter = new ForceReporter(osimModel); osimModel->addAnalysis(reporter); SimTK::State osim_state = osimModel->initSystem(); osimModel->getCoordinateSet()[4].setValue(osim_state, start_h); osimModel->getSystem().realize(osim_state, Stage::Position ); const OpenSim::Body &ball = osimModel->getBodySet().get("ball"); //========================================================================================================== // Compute the force and torque at the specified times. RungeKuttaMersonIntegrator integrator(osimModel->getSystem() ); integrator.setAccuracy(1e-6); Manager manager(*osimModel, integrator); manager.setInitialTime(0.0); double final_t = 2.0; manager.setFinalTime(final_t); manager.integrate(osim_state); //make sure we can access dynamic variables osimModel->getSystem().realize(osim_state, Stage::Acceleration); // Print out the motion for visualizing/debugging manager.getStateStorage().print("bouncing_ball_states.sto"); // Save the forces reporter->getForceStorage().print("elastic_contact_forces.mot"); // Bouncing ball should have settled to rest on groun due to dissipation // In that case the force generated by contact should be identically body weight // in vertical and zero else where. OpenSim::ElasticFoundationForce &contact = (OpenSim::ElasticFoundationForce &)osimModel->getForceSet().get("contact"); Array<double> contact_force = contact.getRecordValues(osim_state); ASSERT_EQUAL(contact_force[0], 0.0, 1e-4); // no horizontal force on the ball ASSERT_EQUAL(contact_force[1], -ball.getMass()*gravity_vec[1], 1e-3); // vertical is weight ASSERT_EQUAL(contact_force[2], 0.0, 1e-4); // no horizontal force on the ball ASSERT_EQUAL(contact_force[3], 0.0, 1e-4); // no torque on the ball ASSERT_EQUAL(contact_force[4], 0.0, 1e-4); // no torque on the ball ASSERT_EQUAL(contact_force[5], 0.0, 1e-4); // no torque on the ball // Before exiting lets see if copying the spring works OpenSim::ElasticFoundationForce *copyOfForce = (OpenSim::ElasticFoundationForce *)contact.copy(); bool isEqual = (*copyOfForce == contact); if(!isEqual){ contact.print("originalForce.xml"); copyOfForce->print("copyOfForce.xml"); } ASSERT(isEqual); return 0; } int main() { testSpringMass(); cout << "spring passed" << endl; testBushingForce(); cout << "bushing passed" << endl; testElasticFoundation(); cout << "elastic foundation force passed" << endl; return 0; } <|endoftext|>
<commit_before>// 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. // // NOTE: These tests are run as part of "unit_tests" (in chrome/test/unit) // rather than as part of test_shell_tests because they rely on being able // to instantiate a MessageLoop of type TYPE_IO. test_shell_tests uses // TYPE_UI, which URLRequest doesn't allow. // #include "webkit/fileapi/file_system_dir_url_request_job.h" #include "build/build_config.h" #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/format_macros.h" #include "base/message_loop.h" #include "base/platform_file.h" #include "base/scoped_temp_dir.h" #include "base/string_piece.h" #include "base/threading/thread.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/http/http_request_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/fileapi/file_system_path_manager.h" namespace fileapi { namespace { // We always use the TEMPORARY FileSystem in this test. static const char kFileSystemURLPrefix[] = "filesystem:http://remote/temporary/"; class FileSystemDirURLRequestJobTest : public testing::Test { protected: FileSystemDirURLRequestJobTest() : message_loop_(MessageLoop::TYPE_IO), // simulate an IO thread ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)) { } virtual void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); // We use the main thread so that we can get the root path synchronously. // TODO(adamk): Run this on the FILE thread we've created as well. path_manager_.reset(new FileSystemPathManager( base::MessageLoopProxy::CreateForCurrentThread(), temp_dir_.path(), false, false)); path_manager_->GetFileSystemRootPath( GURL("http://remote/"), kFileSystemTypeTemporary, true, // create callback_factory_.NewCallback( &FileSystemDirURLRequestJobTest::OnGetRootPath)); MessageLoop::current()->RunAllPending(); file_thread_.reset( new base::Thread("FileSystemDirURLRequestJobTest FILE Thread")); base::Thread::Options options(MessageLoop::TYPE_IO, 0); file_thread_->StartWithOptions(options); net::URLRequest::RegisterProtocolFactory( "filesystem", &FileSystemDirURLRequestJobFactory); } virtual void TearDown() { // NOTE: order matters, request must die before delegate request_.reset(NULL); delegate_.reset(NULL); file_thread_.reset(NULL); net::URLRequest::RegisterProtocolFactory("filesystem", NULL); } void OnGetRootPath(bool success, const FilePath& root_path, const std::string& name) { ASSERT_TRUE(success); root_path_ = root_path; } void TestRequest(const GURL& url) { delegate_.reset(new TestDelegate()); delegate_->set_quit_on_redirect(true); request_.reset(new net::URLRequest(url, delegate_.get())); job_ = new FileSystemDirURLRequestJob(request_.get(), path_manager_.get(), file_thread_->message_loop_proxy()); request_->Start(); ASSERT_TRUE(request_->is_pending()); // verify that we're starting async MessageLoop::current()->Run(); } void CreateDirectory(const base::StringPiece dir_name) { FilePath path = root_path_.AppendASCII(dir_name); ASSERT_TRUE(file_util::CreateDirectory(path)); } GURL CreateFileSystemURL(const std::string path) { return GURL(kFileSystemURLPrefix + path); } static net::URLRequestJob* FileSystemDirURLRequestJobFactory( net::URLRequest* request, const std::string& scheme) { DCHECK(job_); net::URLRequestJob* temp = job_; job_ = NULL; return temp; } ScopedTempDir temp_dir_; FilePath root_path_; scoped_ptr<net::URLRequest> request_; scoped_ptr<TestDelegate> delegate_; scoped_ptr<FileSystemPathManager> path_manager_; scoped_ptr<base::Thread> file_thread_; MessageLoop message_loop_; base::ScopedCallbackFactory<FileSystemDirURLRequestJobTest> callback_factory_; static net::URLRequestJob* job_; }; // static net::URLRequestJob* FileSystemDirURLRequestJobTest::job_ = NULL; // TODO(adamk): Write tighter tests once we've decided on a format for directory // listing responses. TEST_F(FileSystemDirURLRequestJobTest, DirectoryListing) { CreateDirectory("foo"); CreateDirectory("foo/bar"); CreateDirectory("foo/bar/baz"); TestRequest(CreateFileSystemURL("foo/bar/")); ASSERT_FALSE(request_->is_pending()); EXPECT_EQ(1, delegate_->response_started_count()); EXPECT_FALSE(delegate_->received_data_before_response()); EXPECT_GT(delegate_->bytes_received(), 0); } TEST_F(FileSystemDirURLRequestJobTest, InvalidURL) { TestRequest(GURL("filesystem:/foo/bar/baz")); ASSERT_FALSE(request_->is_pending()); EXPECT_TRUE(delegate_->request_failed()); ASSERT_FALSE(request_->status().is_success()); EXPECT_EQ(net::ERR_INVALID_URL, request_->status().os_error()); } TEST_F(FileSystemDirURLRequestJobTest, NoSuchRoot) { TestRequest(GURL("filesystem:http://remote/persistent/somedir/")); ASSERT_FALSE(request_->is_pending()); ASSERT_FALSE(request_->status().is_success()); EXPECT_EQ(net::ERR_FILE_NOT_FOUND, request_->status().os_error()); } TEST_F(FileSystemDirURLRequestJobTest, NoSuchDirectory) { TestRequest(CreateFileSystemURL("somedir/")); ASSERT_FALSE(request_->is_pending()); ASSERT_FALSE(request_->status().is_success()); EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND, request_->status().os_error()); } } // namespace (anonymous) } // namespace fileapi <commit_msg>Make FileSystemDirURLRequestJob test single-threaded in hopes of making it less flaky under Valgrind.<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. // // NOTE: These tests are run as part of "unit_tests" (in chrome/test/unit) // rather than as part of test_shell_tests because they rely on being able // to instantiate a MessageLoop of type TYPE_IO. test_shell_tests uses // TYPE_UI, which URLRequest doesn't allow. // #include "webkit/fileapi/file_system_dir_url_request_job.h" #include "build/build_config.h" #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/format_macros.h" #include "base/message_loop.h" #include "base/platform_file.h" #include "base/scoped_temp_dir.h" #include "base/string_piece.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/http/http_request_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/fileapi/file_system_path_manager.h" namespace fileapi { namespace { // We always use the TEMPORARY FileSystem in this test. static const char kFileSystemURLPrefix[] = "filesystem:http://remote/temporary/"; class FileSystemDirURLRequestJobTest : public testing::Test { protected: FileSystemDirURLRequestJobTest() : message_loop_(MessageLoop::TYPE_IO), // simulate an IO thread ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)) { } virtual void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); file_thread_proxy_ = base::MessageLoopProxy::CreateForCurrentThread(); path_manager_.reset(new FileSystemPathManager( file_thread_proxy_, temp_dir_.path(), false, false)); path_manager_->GetFileSystemRootPath( GURL("http://remote/"), kFileSystemTypeTemporary, true, // create callback_factory_.NewCallback( &FileSystemDirURLRequestJobTest::OnGetRootPath)); MessageLoop::current()->RunAllPending(); net::URLRequest::RegisterProtocolFactory( "filesystem", &FileSystemDirURLRequestJobFactory); } virtual void TearDown() { // NOTE: order matters, request must die before delegate request_.reset(NULL); delegate_.reset(NULL); net::URLRequest::RegisterProtocolFactory("filesystem", NULL); } void OnGetRootPath(bool success, const FilePath& root_path, const std::string& name) { ASSERT_TRUE(success); root_path_ = root_path; } void TestRequest(const GURL& url) { delegate_.reset(new TestDelegate()); delegate_->set_quit_on_redirect(true); request_.reset(new net::URLRequest(url, delegate_.get())); job_ = new FileSystemDirURLRequestJob(request_.get(), path_manager_.get(), file_thread_proxy_); request_->Start(); ASSERT_TRUE(request_->is_pending()); // verify that we're starting async MessageLoop::current()->Run(); } void CreateDirectory(const base::StringPiece dir_name) { FilePath path = root_path_.AppendASCII(dir_name); ASSERT_TRUE(file_util::CreateDirectory(path)); } GURL CreateFileSystemURL(const std::string path) { return GURL(kFileSystemURLPrefix + path); } static net::URLRequestJob* FileSystemDirURLRequestJobFactory( net::URLRequest* request, const std::string& scheme) { DCHECK(job_); net::URLRequestJob* temp = job_; job_ = NULL; return temp; } ScopedTempDir temp_dir_; FilePath root_path_; scoped_ptr<net::URLRequest> request_; scoped_ptr<TestDelegate> delegate_; scoped_ptr<FileSystemPathManager> path_manager_; scoped_refptr<base::MessageLoopProxy> file_thread_proxy_; MessageLoop message_loop_; base::ScopedCallbackFactory<FileSystemDirURLRequestJobTest> callback_factory_; static net::URLRequestJob* job_; }; // static net::URLRequestJob* FileSystemDirURLRequestJobTest::job_ = NULL; // TODO(adamk): Write tighter tests once we've decided on a format for directory // listing responses. TEST_F(FileSystemDirURLRequestJobTest, DirectoryListing) { CreateDirectory("foo"); CreateDirectory("foo/bar"); CreateDirectory("foo/bar/baz"); TestRequest(CreateFileSystemURL("foo/bar/")); ASSERT_FALSE(request_->is_pending()); EXPECT_EQ(1, delegate_->response_started_count()); EXPECT_FALSE(delegate_->received_data_before_response()); EXPECT_GT(delegate_->bytes_received(), 0); } TEST_F(FileSystemDirURLRequestJobTest, InvalidURL) { TestRequest(GURL("filesystem:/foo/bar/baz")); ASSERT_FALSE(request_->is_pending()); EXPECT_TRUE(delegate_->request_failed()); ASSERT_FALSE(request_->status().is_success()); EXPECT_EQ(net::ERR_INVALID_URL, request_->status().os_error()); } TEST_F(FileSystemDirURLRequestJobTest, NoSuchRoot) { TestRequest(GURL("filesystem:http://remote/persistent/somedir/")); ASSERT_FALSE(request_->is_pending()); ASSERT_FALSE(request_->status().is_success()); EXPECT_EQ(net::ERR_FILE_NOT_FOUND, request_->status().os_error()); } TEST_F(FileSystemDirURLRequestJobTest, NoSuchDirectory) { TestRequest(CreateFileSystemURL("somedir/")); ASSERT_FALSE(request_->is_pending()); ASSERT_FALSE(request_->status().is_success()); EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND, request_->status().os_error()); } } // namespace (anonymous) } // namespace fileapi <|endoftext|>
<commit_before>/* | Yahtzee program | | Written by Gabriel Simmer | | I still don't know how to play yahtzee :P | */ #include <iostream> #include <windows.h> #include <stdlib.h> #include <stdio.h> #include <ctime> using namespace std; int main() { SetConsoleTitle("Console Yahtzee"); cout << "Text Yahtzee" << endl; cout << "By Gabriel Simmer" << endl; /* | Set console title, and display needed info | */ srand(time(0)); //Seed random numbers from time int dice1; int dice2; int dice3; int dice4; int dice5; int catones; int cattwos; int catthrees; int catfours; int catfives; int catsixes; int cattotal; int catbonus; int allowedtoroll1; int allowedtoroll2; int allowedtoroll3; int allowedtoroll4; int allowedtoroll5; int loopbreak; int canUsecatones = 0; int canUsecattwos = 0; int canUsecatthrees = 0; int canUsecatfours = 0; int canUsecatfives = 0; int canUsecatsixes = 0; int catlocked1 = 0; int catlocked2 = 0; int catlocked3 = 0; int catlocked4 = 0; int catlocked5 = 0; int catlocked6 = 0; loopbreak = 0; allowedtoroll1 = 0; allowedtoroll2 = 0; allowedtoroll3 = 0; allowedtoroll4 = 0; allowedtoroll5 = 0; //Declares all variables needed cout << "Rolling for round." << endl; //Random numbers occur here dice1 = (1 + rand() % 6); cout << dice1; cout << " "; dice2 = (1 + rand() % 6); cout << dice2; cout << " "; dice3 = (1 + rand() % 6); cout << dice3; cout << " "; dice4 = (1 + rand() % 6); cout << dice4; dice5 = (1 + rand() % 6); cout << " "; cout << dice5 << endl ; int rerolldice; while ( loopbreak != 1 ) { cout << "Reroll which dice?" << endl; cout << "Enter 8 to score current roll or 9 to continue to next round." << endl; cout << "Dice "; cin >> rerolldice; //Make new random numbers if dice is chosen, 9 is exit, 8 is calculate score if ( rerolldice == 1 ) { if ( allowedtoroll1 < 2 ) { //So that you can only roll twice dice1 = (1 + rand() % 6 ); cout << "Dice One: "; cout << dice1 << endl; allowedtoroll1 = allowedtoroll1++; } else { cout << "You can not roll that dice any more." << endl; cout << " " << endl; } } if ( rerolldice == 2 ) { if ( allowedtoroll2 < 2 ) { dice2 = ( 1 + rand() % 6 ); cout << "Dice Two: "; cout << dice2 << endl; allowedtoroll2 = allowedtoroll2++; } else { cout << "You can not roll that dice any more" << endl; cout << " " << endl; } } if ( rerolldice == 3 ) { if ( allowedtoroll3 < 2 ) { dice3 = ( 1 + rand() % 6 ); cout << "Dice Three: "; cout << dice3 << endl; allowedtoroll3 = allowedtoroll3++; } else { cout << "You can not roll this dice any more" << endl; cout << " " << endl; } } if ( rerolldice == 4 ) { if ( allowedtoroll4 < 2 ) { dice4 = ( 1 + rand() % 6 ); cout << "Dice Four: "; cout << dice4 << endl; } } if ( rerolldice == 5 ) { if ( allowedtoroll5 < 2 ) { dice5 = ( 1 + rand() % 6 ); cout << "Dice Five: "; cout << dice5 << endl; } else { cout << "You can not roll this dice any more" << endl; cout << " " << endl; } } if ( rerolldice == 9 ) { exit (EXIT_SUCCESS); } if ( rerolldice == 8 ) { loopbreak = 1; //Breaks the loop cout << "Current numbers rolled:" << endl; cout << dice1; cout << " "; cout << dice2; cout << " "; cout << dice3; cout << " "; cout << dice4; cout << " "; cout << dice5; cout << " " << endl; cout << "Score to which category?" << endl; cout << "aces, twos, thress, fours, fives, or sixes?" << endl; string aces = "aces"; string twos = "twos"; string threes = "threes"; string fours = "fours"; string fives = "fives"; string sixes = "sixes"; string scoresect; cin >> scoresect; //Choice strings if ( scoresect == aces ) { //Thanks to Mr. Last for the help with the catagories! if ( canUsecatones == 0 ){ catones=0; if (dice1==1) catones++; if (dice2==1) catones++; if (dice3==1) catones++; if (dice4==1) catones++; if (dice5==1) catones++; cout << catones << endl; canUsecatones++; } else if ( canUsecatones > 0 ){ cout << "You've already used that catagory!" << endl; } } else if ( scoresect == twos ) { if ( canUsecattwos == 0 ){ cattwos=0; if (dice1==2) cattwos=cattwos+2; if (dice2==2) cattwos=cattwos+2; if (dice3==2) cattwos=cattwos+2; if (dice4==2) cattwos=cattwos+2; if (dice5==2) cattwos=cattwos+2; cout << cattwos << endl; canUsecattwos++; } else if ( canUsecattwos > 0 ){ cout << "You've already used this catagory!" << endl; } } if ( scoresect == threes ){ if ( canUsecatthrees == 0 ){ catthrees=0; if (dice1==3) catthrees=catthrees+3; if (dice2==3) catthrees=catthrees+3; if (dice3==3) catthrees=catthrees+3; if (dice4==3) catthrees=catthrees+3; if (dice5==3) catthrees=catthrees+3; cout << catthrees << endl; canUsecatthrees++; } else if ( canUsecatthrees > 0 ){ cout << "You've already used this catagory!" << endl; } } else if ( scoresect == fours ) { if ( canUsecatfours == 0 ){ catfours=0; if (dice1==4) catfours=catfours+4; if (dice2==4) catfours=catfours+4; if (dice3==4) catfours=catfours+4; if (dice4==4) catfours=catfours+4; if (dice5==4) catfours=catfours+4; cout << catfours << endl; canUsecatfours++; } else if ( canUsecatfours > 0 ){ cout << "You've already used this catagory!" << endl; } } else if ( scoresect == fives ) { if ( canUsecatfives == 0 ){ if (dice1==5) catfives=catfives+5; if (dice2==5) catfives=catfives+5; if (dice3==5) catfives=catfives+5; if (dice4==5) catfives=catfives+5; if (dice5==5) catfives=catfives+5; cout << catfives << endl; } else if ( canUsecatfives > 0 ){ cout << "You've already used this catagory!" << endl; } } else if ( scoresect == sixes ) { if ( canUsecatsixes == 0 ){ if (dice1==6) catsixes=catsixes+6; if (dice2==6) catsixes=catsixes+6; if (dice3==6) catsixes=catsixes+6; if (dice4==6) catsixes=catsixes+6; if (dice5==6) catsixes=catsixes+6; cout << catsixes << endl; } else if ( canUsecatsixes == 0 ){ cout << "You've already used this catagory!" << endl; } } } } return 0; } <commit_msg>Broke sixes<commit_after>/* | Yahtzee program | | Written by Gabriel Simmer | | I still don't know how to play yahtzee :P | */ #include <iostream> #include <windows.h> #include <stdlib.h> #include <stdio.h> #include <ctime> using namespace std; int main() { SetConsoleTitle("Console Yahtzee"); cout << "Text Yahtzee" << endl; cout << "By Gabriel Simmer" << endl; /* | Set console title, and display needed info | */ srand(time(0)); //Seed random numbers from time int dice1; int dice2; int dice3; int dice4; int dice5; int catones; int cattwos; int catthrees; int catfours; int catfives; int catsixes; int cattotal; int catbonus; int allowedtoroll1; int allowedtoroll2; int allowedtoroll3; int allowedtoroll4; int allowedtoroll5; int loopbreak; int canUsecatones = 0; int canUsecattwos = 0; int canUsecatthrees = 0; int canUsecatfours = 0; int canUsecatfives = 0; int canUsecatsixes = 0; int catlocked1 = 0; int catlocked2 = 0; int catlocked3 = 0; int catlocked4 = 0; int catlocked5 = 0; int catlocked6 = 0; loopbreak = 0; allowedtoroll1 = 0; allowedtoroll2 = 0; allowedtoroll3 = 0; allowedtoroll4 = 0; allowedtoroll5 = 0; //Declares all variables needed cout << "Rolling for round." << endl; //Random numbers occur here dice1 = (1 + rand() % 6); cout << dice1; cout << " "; dice2 = (1 + rand() % 6); cout << dice2; cout << " "; dice3 = (1 + rand() % 6); cout << dice3; cout << " "; dice4 = (1 + rand() % 6); cout << dice4; dice5 = (1 + rand() % 6); cout << " "; cout << dice5 << endl ; int rerolldice; while ( loopbreak != 1 ) { cout << "Reroll which dice?" << endl; cout << "Enter 8 to score current roll or 9 to continue to next round." << endl; cout << "Dice "; cin >> rerolldice; //Make new random numbers if dice is chosen, 9 is exit, 8 is calculate score if ( rerolldice == 1 ) { if ( allowedtoroll1 < 2 ) { //So that you can only roll twice dice1 = (1 + rand() % 6 ); cout << "Dice One: "; cout << dice1 << endl; allowedtoroll1 = allowedtoroll1++; } else { cout << "You can not roll that dice any more." << endl; cout << " " << endl; } } if ( rerolldice == 2 ) { if ( allowedtoroll2 < 2 ) { dice2 = ( 1 + rand() % 6 ); cout << "Dice Two: "; cout << dice2 << endl; allowedtoroll2 = allowedtoroll2++; } else { cout << "You can not roll that dice any more" << endl; cout << " " << endl; } } if ( rerolldice == 3 ) { if ( allowedtoroll3 < 2 ) { dice3 = ( 1 + rand() % 6 ); cout << "Dice Three: "; cout << dice3 << endl; allowedtoroll3 = allowedtoroll3++; } else { cout << "You can not roll this dice any more" << endl; cout << " " << endl; } } if ( rerolldice == 4 ) { if ( allowedtoroll4 < 2 ) { dice4 = ( 1 + rand() % 6 ); cout << "Dice Four: "; cout << dice4 << endl; } } if ( rerolldice == 5 ) { if ( allowedtoroll5 < 2 ) { dice5 = ( 1 + rand() % 6 ); cout << "Dice Five: "; cout << dice5 << endl; } else { cout << "You can not roll this dice any more" << endl; cout << " " << endl; } } if ( rerolldice == 9 ) { exit (EXIT_SUCCESS); } if ( rerolldice == 8 ) { loopbreak = 1; //Breaks the loop cout << "Current numbers rolled:" << endl; cout << dice1; cout << " "; cout << dice2; cout << " "; cout << dice3; cout << " "; cout << dice4; cout << " "; cout << dice5; cout << " " << endl; cout << "Score to which category?" << endl; cout << "aces, twos, thress, fours, fives, or sixes?" << endl; string aces = "aces"; string twos = "twos"; string threes = "threes"; string fours = "fours"; string fives = "fives"; string sixes = "sixes"; string scoresect; cin >> scoresect; //Choice strings if ( scoresect == aces ) { //Thanks to Mr. Last for the help with the catagories! if ( canUsecatones == 0 ){ catones=0; if (dice1==1) catones++; if (dice2==1) catones++; if (dice3==1) catones++; if (dice4==1) catones++; if (dice5==1) catones++; cout << catones << endl; canUsecatones++; } else if ( canUsecatones > 0 ){ cout << "You've already used that catagory!" << endl; } } else if ( scoresect == twos ) { if ( canUsecattwos == 0 ){ cattwos=0; if (dice1==2) cattwos=cattwos+2; if (dice2==2) cattwos=cattwos+2; if (dice3==2) cattwos=cattwos+2; if (dice4==2) cattwos=cattwos+2; if (dice5==2) cattwos=cattwos+2; cout << cattwos << endl; canUsecattwos++; } else if ( canUsecattwos > 0 ){ cout << "You've already used this catagory!" << endl; } } if ( scoresect == threes ){ if ( canUsecatthrees == 0 ){ catthrees=0; if (dice1==3) catthrees=catthrees+3; if (dice2==3) catthrees=catthrees+3; if (dice3==3) catthrees=catthrees+3; if (dice4==3) catthrees=catthrees+3; if (dice5==3) catthrees=catthrees+3; cout << catthrees << endl; canUsecatthrees++; } else if ( canUsecatthrees > 0 ){ cout << "You've already used this catagory!" << endl; } } else if ( scoresect == fours ) { if ( canUsecatfours == 0 ){ catfours=0; if (dice1==4) catfours=catfours+4; if (dice2==4) catfours=catfours+4; if (dice3==4) catfours=catfours+4; if (dice4==4) catfours=catfours+4; if (dice5==4) catfours=catfours+4; cout << catfours << endl; canUsecatfours++; } else if ( canUsecatfours > 0 ){ cout << "You've already used this catagory!" << endl; } } else if ( scoresect == fives ) { if ( canUsecatfives == 0 ){ if (dice1==5) catfives=catfives+5; if (dice2==5) catfives=catfives+5; if (dice3==5) catfives=catfives+5; if (dice4==5) catfives=catfives+5; if (dice5==5) catfives=catfives+5; cout << catfives << endl; } else if ( canUsecatfives > 0 ){ cout << "You've already used this catagory!" << endl; } } else if ( scoresect == sixes ) { if ( canUsecatsixes == 0 ){ if (dice1==6) catsixes=catsixes+6; if (dice2==6) catsixes=catsixes+6; if (dice3==6) catsixes=catsixes+6; if (dice4==6) catsixes=catsixes+6; if (dice5==6) catsixes=catsixes+6; cout << catsixes << endl; } else if ( canUsecatsixes > 0 ){ cout << "You've already used this catagory!" << endl; } } } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/delayed_node/delayed_node_plugin.hpp> #include <graphene/chain/protocol/types.hpp> #include <graphene/chain/database.hpp> #include <graphene/app/api.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/api.hpp> #include <fc/smart_ref_impl.hpp> namespace graphene { namespace delayed_node { namespace bpo = boost::program_options; namespace detail { struct delayed_node_plugin_impl { std::string remote_endpoint; fc::http::websocket_client client; std::shared_ptr<fc::rpc::websocket_api_connection> client_connection; fc::api<graphene::app::database_api> database_api; boost::signals2::scoped_connection client_connection_closed; graphene::chain::block_id_type last_received_remote_head; graphene::chain::block_id_type last_processed_remote_head; }; } delayed_node_plugin::delayed_node_plugin() : my(nullptr) {} delayed_node_plugin::~delayed_node_plugin() {} void delayed_node_plugin::plugin_set_program_options(bpo::options_description& cli, bpo::options_description& cfg) { cli.add_options() ("trusted-node", boost::program_options::value<std::string>(), "RPC endpoint of a trusted validating node (required)") ; cfg.add(cli); } void delayed_node_plugin::connect() { my->client_connection = std::make_shared<fc::rpc::websocket_api_connection>(*my->client.connect(my->remote_endpoint), GRAPHENE_NET_MAX_NESTED_OBJECTS); my->database_api = my->client_connection->get_remote_api<graphene::app::database_api>(0); my->client_connection_closed = my->client_connection->closed.connect([this] { connection_failed(); }); } void delayed_node_plugin::plugin_initialize(const boost::program_options::variables_map& options) { FC_ASSERT(options.count("trusted-node") > 0); my = std::unique_ptr<detail::delayed_node_plugin_impl>{ new detail::delayed_node_plugin_impl() }; my->remote_endpoint = "ws://" + options.at("trusted-node").as<std::string>(); } void delayed_node_plugin::sync_with_trusted_node() { auto& db = database(); uint32_t synced_blocks = 0; uint32_t pass_count = 0; while( true ) { graphene::chain::dynamic_global_property_object remote_dpo = my->database_api->get_dynamic_global_properties(); if( remote_dpo.last_irreversible_block_num <= db.head_block_num() ) { if( remote_dpo.last_irreversible_block_num < db.head_block_num() ) { wlog( "Trusted node seems to be behind delayed node" ); } if( synced_blocks > 1 ) { ilog( "Delayed node finished syncing ${n} blocks in ${k} passes", ("n", synced_blocks)("k", pass_count) ); } break; } pass_count++; while( remote_dpo.last_irreversible_block_num > db.head_block_num() ) { fc::optional<graphene::chain::signed_block> block = my->database_api->get_block( db.head_block_num()+1 ); FC_ASSERT(block, "Trusted node claims it has blocks it doesn't actually have."); ilog("Pushing block #${n}", ("n", block->block_num())); db.push_block(*block); synced_blocks++; } } } void delayed_node_plugin::mainloop() { while( true ) { try { fc::usleep( fc::microseconds( 296645 ) ); // wake up a little over 3Hz if( my->last_received_remote_head == my->last_processed_remote_head ) continue; sync_with_trusted_node(); my->last_processed_remote_head = my->last_received_remote_head; } catch( const fc::exception& e ) { elog("Error during connection: ${e}", ("e", e.to_detail_string())); } } } void delayed_node_plugin::plugin_startup() { fc::async([this]() { mainloop(); }); try { connect(); my->database_api->set_block_applied_callback([this]( const fc::variant& block_id ) { fc::from_variant( block_id, my->last_received_remote_head, GRAPHENE_MAX_NESTED_OBJECTS ); } ); return; } catch (const fc::exception& e) { elog("Error during connection: ${e}", ("e", e.to_detail_string())); } fc::async([this]{connection_failed();}); } void delayed_node_plugin::connection_failed() { elog("Connection to trusted node failed; retrying in 5 seconds..."); fc::schedule([this]{connect();}, fc::time_point::now() + fc::seconds(5)); } } } <commit_msg>Change description of delayed_node option<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/delayed_node/delayed_node_plugin.hpp> #include <graphene/chain/protocol/types.hpp> #include <graphene/chain/database.hpp> #include <graphene/app/api.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/api.hpp> #include <fc/smart_ref_impl.hpp> namespace graphene { namespace delayed_node { namespace bpo = boost::program_options; namespace detail { struct delayed_node_plugin_impl { std::string remote_endpoint; fc::http::websocket_client client; std::shared_ptr<fc::rpc::websocket_api_connection> client_connection; fc::api<graphene::app::database_api> database_api; boost::signals2::scoped_connection client_connection_closed; graphene::chain::block_id_type last_received_remote_head; graphene::chain::block_id_type last_processed_remote_head; }; } delayed_node_plugin::delayed_node_plugin() : my(nullptr) {} delayed_node_plugin::~delayed_node_plugin() {} void delayed_node_plugin::plugin_set_program_options(bpo::options_description& cli, bpo::options_description& cfg) { cli.add_options() ("trusted-node", boost::program_options::value<std::string>(), "RPC endpoint of a trusted validating node (required for delayed_node)") ; cfg.add(cli); } void delayed_node_plugin::connect() { my->client_connection = std::make_shared<fc::rpc::websocket_api_connection>(*my->client.connect(my->remote_endpoint), GRAPHENE_NET_MAX_NESTED_OBJECTS); my->database_api = my->client_connection->get_remote_api<graphene::app::database_api>(0); my->client_connection_closed = my->client_connection->closed.connect([this] { connection_failed(); }); } void delayed_node_plugin::plugin_initialize(const boost::program_options::variables_map& options) { FC_ASSERT(options.count("trusted-node") > 0); my = std::unique_ptr<detail::delayed_node_plugin_impl>{ new detail::delayed_node_plugin_impl() }; my->remote_endpoint = "ws://" + options.at("trusted-node").as<std::string>(); } void delayed_node_plugin::sync_with_trusted_node() { auto& db = database(); uint32_t synced_blocks = 0; uint32_t pass_count = 0; while( true ) { graphene::chain::dynamic_global_property_object remote_dpo = my->database_api->get_dynamic_global_properties(); if( remote_dpo.last_irreversible_block_num <= db.head_block_num() ) { if( remote_dpo.last_irreversible_block_num < db.head_block_num() ) { wlog( "Trusted node seems to be behind delayed node" ); } if( synced_blocks > 1 ) { ilog( "Delayed node finished syncing ${n} blocks in ${k} passes", ("n", synced_blocks)("k", pass_count) ); } break; } pass_count++; while( remote_dpo.last_irreversible_block_num > db.head_block_num() ) { fc::optional<graphene::chain::signed_block> block = my->database_api->get_block( db.head_block_num()+1 ); FC_ASSERT(block, "Trusted node claims it has blocks it doesn't actually have."); ilog("Pushing block #${n}", ("n", block->block_num())); db.push_block(*block); synced_blocks++; } } } void delayed_node_plugin::mainloop() { while( true ) { try { fc::usleep( fc::microseconds( 296645 ) ); // wake up a little over 3Hz if( my->last_received_remote_head == my->last_processed_remote_head ) continue; sync_with_trusted_node(); my->last_processed_remote_head = my->last_received_remote_head; } catch( const fc::exception& e ) { elog("Error during connection: ${e}", ("e", e.to_detail_string())); } } } void delayed_node_plugin::plugin_startup() { fc::async([this]() { mainloop(); }); try { connect(); my->database_api->set_block_applied_callback([this]( const fc::variant& block_id ) { fc::from_variant( block_id, my->last_received_remote_head, GRAPHENE_MAX_NESTED_OBJECTS ); } ); return; } catch (const fc::exception& e) { elog("Error during connection: ${e}", ("e", e.to_detail_string())); } fc::async([this]{connection_failed();}); } void delayed_node_plugin::connection_failed() { elog("Connection to trusted node failed; retrying in 5 seconds..."); fc::schedule([this]{connect();}, fc::time_point::now() + fc::seconds(5)); } } } <|endoftext|>
<commit_before>/** * \file parametercontainer.hh * * \brief containing class ParameterContainer **/ #ifndef DUNE_STUFF_PARAMETERCONTAINER_HH_INCLUDED #define DUNE_STUFF_PARAMETERCONTAINER_HH_INCLUDED #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #if HAVE_DUNE_FEM #include <dune/common/deprecated.hh> #include <dune/fem/io/parameter.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/filesystem.hh> #include <dune/stuff/common/misc.hh> #include <dune/stuff/common/parameter/validation.hh> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <vector> #include <algorithm> #include <fstream> #include <boost/format.hpp> namespace Dune { namespace Stuff { namespace Common { /** * \brief class containing global parameters * \deprecated * ParameterContainer contains all the needed global parameters getting them via Dune::Parameter * **/ class ParameterContainer { public: /** * \brief destuctor * * doing nothing **/ ~ParameterContainer() {} /** * \brief prints all parameters * * \todo implement me * * \param out stream to print to **/ void Print(std::ostream& out) const { out << "\nthis is the ParameterContainer.Print() function" << std::endl; } /** * \brief checks command line parameters * * \return true, if comman line arguments are valid **/ bool ReadCommandLine(int argc, char** argv) { if (argc == 2) { parameter_filename_ = argv[1]; Dune::Parameter::append(parameter_filename_); } else { Dune::Parameter::append(argc, argv); } const std::string datadir = Dune::Parameter::getValidValue(std::string("fem.io.datadir"), std::string("data"), ValidateAny< std::string >() ); Dune::Parameter::append("fem.prefix", datadir); if ( !Dune::Parameter::exists("fem.io.logdir") ) Dune::Parameter::append("fem.io.logdir", "log"); warning_output_ = Dune::Parameter::getValue("disableParameterWarnings", warning_output_); return CheckSetup(); } // ReadCommandLine /** \brief checks for mandatory params * * \return true, if all needed parameters exist **/ bool CheckSetup() { typedef std::vector< std::string >::iterator Iterator; Iterator it = mandatory_params_.begin(); Iterator new_end = std::remove_if(it, mandatory_params_.end(), Dune::Parameter::exists); all_set_up_ = (new_end == it); for ( ; new_end != it; ++it) { std::cerr << "\nError: " << parameter_filename_ << " is missing parameter: " << *it << std::endl; } return all_set_up_; } // CheckSetup /** * \brief prints, how a parameterfile schould look like * * \param out stream to print **/ void PrintParameterSpecs(std::ostream& out) { out << "\na valid parameterfile should at least specify the following parameters:\n" << "Remark: the correspondig files have to exist!\n" << "(copy this into your parameterfile)\n"; std::vector< std::string >::const_iterator it = mandatory_params_.begin(); for ( ; it != mandatory_params_.end(); ++it) std::cerr << *it << ": VALUE\n"; std::cerr << std::endl; } // PrintParameterSpecs std::string DgfFilename(unsigned int dim) const { assert(dim > 0 && dim < 4); assert(all_set_up_); std::string retval = Dune::Parameter::getValue< std::string >( (boost::format("dgf_file_%dd") % dim).str() ); Dune::Parameter::append( (boost::format("fem.io.macroGridFile_%dd") % dim).str(), retval ); return retval; } // DgfFilename /** \brief passthrough to underlying Dune::Parameter * \param useDbgStream * needs to be set to false when using this function in Logging::Create, * otherwise an assertion will will cause streams aren't available yet **/ template< typename T > T getParam(std::string name, T def, bool useDbgStream = true) { return getParam(name, def, ValidateAny< T >(), useDbgStream); } template< typename T, class Validator > T getParam(std::string name, T def, const Validator& validator, bool UNUSED_UNLESS_DEBUG(useDbgStream) = true) { assert(all_set_up_); assert( validator(def) ); #ifndef NDEBUG if ( warning_output_ && !Dune::Parameter::exists(name) ) { if (useDbgStream) Dune::Stuff::Common::Logger().debug() << "WARNING: using default value for parameter \"" << name << "\"" << std::endl; else std::cerr << "WARNING: using default value for parameter \"" << name << "\"" << std::endl; } #endif // ifndef NDEBUG try { return Dune::Parameter::getValidValue(name, def, validator); } catch (Dune::ParameterInvalid& p) { std::cerr << boost::format("Dune::Fem::Parameter reports inconsistent parameter: %s\n") % p.what(); } return def; } // getParam std::map< char, std::string > getFunction(const std::string& name, const std::string def = "0") { std::map< char, std::string > ret; ret['x'] = getParam(name + "_x", def); ret['y'] = getParam(name + "_y", def); ret['z'] = getParam(name + "_z", def); return ret; } // getFunction //! passthrough to underlying Dune::Parameter template< typename T > void setParam(std::string name, T val) { assert(all_set_up_); return Dune::Parameter::append( name, Dune::Stuff::Common::toString(val) ); } //! extension to Fem::paramter that allows vector/list like paramteres from a single key template< class T > std::vector< T > getList(const std::string name, T def) { if ( !Dune::Parameter::exists(name) ) { std::vector< T > ret; ret.push_back(def); return ret; } std::string tokenstring = getParam( name, std::string("dummy") ); std::string delimiter = getParam(std::string("parameterlist_delimiter"), std::string(";"), false); return Dune::Stuff::Common::tokenize< T >(tokenstring, delimiter); } // getList private: bool all_set_up_; bool warning_output_; std::string parameter_filename_; std::vector< std::string > mandatory_params_; /** * \brief constuctor * * \attention call ReadCommandLine() to set up parameterParameterContainer **/ ParameterContainer() : all_set_up_(false) , warning_output_(true) { const std::string p[] = { "dgf_file_2d", "dgf_file_3d" }; mandatory_params_ = std::vector< std::string >( p, p + ( sizeof(p) / sizeof(p[0]) ) ); } friend ParameterContainer& Parameters(); }; //! global ParameterContainer instance ParameterContainer& DUNE_DEPRECATED_MSG("use the Dune::ParameterTree based ConfigParameterContainer instead") Parameters() { static ParameterContainer parameters; return parameters; } //! get a path in datadir with existence guarantee (cannot be in filessytem.hh -- cyclic dep ) std::string getFileinDatadir(const std::string& fn) { boost::filesystem::path path( Config().get( "fem.io.datadir", std::string(".") ) ); path /= fn; boost::filesystem::create_directories( path.parent_path() ); return path.string(); } // getFileinDatadir } // namespace Common } // namespace Stuff } // namespace Dune #endif //HAVE_DUNE_FEM #endif // end of DUNE_STUFF_PARAMETERHANDLER.HH /** Copyright (c) 2012, Rene Milk * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ <commit_msg>[param] delete deprecated parameter container<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2016 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/modules/desktop_capture/win/dxgi_texture_staging.h" #include <comdef.h> #include <unknwn.h> #include <DXGI.h> #include <DXGI1_2.h> #include "webrtc/rtc_base/checks.h" #include "webrtc/rtc_base/logging.h" using Microsoft::WRL::ComPtr; namespace webrtc { DxgiTextureStaging::DxgiTextureStaging(const D3dDevice& device) : device_(device) {} DxgiTextureStaging::~DxgiTextureStaging() = default; bool DxgiTextureStaging::InitializeStage(ID3D11Texture2D* texture) { RTC_DCHECK(texture); D3D11_TEXTURE2D_DESC desc = {0}; texture->GetDesc(&desc); desc.ArraySize = 1; desc.BindFlags = 0; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.MipLevels = 1; desc.MiscFlags = 0; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Usage = D3D11_USAGE_STAGING; if (stage_) { AssertStageAndSurfaceAreSameObject(); D3D11_TEXTURE2D_DESC current_desc; stage_->GetDesc(&current_desc); if (memcmp(&desc, &current_desc, sizeof(D3D11_TEXTURE2D_DESC)) == 0) { return true; } // The descriptions are not consistent, we need to create a new // ID3D11Texture2D instance. stage_.Reset(); surface_.Reset(); } else { RTC_DCHECK(!surface_); } _com_error error = device_.d3d_device()->CreateTexture2D( &desc, nullptr, stage_.GetAddressOf()); if (error.Error() != S_OK || !stage_) { LOG(LS_ERROR) << "Failed to create a new ID3D11Texture2D as stage, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } error = stage_.As(&surface_); if (error.Error() != S_OK || !surface_) { LOG(LS_ERROR) << "Failed to convert ID3D11Texture2D to IDXGISurface, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } return true; } void DxgiTextureStaging::AssertStageAndSurfaceAreSameObject() { ComPtr<IUnknown> left; ComPtr<IUnknown> right; bool left_result = SUCCEEDED(stage_.As(&left)); bool right_result = SUCCEEDED(surface_.As(&right)); RTC_DCHECK(left_result); RTC_DCHECK(right_result); RTC_DCHECK(left.Get() == right.Get()); } bool DxgiTextureStaging::CopyFromTexture( const DXGI_OUTDUPL_FRAME_INFO& frame_info, ID3D11Texture2D* texture) { RTC_DCHECK(texture && frame_info.AccumulatedFrames > 0); // AcquireNextFrame returns a CPU inaccessible IDXGIResource, so we need to // copy it to a CPU accessible staging ID3D11Texture2D. if (!InitializeStage(texture)) { return false; } device_.context()->CopyResource(static_cast<ID3D11Resource*>(stage_.Get()), static_cast<ID3D11Resource*>(texture)); *rect() = {0}; _com_error error = surface_->Map(rect(), DXGI_MAP_READ); if (error.Error() != S_OK) { *rect() = {0}; LOG(LS_ERROR) << "Failed to map the IDXGISurface to a bitmap, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } return true; } bool DxgiTextureStaging::DoRelease() { _com_error error = surface_->Unmap(); if (error.Error() != S_OK) { stage_.Reset(); surface_.Reset(); } // If using staging mode, we only need to recreate ID3D11Texture2D instance. // This will happen during next CopyFrom call. So this function always returns // true. return true; } } // namespace webrtc <commit_msg>Track recreation of DxgiTextureStaging<commit_after>/* * Copyright (c) 2016 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/modules/desktop_capture/win/dxgi_texture_staging.h" #include <comdef.h> #include <unknwn.h> #include <DXGI.h> #include <DXGI1_2.h> #include "webrtc/rtc_base/checks.h" #include "webrtc/rtc_base/logging.h" #include "webrtc/system_wrappers/include/metrics.h" using Microsoft::WRL::ComPtr; namespace webrtc { DxgiTextureStaging::DxgiTextureStaging(const D3dDevice& device) : device_(device) {} DxgiTextureStaging::~DxgiTextureStaging() = default; bool DxgiTextureStaging::InitializeStage(ID3D11Texture2D* texture) { RTC_DCHECK(texture); D3D11_TEXTURE2D_DESC desc = {0}; texture->GetDesc(&desc); desc.ArraySize = 1; desc.BindFlags = 0; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.MipLevels = 1; desc.MiscFlags = 0; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Usage = D3D11_USAGE_STAGING; if (stage_) { AssertStageAndSurfaceAreSameObject(); D3D11_TEXTURE2D_DESC current_desc; stage_->GetDesc(&current_desc); const bool recreate_needed = ( memcmp(&desc, &current_desc, sizeof(D3D11_TEXTURE2D_DESC)) != 0); RTC_HISTOGRAM_BOOLEAN("WebRTC.DesktopCapture.StagingTextureRecreate", recreate_needed); if (!recreate_needed) { return true; } // The descriptions are not consistent, we need to create a new // ID3D11Texture2D instance. stage_.Reset(); surface_.Reset(); } else { RTC_DCHECK(!surface_); } _com_error error = device_.d3d_device()->CreateTexture2D( &desc, nullptr, stage_.GetAddressOf()); if (error.Error() != S_OK || !stage_) { LOG(LS_ERROR) << "Failed to create a new ID3D11Texture2D as stage, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } error = stage_.As(&surface_); if (error.Error() != S_OK || !surface_) { LOG(LS_ERROR) << "Failed to convert ID3D11Texture2D to IDXGISurface, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } return true; } void DxgiTextureStaging::AssertStageAndSurfaceAreSameObject() { ComPtr<IUnknown> left; ComPtr<IUnknown> right; bool left_result = SUCCEEDED(stage_.As(&left)); bool right_result = SUCCEEDED(surface_.As(&right)); RTC_DCHECK(left_result); RTC_DCHECK(right_result); RTC_DCHECK(left.Get() == right.Get()); } bool DxgiTextureStaging::CopyFromTexture( const DXGI_OUTDUPL_FRAME_INFO& frame_info, ID3D11Texture2D* texture) { RTC_DCHECK(texture && frame_info.AccumulatedFrames > 0); // AcquireNextFrame returns a CPU inaccessible IDXGIResource, so we need to // copy it to a CPU accessible staging ID3D11Texture2D. if (!InitializeStage(texture)) { return false; } device_.context()->CopyResource(static_cast<ID3D11Resource*>(stage_.Get()), static_cast<ID3D11Resource*>(texture)); *rect() = {0}; _com_error error = surface_->Map(rect(), DXGI_MAP_READ); if (error.Error() != S_OK) { *rect() = {0}; LOG(LS_ERROR) << "Failed to map the IDXGISurface to a bitmap, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } return true; } bool DxgiTextureStaging::DoRelease() { _com_error error = surface_->Unmap(); if (error.Error() != S_OK) { stage_.Reset(); surface_.Reset(); } // If using staging mode, we only need to recreate ID3D11Texture2D instance. // This will happen during next CopyFrom call. So this function always returns // true. return true; } } // namespace webrtc <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * Copyright (C) 2003-2005 3Dlabs Inc. Ltd. * Copyright (C) 2004-2005 Nathan Cournia * Copyright (C) 2008 Zebra Imaging * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial * applications, as long as this copyright notice is maintained. * * This application 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. * */ /* file: src/osg/GLStaticLibrary.cpp * author: Alok Priyadarshi 2010-04-27 */ #include "GLStaticLibrary.h" #include <osg/GL> #include <osg/Notify> #include <map> #include <string> // This file is intended for GL static linking only. #if defined(OSG_GL_LIBRARY_STATIC) using namespace osg; namespace { typedef void (*GLProc)(void); typedef std::map<std::string, GLProc> GLProcAddressMap; static bool sProcAddressInitialized = false; static GLProcAddressMap sProcAddressMap; #define ADD_FUNCTION(FunctionName) sProcAddressMap[#FunctionName] = reinterpret_cast<GLProc>(&FunctionName); void initGLES2ProcAddress() { ADD_FUNCTION(glActiveTexture) ADD_FUNCTION(glAttachShader) ADD_FUNCTION(glBindAttribLocation) ADD_FUNCTION(glBindBuffer) ADD_FUNCTION(glBindFramebuffer) ADD_FUNCTION(glBindRenderbuffer) ADD_FUNCTION(glBindTexture) ADD_FUNCTION(glBlendColor) ADD_FUNCTION(glBlendEquation) ADD_FUNCTION(glBlendEquationSeparate) ADD_FUNCTION(glBlendFunc) ADD_FUNCTION(glBlendFuncSeparate) ADD_FUNCTION(glBufferData) ADD_FUNCTION(glBufferSubData) ADD_FUNCTION(glCheckFramebufferStatus) ADD_FUNCTION(glClear) ADD_FUNCTION(glClearColor) ADD_FUNCTION(glClearDepthf) ADD_FUNCTION(glClearStencil) ADD_FUNCTION(glColorMask) ADD_FUNCTION(glCompileShader) ADD_FUNCTION(glCompressedTexImage2D) ADD_FUNCTION(glCompressedTexSubImage2D) ADD_FUNCTION(glCopyTexImage2D) ADD_FUNCTION(glCopyTexSubImage2D) ADD_FUNCTION(glCreateProgram) ADD_FUNCTION(glCreateShader) ADD_FUNCTION(glCullFace) ADD_FUNCTION(glDeleteBuffers) ADD_FUNCTION(glDeleteFramebuffers) ADD_FUNCTION(glDeleteProgram) ADD_FUNCTION(glDeleteRenderbuffers) ADD_FUNCTION(glDeleteShader) ADD_FUNCTION(glDeleteTextures) ADD_FUNCTION(glDepthFunc) ADD_FUNCTION(glDepthMask) ADD_FUNCTION(glDepthRangef) ADD_FUNCTION(glDetachShader) ADD_FUNCTION(glDisable) ADD_FUNCTION(glDisableVertexAttribArray) ADD_FUNCTION(glDrawArrays) ADD_FUNCTION(glDrawElements) ADD_FUNCTION(glEnable) ADD_FUNCTION(glEnableVertexAttribArray) ADD_FUNCTION(glFinish) ADD_FUNCTION(glFlush) ADD_FUNCTION(glFramebufferRenderbuffer) ADD_FUNCTION(glFramebufferTexture2D) ADD_FUNCTION(glFrontFace) ADD_FUNCTION(glGenBuffers) ADD_FUNCTION(glGenerateMipmap) ADD_FUNCTION(glGenFramebuffers) ADD_FUNCTION(glGenRenderbuffers) ADD_FUNCTION(glGenTextures) ADD_FUNCTION(glGetActiveAttrib) ADD_FUNCTION(glGetActiveUniform) ADD_FUNCTION(glGetAttachedShaders) ADD_FUNCTION(glGetAttribLocation) ADD_FUNCTION(glGetBooleanv) ADD_FUNCTION(glGetBufferParameteriv) ADD_FUNCTION(glGetError) ADD_FUNCTION(glGetFloatv) ADD_FUNCTION(glGetFramebufferAttachmentParameteriv) ADD_FUNCTION(glGetIntegerv) ADD_FUNCTION(glGetProgramiv) ADD_FUNCTION(glGetProgramInfoLog) ADD_FUNCTION(glGetRenderbufferParameteriv) ADD_FUNCTION(glGetShaderiv) ADD_FUNCTION(glGetShaderInfoLog) ADD_FUNCTION(glGetShaderPrecisionFormat) ADD_FUNCTION(glGetShaderSource) ADD_FUNCTION(glGetString) ADD_FUNCTION(glGetTexParameterfv) ADD_FUNCTION(glGetTexParameteriv) ADD_FUNCTION(glGetUniformfv) ADD_FUNCTION(glGetUniformiv) ADD_FUNCTION(glGetUniformLocation) ADD_FUNCTION(glGetVertexAttribfv) ADD_FUNCTION(glGetVertexAttribiv) ADD_FUNCTION(glGetVertexAttribPointerv) ADD_FUNCTION(glHint) ADD_FUNCTION(glIsBuffer) ADD_FUNCTION(glIsEnabled) ADD_FUNCTION(glIsFramebuffer) ADD_FUNCTION(glIsProgram) ADD_FUNCTION(glIsRenderbuffer) ADD_FUNCTION(glIsShader) ADD_FUNCTION(glIsTexture) ADD_FUNCTION(glLineWidth) ADD_FUNCTION(glLinkProgram) ADD_FUNCTION(glPixelStorei) ADD_FUNCTION(glPolygonOffset) ADD_FUNCTION(glReadPixels) ADD_FUNCTION(glReleaseShaderCompiler) ADD_FUNCTION(glRenderbufferStorage) ADD_FUNCTION(glSampleCoverage) ADD_FUNCTION(glScissor) ADD_FUNCTION(glShaderBinary) ADD_FUNCTION(glShaderSource) ADD_FUNCTION(glStencilFunc) ADD_FUNCTION(glStencilFuncSeparate) ADD_FUNCTION(glStencilMask) ADD_FUNCTION(glStencilMaskSeparate) ADD_FUNCTION(glStencilOp) ADD_FUNCTION(glStencilOpSeparate) ADD_FUNCTION(glTexImage2D) ADD_FUNCTION(glTexParameterf) ADD_FUNCTION(glTexParameterfv) ADD_FUNCTION(glTexParameteri) ADD_FUNCTION(glTexParameteriv) ADD_FUNCTION(glTexSubImage2D) ADD_FUNCTION(glUniform1f) ADD_FUNCTION(glUniform1fv) ADD_FUNCTION(glUniform1i) ADD_FUNCTION(glUniform1iv) ADD_FUNCTION(glUniform2f) ADD_FUNCTION(glUniform2fv) ADD_FUNCTION(glUniform2i) ADD_FUNCTION(glUniform2iv) ADD_FUNCTION(glUniform3f) ADD_FUNCTION(glUniform3fv) ADD_FUNCTION(glUniform3i) ADD_FUNCTION(glUniform3iv) ADD_FUNCTION(glUniform4f) ADD_FUNCTION(glUniform4fv) ADD_FUNCTION(glUniform4i) ADD_FUNCTION(glUniform4iv) ADD_FUNCTION(glUniformMatrix2fv) ADD_FUNCTION(glUniformMatrix3fv) ADD_FUNCTION(glUniformMatrix4fv) ADD_FUNCTION(glUseProgram) ADD_FUNCTION(glValidateProgram) ADD_FUNCTION(glVertexAttrib1f) ADD_FUNCTION(glVertexAttrib1fv) ADD_FUNCTION(glVertexAttrib2f) ADD_FUNCTION(glVertexAttrib2fv) ADD_FUNCTION(glVertexAttrib3f) ADD_FUNCTION(glVertexAttrib3fv) ADD_FUNCTION(glVertexAttrib4f) ADD_FUNCTION(glVertexAttrib4fv) ADD_FUNCTION(glVertexAttribPointer) ADD_FUNCTION(glViewport) } void initProcAddress() { #if defined(OSG_GLES2_AVAILABLE) initGLES2ProcAddress(); #else OSG_NOTICE << "initProcAddress() not implemented for static GL lib yet." << std::endl; #endif } } // namespace void* GLStaticLibrary::getProcAddress(const char* procName) { // TODO(alokp): Add a mutex around sProcAddressInitialized. if (!sProcAddressInitialized) { initProcAddress(); sProcAddressInitialized = true; } GLProcAddressMap::const_iterator iter = sProcAddressMap.find(procName); return iter != sProcAddressMap.end() ? iter->second : 0; } #endif // OSG_GLES2_LIBRARY_STATIC <commit_msg>From Alok Priyadarshi, build fix for gcc.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * Copyright (C) 2003-2005 3Dlabs Inc. Ltd. * Copyright (C) 2004-2005 Nathan Cournia * Copyright (C) 2008 Zebra Imaging * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial * applications, as long as this copyright notice is maintained. * * This application 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. * */ /* file: src/osg/GLStaticLibrary.cpp * author: Alok Priyadarshi 2010-04-27 */ #include "GLStaticLibrary.h" #include <osg/GL> #include <osg/Notify> #include <map> #include <string> // This file is intended for GL static linking only. #if defined(OSG_GL_LIBRARY_STATIC) using namespace osg; namespace { typedef void (*GLProc)(void); typedef std::map<std::string, GLProc> GLProcAddressMap; static bool sProcAddressInitialized = false; static GLProcAddressMap sProcAddressMap; #define ADD_FUNCTION(FunctionName) sProcAddressMap[#FunctionName] = reinterpret_cast<GLProc>(&FunctionName); void initGLES2ProcAddress() { ADD_FUNCTION(glActiveTexture) ADD_FUNCTION(glAttachShader) ADD_FUNCTION(glBindAttribLocation) ADD_FUNCTION(glBindBuffer) ADD_FUNCTION(glBindFramebuffer) ADD_FUNCTION(glBindRenderbuffer) ADD_FUNCTION(glBindTexture) ADD_FUNCTION(glBlendColor) ADD_FUNCTION(glBlendEquation) ADD_FUNCTION(glBlendEquationSeparate) ADD_FUNCTION(glBlendFunc) ADD_FUNCTION(glBlendFuncSeparate) ADD_FUNCTION(glBufferData) ADD_FUNCTION(glBufferSubData) ADD_FUNCTION(glCheckFramebufferStatus) ADD_FUNCTION(glClear) ADD_FUNCTION(glClearColor) ADD_FUNCTION(glClearDepthf) ADD_FUNCTION(glClearStencil) ADD_FUNCTION(glColorMask) ADD_FUNCTION(glCompileShader) ADD_FUNCTION(glCompressedTexImage2D) ADD_FUNCTION(glCompressedTexSubImage2D) ADD_FUNCTION(glCopyTexImage2D) ADD_FUNCTION(glCopyTexSubImage2D) ADD_FUNCTION(glCreateProgram) ADD_FUNCTION(glCreateShader) ADD_FUNCTION(glCullFace) ADD_FUNCTION(glDeleteBuffers) ADD_FUNCTION(glDeleteFramebuffers) ADD_FUNCTION(glDeleteProgram) ADD_FUNCTION(glDeleteRenderbuffers) ADD_FUNCTION(glDeleteShader) ADD_FUNCTION(glDeleteTextures) ADD_FUNCTION(glDepthFunc) ADD_FUNCTION(glDepthMask) ADD_FUNCTION(glDepthRangef) ADD_FUNCTION(glDetachShader) ADD_FUNCTION(glDisable) ADD_FUNCTION(glDisableVertexAttribArray) ADD_FUNCTION(glDrawArrays) ADD_FUNCTION(glDrawElements) ADD_FUNCTION(glEnable) ADD_FUNCTION(glEnableVertexAttribArray) ADD_FUNCTION(glFinish) ADD_FUNCTION(glFlush) ADD_FUNCTION(glFramebufferRenderbuffer) ADD_FUNCTION(glFramebufferTexture2D) ADD_FUNCTION(glFrontFace) ADD_FUNCTION(glGenBuffers) ADD_FUNCTION(glGenerateMipmap) ADD_FUNCTION(glGenFramebuffers) ADD_FUNCTION(glGenRenderbuffers) ADD_FUNCTION(glGenTextures) ADD_FUNCTION(glGetActiveAttrib) ADD_FUNCTION(glGetActiveUniform) ADD_FUNCTION(glGetAttachedShaders) ADD_FUNCTION(glGetAttribLocation) ADD_FUNCTION(glGetBooleanv) ADD_FUNCTION(glGetBufferParameteriv) ADD_FUNCTION(glGetError) ADD_FUNCTION(glGetFloatv) ADD_FUNCTION(glGetFramebufferAttachmentParameteriv) ADD_FUNCTION(glGetIntegerv) ADD_FUNCTION(glGetProgramiv) ADD_FUNCTION(glGetProgramInfoLog) ADD_FUNCTION(glGetRenderbufferParameteriv) ADD_FUNCTION(glGetShaderiv) ADD_FUNCTION(glGetShaderInfoLog) ADD_FUNCTION(glGetShaderPrecisionFormat) ADD_FUNCTION(glGetShaderSource) ADD_FUNCTION(glGetString) ADD_FUNCTION(glGetTexParameterfv) ADD_FUNCTION(glGetTexParameteriv) ADD_FUNCTION(glGetUniformfv) ADD_FUNCTION(glGetUniformiv) ADD_FUNCTION(glGetUniformLocation) ADD_FUNCTION(glGetVertexAttribfv) ADD_FUNCTION(glGetVertexAttribiv) ADD_FUNCTION(glGetVertexAttribPointerv) ADD_FUNCTION(glHint) ADD_FUNCTION(glIsBuffer) ADD_FUNCTION(glIsEnabled) ADD_FUNCTION(glIsFramebuffer) ADD_FUNCTION(glIsProgram) ADD_FUNCTION(glIsRenderbuffer) ADD_FUNCTION(glIsShader) ADD_FUNCTION(glIsTexture) ADD_FUNCTION(glLineWidth) ADD_FUNCTION(glLinkProgram) ADD_FUNCTION(glPixelStorei) ADD_FUNCTION(glPolygonOffset) ADD_FUNCTION(glReadPixels) ADD_FUNCTION(glReleaseShaderCompiler) ADD_FUNCTION(glRenderbufferStorage) ADD_FUNCTION(glSampleCoverage) ADD_FUNCTION(glScissor) ADD_FUNCTION(glShaderBinary) ADD_FUNCTION(glShaderSource) ADD_FUNCTION(glStencilFunc) ADD_FUNCTION(glStencilFuncSeparate) ADD_FUNCTION(glStencilMask) ADD_FUNCTION(glStencilMaskSeparate) ADD_FUNCTION(glStencilOp) ADD_FUNCTION(glStencilOpSeparate) ADD_FUNCTION(glTexImage2D) ADD_FUNCTION(glTexParameterf) ADD_FUNCTION(glTexParameterfv) ADD_FUNCTION(glTexParameteri) ADD_FUNCTION(glTexParameteriv) ADD_FUNCTION(glTexSubImage2D) ADD_FUNCTION(glUniform1f) ADD_FUNCTION(glUniform1fv) ADD_FUNCTION(glUniform1i) ADD_FUNCTION(glUniform1iv) ADD_FUNCTION(glUniform2f) ADD_FUNCTION(glUniform2fv) ADD_FUNCTION(glUniform2i) ADD_FUNCTION(glUniform2iv) ADD_FUNCTION(glUniform3f) ADD_FUNCTION(glUniform3fv) ADD_FUNCTION(glUniform3i) ADD_FUNCTION(glUniform3iv) ADD_FUNCTION(glUniform4f) ADD_FUNCTION(glUniform4fv) ADD_FUNCTION(glUniform4i) ADD_FUNCTION(glUniform4iv) ADD_FUNCTION(glUniformMatrix2fv) ADD_FUNCTION(glUniformMatrix3fv) ADD_FUNCTION(glUniformMatrix4fv) ADD_FUNCTION(glUseProgram) ADD_FUNCTION(glValidateProgram) ADD_FUNCTION(glVertexAttrib1f) ADD_FUNCTION(glVertexAttrib1fv) ADD_FUNCTION(glVertexAttrib2f) ADD_FUNCTION(glVertexAttrib2fv) ADD_FUNCTION(glVertexAttrib3f) ADD_FUNCTION(glVertexAttrib3fv) ADD_FUNCTION(glVertexAttrib4f) ADD_FUNCTION(glVertexAttrib4fv) ADD_FUNCTION(glVertexAttribPointer) ADD_FUNCTION(glViewport) } void initProcAddress() { #if defined(OSG_GLES2_AVAILABLE) initGLES2ProcAddress(); #else OSG_NOTICE << "initProcAddress() not implemented for static GL lib yet." << std::endl; #endif } } // namespace void* GLStaticLibrary::getProcAddress(const char* procName) { // TODO(alokp): Add a mutex around sProcAddressInitialized. if (!sProcAddressInitialized) { initProcAddress(); sProcAddressInitialized = true; } GLProcAddressMap::const_iterator iter = sProcAddressMap.find(procName); return iter != sProcAddressMap.end() ? reinterpret_cast<void*>(iter->second) : 0; } #endif // OSG_GLES2_LIBRARY_STATIC <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------------------- /// \class AliAnalysisTaskSingleMu /// Analysis task for single muons in the spectrometer. /// The output is a list of histograms. /// The macro class can run on AOD or ESDs. /// If Monte Carlo information is present, some basics checks are performed. /// /// \author Diego Stocco //----------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Implementation of the class for trigger chamber efficiency determinaltion //---------------------------------------------------------------------------- #define AliAnalysisTaskTrigChEff_cxx // ROOT includes #include "TH1.h" #include "TCanvas.h" #include "TROOT.h" #include "TString.h" #include "TList.h" // STEER includes #include "AliLog.h" #include "AliESDEvent.h" #include "AliESDMuonTrack.h" // ANALYSIS includes #include "AliAnalysisTaskSE.h" #include "AliAnalysisTaskTrigChEff.h" ClassImp(AliAnalysisTaskTrigChEff) //________________________________________________________________________ AliAnalysisTaskTrigChEff::AliAnalysisTaskTrigChEff(const char *name) : AliAnalysisTaskSE(name), fUseGhosts(kFALSE), fList(0) { // /// Constructor. // // Output slot #1 writes into a TObjArray container DefineOutput(1, TList::Class()); if (fUseGhosts) AliInfo("Use also trigger tracks not matching tracker tracks"); } //________________________________________________________________________ AliAnalysisTaskTrigChEff::~AliAnalysisTaskTrigChEff() { delete fList; } //___________________________________________________________________________ void AliAnalysisTaskTrigChEff::UserCreateOutputObjects() { // /// Create histograms /// Called once // TString cathCode[2] = {"bendPlane", "nonBendPlane"}; TString countTypeName[2] = {"CountInCh", "NonCountInCh"}; const Char_t* yAxisTitle = "counts"; const Int_t kNboards = 234; //AliMpConstants::NofLocalBoards(); const Int_t kFirstTrigCh = 11;//AliMpConstants::NofTrackingChambers()+1; Int_t chamberBins = kNchambers; Float_t chamberLow = kFirstTrigCh-0.5, chamberHigh = kFirstTrigCh+kNchambers-0.5; const Char_t* chamberName = "chamber"; Int_t slatBins = kNslats; Float_t slatLow = 0-0.5, slatHigh = kNslats-0.5; const Char_t* slatName = "slat"; Int_t boardBins = kNboards; Float_t boardLow = 1-0.5, boardHigh = kNboards+1.-0.5; const Char_t* boardName = "board"; Int_t angleBins = 280; Float_t angleLow = -70., angleHigh = 70.; const Char_t* angleNameX = "#theta_{x} (deg)"; const Char_t* angleNameY = "#theta_{y} (deg)"; TString baseName, histoName; fList = new TList(); TH1F* histo; histo = new TH1F("nTracksInSlat", "Num. of tracks used for efficiency calculation", slatBins, slatLow, slatHigh); histo->GetXaxis()->SetTitle(slatName); histo->GetYaxis()->SetTitle("num of used tracks"); fList->AddAt(histo, kHtracksInSlat); histo = new TH1F("nTracksInBoard", "Num. of tracks used for efficiency calculation", boardBins, boardLow, boardHigh); histo->GetXaxis()->SetTitle(boardName); histo->GetYaxis()->SetTitle("num of used tracks"); fList->AddAt(histo, kHtracksInBoard); for(Int_t hType=0; hType<kNcounts; hType++){ Int_t hindex = (hType==0) ? kHchamberEff : kHchamberNonEff; for(Int_t cath=0; cath<kNcathodes; cath++){ histoName = Form("%sChamber%s", cathCode[cath].Data(), countTypeName[hType].Data()); histo = new TH1F(histoName, histoName, chamberBins, chamberLow, chamberHigh); histo->GetXaxis()->SetTitle(chamberName); histo->GetYaxis()->SetTitle(yAxisTitle); fList->AddAt(histo, hindex + cath); } // loop on cath } // loop on counts for(Int_t hType=0; hType<kNcounts; hType++){ Int_t hindex = (hType==0) ? kHslatEff : kHslatNonEff; for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ch=0; ch<kNchambers; ch++){ Int_t chCath = GetPlane(cath, ch); histoName = Form("%sSlat%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch); histo = new TH1F(histoName, histoName, slatBins, slatLow, slatHigh); histo->GetXaxis()->SetTitle(slatName); histo->GetYaxis()->SetTitle(yAxisTitle); fList->AddAt(histo, hindex + chCath); } // loop on chamber } // loop on cath } // loop on counts for(Int_t hType=0; hType<kNcounts; hType++){ Int_t hindex = (hType==0) ? kHboardEff : kHboardNonEff; for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ch=0; ch<kNchambers; ch++){ Int_t chCath = GetPlane(cath, ch); histoName = Form("%sBoard%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch); histo = new TH1F(histoName, histoName, boardBins, boardLow, boardHigh); histo->GetXaxis()->SetTitle(boardName); histo->GetYaxis()->SetTitle(yAxisTitle); fList->AddAt(histo, hindex + chCath); } // loop on chamber } // loop on cath } // loop on counts histo = new TH1F("thetaX", "Angular distribution", angleBins, angleLow, angleHigh); histo->GetXaxis()->SetTitle(angleNameX); histo->GetYaxis()->SetTitle("entries"); fList->AddAt(histo, kHthetaX); histo = new TH1F("thetaY", "Angular distribution", angleBins, angleLow, angleHigh); histo->GetXaxis()->SetTitle(angleNameY); histo->GetYaxis()->SetTitle("entries"); fList->AddAt(histo, kHthetaY); } //________________________________________________________________________ void AliAnalysisTaskTrigChEff::UserExec(Option_t *) { // /// Main loop /// Called for each event // AliESDEvent* esdEvent = dynamic_cast<AliESDEvent*> (InputEvent()); if (!esdEvent) { Printf("ERROR: esdEvent not available\n"); return; } Int_t slat = 0, board = 0; UShort_t pattern = 0; AliESDMuonTrack *esdTrack = 0x0; const Float_t kRadToDeg = 180./TMath::Pi(); Int_t nTracks = esdEvent->GetNumberOfMuonTracks(); const Int_t kFirstTrigCh = 11; //AliMpConstants::NofTrackingChambers()+1; TArrayI othersEfficient(kNchambers); for (Int_t itrack = 0; itrack < nTracks; itrack++) { esdTrack = esdEvent->GetMuonTrack(itrack); if ( ! esdTrack->ContainTrackerData() && ! fUseGhosts ) continue; pattern = esdTrack->GetHitsPatternInTrigCh(); Int_t effFlag = AliESDMuonTrack::GetEffFlag(pattern); if(effFlag < AliESDMuonTrack::kChEff) continue; // Track not good for efficiency calculation ((TH1F*)fList->At(kHthetaX))->Fill(esdTrack->GetThetaX() * kRadToDeg); ((TH1F*)fList->At(kHthetaY))->Fill(esdTrack->GetThetaY() * kRadToDeg); othersEfficient.Reset(1); for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ich=0; ich<kNchambers; ich++){ if( ! AliESDMuonTrack::IsChamberHit(pattern, cath, ich)){ for(Int_t jch=0; jch<kNchambers; jch++){ if ( jch != ich) { othersEfficient[jch] = 0; //AliInfo(Form("%s ch %i by New", baseOutString.Data(), jch)); } } // loop on other chambers break; } // if chamber not efficient } // loop on chambers } // loop on cathodes Bool_t rejectTrack = kTRUE; for (Int_t ich=0; ich<kNchambers; ich++){ if ( othersEfficient[ich] > 0 ){ rejectTrack = kFALSE; break; } } if ( rejectTrack ) continue; slat = AliESDMuonTrack::GetSlatOrInfo(pattern); board = esdTrack->LoCircuit(); if(effFlag >= AliESDMuonTrack::kSlatEff) ((TH1F*)fList->At(kHtracksInSlat))->Fill(slat); if(effFlag >= AliESDMuonTrack::kBoardEff) ((TH1F*)fList->At(kHtracksInBoard))->Fill(board); for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ch=0; ch<kNchambers; ch++){ if ( ! othersEfficient[ch] ) continue; // Reject track if the info of the chamber under study // is necessary to create the track itself Int_t whichType = AliESDMuonTrack::IsChamberHit(pattern, cath, ch) ? kChHit : kChNonHit; Int_t iChamber = kFirstTrigCh + ch; Int_t hindex = ( whichType == kChHit ) ? kHchamberEff : kHchamberNonEff; ((TH1F*)fList->At(hindex + cath))->Fill(iChamber); if(effFlag < AliESDMuonTrack::kSlatEff) continue; // Track crossed different slats Int_t chCath = GetPlane(cath, ch); hindex = ( whichType == kChHit ) ? kHslatEff : kHslatNonEff; ((TH1F*)fList->At(hindex + chCath))->Fill(slat); if(effFlag < AliESDMuonTrack::kBoardEff) continue; // Track crossed different boards hindex = ( whichType == kChHit ) ? kHboardEff : kHboardNonEff; ((TH1F*)fList->At(hindex + chCath))->Fill(board); } // loop on chambers } // loop on cathodes } // loop on tracks // Post final data. It will be written to a file with option "RECREATE" PostData(1, fList); } //________________________________________________________________________ void AliAnalysisTaskTrigChEff::Terminate(Option_t *) { // /// Draw result to the screen /// Called once at the end of the query. // if (!gROOT->IsBatch()) { fList = dynamic_cast<TList*> (GetOutputData(1)); TCanvas *can[kNcathodes]; TH1F *num = 0x0; TH1F *den = 0x0; for(Int_t cath=0; cath<kNcathodes; cath++){ TString canName = Form("can%i",cath); can[cath] = new TCanvas(canName.Data(),canName.Data(),10*(1+cath),10*(1+cath),310,310); can[cath]->SetFillColor(10); can[cath]->SetHighLightColor(10); can[cath]->SetLeftMargin(0.15); can[cath]->SetBottomMargin(0.15); can[cath]->Divide(2,2); for(Int_t ch=0; ch<kNchambers; ch++){ Int_t chCath = GetPlane(cath, ch); num = (TH1F*)(fList->At(kHboardEff + chCath)->Clone()); den = (TH1F*)(fList->At(kHboardNonEff + chCath)->Clone()); den->Add(num); num->Divide(den); can[cath]->cd(ch+1); num->DrawCopy("E"); } } } } <commit_msg>1. Correctly fill the theta values for ghosts. 2. Improve the efficiency plots in the terminate function (Diego)<commit_after>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------------------- /// \class AliAnalysisTaskSingleMu /// Analysis task for single muons in the spectrometer. /// The output is a list of histograms. /// The macro class can run on AOD or ESDs. /// If Monte Carlo information is present, some basics checks are performed. /// /// \author Diego Stocco //----------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Implementation of the class for trigger chamber efficiency determinaltion //---------------------------------------------------------------------------- #define AliAnalysisTaskTrigChEff_cxx // ROOT includes #include "TH1.h" #include "TCanvas.h" #include "TROOT.h" #include "TString.h" #include "TList.h" #include "TGraphAsymmErrors.h" // STEER includes #include "AliLog.h" #include "AliESDEvent.h" #include "AliESDMuonTrack.h" // ANALYSIS includes #include "AliAnalysisTaskSE.h" #include "AliAnalysisTaskTrigChEff.h" ClassImp(AliAnalysisTaskTrigChEff) //________________________________________________________________________ AliAnalysisTaskTrigChEff::AliAnalysisTaskTrigChEff(const char *name) : AliAnalysisTaskSE(name), fUseGhosts(kFALSE), fList(0) { // /// Constructor. // // Output slot #1 writes into a TObjArray container DefineOutput(1, TList::Class()); } //________________________________________________________________________ AliAnalysisTaskTrigChEff::~AliAnalysisTaskTrigChEff() { delete fList; } //___________________________________________________________________________ void AliAnalysisTaskTrigChEff::UserCreateOutputObjects() { // /// Create histograms /// Called once // TString cathCode[2] = {"bendPlane", "nonBendPlane"}; TString countTypeName[2] = {"CountInCh", "NonCountInCh"}; const Char_t* yAxisTitle = "counts"; const Int_t kNboards = 234; //AliMpConstants::NofLocalBoards(); const Int_t kFirstTrigCh = 11;//AliMpConstants::NofTrackingChambers()+1; Int_t chamberBins = kNchambers; Float_t chamberLow = kFirstTrigCh-0.5, chamberHigh = kFirstTrigCh+kNchambers-0.5; const Char_t* chamberName = "chamber"; Int_t slatBins = kNslats; Float_t slatLow = 0-0.5, slatHigh = kNslats-0.5; const Char_t* slatName = "slat"; Int_t boardBins = kNboards; Float_t boardLow = 1-0.5, boardHigh = kNboards+1.-0.5; const Char_t* boardName = "board"; Int_t angleBins = 280; Float_t angleLow = -70., angleHigh = 70.; const Char_t* angleNameX = "#theta_{x} (deg)"; const Char_t* angleNameY = "#theta_{y} (deg)"; TString baseName, histoName; fList = new TList(); TH1F* histo; histo = new TH1F("nTracksInSlat", "Num. of tracks used for efficiency calculation", slatBins, slatLow, slatHigh); histo->GetXaxis()->SetTitle(slatName); histo->GetYaxis()->SetTitle("num of used tracks"); fList->AddAt(histo, kHtracksInSlat); histo = new TH1F("nTracksInBoard", "Num. of tracks used for efficiency calculation", boardBins, boardLow, boardHigh); histo->GetXaxis()->SetTitle(boardName); histo->GetYaxis()->SetTitle("num of used tracks"); fList->AddAt(histo, kHtracksInBoard); for(Int_t hType=0; hType<kNcounts; hType++){ Int_t hindex = (hType==0) ? kHchamberEff : kHchamberNonEff; for(Int_t cath=0; cath<kNcathodes; cath++){ histoName = Form("%sChamber%s", cathCode[cath].Data(), countTypeName[hType].Data()); histo = new TH1F(histoName, histoName, chamberBins, chamberLow, chamberHigh); histo->GetXaxis()->SetTitle(chamberName); histo->GetYaxis()->SetTitle(yAxisTitle); fList->AddAt(histo, hindex + cath); } // loop on cath } // loop on counts for(Int_t hType=0; hType<kNcounts; hType++){ Int_t hindex = (hType==0) ? kHslatEff : kHslatNonEff; for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ch=0; ch<kNchambers; ch++){ Int_t chCath = GetPlane(cath, ch); histoName = Form("%sSlat%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch); histo = new TH1F(histoName, histoName, slatBins, slatLow, slatHigh); histo->GetXaxis()->SetTitle(slatName); histo->GetYaxis()->SetTitle(yAxisTitle); fList->AddAt(histo, hindex + chCath); } // loop on chamber } // loop on cath } // loop on counts for(Int_t hType=0; hType<kNcounts; hType++){ Int_t hindex = (hType==0) ? kHboardEff : kHboardNonEff; for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ch=0; ch<kNchambers; ch++){ Int_t chCath = GetPlane(cath, ch); histoName = Form("%sBoard%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch); histo = new TH1F(histoName, histoName, boardBins, boardLow, boardHigh); histo->GetXaxis()->SetTitle(boardName); histo->GetYaxis()->SetTitle(yAxisTitle); fList->AddAt(histo, hindex + chCath); } // loop on chamber } // loop on cath } // loop on counts histo = new TH1F("thetaX", "Angular distribution", angleBins, angleLow, angleHigh); histo->GetXaxis()->SetTitle(angleNameX); histo->GetYaxis()->SetTitle("entries"); fList->AddAt(histo, kHthetaX); histo = new TH1F("thetaY", "Angular distribution", angleBins, angleLow, angleHigh); histo->GetXaxis()->SetTitle(angleNameY); histo->GetYaxis()->SetTitle("entries"); fList->AddAt(histo, kHthetaY); } //________________________________________________________________________ void AliAnalysisTaskTrigChEff::UserExec(Option_t *) { // /// Main loop /// Called for each event // AliESDEvent* esdEvent = dynamic_cast<AliESDEvent*> (InputEvent()); if (!esdEvent) { Printf("ERROR: esdEvent not available\n"); return; } Int_t slat = 0, board = 0; UShort_t pattern = 0; AliESDMuonTrack *esdTrack = 0x0; Int_t nTracks = esdEvent->GetNumberOfMuonTracks(); const Int_t kFirstTrigCh = 11; //AliMpConstants::NofTrackingChambers()+1; TArrayI othersEfficient(kNchambers); for (Int_t itrack = 0; itrack < nTracks; itrack++) { esdTrack = esdEvent->GetMuonTrack(itrack); if ( ! esdTrack->ContainTrackerData() && ! fUseGhosts ) continue; pattern = esdTrack->GetHitsPatternInTrigCh(); Int_t effFlag = AliESDMuonTrack::GetEffFlag(pattern); if(effFlag < AliESDMuonTrack::kChEff) continue; // Track not good for efficiency calculation ((TH1F*)fList->At(kHthetaX))->Fill(esdTrack->GetThetaXUncorrected() * TMath::RadToDeg()); ((TH1F*)fList->At(kHthetaY))->Fill(esdTrack->GetThetaYUncorrected() * TMath::RadToDeg()); othersEfficient.Reset(1); for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ich=0; ich<kNchambers; ich++){ if( ! AliESDMuonTrack::IsChamberHit(pattern, cath, ich)){ for(Int_t jch=0; jch<kNchambers; jch++){ if ( jch != ich) { othersEfficient[jch] = 0; //AliInfo(Form("%s ch %i by New", baseOutString.Data(), jch)); } } // loop on other chambers break; } // if chamber not efficient } // loop on chambers } // loop on cathodes Bool_t rejectTrack = kTRUE; for (Int_t ich=0; ich<kNchambers; ich++){ if ( othersEfficient[ich] > 0 ){ rejectTrack = kFALSE; break; } } if ( rejectTrack ) continue; slat = AliESDMuonTrack::GetSlatOrInfo(pattern); board = esdTrack->LoCircuit(); if(effFlag >= AliESDMuonTrack::kSlatEff) ((TH1F*)fList->At(kHtracksInSlat))->Fill(slat); if(effFlag >= AliESDMuonTrack::kBoardEff) ((TH1F*)fList->At(kHtracksInBoard))->Fill(board); for(Int_t cath=0; cath<kNcathodes; cath++){ for(Int_t ch=0; ch<kNchambers; ch++){ if ( ! othersEfficient[ch] ) continue; // Reject track if the info of the chamber under study // is necessary to create the track itself Int_t whichType = AliESDMuonTrack::IsChamberHit(pattern, cath, ch) ? kChHit : kChNonHit; Int_t iChamber = kFirstTrigCh + ch; Int_t hindex = ( whichType == kChHit ) ? kHchamberEff : kHchamberNonEff; ((TH1F*)fList->At(hindex + cath))->Fill(iChamber); if(effFlag < AliESDMuonTrack::kSlatEff) continue; // Track crossed different slats Int_t chCath = GetPlane(cath, ch); hindex = ( whichType == kChHit ) ? kHslatEff : kHslatNonEff; ((TH1F*)fList->At(hindex + chCath))->Fill(slat); if(effFlag < AliESDMuonTrack::kBoardEff) continue; // Track crossed different boards hindex = ( whichType == kChHit ) ? kHboardEff : kHboardNonEff; ((TH1F*)fList->At(hindex + chCath))->Fill(board); } // loop on chambers } // loop on cathodes } // loop on tracks // Post final data. It will be written to a file with option "RECREATE" PostData(1, fList); } //________________________________________________________________________ void AliAnalysisTaskTrigChEff::Terminate(Option_t *) { // /// Draw result to the screen /// Called once at the end of the query. // if ( gROOT->IsBatch() ) return; fList = dynamic_cast<TList*> (GetOutputData(1)); TCanvas *can; TH1F *num = 0x0; TH1F *den = 0x0; TGraphAsymmErrors* effGraph = 0x0; TString baseName[3] = {"Chamber", "RPC", "Board"}; Int_t baseIndex1[3] = {kHchamberEff, kHslatEff, kHboardEff}; Int_t baseIndex2[3] = {kHchamberNonEff, kHslatNonEff, kHboardNonEff}; TString cathName[2] = {"BendPlane", "NonBendPlane"}; for (Int_t itype=0; itype<3; itype++) { for(Int_t cath=0; cath<kNcathodes; cath++){ TString canName = Form("efficiencyPer%s_%s",baseName[itype].Data(),cathName[cath].Data()); can = new TCanvas(canName.Data(),canName.Data(),10*(1+2*itype+cath),10*(1+2*itype+cath),310,310); can->SetFillColor(10); can->SetHighLightColor(10); can->SetLeftMargin(0.15); can->SetBottomMargin(0.15); if ( itype > 0 ) can->Divide(2,2); for(Int_t ch=0; ch<kNchambers; ch++){ Int_t chCath = ( itype == 0 ) ? cath : GetPlane(cath, ch); num = (TH1F*)(fList->At(baseIndex1[itype] + chCath)->Clone()); den = (TH1F*)(fList->At(baseIndex2[itype] + chCath)->Clone()); den->Add(num); effGraph = new TGraphAsymmErrors(num, den); effGraph->GetYaxis()->SetRangeUser(0., 1.1); effGraph->GetYaxis()->SetTitle("Efficiency"); effGraph->GetXaxis()->SetTitle(baseName[itype].Data()); can->cd(ch+1); effGraph->Draw("AP"); if ( itype == 0 ) break; } // loop on chamber } // loop on cathode } // loop on histo } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 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/modules/desktop_capture/window_capturer.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/desktop_capture/desktop_capture_options.h" #include "webrtc/modules/desktop_capture/desktop_frame.h" #include "webrtc/modules/desktop_capture/desktop_region.h" #include "webrtc/system_wrappers/interface/logging.h" namespace webrtc { class WindowCapturerTest : public testing::Test, public DesktopCapturer::Callback { public: void SetUp() override { capturer_.reset( WindowCapturer::Create(DesktopCaptureOptions::CreateDefault())); } void TearDown() override {} // DesktopCapturer::Callback interface SharedMemory* CreateSharedMemory(size_t size) override { return NULL; } void OnCaptureCompleted(DesktopFrame* frame) override { frame_.reset(frame); } protected: rtc::scoped_ptr<WindowCapturer> capturer_; rtc::scoped_ptr<DesktopFrame> frame_; }; // Verify that we can enumerate windows. TEST_F(WindowCapturerTest, Enumerate) { WindowCapturer::WindowList windows; EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Verify that window titles are set. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { EXPECT_FALSE(it->title.empty()); } } // Verify we can capture a window. // // TODO(sergeyu): Currently this test just looks at the windows that already // exist. Ideally it should create a test window and capture from it, but there // is no easy cross-platform way to create new windows (potentially we could // have a python script showing Tk dialog, but launching code will differ // between platforms). TEST_F(WindowCapturerTest, Capture) { WindowCapturer::WindowList windows; capturer_->Start(this); EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Verify that we can select and capture each window. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { frame_.reset(); if (capturer_->SelectWindow(it->id)) { capturer_->Capture(DesktopRegion()); } // If we failed to capture a window make sure it no longer exists. if (!frame_.get()) { WindowCapturer::WindowList new_list; EXPECT_TRUE(capturer_->GetWindowList(&new_list)); for (WindowCapturer::WindowList::iterator new_list_it = windows.begin(); new_list_it != windows.end(); ++new_list_it) { EXPECT_FALSE(it->id == new_list_it->id); } continue; } EXPECT_GT(frame_->size().width(), 0); EXPECT_GT(frame_->size().height(), 0); } } } // namespace webrtc <commit_msg>Fix an apparent typo in a unittest that caused it to not actually check the new window list it fetched.<commit_after>/* * Copyright (c) 2013 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/modules/desktop_capture/window_capturer.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/desktop_capture/desktop_capture_options.h" #include "webrtc/modules/desktop_capture/desktop_frame.h" #include "webrtc/modules/desktop_capture/desktop_region.h" #include "webrtc/system_wrappers/interface/logging.h" namespace webrtc { class WindowCapturerTest : public testing::Test, public DesktopCapturer::Callback { public: void SetUp() override { capturer_.reset( WindowCapturer::Create(DesktopCaptureOptions::CreateDefault())); } void TearDown() override {} // DesktopCapturer::Callback interface SharedMemory* CreateSharedMemory(size_t size) override { return NULL; } void OnCaptureCompleted(DesktopFrame* frame) override { frame_.reset(frame); } protected: rtc::scoped_ptr<WindowCapturer> capturer_; rtc::scoped_ptr<DesktopFrame> frame_; }; // Verify that we can enumerate windows. TEST_F(WindowCapturerTest, Enumerate) { WindowCapturer::WindowList windows; EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Verify that window titles are set. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { EXPECT_FALSE(it->title.empty()); } } // Verify we can capture a window. // // TODO(sergeyu): Currently this test just looks at the windows that already // exist. Ideally it should create a test window and capture from it, but there // is no easy cross-platform way to create new windows (potentially we could // have a python script showing Tk dialog, but launching code will differ // between platforms). TEST_F(WindowCapturerTest, Capture) { WindowCapturer::WindowList windows; capturer_->Start(this); EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Verify that we can select and capture each window. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { frame_.reset(); if (capturer_->SelectWindow(it->id)) { capturer_->Capture(DesktopRegion()); } // If we failed to capture a window make sure it no longer exists. if (!frame_.get()) { WindowCapturer::WindowList new_list; EXPECT_TRUE(capturer_->GetWindowList(&new_list)); for (WindowCapturer::WindowList::iterator new_list_it = new_list.begin(); new_list_it != new_list.end(); ++new_list_it) { EXPECT_FALSE(it->id == new_list_it->id); } continue; } EXPECT_GT(frame_->size().width(), 0); EXPECT_GT(frame_->size().height(), 0); } } } // namespace webrtc <|endoftext|>
<commit_before>/// @brief provides CORDIC for cos function /// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures" #include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp" namespace std { template<typename T, size_t n, size_t f, class op, class up> utils::number<T, n, f, op, up> cos(utils::number<T, n, f, op, up> const& val) { #define pi fixed_point(3.141592653589793) #define pi2 fixed_point(6.283185307179586) #define pi_half fixed_point(1.5707963267948965) typedef utils::number<T, n, f, op, up> fixed_point; using utils::cordic::lut; BOOST_STATIC_ASSERT(std::numeric_limits<fixed_point>::is_signed); // convergence interval for CORDIC rotations is [-pi/2, pi/2]. // So one has to map input angle to that interval fixed_point arg(0); int sign(-1); { // put argument to [-pi, pi] interval (with change of sign for // cos) fixed_point const x = pi - std::fmod(val, pi2); if (x < -pi_half) { // convert to interval [-pi/2, pi/2] arg = x + pi; sign = 1; } else if (x > pi_half) { arg = x - pi; sign = 1; } else { arg = x; } } typedef lut<f, fixed_point> lut_type; static lut_type const angles = lut_type::build_arctan_lut(); // normalization factor: see page 10, table 24.1 and pages 4-5, equations // (5)-(6) // factor converges to the limit 1.64676 very fast: it tooks 8 iterations // only. 8 iterations correpsonds to precision of size 0.007812 for // angle approximation static fixed_point norm_factor(1.0 / lut_type::compute_circular_scale(f)); // rotation mode: see page 6 // shift sequence is just 0, 1, ... (circular coordinate system) fixed_point x(norm_factor), y(0.0), z(arg); fixed_point x1, y1, z1; BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1)) { int const sign = (z > fixed_point(0)) ? 1 : -1; fixed_point const x_scaled = fixed_point::wrap(sign * (x.value() >> i)); fixed_point const y_scaled = fixed_point::wrap(sign * (y.value() >> i)); x1 = fixed_point(x - y_scaled); y1 = fixed_point(y + x_scaled); z1 = fixed_point(z - fixed_point((sign > 0) ? angles[i] : -angles[i])); x = x1; y = y1; z = z1; } return (sign > 0) ? x : - x; #undef pi #undef pi2 #undef pi_half } } <commit_msg>cos.inl: core namespace + 'number' -> 'fixed_point' + using of math constants from fixed-point class<commit_after>/// @brief provides CORDIC for cos function /// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures" #include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp" namespace std { template<typename T, size_t n, size_t f, class op, class up> core::fixed_point<T, n, f, op, up> cos(core::fixed_point<T, n, f, op, up> const& val) { typedef core::fixed_point<T, n, f, op, up> fp; using core::cordic::lut; BOOST_STATIC_ASSERT(std::numeric_limits<fixed_point>::is_signed); // convergence interval for CORDIC rotations is [-pi/2, pi/2]. // So one has to map input angle to that interval fp arg(0); int sign(-1); { // put argument to [-pi, pi] interval (with change of sign for // cos) fp const x = fp::CONST_PI - std::fmod(val, fp::CONST_2PI); if (x < -fp::CONST_PI_2) { // convert to interval [-pi/2, pi/2] arg = x + fp::CONST_PI; sign = 1; } else if (x > fp::CONST_PI_2) { arg = x - fp::CONST_PI; sign = 1; } else { arg = x; } } typedef lut<f, fp> lut_type; static lut_type const angles = lut_type::build_arctan_lut(); // normalization factor: see page 10, table 24.1 and pages 4-5, equations // (5)-(6) // factor converges to the limit 1.64676 very fast: it tooks 8 iterations // only. 8 iterations correpsonds to precision of size 0.007812 for // angle approximation static fp norm_factor(1.0 / lut_type::compute_circular_scale(f)); // rotation mode: see page 6 // shift sequence is just 0, 1, ... (circular coordinate system) fp x(norm_factor), y(0.0), z(arg); fp x1, y1, z1; BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1)) { int const sign = (z > fp(0)) ? 1 : -1; fp const x_scaled = fp::wrap(sign * (x.value() >> i)); fp const y_scaled = fp::wrap(sign * (y.value() >> i)); x1 = fp(x - y_scaled); y1 = fp(y + x_scaled); z1 = fp(z - fp((sign > 0) ? angles[i] : -angles[i])); x = x1; y = y1; z = z1; } return (sign > 0) ? x : - x; } } <|endoftext|>
<commit_before>#include "PropertySetting.h" #include "Sprite.h" #include "Symbol.h" #include <sprite2/UpdateParams.h> #include <ee/panel_msg.h> namespace libanim { PropertySetting::PropertySetting(ee::EditPanelImpl* edit_impl, Sprite* spr) : ee::SpritePropertySetting(edit_impl, spr) { m_type = "Animation"; } void PropertySetting::OnPropertyGridChange(const std::string& name, const wxAny& value) { ee::SpritePropertySetting::OnPropertyGridChange(name, value); Sprite* spr = static_cast<Sprite*>(GetSprite()); if (name == "Loop") { spr->SetLoop(wxANY_AS(value, bool)); } else if (name == "Interval") { spr->SetInterval(wxANY_AS(value, float)); } else if (name == "FPS") { spr->SetFPS(wxANY_AS(value, int)); } else if (name == "Start Random") { spr->SetStartRandom(s2::UpdateParams(), wxANY_AS(value, bool)); } else if (name == "Static") { spr->SetStaticTime(wxANY_AS(value, int)); spr->SetActive(false, NULL); ee::SetCanvasDirtySJ::Instance()->SetDirty(); } else if (name == "Active") { spr->SetActive(wxANY_AS(value, bool), NULL); } } void PropertySetting::UpdateProperties(wxPropertyGrid* pg) { ee::SpritePropertySetting::UpdateProperties(pg); Sprite* spr = static_cast<Sprite*>(GetSprite()); pg->GetProperty("Loop")->SetValue(spr->IsLoop()); pg->GetProperty("Interval")->SetValue(spr->GetInterval()); pg->GetProperty("FPS")->SetValue(spr->GetFPS()); pg->GetProperty("Start Random")->SetValue(spr->IsStartRandom()); pg->GetProperty("Static")->SetValue(spr->GetStaticTime()); pg->GetProperty("Active")->SetValue(spr->IsActive()); } void PropertySetting::InitProperties(wxPropertyGrid* pg) { ee::SpritePropertySetting::InitProperties(pg); pg->Append(new wxPropertyCategory("ANIMATION", wxPG_LABEL)); Sprite* spr = static_cast<Sprite*>(GetSprite()); pg->Append(new wxBoolProperty("Loop", wxPG_LABEL, spr->IsLoop())); pg->SetPropertyAttribute("Loop", wxPG_BOOL_USE_CHECKBOX, spr->IsLoop(), wxPG_RECURSE); pg->Append(new wxFloatProperty("Interval", wxPG_LABEL, spr->GetInterval())); pg->Append(new wxIntProperty("FPS", wxPG_LABEL, spr->GetFPS())); pg->Append(new wxBoolProperty("Start Random", wxPG_LABEL, spr->IsStartRandom())); pg->SetPropertyAttribute("Start Random", wxPG_BOOL_USE_CHECKBOX, spr->IsStartRandom(), wxPG_RECURSE); wxIntProperty* static_prop = new wxIntProperty("Static", wxPG_LABEL, spr->GetStaticTime()); static_prop->SetValue(spr->GetStaticTime()); pg->Append(static_prop); pg->Append(new wxBoolProperty("Active", wxPG_LABEL, spr->IsActive())); pg->SetPropertyAttribute("Active", wxPG_BOOL_USE_CHECKBOX, spr->IsLoop(), wxPG_RECURSE); } }<commit_msg>[FIXED] anim property's wxPG_BOOL_USE_CHECKBOX<commit_after>#include "PropertySetting.h" #include "Sprite.h" #include "Symbol.h" #include <sprite2/UpdateParams.h> #include <ee/panel_msg.h> namespace libanim { PropertySetting::PropertySetting(ee::EditPanelImpl* edit_impl, Sprite* spr) : ee::SpritePropertySetting(edit_impl, spr) { m_type = "Animation"; } void PropertySetting::OnPropertyGridChange(const std::string& name, const wxAny& value) { ee::SpritePropertySetting::OnPropertyGridChange(name, value); Sprite* spr = static_cast<Sprite*>(GetSprite()); if (name == "Loop") { spr->SetLoop(wxANY_AS(value, bool)); } else if (name == "Interval") { spr->SetInterval(wxANY_AS(value, float)); } else if (name == "FPS") { spr->SetFPS(wxANY_AS(value, int)); } else if (name == "Start Random") { spr->SetStartRandom(s2::UpdateParams(), wxANY_AS(value, bool)); } else if (name == "Static") { spr->SetStaticTime(wxANY_AS(value, int)); spr->SetActive(false, NULL); ee::SetCanvasDirtySJ::Instance()->SetDirty(); } else if (name == "Active") { spr->SetActive(wxANY_AS(value, bool), NULL); } } void PropertySetting::UpdateProperties(wxPropertyGrid* pg) { ee::SpritePropertySetting::UpdateProperties(pg); Sprite* spr = static_cast<Sprite*>(GetSprite()); pg->GetProperty("Loop")->SetValue(spr->IsLoop()); pg->GetProperty("Interval")->SetValue(spr->GetInterval()); pg->GetProperty("FPS")->SetValue(spr->GetFPS()); pg->GetProperty("Start Random")->SetValue(spr->IsStartRandom()); pg->GetProperty("Static")->SetValue(spr->GetStaticTime()); pg->GetProperty("Active")->SetValue(spr->IsActive()); } void PropertySetting::InitProperties(wxPropertyGrid* pg) { ee::SpritePropertySetting::InitProperties(pg); pg->Append(new wxPropertyCategory("ANIMATION", wxPG_LABEL)); Sprite* spr = static_cast<Sprite*>(GetSprite()); pg->Append(new wxBoolProperty("Loop", wxPG_LABEL, spr->IsLoop())); pg->SetPropertyAttribute("Loop", wxPG_BOOL_USE_CHECKBOX, true, wxPG_RECURSE); pg->Append(new wxFloatProperty("Interval", wxPG_LABEL, spr->GetInterval())); pg->Append(new wxIntProperty("FPS", wxPG_LABEL, spr->GetFPS())); pg->Append(new wxBoolProperty("Start Random", wxPG_LABEL, spr->IsStartRandom())); pg->SetPropertyAttribute("Start Random", wxPG_BOOL_USE_CHECKBOX, true, wxPG_RECURSE); wxIntProperty* static_prop = new wxIntProperty("Static", wxPG_LABEL, spr->GetStaticTime()); static_prop->SetValue(spr->GetStaticTime()); pg->Append(static_prop); pg->Append(new wxBoolProperty("Active", wxPG_LABEL, spr->IsActive())); pg->SetPropertyAttribute("Active", wxPG_BOOL_USE_CHECKBOX, true, wxPG_RECURSE); } }<|endoftext|>
<commit_before>#include "locomotion_control.h" Locomotion_Control::Locomotion_Control(ros::NodeHandle* nh, AL::ALMotionProxy* mProxy) { nh_ = nh; mProxy_ = mProxy; INFO("Setting up Nao locomotion publishers" << std::endl); moving_pub_ = nh_->advertise<std_msgs::Bool>("isMoving", 10); INFO("Setting up Nao motion publishers" << std::endl); srv_move_ = nh_->advertiseService("move", &Locomotion_Control::move, this); srv_move_to_ = nh_->advertiseService("moveTo", &Locomotion_Control::moveTo, this); srv_move_toward_ = nh_->advertiseService("moveToward", &Locomotion_Control::moveToward, this); srv_move_init_ = nh_->advertiseService("moveInit", &Locomotion_Control::moveInit, this); srv_wait_move_finished_ = nh_->advertiseService("waitMoveFinish", &Locomotion_Control::waitUntilMoveIsFinished, this); srv_stop_move_ = nh_->advertiseService("stopMove", &Locomotion_Control::stopMove, this); srv_get_move_config_ = nh_->advertiseService("getMoveConfig", &Locomotion_Control::getMoveConfig, this); srv_get_robot_position_ = nh_->advertiseService("getRobotPosition", &Locomotion_Control::getRobotPosition, this); srv_get_next_robot_position_ = nh_->advertiseService("getNextRobotPosition", &Locomotion_Control::getNextRobotPosition, this); srv_get_robot_velocity_ = nh_->advertiseService("getRobotVelocity", &Locomotion_Control::getRobotVelocity, this); srv_get_walk_arms_enabled_ = nh_->advertiseService("getWalkArmsEnabled", &Locomotion_Control::getWalkArmsEnabled, this); srv_set_walk_arms_enabled_ = nh_->advertiseService("setWalkArmsEnabled", &Locomotion_Control::setWalkArmsEnabled, this); } Locomotion_Control::~Locomotion_Control() { ros::shutdown(); } bool Locomotion_Control::move(motion::move::Request &req, motion::move::Response &res) { // Check for size of moveConfiguration int configSize = req.moveConfiguration.names.size(); AL::ALValue moveConfiguration; if (configSize > 0) { moveConfiguration.arraySetSize(configSize); for (int i = 0; i < configSize; ++i) { moveConfiguration[i] = AL::ALValue::array( req.moveConfiguration.names[i], req.moveConfiguration.values[i]); } } res.res = true; if (configSize == 0) { mProxy_->move(req.targetVelocity.x, req.targetVelocity.y, req.targetVelocity.theta); } else if (configSize > 0) { mProxy_->move(req.targetVelocity.x, req.targetVelocity.y, req.targetVelocity.theta, moveConfiguration); } else { res.res = false; } return true; } bool Locomotion_Control::moveTo(motion::moveTo::Request &req, motion::moveTo::Response &res) { // Check for multiple positions int posNum = req.controlPoints.size(); AL::ALValue controlPoints; if (posNum > 1) { controlPoints.arraySetSize(posNum); for (int i = 0; i < posNum; ++i) { controlPoints[i] = AL::ALValue::array(req.controlPoints[i].x, req.controlPoints[i].y, req.controlPoints[i].theta); } } // Check for size of moveConfiguration int configSize = req.moveConfiguration.names.size(); AL::ALValue moveConfiguration; if (configSize > 0) { moveConfiguration.arraySetSize(configSize); for (int i = 0; i < configSize; ++i) { moveConfiguration[i] = AL::ALValue::array( req.moveConfiguration.names[i], req.moveConfiguration.values[i]); } } res.res = true; if (posNum == 1 && configSize == 0) { mProxy_->post.moveTo(req.controlPoints[0].x, req.controlPoints[0].y, req.controlPoints[0].theta); } else if (posNum > 1 && configSize == 0) { mProxy_->post.moveTo(controlPoints); } else if (posNum == 1 && configSize > 0) { mProxy_->post.moveTo(req.controlPoints[0].x, req.controlPoints[0].y, req.controlPoints[0].theta, moveConfiguration); } else if (posNum > 1 && configSize > 0) { mProxy_->post.moveTo(controlPoints, moveConfiguration); } else { res.res = false; } return true; } bool Locomotion_Control::moveToward(motion::moveToward::Request &req, motion::moveToward::Response &res) { // Check for size of moveConfiguration int configSize = req.moveConfiguration.names.size(); AL::ALValue moveConfiguration; if (configSize > 0) { moveConfiguration.arraySetSize(configSize); for (int i = 0; i < configSize; ++i) { moveConfiguration[i] = AL::ALValue::array( req.moveConfiguration.names[i], req.moveConfiguration.values[i]); } } res.res = true; if (configSize == 0) { mProxy_->moveToward(req.normVelocity.x, req.normVelocity.y, req.normVelocity.theta); } else if (configSize > 0) { mProxy_->moveToward(req.normVelocity.x, req.normVelocity.y, req.normVelocity.theta, moveConfiguration); } else { res.res = false; } return true; } bool Locomotion_Control::moveInit(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { mProxy_->moveInit(); return true; } bool Locomotion_Control::waitUntilMoveIsFinished( std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { mProxy_->waitUntilMoveIsFinished(); return true; } bool Locomotion_Control::moveIsActive() { mProxy_->moveIsActive(); return true; } bool Locomotion_Control::stopMove(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { mProxy_->stopMove(); return true; } bool Locomotion_Control::getMoveConfig(motion::getMoveConfig::Request &req, motion::getMoveConfig::Response &res) { AL::ALValue moveConfiguration; moveConfiguration = mProxy_->getMoveConfig(req.config); std::size_t CSize = moveConfiguration.getSize(); res.moveConfiguration.names.resize(CSize); res.moveConfiguration.values.resize(CSize); for (int i = 0; i < CSize; ++i) { res.moveConfiguration.names[i] = moveConfiguration[i][0].toString(); res.moveConfiguration.values[i] = moveConfiguration[i][1]; } return true; } bool Locomotion_Control::getRobotPosition( motion::getRobotPosition::Request &req, motion::getRobotPosition::Response &res) { bool useSensors = req.useSensors; res.positions = mProxy_->getRobotPosition(useSensors); return true; } bool Locomotion_Control::getNextRobotPosition( motion::getNextRobotPosition::Request &req, motion::getNextRobotPosition::Response &res) { res.positions = mProxy_->getNextRobotPosition(); return true; } bool Locomotion_Control::getRobotVelocity( motion::getRobotVelocity::Request &req, motion::getRobotVelocity::Response &res) { res.velocity = mProxy_->getRobotVelocity(); return true; } bool Locomotion_Control::getWalkArmsEnabled( motion::getWalkArmsEnabled::Request &req, motion::getWalkArmsEnabled::Response &res) { AL::ALValue result = mProxy_->getWalkArmsEnabled(); res.armMotions.resize(2); res.armMotions[0] = static_cast<bool>(result[0]); res.armMotions[1] = static_cast<bool>(result[1]); return true; } bool Locomotion_Control::setWalkArmsEnabled( motion::setWalkArmsEnabled::Request &req, motion::setWalkArmsEnabled::Response &res) { bool left = req.leftArmEnable; bool right = req.rightArmEnable; mProxy_->setWalkArmsEnabled(left, right); return true; } void Locomotion_Control::spinTopics() { std_msgs::Bool msg; msg.data = moveIsActive(); moving_pub_.publish(msg); } <commit_msg>Fix isMoveActive function, so that real result is actually published<commit_after>#include "locomotion_control.h" Locomotion_Control::Locomotion_Control(ros::NodeHandle* nh, AL::ALMotionProxy* mProxy) { nh_ = nh; mProxy_ = mProxy; INFO("Setting up Nao locomotion publishers" << std::endl); moving_pub_ = nh_->advertise<std_msgs::Bool>("isMoving", 10); INFO("Setting up Nao motion publishers" << std::endl); srv_move_ = nh_->advertiseService("move", &Locomotion_Control::move, this); srv_move_to_ = nh_->advertiseService("moveTo", &Locomotion_Control::moveTo, this); srv_move_toward_ = nh_->advertiseService("moveToward", &Locomotion_Control::moveToward, this); srv_move_init_ = nh_->advertiseService("moveInit", &Locomotion_Control::moveInit, this); srv_wait_move_finished_ = nh_->advertiseService("waitMoveFinish", &Locomotion_Control::waitUntilMoveIsFinished, this); srv_stop_move_ = nh_->advertiseService("stopMove", &Locomotion_Control::stopMove, this); srv_get_move_config_ = nh_->advertiseService("getMoveConfig", &Locomotion_Control::getMoveConfig, this); srv_get_robot_position_ = nh_->advertiseService("getRobotPosition", &Locomotion_Control::getRobotPosition, this); srv_get_next_robot_position_ = nh_->advertiseService("getNextRobotPosition", &Locomotion_Control::getNextRobotPosition, this); srv_get_robot_velocity_ = nh_->advertiseService("getRobotVelocity", &Locomotion_Control::getRobotVelocity, this); srv_get_walk_arms_enabled_ = nh_->advertiseService("getWalkArmsEnabled", &Locomotion_Control::getWalkArmsEnabled, this); srv_set_walk_arms_enabled_ = nh_->advertiseService("setWalkArmsEnabled", &Locomotion_Control::setWalkArmsEnabled, this); } Locomotion_Control::~Locomotion_Control() { ros::shutdown(); } bool Locomotion_Control::move(motion::move::Request &req, motion::move::Response &res) { // Check for size of moveConfiguration int configSize = req.moveConfiguration.names.size(); AL::ALValue moveConfiguration; if (configSize > 0) { moveConfiguration.arraySetSize(configSize); for (int i = 0; i < configSize; ++i) { moveConfiguration[i] = AL::ALValue::array( req.moveConfiguration.names[i], req.moveConfiguration.values[i]); } } res.res = true; if (configSize == 0) { mProxy_->move(req.targetVelocity.x, req.targetVelocity.y, req.targetVelocity.theta); } else if (configSize > 0) { mProxy_->move(req.targetVelocity.x, req.targetVelocity.y, req.targetVelocity.theta, moveConfiguration); } else { res.res = false; } return true; } bool Locomotion_Control::moveTo(motion::moveTo::Request &req, motion::moveTo::Response &res) { // Check for multiple positions int posNum = req.controlPoints.size(); AL::ALValue controlPoints; if (posNum > 1) { controlPoints.arraySetSize(posNum); for (int i = 0; i < posNum; ++i) { controlPoints[i] = AL::ALValue::array(req.controlPoints[i].x, req.controlPoints[i].y, req.controlPoints[i].theta); } } // Check for size of moveConfiguration int configSize = req.moveConfiguration.names.size(); AL::ALValue moveConfiguration; if (configSize > 0) { moveConfiguration.arraySetSize(configSize); for (int i = 0; i < configSize; ++i) { moveConfiguration[i] = AL::ALValue::array( req.moveConfiguration.names[i], req.moveConfiguration.values[i]); } } res.res = true; if (posNum == 1 && configSize == 0) { mProxy_->post.moveTo(req.controlPoints[0].x, req.controlPoints[0].y, req.controlPoints[0].theta); } else if (posNum > 1 && configSize == 0) { mProxy_->post.moveTo(controlPoints); } else if (posNum == 1 && configSize > 0) { mProxy_->post.moveTo(req.controlPoints[0].x, req.controlPoints[0].y, req.controlPoints[0].theta, moveConfiguration); } else if (posNum > 1 && configSize > 0) { mProxy_->post.moveTo(controlPoints, moveConfiguration); } else { res.res = false; } return true; } bool Locomotion_Control::moveToward(motion::moveToward::Request &req, motion::moveToward::Response &res) { // Check for size of moveConfiguration int configSize = req.moveConfiguration.names.size(); AL::ALValue moveConfiguration; if (configSize > 0) { moveConfiguration.arraySetSize(configSize); for (int i = 0; i < configSize; ++i) { moveConfiguration[i] = AL::ALValue::array( req.moveConfiguration.names[i], req.moveConfiguration.values[i]); } } res.res = true; if (configSize == 0) { mProxy_->moveToward(req.normVelocity.x, req.normVelocity.y, req.normVelocity.theta); } else if (configSize > 0) { mProxy_->moveToward(req.normVelocity.x, req.normVelocity.y, req.normVelocity.theta, moveConfiguration); } else { res.res = false; } return true; } bool Locomotion_Control::moveInit(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { mProxy_->moveInit(); return true; } bool Locomotion_Control::waitUntilMoveIsFinished( std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { mProxy_->waitUntilMoveIsFinished(); return true; } bool Locomotion_Control::moveIsActive() { return mProxy_->moveIsActive(); } bool Locomotion_Control::stopMove(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { mProxy_->stopMove(); return true; } bool Locomotion_Control::getMoveConfig(motion::getMoveConfig::Request &req, motion::getMoveConfig::Response &res) { AL::ALValue moveConfiguration; moveConfiguration = mProxy_->getMoveConfig(req.config); std::size_t CSize = moveConfiguration.getSize(); res.moveConfiguration.names.resize(CSize); res.moveConfiguration.values.resize(CSize); for (int i = 0; i < CSize; ++i) { res.moveConfiguration.names[i] = moveConfiguration[i][0].toString(); res.moveConfiguration.values[i] = moveConfiguration[i][1]; } return true; } bool Locomotion_Control::getRobotPosition( motion::getRobotPosition::Request &req, motion::getRobotPosition::Response &res) { bool useSensors = req.useSensors; res.positions = mProxy_->getRobotPosition(useSensors); return true; } bool Locomotion_Control::getNextRobotPosition( motion::getNextRobotPosition::Request &req, motion::getNextRobotPosition::Response &res) { res.positions = mProxy_->getNextRobotPosition(); return true; } bool Locomotion_Control::getRobotVelocity( motion::getRobotVelocity::Request &req, motion::getRobotVelocity::Response &res) { res.velocity = mProxy_->getRobotVelocity(); return true; } bool Locomotion_Control::getWalkArmsEnabled( motion::getWalkArmsEnabled::Request &req, motion::getWalkArmsEnabled::Response &res) { AL::ALValue result = mProxy_->getWalkArmsEnabled(); res.armMotions.resize(2); res.armMotions[0] = static_cast<bool>(result[0]); res.armMotions[1] = static_cast<bool>(result[1]); return true; } bool Locomotion_Control::setWalkArmsEnabled( motion::setWalkArmsEnabled::Request &req, motion::setWalkArmsEnabled::Response &res) { bool left = req.leftArmEnable; bool right = req.rightArmEnable; mProxy_->setWalkArmsEnabled(left, right); return true; } void Locomotion_Control::spinTopics() { std_msgs::Bool msg; msg.data = moveIsActive(); moving_pub_.publish(msg); } <|endoftext|>
<commit_before>#include <cstddef> #include <cstdlib> #include <hls_video.h> #include "Accel.h" #include "AccelSchedule.h" #include "AccelTest.h" #include "Dense.h" #include "ZipIO.h" #include "ParamIO.h" #include "DataIO.h" #include "Timer.h" int main(int argc, char** argv) { if (argc < 2) { printf ("Give number of character to produce as 1st arg\n"); printf ("Give the initial srting as 2nd arg optional\n"); return 0; } const unsigned n_char = std::stoi(argv[1]); bool Init = false; char* str_init = NULL; if (argc == 3) { Init = true; printf("* Initial string is %s\n", str_init); str_init = argv[2]; // *ML: cant loas text with ' ' } // print some config numbers printf ("* WT_WORDS = %u\n", WT_WORDS); printf ("* BIAS_WORDS = %u\n", BIAS_WORDS); // Load input data //printf ("## Loading input data ##\n"); // ML: hidden state can be initialized by a given string // Load parameters printf ("## Loading parameters ##\n"); Params params(get_root_dir() + "/params/rnn_parameters.zip"); // --------------------------------------------------------------------- // allocate and binarize all weights // --------------------------------------------------------------------- Word* wt[N_LAYERS]; Word* b[N_LAYERS]; for (unsigned l = 0; l < N_LAYERS; ++l) { const unsigned M = M_tab[l]; const unsigned N = N_tab[l]; if (layer_is_rnn(l+1)) { wt[l] = new Word[(M+N)*4*N / WORD_SIZE]; b[l] = new Word[4*N / WORD_SIZE]; } else { wt[l] = new Word[M*N / WORD_SIZE]; // ML: RNN layers b[l] = new Word[N / WORD_SIZE]; } if (layer_is_rnn(l+1)) { for (unsigned w_l = 0; w_l < N_W_LAYERS; ++w_l) { // ML: set in_to weight and hid_to weight const float* weights_in = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l]); const float* weights_hid = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l +1]); set_rnn_weight_array(wt[l], weights_in, weights_hid, l+1, w_l); // ML: set bias const float* bias = params.float_data(bidx_tab[l*N_W_LAYERS + w_l]); set_rnn_bias_array(b[l], bias, l+1, w_l); } } else { const float* weights = params.float_data(widx_tab[16]); set_dense_weight_array(wt[l], weights, l+1); const float* bias = params.float_data(bidx_tab[8]); set_dense_bias_array(b[l], bias, l+1); } } // --------------------------------------------------------------------- // // compute accelerator schedule (divides up weights) // --------------------------------------------------------------------- AccelSchedule layer_sched[N_LAYERS]; for (unsigned l = 0; l < N_LAYERS; ++l) { compute_accel_schedule( wt[l], b[l], M_tab[l], N_tab[l], T_tab[l], layer_sched[l], l ); } // allocate memories for data i/o for the accelerator Word* data_i = (Word*) MEM_ALLOC( DMEM_WORDS * sizeof(Word) ); // ML: need to be modified! Word* data_o = (Word*) MEM_ALLOC( DMEM_O_WORDS * sizeof(Word) ); if (!data_i || !data_o) { fprintf (stderr, "**** ERROR: Alloc failed in %s\n", __FILE__); return (-2); } unsigned n_errors = 0; printf("## Initialing the RNN\n"); if (Init) { unsigned i = 0; while (str_init[i] != '\0') { set_char_to_word(data_i, str_init[i]); for (unsigned l = 1; l <= 3; ++l) { const unsigned M = M_tab[l-1]; const unsigned N = N_tab[l-1]; dense_layer( data_i, data_o, l-1, (l==1) ? (64/DATA_PER_WORD) : 0, // input_words 0, // output_words = 0 layer_sched[l-1] ); } i++; } } printf ("## Running RNN for %d characters\n", n_char); //-------------------------------------------------------------- // Run RNN //-------------------------------------------------------------- // ML: load an arbitrary input character [1, 0. 0, ..., 0] for (unsigned i = 0; i < VOCAB_SIZE/DATA_PER_WORD; ++i) { if (i == 0) { data_i[i] = 0; DATA start_seed = 1; data_i[i](15,0) = start_seed(15,0); } else { data_i[i] = 0; } } for (unsigned n = 0; n < n_char; ++n) { //------------------------------------------------------------ // Execute RNN layers //------------------------------------------------------------ for (unsigned l = 1; l <= 3; ++l) { const unsigned M = M_tab[l-1]; const unsigned N = N_tab[l-1]; dense_layer( data_i, data_o, l-1, (n==0 && l==1 && (~Init)) ? (64/DATA_PER_WORD) : 0, // input_words (l==3) ? (64/DATA_PER_WORD) : 0, layer_sched[l-1] ); } //------------------------------------------------------------ // Execute the prediciton //------------------------------------------------------------ int prediction = 0; int max = -512; // ML: may shoulb be less for (unsigned i = 0; i < VOCAB_SIZE; i++) { DATA temp; int add = i / DATA_PER_WORD; int off = i % DATA_PER_WORD; temp(15,0) = data_o[add]((off+1)*16-1,off*16); if (temp.to_int() > max) { max = temp; prediction = i; } } assert(prediction >= 0 && prediction <= 63); std::cout<<vocab[prediction]; } printf("\n"); /*printf ("\n"); printf ("Errors: %u (%4.2f%%)\n", n_errors, float(n_errors)*100/n_imgs); printf ("\n"); printf ("Total accel runtime = %10.4f seconds\n", total_time()); printf ("\n");*/ MEM_FREE( data_o ); MEM_FREE( data_i ); for (unsigned n = 0; n < N_LAYERS; ++n) { delete[] wt[n]; delete[] b[n]; } return 0; } <commit_msg>fixed a bug<commit_after>#include <cstddef> #include <cstdlib> #include <hls_video.h> #include "Accel.h" #include "AccelSchedule.h" #include "AccelTest.h" #include "Dense.h" #include "ZipIO.h" #include "ParamIO.h" #include "DataIO.h" #include "Timer.h" int main(int argc, char** argv) { if (argc < 2) { printf ("Give number of character to produce as 1st arg\n"); printf ("Give the initial srting as 2nd arg optional\n"); return 0; } const unsigned n_char = std::stoi(argv[1]); bool Init = false; char* str_init = NULL; if (argc == 3) { Init = true; str_init = argv[2]; // *ML: cant loas text with ' ' printf("* Initial string is %s\n", str_init); } // print some config numbers printf ("* WT_WORDS = %u\n", WT_WORDS); printf ("* BIAS_WORDS = %u\n", BIAS_WORDS); // Load input data //printf ("## Loading input data ##\n"); // ML: hidden state can be initialized by a given string // Load parameters printf ("## Loading parameters ##\n"); Params params(get_root_dir() + "/params/rnn_parameters.zip"); // --------------------------------------------------------------------- // allocate and binarize all weights // --------------------------------------------------------------------- Word* wt[N_LAYERS]; Word* b[N_LAYERS]; for (unsigned l = 0; l < N_LAYERS; ++l) { const unsigned M = M_tab[l]; const unsigned N = N_tab[l]; if (layer_is_rnn(l+1)) { wt[l] = new Word[(M+N)*4*N / WORD_SIZE]; b[l] = new Word[4*N / WORD_SIZE]; } else { wt[l] = new Word[M*N / WORD_SIZE]; // ML: RNN layers b[l] = new Word[N / WORD_SIZE]; } if (layer_is_rnn(l+1)) { for (unsigned w_l = 0; w_l < N_W_LAYERS; ++w_l) { // ML: set in_to weight and hid_to weight const float* weights_in = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l]); const float* weights_hid = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l +1]); set_rnn_weight_array(wt[l], weights_in, weights_hid, l+1, w_l); // ML: set bias const float* bias = params.float_data(bidx_tab[l*N_W_LAYERS + w_l]); set_rnn_bias_array(b[l], bias, l+1, w_l); } } else { const float* weights = params.float_data(widx_tab[16]); set_dense_weight_array(wt[l], weights, l+1); const float* bias = params.float_data(bidx_tab[8]); set_dense_bias_array(b[l], bias, l+1); } } // --------------------------------------------------------------------- // // compute accelerator schedule (divides up weights) // --------------------------------------------------------------------- AccelSchedule layer_sched[N_LAYERS]; for (unsigned l = 0; l < N_LAYERS; ++l) { compute_accel_schedule( wt[l], b[l], M_tab[l], N_tab[l], T_tab[l], layer_sched[l], l ); } // allocate memories for data i/o for the accelerator Word* data_i = (Word*) MEM_ALLOC( DMEM_WORDS * sizeof(Word) ); // ML: need to be modified! Word* data_o = (Word*) MEM_ALLOC( DMEM_O_WORDS * sizeof(Word) ); if (!data_i || !data_o) { fprintf (stderr, "**** ERROR: Alloc failed in %s\n", __FILE__); return (-2); } unsigned n_errors = 0; printf("## Initialing the RNN\n"); if (Init) { unsigned i = 0; while (str_init[i] != '\0') { set_char_to_word(data_i, str_init[i]); for (unsigned l = 1; l <= 3; ++l) { const unsigned M = M_tab[l-1]; const unsigned N = N_tab[l-1]; dense_layer( data_i, data_o, l-1, (l==1) ? (64/DATA_PER_WORD) : 0, // input_words 0, // output_words = 0 layer_sched[l-1] ); } i++; } } printf ("## Running RNN for %d characters\n", n_char); //-------------------------------------------------------------- // Run RNN //-------------------------------------------------------------- // ML: load an arbitrary input character [1, 0. 0, ..., 0] for (unsigned i = 0; i < VOCAB_SIZE/DATA_PER_WORD; ++i) { if (i == 0) { data_i[i] = 0; DATA start_seed = 1; data_i[i](15,0) = start_seed(15,0); } else { data_i[i] = 0; } } for (unsigned n = 0; n < n_char; ++n) { //------------------------------------------------------------ // Execute RNN layers //------------------------------------------------------------ for (unsigned l = 1; l <= 3; ++l) { const unsigned M = M_tab[l-1]; const unsigned N = N_tab[l-1]; dense_layer( data_i, data_o, l-1, (n==0 && l==1 && (~Init)) ? (64/DATA_PER_WORD) : 0, // input_words (l==3) ? (64/DATA_PER_WORD) : 0, layer_sched[l-1] ); } //------------------------------------------------------------ // Execute the prediciton //------------------------------------------------------------ int prediction = 0; int max = -512; // ML: may shoulb be less for (unsigned i = 0; i < VOCAB_SIZE; i++) { DATA temp; int add = i / DATA_PER_WORD; int off = i % DATA_PER_WORD; temp(15,0) = data_o[add]((off+1)*16-1,off*16); if (temp.to_int() > max) { max = temp; prediction = i; } } assert(prediction >= 0 && prediction <= 63); std::cout<<vocab[prediction]; } printf("\n"); /*printf ("\n"); printf ("Errors: %u (%4.2f%%)\n", n_errors, float(n_errors)*100/n_imgs); printf ("\n"); printf ("Total accel runtime = %10.4f seconds\n", total_time()); printf ("\n");*/ MEM_FREE( data_o ); MEM_FREE( data_i ); for (unsigned n = 0; n < N_LAYERS; ++n) { delete[] wt[n]; delete[] b[n]; } return 0; } <|endoftext|>
<commit_before>// Test harness for the HtmlParser class. #include <iostream> #include <cstdlib> #include "FileUtil.h" #include "HtmlParser.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " html_filename\n"; std::exit(EXIT_FAILURE); } class Parser: public HtmlParser { public: Parser(const std::string &document): HtmlParser(document) { } virtual void notify(const HtmlParser::Chunk &chunk); }; void Parser::notify(const HtmlParser::Chunk &chunk) { std::cout << chunk.toString() << '\n'; } int main(int argc, char *argv[]) { ::progname = argv[1]; if (argc != 2) Usage(); try { const std::string input_filename(argv[1]); std::string html_document; if (not FileUtil::ReadString(input_filename, &html_document)) ERROR("failed to read an HTML document from \"" + input_filename + "\"!"); Parser parser(html_document); parser.parse(); } catch (const std::exception &x) { ERROR(x.what()); } } <commit_msg>Fixed an invalid default argument bug.<commit_after>// Test harness for the HtmlParser class. #include <iostream> #include <cstdlib> #include "FileUtil.h" #include "HtmlParser.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " html_filename\n"; std::exit(EXIT_FAILURE); } class Parser: public HtmlParser { public: Parser(const std::string &document) : HtmlParser(document, HtmlParser::EVERYTHING & ~(HtmlParser::WORD | HtmlParser::PUNCTUATION | HtmlParser::WHITESPACE)) { } virtual void notify(const HtmlParser::Chunk &chunk); }; void Parser::notify(const HtmlParser::Chunk &chunk) { std::cout << chunk.toString() << '\n'; } int main(int argc, char *argv[]) { ::progname = argv[1]; if (argc != 2) Usage(); try { const std::string input_filename(argv[1]); std::string html_document; if (not FileUtil::ReadString(input_filename, &html_document)) ERROR("failed to read an HTML document from \"" + input_filename + "\"!"); Parser parser(html_document); parser.parse(); } catch (const std::exception &x) { ERROR(x.what()); } } <|endoftext|>
<commit_before>#include <iostream> #include <boost/filesystem.hpp> #include <opencv2/highgui.hpp> #include "core/core.h" #include "encoding/populationcode.h" #include "io/readmnist.h" #include "neuron/wtapoisson.h" #include "neuron/neuron.h" #include "neuron/zneuron.h" using namespace cv; using namespace std; namespace bfs=boost::filesystem; class Simulation { public: Simulation() { } void Learn() { ReadMNISTImages r; bfs::path p("C:\\Users\\woodstock\\dev\\data\\MNIST\\train-images.idx3-ubyte"); r.ReadHeader(p.string().c_str()); MutexPopulationCode pop_code; WTAPoisson wta_z(1.f, 1000.f); bool first_pass = true; while(!r.IS_EOF()) { Mat img = r.Next(); cv::imshow("i", img); pop_code.State(img); Mat1f pc = pop_code.PopCode(); YNeuron neuron_y; neuron_y.init(1.f, 1000.f); Mat1f spikes_y(1, pc.total()); for(size_t i; i<pc.total(); i++) { spikes_y(i) = neuron_y.State(pc(i)); } if(first_pass) { for(size_t i; i<spikes_y.total(); i++) { shared_ptr<ZNeuron> p(new ZNeuron); p->init(spikes_y.total(), 10); } } Mat1f u(1, layer_z_.size()); for(size_t i; i<layer_z_.size(); i++) { u(i) = layer_z_[i]->Predict(spikes_y).at<float>(0); } Mat1f spikes_z = wta_z.Compete(layer_z_); for(size_t i; i<layer_z_.size(); i++) { layer_z_[i]->Learn(spikes_z.col(i) > 0); } if(first_pass) { first_pass = false; } waitKey(); } } void Test() { ReadMNISTImages r; bfs::path p("C:\\Users\\woodstock\\dev\\data\\MNIST\\t10k-images.idx3-ubyte"); r.ReadHeader(p.string().c_str()); MutexPopulationCode pop_code; WTAPoisson wta_z(1.f, 1000.f); bool first_pass = true; while(!r.IS_EOF()) { Mat img = r.Next(); cv::imshow("i", img); pop_code.State(img); Mat1f pc = pop_code.PopCode(); YNeuron neuron_y; neuron_y.init(1.f, 1000.f); Mat1f spikes_y(1, pc.total()); for(size_t i; i<pc.total(); i++) { spikes_y(i) = neuron_y.State(pc(i)); } if(first_pass) { for(size_t i; i<spikes_y.total(); i++) { shared_ptr<ZNeuron> p(new ZNeuron); p->init(spikes_y.total(), 10); } } Mat1f u(1, layer_z_.size()); for(size_t i; i<layer_z_.size(); i++) { u(i) = layer_z_[i]->Predict(spikes_y).at<float>(0); } Mat1f spikes_z = wta_z.Compete(layer_z_); if(first_pass) { first_pass = false; } waitKey(); } } private: vector<std::shared_ptr<base_Learner> > layer_z_; }; int main() { std::cout<<sem::GetVersion(); Simulation s; s.Learn(); s.Test(); return 0; } <commit_msg>fix for loop initializations<commit_after>#include <iostream> #include <boost/filesystem.hpp> #include <opencv2/highgui.hpp> #include "core/core.h" #include "core/mat_utils.h" #include "encoding/populationcode.h" #include "io/readmnist.h" #include "neuron/wtapoisson.h" #include "neuron/neuron.h" #include "neuron/zneuron.h" using namespace cv; using namespace std; namespace bfs=boost::filesystem; class Simulation { public: Simulation() : nb_learners_(10) { } void Learn() { ReadMNISTImages r; bfs::path p("C:\\Users\\woodstock\\dev\\data\\MNIST\\train-images.idx3-ubyte"); r.ReadHeader(p.string().c_str()); MutexPopulationCode pop_code; WTAPoisson wta_z(1.f, 1000.f); bool first_pass = true; int ri=0; while(!r.IS_EOF()) { //cout<<"i"<<ri++<<endl; Mat img = r.Next(); //cv::imshow("i", img); pop_code.State(img); Mat1f pc = pop_code.PopCode(); YNeuron neuron_y; neuron_y.init(1.f, 1000.f); Mat1f spikes_y(1, pc.total()); for(size_t i=0; i<pc.total(); i++) { spikes_y(i) = neuron_y.State(pc(i)); } if(first_pass) { for(size_t i=0; i<nb_learners_; i++) { shared_ptr<ZNeuron> p(new ZNeuron); p->init(spikes_y.total(), 10); layer_z_.push_back(p); } } Mat1f u(1, layer_z_.size()); for(size_t i=0; i<layer_z_.size(); i++) { u(i) = layer_z_[i]->Predict(spikes_y).at<float>(0); } //cout<<"x6"<<layer_z_.size()<<endl; Mat1i spikes_z = wta_z.Compete(layer_z_); //cout<<spikes_z<<endl; for(size_t i=0; i<layer_z_.size(); i++) { //cout<<spikes_z.col(i)<<endl; layer_z_[i]->Learn(spikes_z.col(i)); } //cout<<"x7"<<endl; if(first_pass) { first_pass = false; } //waitKey(); } } void Test() { ReadMNISTImages r; bfs::path p("C:\\Users\\woodstock\\dev\\data\\MNIST\\t10k-images.idx3-ubyte"); r.ReadHeader(p.string().c_str()); MutexPopulationCode pop_code; WTAPoisson wta_z(1.f, 1000.f); while(!r.IS_EOF()) { Mat img = r.Next(); //cv::imshow("i", img); pop_code.State(img); Mat1f pc = pop_code.PopCode(); YNeuron neuron_y; neuron_y.init(1.f, 1000.f); Mat1f spikes_y(1, pc.total()); for(size_t i=0; i<pc.total(); i++) { spikes_y(i) = neuron_y.State(pc(i)); } Mat1f u(1, layer_z_.size()); for(size_t i=0; i<layer_z_.size(); i++) { u(i) = layer_z_[i]->Predict(spikes_y).at<float>(0); } //Mat1f spikes_z = wta_z.Compete(layer_z_); //waitKey(); } } void Eval() { for(size_t i=0; i<layer_z_.size(); i++) { Mat1f w = static_pointer_cast<ZNeuron>(layer_z_[i])->Weights(); Mat1f w_on(w.size()); Mat1f w_off(w.size()); for(size_t i=0, j=0; i<w.total(); i+=2, j++) { w_on(j) = w(i); w_off(j) = w(i+1); } imshow("on", sem::ConvertTo8U(w_on)); imshow("off", sem::ConvertTo8U(w_off)); waitKey(); } } private: vector<std::shared_ptr<base_Learner> > layer_z_; int nb_learners_; ///< no. of learners (e.g. ZNeuron) }; int main() { cout<<sem::GetVersion()<<endl; Simulation s; cout<<"Learn()"<<endl; s.Learn(); cout<<"Test()"<<endl; s.Test(); cout<<"Eval()"<<endl; s.Eval(); return 0; } <|endoftext|>
<commit_before><?hh //strict /** * This file is part of hhpack\codegen. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace HHPack\Codegen\Cli; use HHPack\Codegen\{ LibraryFileGenerator, ClassFileGenerator, GenerateType, ClassFileGeneratable, OutputNamespace }; use HHPack\Codegen\Project\{PackageClassGenerator}; use HHPack\Codegen\HackUnit\{TestClassGenerator}; use function HHPack\Getopt\{optparser, take_on, on}; use HHPack\Getopt\Parser\{OptionParser}; use HHPack\Codegen\Cli\{CodegenGenerators}; use Facebook\DefinitionFinder\{TreeParser}; use Facebook\HackCodegen\{ HackCodegenFactory, HackCodegenConfig, CodegenFileResult }; final class Codegen { const string PROGRAM_NAME = 'codegen'; const string PROGRAM_VERSION = '0.1.0'; private bool $help = false; private bool $version = false; private OptionParser $optionParser; public function __construct() { $this->optionParser = optparser( [ on( ['-h', '--help'], 'Display help message', () ==> { $this->help = true; }, ), on( ['-v', '--version'], 'Display version', () ==> { $this->version = true; }, ), ], ); } public function run(Traversable<string> $argv): void { $args = ImmVector::fromItems($argv)->skip(1); $remainArgs = $this->optionParser->parse($args); if ($this->help) { $this->displayHelp(); } else if ($this->version) { $this->displayVersion(); } else { $type = $remainArgs->at(0); $name = $remainArgs->at(1); $genType = GenerateType::assert($type); $this->generateBy(Pair {$genType, $name}); } } private function generateBy( Pair<GenerateType, string> $generateClass, ): void { $generators = (new DevGeneratorProvider(dev_roots()))->generators(); $generator = LibraryFileGenerator::fromItems($generators); $classFile = $generator->generate($generateClass); $result = $classFile->save(); if ($result === CodegenFileResult::CREATE) { fwrite( STDOUT, sprintf("File %s is created\n", $classFile->getFileName()), ); } else if ($result === CodegenFileResult::UPDATE) { fwrite( STDOUT, sprintf("File %s is updated\n", $classFile->getFileName()), ); } else if ($result === CodegenFileResult::NONE) { fwrite( STDOUT, sprintf("File %s is already exists\n", $classFile->getFileName()), ); } } private function displayVersion(): void { fwrite( STDOUT, sprintf("%s - %s\n", static::PROGRAM_NAME, static::PROGRAM_VERSION), ); } private function displayHelp(): void { fwrite( STDOUT, sprintf("Usage: %s [OPTIONS] [TYPE] [NAME]\n\n", static::PROGRAM_NAME), ); fwrite(STDOUT, "Arguments:\n"); fwrite(STDOUT, " TYPE: generate type (ex. lib, test) \n"); fwrite(STDOUT, " NAME: generate class name (ex. Foo\\Bar)\n\n"); $this->optionParser->displayHelp(); } } <commit_msg>v0.1.1<commit_after><?hh //strict /** * This file is part of hhpack\codegen. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace HHPack\Codegen\Cli; use HHPack\Codegen\{ LibraryFileGenerator, ClassFileGenerator, GenerateType, ClassFileGeneratable, OutputNamespace }; use HHPack\Codegen\Project\{PackageClassGenerator}; use HHPack\Codegen\HackUnit\{TestClassGenerator}; use function HHPack\Getopt\{optparser, take_on, on}; use HHPack\Getopt\Parser\{OptionParser}; use HHPack\Codegen\Cli\{CodegenGenerators}; use Facebook\DefinitionFinder\{TreeParser}; use Facebook\HackCodegen\{ HackCodegenFactory, HackCodegenConfig, CodegenFileResult }; final class Codegen { const string PROGRAM_NAME = 'codegen'; const string PROGRAM_VERSION = '0.1.1'; private bool $help = false; private bool $version = false; private OptionParser $optionParser; public function __construct() { $this->optionParser = optparser( [ on( ['-h', '--help'], 'Display help message', () ==> { $this->help = true; }, ), on( ['-v', '--version'], 'Display version', () ==> { $this->version = true; }, ), ], ); } public function run(Traversable<string> $argv): void { $args = ImmVector::fromItems($argv)->skip(1); $remainArgs = $this->optionParser->parse($args); if ($this->help) { $this->displayHelp(); } else if ($this->version) { $this->displayVersion(); } else { $type = $remainArgs->at(0); $name = $remainArgs->at(1); $genType = GenerateType::assert($type); $this->generateBy(Pair {$genType, $name}); } } private function generateBy( Pair<GenerateType, string> $generateClass, ): void { $generators = (new DevGeneratorProvider(dev_roots()))->generators(); $generator = LibraryFileGenerator::fromItems($generators); $classFile = $generator->generate($generateClass); $result = $classFile->save(); if ($result === CodegenFileResult::CREATE) { fwrite( STDOUT, sprintf("File %s is created\n", $classFile->getFileName()), ); } else if ($result === CodegenFileResult::UPDATE) { fwrite( STDOUT, sprintf("File %s is updated\n", $classFile->getFileName()), ); } else if ($result === CodegenFileResult::NONE) { fwrite( STDOUT, sprintf("File %s is already exists\n", $classFile->getFileName()), ); } } private function displayVersion(): void { fwrite( STDOUT, sprintf("%s - %s\n", static::PROGRAM_NAME, static::PROGRAM_VERSION), ); } private function displayHelp(): void { fwrite( STDOUT, sprintf("Usage: %s [OPTIONS] [TYPE] [NAME]\n\n", static::PROGRAM_NAME), ); fwrite(STDOUT, "Arguments:\n"); fwrite(STDOUT, " TYPE: generate type (ex. lib, test) \n"); fwrite(STDOUT, " NAME: generate class name (ex. Foo\\Bar)\n\n"); $this->optionParser->displayHelp(); } } <|endoftext|>
<commit_before>#include <bits/stdc++.h> using namespace std; // https://cp-algorithms.com/data_structures/treap.html mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); struct Node { int key; int size; long long prio; Node *l, *r; Node(int key) : key(key), prio(rng()), size(1), l(nullptr), r(nullptr) {} void update() { size = 1 + get_size(l) + get_size(r); } static int get_size(Node *node) { return node ? node->size : 0; } }; using pNode = Node *; void split(pNode t, int key, pNode &l, pNode &r) { if (!t) l = r = nullptr; else if (key < t->key) split(t->l, key, l, t->l), r = t, t->update(); else split(t->r, key, t->r, r), l = t, t->update(); } void merge(pNode &t, pNode l, pNode r) { if (!l || !r) t = l ? l : r; else if (l->prio > r->prio) merge(l->r, l->r, r), t = l, t->update(); else merge(r->l, l, r->l), t = r, t->update(); } void insert(pNode &t, pNode it) { if (!t) t = it; else if (it->prio > t->prio) split(t, it->key, it->l, it->r), t = it, t->update(); else insert(it->key < t->key ? t->l : t->r, it), t->update(); } void erase(pNode &t, int key) { if (t->key == key) { pNode l = t->l; pNode r = t->r; delete t; merge(t, l, r); } else { erase(key < t->key ? t->l : t->r, key), t->update(); } } int kth(pNode t, int k) { if (k < Node::get_size(t->l)) return kth(t->l, k); else if (k > Node::get_size(t->l)) return kth(t->r, k - Node::get_size(t->l) - 1); return t->key; } void print(pNode t) { if (!t) return; print(t->l); cout << t->key << endl; print(t->r); } void clear(pNode &t) { if (!t) return; clear(t->l); clear(t->r); delete t; t = nullptr; } // usage example int main() { pNode t1 = nullptr; int a1[] = {1, 2}; for (int x: a1) insert(t1, new Node(x)); pNode t2 = nullptr; int a2[] = {7, 4, 5}; for (int x: a2) insert(t2, new Node(x)); pNode t = nullptr; merge(t, t1, t2); for (int i = 0; i < t->size; ++i) { cout << kth(t, i) << endl; } clear(t); } <commit_msg>update<commit_after>#include <bits/stdc++.h> using namespace std; // https://cp-algorithms.com/data_structures/treap.html mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); struct Node { int key; int size; long long prio; Node *l, *r; Node(int key) : key(key), prio(rng()), size(1), l(nullptr), r(nullptr) {} void update() { size = 1 + get_size(l) + get_size(r); } static int get_size(Node *node) { return node ? node->size : 0; } }; using pNode = Node *; void split(pNode t, int key, pNode &l, pNode &r) { if (!t) l = r = nullptr; else if (key < t->key) split(t->l, key, l, t->l), r = t, t->update(); else split(t->r, key, t->r, r), l = t, t->update(); } void merge(pNode &t, pNode l, pNode r) { if (!l || !r) t = l ? l : r; else if (l->prio > r->prio) merge(l->r, l->r, r), t = l, t->update(); else merge(r->l, l, r->l), t = r, t->update(); } void insert(pNode &t, pNode it) { if (!t) t = it; else if (it->prio > t->prio) split(t, it->key, it->l, it->r), t = it, t->update(); else insert(it->key < t->key ? t->l : t->r, it), t->update(); } void erase(pNode &t, int key) { if (t->key == key) { pNode l = t->l; pNode r = t->r; delete t; merge(t, l, r); } else { erase(key < t->key ? t->l : t->r, key), t->update(); } } pNode unite(pNode l, pNode r) { if (!l || !r) return l ? l : r; if (l->prio < r->prio) swap(l, r); pNode lt, rt; split(r, l->key, lt, rt); l->l = unite(l->l, lt); l->r = unite(l->r, rt); return l; } int kth(pNode t, int k) { if (k < Node::get_size(t->l)) return kth(t->l, k); else if (k > Node::get_size(t->l)) return kth(t->r, k - Node::get_size(t->l) - 1); return t->key; } void print(pNode t) { if (!t) return; print(t->l); cout << t->key << endl; print(t->r); } void clear(pNode &t) { if (!t) return; clear(t->l); clear(t->r); delete t; t = nullptr; } // usage example int main() { pNode t1 = nullptr; int a1[] = {1, 2}; for (int x: a1) insert(t1, new Node(x)); pNode t2 = nullptr; int a2[] = {7, 4, 5}; for (int x: a2) insert(t2, new Node(x)); pNode t = nullptr; merge(t, t1, t2); for (int i = 0; i < t->size; ++i) { cout << kth(t, i) << endl; } clear(t); } <|endoftext|>
<commit_before>#include <pluginlib/class_list_macros.h> #include <kdl_parser/kdl_parser.hpp> #include <math.h> #include <Eigen/LU> #include <utils/pseudo_inversion.h> #include <utils/skew_symmetric.h> #include <lwr_controllers/one_task_inverse_kinematics.h> namespace lwr_controllers { OneTaskInverseKinematics::OneTaskInverseKinematics() {} OneTaskInverseKinematics::~OneTaskInverseKinematics() {} bool OneTaskInverseKinematics::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { nh_ = n; // get URDF and name of root and tip from the parameter server std::string robot_description, root_name, tip_name; if (!ros::param::search(n.getNamespace(),"robot_description", robot_description)) { ROS_ERROR_STREAM("OneTaskInverseKinematics: No robot description (URDF) found on parameter server ("<<n.getNamespace()<<"/robot_description)"); return false; } if (!nh_.getParam("root_name", root_name)) { ROS_ERROR_STREAM("OneTaskInverseKinematics: No root name found on parameter server ("<<n.getNamespace()<<"/root_name)"); return false; } if (!nh_.getParam("tip_name", tip_name)) { ROS_ERROR_STREAM("OneTaskInverseKinematics: No tip name found on parameter server ("<<n.getNamespace()<<"/tip_name)"); return false; } // Get the gravity vector (direction and magnitude) KDL::Vector gravity_ = KDL::Vector::Zero(); gravity_(2) = -9.81; // Construct an URDF model from the xml string std::string xml_string; if (n.hasParam(robot_description)) n.getParam(robot_description.c_str(), xml_string); else { ROS_ERROR("Parameter %s not set, shutting down node...", robot_description.c_str()); n.shutdown(); return false; } if (xml_string.size() == 0) { ROS_ERROR("Unable to load robot model from parameter %s",robot_description.c_str()); n.shutdown(); return false; } ROS_DEBUG("%s content\n%s", robot_description.c_str(), xml_string.c_str()); // Get urdf model out of robot_description urdf::Model model; if (!model.initString(xml_string)) { ROS_ERROR("Failed to parse urdf file"); n.shutdown(); return false; } ROS_INFO("Successfully parsed urdf file"); KDL::Tree kdl_tree_; if (!kdl_parser::treeFromUrdfModel(model, kdl_tree_)) { ROS_ERROR("Failed to construct kdl tree"); n.shutdown(); return false; } // Parsing joint limits from urdf model boost::shared_ptr<const urdf::Link> link_ = model.getLink(tip_name); boost::shared_ptr<const urdf::Joint> joint_; joint_limits_.min.resize(kdl_tree_.getNrOfJoints()); joint_limits_.max.resize(kdl_tree_.getNrOfJoints()); joint_limits_.center.resize(kdl_tree_.getNrOfJoints()); int index; for (int i = 0; i < kdl_tree_.getNrOfJoints() && link_; i++) { joint_ = model.getJoint(link_->parent_joint->name); index = kdl_tree_.getNrOfJoints() - i - 1; joint_limits_.min(index) = joint_->limits->lower; joint_limits_.max(index) = joint_->limits->upper; joint_limits_.center(index) = (joint_limits_.min(index) + joint_limits_.max(index))/2; link_ = model.getLink(link_->getParent()->name); } // Populate the KDL chain if(!kdl_tree_.getChain(root_name, tip_name, kdl_chain_)) { ROS_ERROR_STREAM("Failed to get KDL chain from tree: "); ROS_ERROR_STREAM(" "<<root_name<<" --> "<<tip_name); ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfJoints()<<" joints"); ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfSegments()<<" segments"); ROS_ERROR_STREAM(" The segments are:"); KDL::SegmentMap segment_map = kdl_tree_.getSegments(); KDL::SegmentMap::iterator it; for( it=segment_map.begin(); it != segment_map.end(); it++ ) ROS_ERROR_STREAM( " "<<(*it).first); return false; } ROS_DEBUG("Number of segments: %d", kdl_chain_.getNrOfSegments()); ROS_DEBUG("Number of joints in chain: %d", kdl_chain_.getNrOfJoints()); // Get joint handles for all of the joints in the chain for(std::vector<KDL::Segment>::const_iterator it = kdl_chain_.segments.begin()+1; it != kdl_chain_.segments.end(); ++it) { joint_handles_.push_back(robot->getHandle(it->getJoint().getName())); ROS_DEBUG("%s", it->getJoint().getName().c_str() ); } ROS_DEBUG(" Number of joints in handle = %lu", joint_handles_.size() ); jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kdl_chain_)); id_solver_.reset(new KDL::ChainDynParam(kdl_chain_,gravity_)); fk_pos_solver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_)); ik_vel_solver_.reset(new KDL::ChainIkSolverVel_pinv(kdl_chain_)); ik_pos_solver_.reset(new KDL::ChainIkSolverPos_NR_JL(kdl_chain_,joint_limits_.min,joint_limits_.max,*fk_pos_solver_,*ik_vel_solver_)); joint_msr_states_.resize(kdl_chain_.getNrOfJoints()); joint_des_states_.resize(kdl_chain_.getNrOfJoints()); tau_cmd_.resize(kdl_chain_.getNrOfJoints()); J_.resize(kdl_chain_.getNrOfJoints()); PIDs_.resize(kdl_chain_.getNrOfJoints()); sub_command_ = nh_.subscribe("command_configuration", 1, &OneTaskInverseKinematics::command_configuration, this); sub_gains_ = nh_.subscribe("set_gains", 1, &OneTaskInverseKinematics::set_gains, this); return true; } void OneTaskInverseKinematics::starting(const ros::Time& time) { // get joint positions for(int i=0; i < joint_handles_.size(); i++) { joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); joint_des_states_.q(i) = joint_msr_states_.q(i); } Kp = 60; Ki = 1.2; Kd = 10; for (int i = 0; i < PIDs_.size(); i++) PIDs_[i].initPid(Kp,Ki,Kd,0.3,-0.3); ROS_INFO("PIDs gains are: Kp = %f, Ki = %f, Kd = %f",Kp,Ki,Kd); // computing forward kinematics fk_pos_solver_->JntToCart(joint_msr_states_.q,x_); //Desired posture x_des_ = x_; cmd_flag_ = 0; } void OneTaskInverseKinematics::update(const ros::Time& time, const ros::Duration& period) { // get joint positions for(int i=0; i < joint_handles_.size(); i++) { joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); } if (cmd_flag_) { /* ANALYTIC METHOD FOR INVERSE KINEMATICS // computing Jacobian jnt_to_jac_solver_->JntToJac(joint_msr_states_.q,J_); // computing J_pinv_ pseudo_inverse(J_.data,J_pinv_); // computing forward kinematics fk_pos_solver_->JntToCart(joint_msr_states_.q,x_); // end-effector position/orientation error x_err_.vel = x_des_.p - x_.p; // getting quaternion from rotation matrix x_.M.GetQuaternion(quat_curr_.v(0),quat_curr_.v(1),quat_curr_.v(2),quat_curr_.a); x_des_.M.GetQuaternion(quat_des_.v(0),quat_des_.v(1),quat_des_.v(2),quat_des_.a); skew_symmetric(quat_des_.v,skew_); for (int i = 0; i < skew_.rows(); i++) { v_temp_(i) = 0.0; for (int k = 0; k < skew_.cols(); k++) v_temp_(i) += skew_(i,k)*(quat_curr_.v(k)); } x_err_.rot = quat_curr_.a*quat_des_.v - quat_des_.a*quat_curr_.v - v_temp_; // computing q_dot for (int i = 0; i < J_pinv_.rows(); i++) { joint_des_states_.qdot(i) = 0.0; for (int k = 0; k < J_pinv_.cols(); k++) joint_des_states_.qdot(i) += J_pinv_(i,k)*x_err_(k); } // integrating q_dot -> getting q (Euler method) for (int i = 0; i < joint_handles_.size(); i++) joint_des_states_.q(i) += period.toSec()*joint_des_states_.qdot(i); */ // computing differential inverse kinematics ik_pos_solver_->CartToJnt(joint_msr_states_.q,x_des_,joint_des_states_.q); // computing forward kinematics fk_pos_solver_->JntToCart(joint_msr_states_.q,x_); if (Equal(x_,x_des_,0.025)) { ROS_INFO("On target"); cmd_flag_ = 0; } } // set controls for joints for (int i = 0; i < joint_handles_.size(); i++) { tau_cmd_(i) = PIDs_[i].computeCommand(joint_des_states_.q(i) - joint_msr_states_.q(i),period); joint_handles_[i].setCommand(tau_cmd_(i)); } } void OneTaskInverseKinematics::command_configuration(const lwr_controllers::PoseRPY::ConstPtr &msg) { KDL::Frame frame_des_; switch(msg->id) { case 0: frame_des_ = KDL::Frame( KDL::Rotation::RPY(msg->orientation.roll, msg->orientation.pitch, msg->orientation.yaw), KDL::Vector(msg->position.x, msg->position.y, msg->position.z)); break; case 1: // position only frame_des_ = KDL::Frame( KDL::Vector(msg->position.x, msg->position.y, msg->position.z)); break; case 2: // orientation only frame_des_ = KDL::Frame( KDL::Rotation::RPY(msg->orientation.roll, msg->orientation.pitch, msg->orientation.yaw)); break; default: ROS_INFO("Wrong message ID"); return; } x_des_ = frame_des_; cmd_flag_ = 1; } void OneTaskInverseKinematics::set_gains(const std_msgs::Float64MultiArray::ConstPtr &msg) { if(msg->data.size() == 3) { for(int i = 0; i < PIDs_.size(); i++) PIDs_[i].setGains(msg->data[0],msg->data[1],msg->data[2],0.3,-0.3); ROS_INFO("New gains set: Kp = %f, Ki = %f, Kd = %f",msg->data[0],msg->data[1],msg->data[2]); } else ROS_INFO("PIDs gains needed are 3 (Kp, Ki and Kd)"); } } PLUGINLIB_EXPORT_CLASS(lwr_controllers::OneTaskInverseKinematics, controller_interface::ControllerBase) <commit_msg>Removed KDL_SOLVERIK_JL and added limits by hand<commit_after>#include <pluginlib/class_list_macros.h> #include <kdl_parser/kdl_parser.hpp> #include <math.h> #include <Eigen/LU> #include <utils/pseudo_inversion.h> #include <utils/skew_symmetric.h> #include <lwr_controllers/one_task_inverse_kinematics.h> namespace lwr_controllers { OneTaskInverseKinematics::OneTaskInverseKinematics() {} OneTaskInverseKinematics::~OneTaskInverseKinematics() {} bool OneTaskInverseKinematics::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { nh_ = n; // get URDF and name of root and tip from the parameter server std::string robot_description, root_name, tip_name; if (!ros::param::search(n.getNamespace(),"robot_description", robot_description)) { ROS_ERROR_STREAM("OneTaskInverseKinematics: No robot description (URDF) found on parameter server ("<<n.getNamespace()<<"/robot_description)"); return false; } if (!nh_.getParam("root_name", root_name)) { ROS_ERROR_STREAM("OneTaskInverseKinematics: No root name found on parameter server ("<<n.getNamespace()<<"/root_name)"); return false; } if (!nh_.getParam("tip_name", tip_name)) { ROS_ERROR_STREAM("OneTaskInverseKinematics: No tip name found on parameter server ("<<n.getNamespace()<<"/tip_name)"); return false; } // Get the gravity vector (direction and magnitude) KDL::Vector gravity_ = KDL::Vector::Zero(); gravity_(2) = -9.81; // Construct an URDF model from the xml string std::string xml_string; if (n.hasParam(robot_description)) n.getParam(robot_description.c_str(), xml_string); else { ROS_ERROR("Parameter %s not set, shutting down node...", robot_description.c_str()); n.shutdown(); return false; } if (xml_string.size() == 0) { ROS_ERROR("Unable to load robot model from parameter %s",robot_description.c_str()); n.shutdown(); return false; } ROS_DEBUG("%s content\n%s", robot_description.c_str(), xml_string.c_str()); // Get urdf model out of robot_description urdf::Model model; if (!model.initString(xml_string)) { ROS_ERROR("Failed to parse urdf file"); n.shutdown(); return false; } ROS_INFO("Successfully parsed urdf file"); KDL::Tree kdl_tree_; if (!kdl_parser::treeFromUrdfModel(model, kdl_tree_)) { ROS_ERROR("Failed to construct kdl tree"); n.shutdown(); return false; } // Parsing joint limits from urdf model boost::shared_ptr<const urdf::Link> link_ = model.getLink(tip_name); boost::shared_ptr<const urdf::Joint> joint_; joint_limits_.min.resize(kdl_tree_.getNrOfJoints()); joint_limits_.max.resize(kdl_tree_.getNrOfJoints()); joint_limits_.center.resize(kdl_tree_.getNrOfJoints()); int index; for (int i = 0; i < kdl_tree_.getNrOfJoints() && link_; i++) { joint_ = model.getJoint(link_->parent_joint->name); index = kdl_tree_.getNrOfJoints() - i - 1; joint_limits_.min(index) = joint_->limits->lower; joint_limits_.max(index) = joint_->limits->upper; joint_limits_.center(index) = (joint_limits_.min(index) + joint_limits_.max(index))/2; link_ = model.getLink(link_->getParent()->name); } // Populate the KDL chain if(!kdl_tree_.getChain(root_name, tip_name, kdl_chain_)) { ROS_ERROR_STREAM("Failed to get KDL chain from tree: "); ROS_ERROR_STREAM(" "<<root_name<<" --> "<<tip_name); ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfJoints()<<" joints"); ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfSegments()<<" segments"); ROS_ERROR_STREAM(" The segments are:"); KDL::SegmentMap segment_map = kdl_tree_.getSegments(); KDL::SegmentMap::iterator it; for( it=segment_map.begin(); it != segment_map.end(); it++ ) ROS_ERROR_STREAM( " "<<(*it).first); return false; } ROS_DEBUG("Number of segments: %d", kdl_chain_.getNrOfSegments()); ROS_DEBUG("Number of joints in chain: %d", kdl_chain_.getNrOfJoints()); // Get joint handles for all of the joints in the chain for(std::vector<KDL::Segment>::const_iterator it = kdl_chain_.segments.begin()+1; it != kdl_chain_.segments.end(); ++it) { joint_handles_.push_back(robot->getHandle(it->getJoint().getName())); ROS_DEBUG("%s", it->getJoint().getName().c_str() ); } ROS_DEBUG(" Number of joints in handle = %lu", joint_handles_.size() ); jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kdl_chain_)); id_solver_.reset(new KDL::ChainDynParam(kdl_chain_,gravity_)); fk_pos_solver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_)); ik_vel_solver_.reset(new KDL::ChainIkSolverVel_pinv(kdl_chain_)); ik_pos_solver_.reset(new KDL::ChainIkSolverPos_NR_JL(kdl_chain_,joint_limits_.min,joint_limits_.max,*fk_pos_solver_,*ik_vel_solver_)); joint_msr_states_.resize(kdl_chain_.getNrOfJoints()); joint_des_states_.resize(kdl_chain_.getNrOfJoints()); tau_cmd_.resize(kdl_chain_.getNrOfJoints()); J_.resize(kdl_chain_.getNrOfJoints()); PIDs_.resize(kdl_chain_.getNrOfJoints()); sub_command_ = nh_.subscribe("command_configuration", 1, &OneTaskInverseKinematics::command_configuration, this); sub_gains_ = nh_.subscribe("set_gains", 1, &OneTaskInverseKinematics::set_gains, this); return true; } void OneTaskInverseKinematics::starting(const ros::Time& time) { // get joint positions for(int i=0; i < joint_handles_.size(); i++) { joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); joint_des_states_.q(i) = joint_msr_states_.q(i); } Kp = 60; Ki = 1.2; Kd = 10; for (int i = 0; i < PIDs_.size(); i++) PIDs_[i].initPid(Kp,Ki,Kd,0.3,-0.3); ROS_INFO("PIDs gains are: Kp = %f, Ki = %f, Kd = %f",Kp,Ki,Kd); // computing forward kinematics fk_pos_solver_->JntToCart(joint_msr_states_.q,x_); //Desired posture x_des_ = x_; cmd_flag_ = 0; } void OneTaskInverseKinematics::update(const ros::Time& time, const ros::Duration& period) { // get joint positions for(int i=0; i < joint_handles_.size(); i++) { joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); } if (cmd_flag_) { // ANALYTIC METHOD FOR INVERSE KINEMATICS // computing Jacobian jnt_to_jac_solver_->JntToJac(joint_msr_states_.q,J_); // computing J_pinv_ pseudo_inverse(J_.data,J_pinv_); // computing forward kinematics fk_pos_solver_->JntToCart(joint_msr_states_.q,x_); // end-effector position/orientation error x_err_.vel = x_des_.p - x_.p; // getting quaternion from rotation matrix x_.M.GetQuaternion(quat_curr_.v(0),quat_curr_.v(1),quat_curr_.v(2),quat_curr_.a); x_des_.M.GetQuaternion(quat_des_.v(0),quat_des_.v(1),quat_des_.v(2),quat_des_.a); skew_symmetric(quat_des_.v,skew_); for (int i = 0; i < skew_.rows(); i++) { v_temp_(i) = 0.0; for (int k = 0; k < skew_.cols(); k++) v_temp_(i) += skew_(i,k)*(quat_curr_.v(k)); } x_err_.rot = quat_curr_.a*quat_des_.v - quat_des_.a*quat_curr_.v - v_temp_; // computing q_dot for (int i = 0; i < J_pinv_.rows(); i++) { joint_des_states_.qdot(i) = 0.0; for (int k = 0; k < J_pinv_.cols(); k++) joint_des_states_.qdot(i) += .3*J_pinv_(i,k)*x_err_(k); } // integrating q_dot -> getting q (Euler method) for (int i = 0; i < joint_handles_.size(); i++) joint_des_states_.q(i) += period.toSec()*joint_des_states_.qdot(i); for (int i =0; i < joint_handles_.size(); i++) { if (joint_des_states_.q(i) < joint_limits_.min(i) ) joint_des_states_.q(i) = joint_limits_.min(i); if (joint_des_states_.q(i) > joint_limits_.max(i) ) joint_des_states_.q(i) = joint_limits_.max(i); } // computing differential inverse kinematics // ik_pos_solver_->CartToJnt(joint_msr_states_.q,x_des_,joint_des_states_.q); // computing forward kinematics // fk_pos_solver_->JntToCart(joint_msr_states_.q,x_); if (Equal(x_,x_des_,0.025)) { ROS_INFO("On target"); cmd_flag_ = 0; } } // set controls for joints for (int i = 0; i < joint_handles_.size(); i++) { tau_cmd_(i) = PIDs_[i].computeCommand(joint_des_states_.q(i) - joint_msr_states_.q(i),period); joint_handles_[i].setCommand(tau_cmd_(i)); } } void OneTaskInverseKinematics::command_configuration(const lwr_controllers::PoseRPY::ConstPtr &msg) { KDL::Frame frame_des_; switch(msg->id) { case 0: frame_des_ = KDL::Frame( KDL::Rotation::RPY(msg->orientation.roll, msg->orientation.pitch, msg->orientation.yaw), KDL::Vector(msg->position.x, msg->position.y, msg->position.z)); break; case 1: // position only frame_des_ = KDL::Frame( KDL::Vector(msg->position.x, msg->position.y, msg->position.z)); break; case 2: // orientation only frame_des_ = KDL::Frame( KDL::Rotation::RPY(msg->orientation.roll, msg->orientation.pitch, msg->orientation.yaw)); break; default: ROS_INFO("Wrong message ID"); return; } x_des_ = frame_des_; cmd_flag_ = 1; } void OneTaskInverseKinematics::set_gains(const std_msgs::Float64MultiArray::ConstPtr &msg) { if(msg->data.size() == 3) { for(int i = 0; i < PIDs_.size(); i++) PIDs_[i].setGains(msg->data[0],msg->data[1],msg->data[2],0.3,-0.3); ROS_INFO("New gains set: Kp = %f, Ki = %f, Kd = %f",msg->data[0],msg->data[1],msg->data[2]); } else ROS_INFO("PIDs gains needed are 3 (Kp, Ki and Kd)"); } } PLUGINLIB_EXPORT_CLASS(lwr_controllers::OneTaskInverseKinematics, controller_interface::ControllerBase) <|endoftext|>
<commit_before>// Copyright 2016 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cmath> #include <Correlator.hpp> namespace TuneBench { CorrelatorConf::CorrelatorConf() : isa::OpenCL::KernelConf(), width(1), height(1) {} std::string CorrelatorConf::print() const { return std::to_string(width) + " " + std::to_string(height) + " " + isa::OpenCL::KernelConf::print(); } std::string * getCorrelatorOpenCL(const CorrelatorConf & conf, const std::string & dataName, const unsigned int padding, const unsigned int nrChannels, const unsigned int nrStations, const unsigned int nrSamples, const unsigned int nrPolarizations) { std::string * code = new std::string(); // Begin kernel's template *code = "__kernel void correlator(__global const " + dataName + "4 * const restrict input, __global " + dataName + "8 * const restrict output, __global const unsigned int * const restrict cellMapX, __global const unsigned int * const restrict cellMapY) {\n" "const unsigned int cell = (get_group_id(0) * " + std::to_string(conf.getNrThreadsD0() * conf.getNrItemsD0()) + ") + get_local_id(0);\n" "const unsigned int channel = (get_group_id(2) * " + std::to_string(conf.getNrThreadsD2()) + ") + get_local_id(2);\n" "const unsigned int baseStationX = cellMapX[cell];\n" "const unsigned int baseStationY = cellMapY[cell];\n" "<%DEFINE_STATION%>" "<%DEFINE_CELL%>" "\n" "// Compute\n" "for ( unsigned int sample = 0; sample < " + std::to_string(nrSamples) + "; sample += " + std::to_string(conf.getNrItemsD1()) + " ) {\n" "<%LOAD_AND_COMPUTE%>" "}\n" "<%STORE%>" "}\n"; std::string defineStationX_sTemplate = dataName + "4 sampleStationX<%STATION%>P0 = (" + dataName + "4)(0.0);\n"; std::string defineStationY_sTemplate = dataName + "4 sampleStationY<%STATION%>P1 = (" + dataName + "4)(0.0);\n"; std::string defineCell_sTemplate = dataName + "8 accumulator<%CELL%> = (" + dataName + "8)(0.0);\n"; std::string loadX_sTemplate = "sampleStationX<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationX<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::string loadY_sTemplate = "sampleStationY<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationY<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::vector< std::string > compute_sTemplate(8); compute_sTemplate[0] = "accumulator<%CELL%>.s0 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.y));\n"; compute_sTemplate[1] = "accumulator<%CELL%>.s1 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.x);\n"; compute_sTemplate[2] = "accumulator<%CELL%>.s2 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.w));\n"; compute_sTemplate[3] = "accumulator<%CELL%>.s3 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.z);\n"; compute_sTemplate[4] = "accumulator<%CELL%>.s4 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.y));\n"; compute_sTemplate[5] = "accumulator<%CELL%>.s5 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.x);\n"; compute_sTemplate[6] = "accumulator<%CELL%>.s6 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.w));\n"; compute_sTemplate[7] = "accumulator<%CELL%>.s7 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.z);\n"; std::string store_sTemplate = "output[(((((stationY + <%HEIGHT%>) * (stationY + <%HEIGHT%> + 1)) / 2) + stationX + <%WIDTH%>) * " + std::to_string(nrChannels) + ") + channel] = accumulator<%CELL%>;\n"; // End kernel's template std::string * defineStation_s = new std::string(); std::string * defineCell_s = new std::string(); std::string * loadCompute_s = new std::string(); std::string * store_s = new std::string(); std::string * temp = 0; std::string empty_s = ""; for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); temp = isa::utils::replace(&defineStationX_sTemplate, "<%STATION%>", width_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineStationY_sTemplate, "<%STATION%>", height_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string cell_s = std::to_string(width) + std::to_string(height); std::string width_s = std::to_string(width); std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineCell_sTemplate, "<%CELL%>", cell_s); defineCell_s->append(*temp); delete temp; if ( width == 0 ) { temp = isa::utils::replace(&store_sTemplate, " + <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&store_sTemplate, "<%WIDTH%>", width_s); } if ( height == 0 ) { temp = isa::utils::replace(temp, " + <%HEIGHT%>", empty_s, true); } else { temp = isa::utils::replace(temp, "<%HEIGHT%>", height_s, true); } temp = isa::utils::replace(temp, "<%CELL%>", cell_s, true); store_s->append(*temp); delete temp; } } for ( unsigned int sample = 0; sample < conf.getNrItemsD1(); sample++ ) { std::string offsetD1_s = std::to_string(sample); for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); if ( width == 0 ) { temp = isa::utils::replace(&loadX_sTemplate, "+ <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&loadX_sTemplate, "<%WIDTH%>", width_s); } temp = isa::utils::replace(temp, "<%STATION%>", width_s, true); loadCompute_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); if ( height == 0 ) { temp = isa::utils::replace(&loadY_sTemplate, "+ <%HEIGHT%>", empty_s); } else { temp = isa::utils::replace(&loadY_sTemplate, "<%HEIGHT%>", height_s); } temp = isa::utils::replace(temp, "<%STATION%>", height_s, true); loadCompute_s->append(*temp); delete temp; } loadCompute_s = isa::utils::replace(loadCompute_s, "<%OFFSETD1%>", offsetD1_s, true); for ( unsigned int computeStatement = 0; computeStatement < 8; computeStatement++ ) { for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string cell_s = std::to_string(width) + std::to_string(height); temp = isa::utils::replace(&compute_sTemplate[computeStatement], "<%CELL%>", cell_s); loadCompute_s->append(*temp); delete temp; } } } } code = isa::utils::replace(code, "<%DEFINE_STATION%>", *defineStation_s, true); code = isa::utils::replace(code, "<%DEFINE_CELL%>", *defineCell_s, true); code = isa::utils::replace(code, "<%LOAD_AND_COMPUTE%>", *loadCompute_s, true); code = isa::utils::replace(code, "<%STORE%>", *store_s, true); delete defineStation_s; delete defineCell_s; delete loadCompute_s; delete store_s; return code; } unsigned int generateCellMap(const CorrelatorConf & conf, std::vector< unsigned int > & cellMapX, std::vector< unsigned int > & cellMapY, const unsigned int nrStations) { unsigned int nrCells = 0; cellMapX.clear(); cellMapY.clear(); for ( int stationY = nrStations - conf.getCellHeight(); stationY >= 0; stationY -= conf.getCellHeight() ) { for ( int stationX = 0; stationX + static_cast< int >(conf.getCellWidth()) - 1 <= stationY; stationX += conf.getCellWidth() ) { nrCells++; cellMapX.push_back(stationX); cellMapY.push_back(stationY); } } return nrCells; } }; // TuneBench <commit_msg>Cleaning the sample in the loads.<commit_after>// Copyright 2016 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cmath> #include <Correlator.hpp> namespace TuneBench { CorrelatorConf::CorrelatorConf() : isa::OpenCL::KernelConf(), width(1), height(1) {} std::string CorrelatorConf::print() const { return std::to_string(width) + " " + std::to_string(height) + " " + isa::OpenCL::KernelConf::print(); } std::string * getCorrelatorOpenCL(const CorrelatorConf & conf, const std::string & dataName, const unsigned int padding, const unsigned int nrChannels, const unsigned int nrStations, const unsigned int nrSamples, const unsigned int nrPolarizations) { std::string * code = new std::string(); // Begin kernel's template *code = "__kernel void correlator(__global const " + dataName + "4 * const restrict input, __global " + dataName + "8 * const restrict output, __global const unsigned int * const restrict cellMapX, __global const unsigned int * const restrict cellMapY) {\n" "const unsigned int cell = (get_group_id(0) * " + std::to_string(conf.getNrThreadsD0() * conf.getNrItemsD0()) + ") + get_local_id(0);\n" "const unsigned int channel = (get_group_id(2) * " + std::to_string(conf.getNrThreadsD2()) + ") + get_local_id(2);\n" "const unsigned int baseStationX = cellMapX[cell];\n" "const unsigned int baseStationY = cellMapY[cell];\n" "<%DEFINE_STATION%>" "<%DEFINE_CELL%>" "\n" "// Compute\n" "for ( unsigned int sample = 0; sample < " + std::to_string(nrSamples) + "; sample += " + std::to_string(conf.getNrItemsD1()) + " ) {\n" "<%LOAD_AND_COMPUTE%>" "}\n" "<%STORE%>" "}\n"; std::string defineStationX_sTemplate = dataName + "4 sampleStationX<%STATION%>P0 = (" + dataName + "4)(0.0);\n"; std::string defineStationY_sTemplate = dataName + "4 sampleStationY<%STATION%>P1 = (" + dataName + "4)(0.0);\n"; std::string defineCell_sTemplate = dataName + "8 accumulator<%CELL%> = (" + dataName + "8)(0.0);\n"; std::string loadX_sTemplate = "sampleStationX<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationX<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::string loadY_sTemplate = "sampleStationY<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationY<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::vector< std::string > compute_sTemplate(8); compute_sTemplate[0] = "accumulator<%CELL%>.s0 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.y));\n"; compute_sTemplate[1] = "accumulator<%CELL%>.s1 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.x);\n"; compute_sTemplate[2] = "accumulator<%CELL%>.s2 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.w));\n"; compute_sTemplate[3] = "accumulator<%CELL%>.s3 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.z);\n"; compute_sTemplate[4] = "accumulator<%CELL%>.s4 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.y));\n"; compute_sTemplate[5] = "accumulator<%CELL%>.s5 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.x);\n"; compute_sTemplate[6] = "accumulator<%CELL%>.s6 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.w));\n"; compute_sTemplate[7] = "accumulator<%CELL%>.s7 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.z);\n"; std::string store_sTemplate = "output[(((((stationY + <%HEIGHT%>) * (stationY + <%HEIGHT%> + 1)) / 2) + stationX + <%WIDTH%>) * " + std::to_string(nrChannels) + ") + channel] = accumulator<%CELL%>;\n"; // End kernel's template std::string * defineStation_s = new std::string(); std::string * defineCell_s = new std::string(); std::string * loadCompute_s = new std::string(); std::string * store_s = new std::string(); std::string * temp = 0; std::string empty_s = ""; for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); temp = isa::utils::replace(&defineStationX_sTemplate, "<%STATION%>", width_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineStationY_sTemplate, "<%STATION%>", height_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string cell_s = std::to_string(width) + std::to_string(height); std::string width_s = std::to_string(width); std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineCell_sTemplate, "<%CELL%>", cell_s); defineCell_s->append(*temp); delete temp; if ( width == 0 ) { temp = isa::utils::replace(&store_sTemplate, " + <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&store_sTemplate, "<%WIDTH%>", width_s); } if ( height == 0 ) { temp = isa::utils::replace(temp, " + <%HEIGHT%>", empty_s, true); } else { temp = isa::utils::replace(temp, "<%HEIGHT%>", height_s, true); } temp = isa::utils::replace(temp, "<%CELL%>", cell_s, true); store_s->append(*temp); delete temp; } } for ( unsigned int sample = 0; sample < conf.getNrItemsD1(); sample++ ) { std::string offsetD1_s = std::to_string(sample); for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); if ( width == 0 ) { temp = isa::utils::replace(&loadX_sTemplate, "+ <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&loadX_sTemplate, "<%WIDTH%>", width_s); } temp = isa::utils::replace(temp, "<%STATION%>", width_s, true); loadCompute_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); if ( height == 0 ) { temp = isa::utils::replace(&loadY_sTemplate, "+ <%HEIGHT%>", empty_s); } else { temp = isa::utils::replace(&loadY_sTemplate, "<%HEIGHT%>", height_s); } temp = isa::utils::replace(temp, "<%STATION%>", height_s, true); loadCompute_s->append(*temp); delete temp; } if ( sample == 0 ) { loadCompute_s = isa::utils::replace(loadCompute_s, " + <%OFFSETD1%>", empty_s, true); } else { loadCompute_s = isa::utils::replace(loadCompute_s, "<%OFFSETD1%>", offsetD1_s, true); } for ( unsigned int computeStatement = 0; computeStatement < 8; computeStatement++ ) { for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string cell_s = std::to_string(width) + std::to_string(height); temp = isa::utils::replace(&compute_sTemplate[computeStatement], "<%CELL%>", cell_s); loadCompute_s->append(*temp); delete temp; } } } } code = isa::utils::replace(code, "<%DEFINE_STATION%>", *defineStation_s, true); code = isa::utils::replace(code, "<%DEFINE_CELL%>", *defineCell_s, true); code = isa::utils::replace(code, "<%LOAD_AND_COMPUTE%>", *loadCompute_s, true); code = isa::utils::replace(code, "<%STORE%>", *store_s, true); delete defineStation_s; delete defineCell_s; delete loadCompute_s; delete store_s; return code; } unsigned int generateCellMap(const CorrelatorConf & conf, std::vector< unsigned int > & cellMapX, std::vector< unsigned int > & cellMapY, const unsigned int nrStations) { unsigned int nrCells = 0; cellMapX.clear(); cellMapY.clear(); for ( int stationY = nrStations - conf.getCellHeight(); stationY >= 0; stationY -= conf.getCellHeight() ) { for ( int stationX = 0; stationX + static_cast< int >(conf.getCellWidth()) - 1 <= stationY; stationX += conf.getCellWidth() ) { nrCells++; cellMapX.push_back(stationX); cellMapY.push_back(stationY); } } return nrCells; } }; // TuneBench <|endoftext|>
<commit_before>/** * @function findContours_Demo.cpp * @brief Demo code to find contours in an image * @author OpenCV team */ #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace cv; using namespace std; Mat src; Mat src_gray; int thresh = 100; int max_thresh = 255; RNG rng(12345); /// Function header void thresh_callback(int, void* ); /** * @function main */ int main( int, char** argv ) { /// Load source image and convert it to gray src = imread( argv[1], 1 ); /// Convert image to gray and blur it cvtColor( src, src_gray, COLOR_BGR2GRAY ); blur( src_gray, src_gray, Size(3,3) ); /// Create Window const char* source_window = "Source"; namedWindow( source_window, WINDOW_AUTOSIZE ); imshow( source_window, src ); createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback ); thresh_callback( 0, 0 ); waitKey(0); return(0); } /** * @function thresh_callback */ void thresh_callback(int, void* ) { Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// Detect edges using canny Canny( src_gray, canny_output, thresh, thresh*2, 3 ); /// Find contours findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) ); /// Draw contours Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 ); for( size_t i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point() ); } /// Show in a window namedWindow( "Contours", WINDOW_AUTOSIZE ); imshow( "Contours", drawing ); } <commit_msg>findcontour_example check image empty<commit_after>/** * @function findContours_Demo.cpp * @brief Demo code to find contours in an image * @author OpenCV team */ #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace cv; using namespace std; Mat src; Mat src_gray; int thresh = 100; int max_thresh = 255; RNG rng(12345); /// Function header void thresh_callback(int, void* ); /** * @function main */ int main( int, char** argv ) { /// Load source image src = imread(argv[1]); if (src.empty()) { cerr << "No image supplied ..." << endl; return -1; } /// Convert image to gray and blur it cvtColor( src, src_gray, COLOR_BGR2GRAY ); blur( src_gray, src_gray, Size(3,3) ); /// Create Window const char* source_window = "Source"; namedWindow( source_window, WINDOW_AUTOSIZE ); imshow( source_window, src ); createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback ); thresh_callback( 0, 0 ); waitKey(0); return(0); } /** * @function thresh_callback */ void thresh_callback(int, void* ) { Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// Detect edges using canny Canny( src_gray, canny_output, thresh, thresh*2, 3 ); /// Find contours findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) ); /// Draw contours Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 ); for( size_t i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point() ); } /// Show in a window namedWindow( "Contours", WINDOW_AUTOSIZE ); imshow( "Contours", drawing ); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/planning/lattice/trajectory_generator/trajectory_combiner.h" #include <algorithm> #include "modules/planning/common/planning_gflags.h" #include "modules/planning/lattice/util/reference_line_matcher.h" #include "modules/planning/math/frame_conversion/cartesian_frenet_conversion.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; DiscretizedTrajectory TrajectoryCombiner::Combine( const std::vector<PathPoint>& reference_line, const Curve1d& lon_trajectory, const Curve1d& lat_trajectory, const double init_relative_time) { DiscretizedTrajectory combined_trajectory; double s0 = lon_trajectory.Evaluate(0, 0.0); double s_ref_max = reference_line.back().s(); double t_param = 0.0; while (t_param < FLAGS_trajectory_time_length) { // linear extrapolation is handled internally in LatticeTrajectory1d; // no worry about t_param > lon_trajectory.ParamLength() situation double s = lon_trajectory.Evaluate(0, t_param); double s_dot = std::max(FLAGS_lattice_epsilon, lon_trajectory.Evaluate(1, t_param)); double s_ddot = lon_trajectory.Evaluate(2, t_param); if (s > s_ref_max) { break; } double s_param = s - s0; // linear extrapolation is handled internally in LatticeTrajectory1d; // no worry about s_param > lat_trajectory.ParamLength() situation double d = lat_trajectory.Evaluate(0, s_param); double d_prime = lat_trajectory.Evaluate(1, s_param); double d_pprime = lat_trajectory.Evaluate(2, s_param); PathPoint matched_ref_point = ReferenceLineMatcher::MatchToReferenceLine(reference_line, s); double x = 0.0; double y = 0.0; double theta = 0.0; double kappa = 0.0; double v = 0.0; double a = 0.0; const double rs = matched_ref_point.s(); const double rx = matched_ref_point.x(); const double ry = matched_ref_point.y(); const double rtheta = matched_ref_point.theta(); const double rkappa = matched_ref_point.kappa(); const double rdkappa = matched_ref_point.dkappa(); std::array<double, 3> s_conditions = {rs, s_dot, s_ddot}; std::array<double, 3> d_conditions = {d, d_prime, d_pprime}; CartesianFrenetConverter::frenet_to_cartesian( rs, rx, ry, rtheta, rkappa, rdkappa, s_conditions, d_conditions, &x, &y, &theta, &kappa, &v, &a); TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->set_x(x); trajectory_point.mutable_path_point()->set_y(y); trajectory_point.mutable_path_point()->set_theta(theta); trajectory_point.mutable_path_point()->set_kappa(kappa); trajectory_point.set_v(v); trajectory_point.set_a(a); trajectory_point.set_relative_time(t_param + init_relative_time); combined_trajectory.AppendTrajectoryPoint(trajectory_point); t_param = t_param + FLAGS_trajectory_time_resolution; } return combined_trajectory; } } // namespace planning } // namespace apollo <commit_msg>Planning: [lattice] set s in trajectory point<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/planning/lattice/trajectory_generator/trajectory_combiner.h" #include <algorithm> #include "modules/planning/common/planning_gflags.h" #include "modules/planning/lattice/util/reference_line_matcher.h" #include "modules/planning/math/frame_conversion/cartesian_frenet_conversion.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; DiscretizedTrajectory TrajectoryCombiner::Combine( const std::vector<PathPoint>& reference_line, const Curve1d& lon_trajectory, const Curve1d& lat_trajectory, const double init_relative_time) { DiscretizedTrajectory combined_trajectory; double s0 = lon_trajectory.Evaluate(0, 0.0); double s_ref_max = reference_line.back().s(); double accumulated_trajectory_s = 0.0; PathPoint prev_trajectory_point; double t_param = 0.0; while (t_param < FLAGS_trajectory_time_length) { // linear extrapolation is handled internally in LatticeTrajectory1d; // no worry about t_param > lon_trajectory.ParamLength() situation double s = lon_trajectory.Evaluate(0, t_param); double s_dot = std::max(FLAGS_lattice_epsilon, lon_trajectory.Evaluate(1, t_param)); double s_ddot = lon_trajectory.Evaluate(2, t_param); if (s > s_ref_max) { break; } double s_param = s - s0; // linear extrapolation is handled internally in LatticeTrajectory1d; // no worry about s_param > lat_trajectory.ParamLength() situation double d = lat_trajectory.Evaluate(0, s_param); double d_prime = lat_trajectory.Evaluate(1, s_param); double d_pprime = lat_trajectory.Evaluate(2, s_param); PathPoint matched_ref_point = ReferenceLineMatcher::MatchToReferenceLine(reference_line, s); double x = 0.0; double y = 0.0; double theta = 0.0; double kappa = 0.0; double v = 0.0; double a = 0.0; const double rs = matched_ref_point.s(); const double rx = matched_ref_point.x(); const double ry = matched_ref_point.y(); const double rtheta = matched_ref_point.theta(); const double rkappa = matched_ref_point.kappa(); const double rdkappa = matched_ref_point.dkappa(); std::array<double, 3> s_conditions = {rs, s_dot, s_ddot}; std::array<double, 3> d_conditions = {d, d_prime, d_pprime}; CartesianFrenetConverter::frenet_to_cartesian( rs, rx, ry, rtheta, rkappa, rdkappa, s_conditions, d_conditions, &x, &y, &theta, &kappa, &v, &a); if (prev_trajectory_point.has_x() && prev_trajectory_point.has_y()) { double delta_x = x - prev_trajectory_point.x(); double delta_y = y - prev_trajectory_point.y(); double delta_s = std::hypot(delta_x, delta_y); accumulated_trajectory_s += delta_s; } TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->set_x(x); trajectory_point.mutable_path_point()->set_y(y); trajectory_point.mutable_path_point()->set_s(accumulated_trajectory_s); trajectory_point.mutable_path_point()->set_theta(theta); trajectory_point.mutable_path_point()->set_kappa(kappa); trajectory_point.set_v(v); trajectory_point.set_a(a); trajectory_point.set_relative_time(t_param + init_relative_time); combined_trajectory.AppendTrajectoryPoint(trajectory_point); t_param = t_param + FLAGS_trajectory_time_resolution; prev_trajectory_point = trajectory_point.path_point(); } return combined_trajectory; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// Copyright 2018 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "src/pdf/SkPDFSubsetFont.h" #if defined(SK_USING_THIRD_PARTY_ICU) #include "SkLoadICU.h" #endif #if defined(SK_PDF_USE_HARFBUZZ_SUBSET) #include "include/private/SkTemplates.h" #include "include/private/SkTo.h" #include "src/utils/SkCallableTraits.h" #include "hb.h" #include "hb-subset.h" template <class T, void(*P)(T*)> using resource = std::unique_ptr<T, SkFunctionWrapper<std::remove_pointer_t<decltype(P)>, P>>; using HBBlob = resource<hb_blob_t, &hb_blob_destroy>; using HBFace = resource<hb_face_t, &hb_face_destroy>; using HBSubsetInput = resource<hb_subset_input_t, &hb_subset_input_destroy>; using HBSet = resource<hb_set_t, &hb_set_destroy>; static HBBlob to_blob(sk_sp<SkData> data) { using blob_size_t = SkCallableTraits<decltype(hb_blob_create)>::argument<1>::type; if (!SkTFitsIn<blob_size_t>(data->size())) { return nullptr; } const char* blobData = static_cast<const char*>(data->data()); blob_size_t blobSize = SkTo<blob_size_t>(data->size()); return HBBlob(hb_blob_create(blobData, blobSize, HB_MEMORY_MODE_READONLY, data.release(), [](void* p){ ((SkData*)p)->unref(); })); } static sk_sp<SkData> to_data(HBBlob blob) { if (!blob) { return nullptr; } unsigned int length; const char* data = hb_blob_get_data(blob.get(), &length); if (!data || !length) { return nullptr; } return SkData::MakeWithProc(data, SkToSizeT(length), [](const void*, void* ctx) { hb_blob_destroy((hb_blob_t*)ctx); }, blob.release()); } template<typename...> using void_t = void; template<typename T, typename = void> struct SkPDFHarfBuzzSubset { // This is the HarfBuzz 3.0 interface. // hb_subset_flags_t does not exist in 2.0. It isn't dependent on T, so inline the value of // HB_SUBSET_FLAGS_RETAIN_GIDS until 2.0 is no longer supported. static HBFace Make(T input, hb_face_t* face) { // TODO: When possible, check if a font is 'tricky' with FT_IS_TRICKY. // If it isn't known if a font is 'tricky', retain the hints. hb_subset_input_set_flags(input, 2/*HB_SUBSET_FLAGS_RETAIN_GIDS*/); return HBFace(hb_subset_or_fail(face, input)); } }; template<typename T> struct SkPDFHarfBuzzSubset<T, void_t< decltype(hb_subset_input_set_retain_gids(std::declval<T>(), std::declval<bool>())), decltype(hb_subset_input_set_drop_hints(std::declval<T>(), std::declval<bool>())), decltype(hb_subset(std::declval<hb_face_t*>(), std::declval<T>())) >> { // This is the HarfBuzz 2.0 (non-public) interface, used if it exists. // This code should be removed as soon as all users are migrated to the newer API. static HBFace Make(T input, hb_face_t* face) { hb_subset_input_set_retain_gids(input, true); // TODO: When possible, check if a font is 'tricky' with FT_IS_TRICKY. // If it isn't known if a font is 'tricky', retain the hints. hb_subset_input_set_drop_hints(input, false); return HBFace(hb_subset(face, input)); } }; static sk_sp<SkData> subset_harfbuzz(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, int ttcIndex) { #if defined(SK_USING_THIRD_PARTY_ICU) if (!SkLoadICU()) { return nullptr; } #endif if (!fontData) { return nullptr; } HBFace face(hb_face_create(to_blob(std::move(fontData)).get(), ttcIndex)); SkASSERT(face); HBSubsetInput input(hb_subset_input_create_or_fail()); SkASSERT(input); if (!face || !input) { return nullptr; } hb_set_t* glyphs = hb_subset_input_glyph_set(input.get()); glyphUsage.getSetValues([&glyphs](unsigned gid) { hb_set_add(glyphs, gid);}); HBFace subset = SkPDFHarfBuzzSubset<hb_subset_input_t*>::Make(input.get(), face.get()); if (!subset) { return nullptr; } HBBlob result(hb_face_reference_blob(subset.get())); return to_data(std::move(result)); } #endif // defined(SK_PDF_USE_HARFBUZZ_SUBSET) //////////////////////////////////////////////////////////////////////////////// #if defined(SK_PDF_USE_SFNTLY) #include "sample/chromium/font_subsetter.h" #include <vector> static sk_sp<SkData> subset_sfntly(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, const char* fontName, int ttcIndex) { #if defined(SK_USING_THIRD_PARTY_ICU) if (!SkLoadICU()) { return nullptr; } #endif // Generate glyph id array in format needed by sfntly. // TODO(halcanary): sfntly should take a more compact format. std::vector<unsigned> subset; glyphUsage.getSetValues([&subset](unsigned v) { subset.push_back(v); }); unsigned char* subsetFont{nullptr}; #if defined(SK_BUILD_FOR_GOOGLE3) // TODO(halcanary): update SK_BUILD_FOR_GOOGLE3 to newest version of Sfntly. (void)ttcIndex; int subsetFontSize = SfntlyWrapper::SubsetFont(fontName, fontData->bytes(), fontData->size(), subset.data(), subset.size(), &subsetFont); #else // defined(SK_BUILD_FOR_GOOGLE3) (void)fontName; int subsetFontSize = SfntlyWrapper::SubsetFont(ttcIndex, fontData->bytes(), fontData->size(), subset.data(), subset.size(), &subsetFont); #endif // defined(SK_BUILD_FOR_GOOGLE3) SkASSERT(subsetFontSize > 0 || subsetFont == nullptr); if (subsetFontSize < 1 || subsetFont == nullptr) { return nullptr; } return SkData::MakeWithProc(subsetFont, subsetFontSize, [](const void* p, void*) { delete[] (unsigned char*)p; }, nullptr); } #endif // defined(SK_PDF_USE_SFNTLY) //////////////////////////////////////////////////////////////////////////////// #if defined(SK_PDF_USE_SFNTLY) && defined(SK_PDF_USE_HARFBUZZ_SUBSET) sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, SkPDF::Metadata::Subsetter subsetter, const char* fontName, int ttcIndex) { switch (subsetter) { case SkPDF::Metadata::kHarfbuzz_Subsetter: return subset_harfbuzz(std::move(fontData), glyphUsage, ttcIndex); case SkPDF::Metadata::kSfntly_Subsetter: return subset_sfntly(std::move(fontData), glyphUsage, fontName, ttcIndex); } return nullptr; } #elif defined(SK_PDF_USE_SFNTLY) sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, SkPDF::Metadata::Subsetter, const char* fontName, int ttcIndex) { return subset_sfntly(std::move(fontData), glyphUsage, fontName, ttcIndex); } #elif defined(SK_PDF_USE_HARFBUZZ_SUBSET) sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, SkPDF::Metadata::Subsetter, const char*, int ttcIndex) { return subset_harfbuzz(std::move(fontData), glyphUsage, ttcIndex); } #else sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData>, const SkPDFGlyphUse&, SkPDF::Metadata::Subsetter, const char*, int) { return nullptr; } #endif // defined(SK_PDF_USE_SFNTLY) <commit_msg>Remove ICU check from subset_harfbuzz<commit_after>// Copyright 2018 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "src/pdf/SkPDFSubsetFont.h" #if defined(SK_PDF_USE_HARFBUZZ_SUBSET) #include "include/private/SkTemplates.h" #include "include/private/SkTo.h" #include "src/utils/SkCallableTraits.h" #include "hb.h" #include "hb-subset.h" template <class T, void(*P)(T*)> using resource = std::unique_ptr<T, SkFunctionWrapper<std::remove_pointer_t<decltype(P)>, P>>; using HBBlob = resource<hb_blob_t, &hb_blob_destroy>; using HBFace = resource<hb_face_t, &hb_face_destroy>; using HBSubsetInput = resource<hb_subset_input_t, &hb_subset_input_destroy>; using HBSet = resource<hb_set_t, &hb_set_destroy>; static HBBlob to_blob(sk_sp<SkData> data) { using blob_size_t = SkCallableTraits<decltype(hb_blob_create)>::argument<1>::type; if (!SkTFitsIn<blob_size_t>(data->size())) { return nullptr; } const char* blobData = static_cast<const char*>(data->data()); blob_size_t blobSize = SkTo<blob_size_t>(data->size()); return HBBlob(hb_blob_create(blobData, blobSize, HB_MEMORY_MODE_READONLY, data.release(), [](void* p){ ((SkData*)p)->unref(); })); } static sk_sp<SkData> to_data(HBBlob blob) { if (!blob) { return nullptr; } unsigned int length; const char* data = hb_blob_get_data(blob.get(), &length); if (!data || !length) { return nullptr; } return SkData::MakeWithProc(data, SkToSizeT(length), [](const void*, void* ctx) { hb_blob_destroy((hb_blob_t*)ctx); }, blob.release()); } template<typename...> using void_t = void; template<typename T, typename = void> struct SkPDFHarfBuzzSubset { // This is the HarfBuzz 3.0 interface. // hb_subset_flags_t does not exist in 2.0. It isn't dependent on T, so inline the value of // HB_SUBSET_FLAGS_RETAIN_GIDS until 2.0 is no longer supported. static HBFace Make(T input, hb_face_t* face) { // TODO: When possible, check if a font is 'tricky' with FT_IS_TRICKY. // If it isn't known if a font is 'tricky', retain the hints. hb_subset_input_set_flags(input, 2/*HB_SUBSET_FLAGS_RETAIN_GIDS*/); return HBFace(hb_subset_or_fail(face, input)); } }; template<typename T> struct SkPDFHarfBuzzSubset<T, void_t< decltype(hb_subset_input_set_retain_gids(std::declval<T>(), std::declval<bool>())), decltype(hb_subset_input_set_drop_hints(std::declval<T>(), std::declval<bool>())), decltype(hb_subset(std::declval<hb_face_t*>(), std::declval<T>())) >> { // This is the HarfBuzz 2.0 (non-public) interface, used if it exists. // This code should be removed as soon as all users are migrated to the newer API. static HBFace Make(T input, hb_face_t* face) { hb_subset_input_set_retain_gids(input, true); // TODO: When possible, check if a font is 'tricky' with FT_IS_TRICKY. // If it isn't known if a font is 'tricky', retain the hints. hb_subset_input_set_drop_hints(input, false); return HBFace(hb_subset(face, input)); } }; static sk_sp<SkData> subset_harfbuzz(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, int ttcIndex) { if (!fontData) { return nullptr; } HBFace face(hb_face_create(to_blob(std::move(fontData)).get(), ttcIndex)); SkASSERT(face); HBSubsetInput input(hb_subset_input_create_or_fail()); SkASSERT(input); if (!face || !input) { return nullptr; } hb_set_t* glyphs = hb_subset_input_glyph_set(input.get()); glyphUsage.getSetValues([&glyphs](unsigned gid) { hb_set_add(glyphs, gid);}); HBFace subset = SkPDFHarfBuzzSubset<hb_subset_input_t*>::Make(input.get(), face.get()); if (!subset) { return nullptr; } HBBlob result(hb_face_reference_blob(subset.get())); return to_data(std::move(result)); } #endif // defined(SK_PDF_USE_HARFBUZZ_SUBSET) //////////////////////////////////////////////////////////////////////////////// #if defined(SK_PDF_USE_SFNTLY) #include "sample/chromium/font_subsetter.h" #include <vector> static sk_sp<SkData> subset_sfntly(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, const char* fontName, int ttcIndex) { #if defined(SK_USING_THIRD_PARTY_ICU) if (!SkLoadICU()) { return nullptr; } #endif // Generate glyph id array in format needed by sfntly. // TODO(halcanary): sfntly should take a more compact format. std::vector<unsigned> subset; glyphUsage.getSetValues([&subset](unsigned v) { subset.push_back(v); }); unsigned char* subsetFont{nullptr}; #if defined(SK_BUILD_FOR_GOOGLE3) // TODO(halcanary): update SK_BUILD_FOR_GOOGLE3 to newest version of Sfntly. (void)ttcIndex; int subsetFontSize = SfntlyWrapper::SubsetFont(fontName, fontData->bytes(), fontData->size(), subset.data(), subset.size(), &subsetFont); #else // defined(SK_BUILD_FOR_GOOGLE3) (void)fontName; int subsetFontSize = SfntlyWrapper::SubsetFont(ttcIndex, fontData->bytes(), fontData->size(), subset.data(), subset.size(), &subsetFont); #endif // defined(SK_BUILD_FOR_GOOGLE3) SkASSERT(subsetFontSize > 0 || subsetFont == nullptr); if (subsetFontSize < 1 || subsetFont == nullptr) { return nullptr; } return SkData::MakeWithProc(subsetFont, subsetFontSize, [](const void* p, void*) { delete[] (unsigned char*)p; }, nullptr); } #endif // defined(SK_PDF_USE_SFNTLY) //////////////////////////////////////////////////////////////////////////////// #if defined(SK_PDF_USE_SFNTLY) && defined(SK_PDF_USE_HARFBUZZ_SUBSET) sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, SkPDF::Metadata::Subsetter subsetter, const char* fontName, int ttcIndex) { switch (subsetter) { case SkPDF::Metadata::kHarfbuzz_Subsetter: return subset_harfbuzz(std::move(fontData), glyphUsage, ttcIndex); case SkPDF::Metadata::kSfntly_Subsetter: return subset_sfntly(std::move(fontData), glyphUsage, fontName, ttcIndex); } return nullptr; } #elif defined(SK_PDF_USE_SFNTLY) sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, SkPDF::Metadata::Subsetter, const char* fontName, int ttcIndex) { return subset_sfntly(std::move(fontData), glyphUsage, fontName, ttcIndex); } #elif defined(SK_PDF_USE_HARFBUZZ_SUBSET) sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData> fontData, const SkPDFGlyphUse& glyphUsage, SkPDF::Metadata::Subsetter, const char*, int ttcIndex) { return subset_harfbuzz(std::move(fontData), glyphUsage, ttcIndex); } #else sk_sp<SkData> SkPDFSubsetFont(sk_sp<SkData>, const SkPDFGlyphUse&, SkPDF::Metadata::Subsetter, const char*, int) { return nullptr; } #endif // defined(SK_PDF_USE_SFNTLY) <|endoftext|>
<commit_before>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include <stdlib.h> #include "packet.h" #define BUFSIZE 121 #define FILENAME "Testfile" #define TEST_FILENAME "Testfile2" #define PORT 10038 #define PAKSIZE 128 #define ACK 0 #define NAK 1 using namespace std; bool gremlin(Packet * pack, int corruptProb, int lossProb); bool init(int argc, char** argv); bool loadFile(); bool sendFile(); bool getFile(); char * recvPkt(); bool isvpack(unsigned char * p); Packet createPacket(int index); bool sendPacket(); bool isAck(); void handleAck(); void handleNak(int& x); int seqNum; int s; int probCorrupt; int probLoss; string hs; short int port; char * file; unsigned char* window[16]; //packet window int windowBase; //used to determine position in window of arriving packets int length; struct sockaddr_in a; struct sockaddr_in sa; socklen_t salen; string fstr; bool dropPck; Packet p; int delayT; unsigned char b[BUFSIZE]; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } getFile(); return 0; } bool init(int argc, char** argv) { windowBase = 0; //initialize windowBase s = 0; hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */ port = 10038; /* Can be any port within 10038-10041, inclusive. */ char* delayTStr = argv[2]; delayT = boost::lexical_cast<int>(delayTStr); /*if(!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; }*/ if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0? a.sin_port = htons(0); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){ cout << "Socket binding failed. (socket s, address a)" << endl; return false; } memset((char *)&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(port); inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr)); cout << endl; cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl; cout << "Port: " << ntohs(sa.sin_port) << endl; cout << endl << endl; /*fstr = string(file); cout << "File: " << endl << fstr << endl << endl;*/ seqNum = 0; dropPck = false; return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } bool sendFile() { for(int x = 0; x <= length / BUFSIZE; x++) { p = createPacket(x); if(!sendPacket()) continue; if(isAck()) { handleAck(); } else { handleNak(x); } memset(b, 0, BUFSIZE); } return true; } Packet createPacket(int index){ cout << endl; cout << "=== TRANSMISSION START" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(index * BUFSIZE + BUFSIZE > length) { mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (seqNum, mstr.c_str()); } bool sendPacket(){ int pc = probCorrupt; int pl = probLoss; if((dropPck = gremlin(&p, pc, pl)) == false){ if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } else return false; } bool isAck() { recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen); cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool gremlin(Packet * pack, int corruptProb, int lossProb){ bool dropPacket = false; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; if(r <= (lossProb)){ dropPacket = true; cout << "Dropped!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } else seqNum = (seqNum) ? false : true; cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; cout << "Message: " << pack->getDataBuffer() << endl; return dropPacket; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[6]; memcpy(css, &p[1], 6); css[5] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[7], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == seqNum) return false; if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); int rlen; int ack; for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen); /* Begin Window Loading */ int tempSeqNum = boost::lexical_cast<int>(packet[0]); int properIndex = tempSeqNum - windowBase; window[properIndex] = packet; cout << "Packet loaded into window" << endl; char* tempTest = new char[6]; memcpy(tempTest, &window[1], 0); tempTest[5] = '\0'; cout << "The Checksum pulled from client window: " << tempTest[0] << endl; for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; if(isvpack(packet)) { ack = ACK; if(boost::lexical_cast<int>(packet[0]) == windowBase) windowBase++; //increment base of window //FIXME file << dataPull; file.flush(); } else { ack = NAK; } cout << "Sent response: "; cout << ((ack == ACK) ? "ACK " : "NAK ") << windowBase << endl; if(packet[6] == '1') usleep(delayT*1000); if(sendto(s, *windowBase, PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } <commit_msg>please work so close omg<commit_after>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include <stdlib.h> #include "packet.h" #define BUFSIZE 121 #define FILENAME "Testfile" #define TEST_FILENAME "Testfile2" #define PORT 10038 #define PAKSIZE 128 #define ACK 0 #define NAK 1 using namespace std; bool gremlin(Packet * pack, int corruptProb, int lossProb); bool init(int argc, char** argv); bool loadFile(); bool sendFile(); bool getFile(); char * recvPkt(); bool isvpack(unsigned char * p); Packet createPacket(int index); bool sendPacket(); bool isAck(); void handleAck(); void handleNak(int& x); int seqNum; int s; int probCorrupt; int probLoss; string hs; short int port; char * file; unsigned char* window[16]; //packet window int windowBase; //used to determine position in window of arriving packets int length; struct sockaddr_in a; struct sockaddr_in sa; socklen_t salen; string fstr; bool dropPck; Packet p; int delayT; unsigned char b[BUFSIZE]; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } getFile(); return 0; } bool init(int argc, char** argv) { windowBase = 0; //initialize windowBase s = 0; hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */ port = 10038; /* Can be any port within 10038-10041, inclusive. */ char* delayTStr = argv[2]; delayT = boost::lexical_cast<int>(delayTStr); /*if(!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; }*/ if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0? a.sin_port = htons(0); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){ cout << "Socket binding failed. (socket s, address a)" << endl; return false; } memset((char *)&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(port); inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr)); cout << endl; cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl; cout << "Port: " << ntohs(sa.sin_port) << endl; cout << endl << endl; /*fstr = string(file); cout << "File: " << endl << fstr << endl << endl;*/ seqNum = 0; dropPck = false; return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } bool sendFile() { for(int x = 0; x <= length / BUFSIZE; x++) { p = createPacket(x); if(!sendPacket()) continue; if(isAck()) { handleAck(); } else { handleNak(x); } memset(b, 0, BUFSIZE); } return true; } Packet createPacket(int index){ cout << endl; cout << "=== TRANSMISSION START" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(index * BUFSIZE + BUFSIZE > length) { mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (seqNum, mstr.c_str()); } bool sendPacket(){ int pc = probCorrupt; int pl = probLoss; if((dropPck = gremlin(&p, pc, pl)) == false){ if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } else return false; } bool isAck() { recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen); cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool gremlin(Packet * pack, int corruptProb, int lossProb){ bool dropPacket = false; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; if(r <= (lossProb)){ dropPacket = true; cout << "Dropped!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } else seqNum = (seqNum) ? false : true; cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; cout << "Message: " << pack->getDataBuffer() << endl; return dropPacket; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[6]; memcpy(css, &p[1], 6); css[5] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[7], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == seqNum) return false; if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); int rlen; int ack; for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen); /* Begin Window Loading */ int tempSeqNum = boost::lexical_cast<int>(packet[0]); int properIndex = tempSeqNum - windowBase; window[properIndex] = packet; cout << "Packet loaded into window" << endl; char* tempTest = new char[6]; memcpy(tempTest, &window[1], 0); tempTest[5] = '\0'; cout << "The Checksum pulled from client window: " << tempTest[0] << endl; for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; if(isvpack(packet)) { ack = ACK; if(boost::lexical_cast<int>(packet[0]) == windowBase) windowBase++; //increment base of window //FIXME file << dataPull; file.flush(); } else { ack = NAK; } cout << "Sent response: "; cout << ((ack == ACK) ? "ACK " : "NAK ") << windowBase << endl; if(packet[6] == '1') usleep(delayT*1000); string s = tostring(windowBase); const char * ackval = s.c_str(); if(sendto(s, *windowBase, PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/PhysicsComponent.hpp> #include <NDK/Components/VelocityComponent.hpp> namespace Ndk { VelocitySystem::VelocitySystem() { Requires<NodeComponent, VelocityComponent>(); Excludes<PhysicsComponent>(); } void VelocitySystem::OnUpdate(float elapsedTime) { for (const Ndk::EntityHandle& entity : GetEntities()) { NodeComponent& node = entity->GetComponent<NodeComponent>(); const VelocityComponent& velocity = entity->GetComponent<VelocityComponent>(); node.Move(velocity.linearVelocity * elapsedTime); } } SystemIndex VelocitySystem::systemIndex; } <commit_msg>SDK/VelocitySystem: Make VelocitySystem move the node in the global space<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/PhysicsComponent.hpp> #include <NDK/Components/VelocityComponent.hpp> namespace Ndk { VelocitySystem::VelocitySystem() { Requires<NodeComponent, VelocityComponent>(); Excludes<PhysicsComponent>(); } void VelocitySystem::OnUpdate(float elapsedTime) { for (const Ndk::EntityHandle& entity : GetEntities()) { NodeComponent& node = entity->GetComponent<NodeComponent>(); const VelocityComponent& velocity = entity->GetComponent<VelocityComponent>(); node.Move(velocity.linearVelocity * elapsedTime, Nz::CoordSys_Global); } } SystemIndex VelocitySystem::systemIndex; } <|endoftext|>
<commit_before>#include "DebugPanel.h" #include <ui\IMGUI.h> DebugPanel::DebugPanel() : _count(0) , _pos(10,710), _state(1) { } DebugPanel::~DebugPanel() { } void DebugPanel::reset() { _count = 0; } void DebugPanel::show(const char* name, float value) { if (_count + 1 < 32) { DebugEntry& entry = _entries[_count++]; entry.name = name; entry.type = DebugEntry::DT_FLOAT; entry.values[0] = value; } } void DebugPanel::show(const char* name, int value) { if (_count + 1 < 32) { DebugEntry& entry = _entries[_count++]; entry.name = name; entry.type = DebugEntry::DT_INT; entry.values[0] = value; } } void DebugPanel::show(const char* name, const v2& value) { if (_count + 1 < 32) { DebugEntry& entry = _entries[_count++]; entry.name = name; entry.type = DebugEntry::DT_VEC2; entry.values[0] = value.x; entry.values[1] = value.y; } } void DebugPanel::render() { gui::start(1, &_pos); char buffer[128]; if (gui::begin("Debug values", &_state)) { for (int i = 0; i < _count; ++i) { const DebugEntry& entry = _entries[i]; switch (entry.type) { case DebugEntry::DT_FLOAT : sprintf_s(buffer, 128, "%s : %3.2f", entry.name, entry.values[0]); break; case DebugEntry::DT_VEC2: sprintf_s(buffer, 128, "%s : %3.2f , %3.2f", entry.name, entry.values[0], entry.values[1]); break; case DebugEntry::DT_INT: sprintf_s(buffer, 128, "%s : %d", entry.name, static_cast<int>(entry.values[0])); break; } gui::Label(2 + i, buffer); } } gui::end(); }<commit_msg>no more id used by IMGUI<commit_after>#include "DebugPanel.h" #include <ui\IMGUI.h> DebugPanel::DebugPanel() : _count(0) , _pos(10,710), _state(1) { } DebugPanel::~DebugPanel() { } void DebugPanel::reset() { _count = 0; } void DebugPanel::show(const char* name, float value) { if (_count + 1 < 32) { DebugEntry& entry = _entries[_count++]; entry.name = name; entry.type = DebugEntry::DT_FLOAT; entry.values[0] = value; } } void DebugPanel::show(const char* name, int value) { if (_count + 1 < 32) { DebugEntry& entry = _entries[_count++]; entry.name = name; entry.type = DebugEntry::DT_INT; entry.values[0] = value; } } void DebugPanel::show(const char* name, const v2& value) { if (_count + 1 < 32) { DebugEntry& entry = _entries[_count++]; entry.name = name; entry.type = DebugEntry::DT_VEC2; entry.values[0] = value.x; entry.values[1] = value.y; } } void DebugPanel::render() { gui::start(1, &_pos); char buffer[128]; if (gui::begin("Debug values", &_state)) { for (int i = 0; i < _count; ++i) { const DebugEntry& entry = _entries[i]; switch (entry.type) { case DebugEntry::DT_FLOAT : sprintf_s(buffer, 128, "%s : %3.2f", entry.name, entry.values[0]); break; case DebugEntry::DT_VEC2: sprintf_s(buffer, 128, "%s : %3.2f , %3.2f", entry.name, entry.values[0], entry.values[1]); break; case DebugEntry::DT_INT: sprintf_s(buffer, 128, "%s : %d", entry.name, static_cast<int>(entry.values[0])); break; } gui::Label(buffer); } } gui::end(); }<|endoftext|>
<commit_before>#include "Flesh.h" Flesh::Flesh(string skin, float x, float y, int cid, Fighter *cpartner) : Fighter(cid, x, cpartner){ path = "flesh/" + skin + "/"; sprite[IDLE] = Sprite(path + "idle.png", 8, 10); sprite[RUNNING] = Sprite(path + "running.png", 8, 10); sprite[JUMPING] = Sprite(path + "jumping.png", 6, 10); sprite[FALLING] = Sprite(path + "falling.png", 7, 10); sprite[CROUCH] = Sprite(path + "crouch.png", 6, 20); sprite[IDLE_ATK_NEUTRAL_1] = Sprite(path + "idle_atk_neutral.png", 12, 10); sprite[IDLE_ATK_NEUTRAL_2] = Sprite(path + "idle_atk_neutral.png", 12, 10); sprite[IDLE_ATK_NEUTRAL_3] = Sprite(path + "idle_atk_neutral.png", 12, 10); sprite[IDLE_ATK_FRONT] = Sprite(path + "idle_atk_front.png", 4, 10); sprite[JUMP_ATK_DOWN_FALLLOOP] = Sprite(path + "jump_atk_down_fallloop.png", 3, 10); sprite[JUMP_ATK_DOWN_DMG] = Sprite(path + "jump_atk_down_dmg.png", 3, 10); sprite[IDLE_ATK_DOWN] = Sprite(path + "idle_atk_down.png", 4, 10); crouching_size = Vector(84, 59); not_crouching_size = Vector(84, 84); tags["flesh"] = true; tags[skin] = true; box = Rectangle(x, y, 84, 84); } void Flesh::update_machine_state(float delta){ switch(state){ case FighterState::IDLE_ATK_NEUTRAL_1: if(sprite[state].is_finished()){ check_idle(); check_crouch(); check_idle_atk_neutral_2(); }else if(pressed[ATTACK_BUTTON]){ combo++; } break; case FighterState::IDLE_ATK_NEUTRAL_2: if(sprite[state].is_finished()){ check_idle(); check_crouch(); check_idle_atk_neutral_3(); }else if(pressed[ATTACK_BUTTON]){ combo++; } break; case FighterState::IDLE_ATK_NEUTRAL_3: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::IDLE_ATK_FRONT: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::JUMP_ATK_DOWN_FALLLOOP: speed.x = 3 * (orientation == LEFT ? -1 : 1); speed.y = 3; check_jump_atk_down_dmg(); if(on_floor){ printf("to no chao, parsa\n"); speed.x = 0; speed.y = 0; check_idle(); check_left(); check_right(); } break; case FighterState::JUMP_ATK_DOWN_DMG: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::IDLE_ATK_DOWN: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::IDLE: combo = 0; check_jump(); check_left(); check_right(); check_idle_atk_down(); check_crouch(); check_fall(); check_idle_atk_neutral_1(); check_idle_atk_front(); break; case FighterState::JUMPING: check_left(false); check_right(false); check_fall(); check_jump_atk_down_fallloop(); check_idle(); break; case FighterState::FALLING: check_idle(); check_left(false); check_right(false); check_fall(); check_crouch(); check_jump_atk_down_fallloop(); break; case FighterState::RUNNING: check_jump(); check_left(false); check_right(false); check_idle(); check_crouch(); check_idle_atk_neutral_1(); check_idle_atk_front(); check_fall(); break; case FighterState::CROUCH: check_idle(); check_fall(); break; } } void Flesh::check_jump(bool change){ if(pressed[JUMP_BUTTON]){ if(change) temporary_state = FighterState::JUMPING; speed.y = -5; on_floor = false; } } void Flesh::check_fall(bool change){ if(speed.y > 0){ if(change) temporary_state = FighterState::FALLING; } } void Flesh::check_left(bool change){ if(is_holding[LEFT_BUTTON]){ if(change) temporary_state = FighterState::RUNNING; speed.x = -2; orientation = Orientation::LEFT; } } void Flesh::check_right(bool change){ if(is_holding[RIGHT_BUTTON]){ if(change) temporary_state = FighterState::RUNNING; speed.x = 2; orientation = Orientation::RIGHT; } } void Flesh::check_idle(bool change){ if(speed.x == 0 and on_floor and not is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::IDLE; printf("Temporary state = %d\n", temporary_state); } } void Flesh::check_crouch(bool change){ if(is_holding[DOWN_BUTTON] and not is_holding[ATTACK_BUTTON] and on_floor){ if(change) temporary_state = FighterState::CROUCH; } } void Flesh::check_idle_atk_neutral_1(bool change){ if(pressed[ATTACK_BUTTON] and not is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::IDLE_ATK_NEUTRAL_1; } } void Flesh::check_idle_atk_neutral_2(bool change){ printf("Pressing: %d\n", is_holding[ATTACK_BUTTON]); if(combo){ combo--; if(change) temporary_state = FighterState::IDLE_ATK_NEUTRAL_2; } } void Flesh::check_idle_atk_neutral_3(bool change){ if(combo){ combo--; if(change) temporary_state = FighterState::IDLE_ATK_NEUTRAL_3; } } void Flesh::check_idle_atk_front(bool change){ if(pressed[ATTACK_BUTTON] and (is_holding[LEFT_BUTTON] or is_holding[RIGHT_BUTTON])){ if(change) temporary_state = FighterState::IDLE_ATK_FRONT; orientation = is_holding[LEFT_BUTTON] ? Orientation::LEFT : Orientation::RIGHT; } } void Flesh::check_jump_atk_down_fallloop(bool change){ if(pressed[ATTACK_BUTTON] and is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::JUMP_ATK_DOWN_FALLLOOP; } } void Flesh::check_jump_atk_down_dmg(bool change){ if(grab){ if(change) temporary_state = FighterState::JUMP_ATK_DOWN_DMG; } } void Flesh::check_idle_atk_down(bool change){ if(is_holding[ATTACK_BUTTON] and is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::IDLE_ATK_DOWN; } } void Flesh::check_pass_through_platform(bool change){ } void Flesh::check_defense(bool change){ } void Flesh::check_stunt(bool change){ } void Flesh::check_dead(bool change){ } <commit_msg>Fix fallloop bug<commit_after>#include "Flesh.h" Flesh::Flesh(string skin, float x, float y, int cid, Fighter *cpartner) : Fighter(cid, x, cpartner){ path = "flesh/" + skin + "/"; sprite[IDLE] = Sprite(path + "idle.png", 8, 10); sprite[RUNNING] = Sprite(path + "running.png", 8, 10); sprite[JUMPING] = Sprite(path + "jumping.png", 6, 10); sprite[FALLING] = Sprite(path + "falling.png", 7, 10); sprite[CROUCH] = Sprite(path + "crouch.png", 6, 20); sprite[IDLE_ATK_NEUTRAL_1] = Sprite(path + "idle_atk_neutral.png", 12, 10); sprite[IDLE_ATK_NEUTRAL_2] = Sprite(path + "idle_atk_neutral.png", 12, 10); sprite[IDLE_ATK_NEUTRAL_3] = Sprite(path + "idle_atk_neutral.png", 12, 10); sprite[IDLE_ATK_FRONT] = Sprite(path + "idle_atk_front.png", 4, 10); sprite[JUMP_ATK_DOWN_FALLLOOP] = Sprite(path + "jump_atk_down_fallloop.png", 3, 10); sprite[JUMP_ATK_DOWN_DMG] = Sprite(path + "jump_atk_down_dmg.png", 3, 10); sprite[IDLE_ATK_DOWN] = Sprite(path + "idle_atk_down.png", 4, 10); crouching_size = Vector(84, 59); not_crouching_size = Vector(84, 84); tags["flesh"] = true; tags[skin] = true; box = Rectangle(x, y, 84, 84); } void Flesh::update_machine_state(float delta){ switch(state){ case FighterState::IDLE_ATK_NEUTRAL_1: if(sprite[state].is_finished()){ check_idle(); check_crouch(); check_idle_atk_neutral_2(); }else if(pressed[ATTACK_BUTTON]){ combo++; } break; case FighterState::IDLE_ATK_NEUTRAL_2: if(sprite[state].is_finished()){ check_idle(); check_crouch(); check_idle_atk_neutral_3(); }else if(pressed[ATTACK_BUTTON]){ combo++; } break; case FighterState::IDLE_ATK_NEUTRAL_3: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::IDLE_ATK_FRONT: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::JUMP_ATK_DOWN_FALLLOOP: speed.x = 3 * (orientation == LEFT ? -1 : 1); speed.y = 3; attack_damage = 1; attack_mask = (1 << 4) - 1; check_jump_atk_down_dmg(); if(on_floor){ printf("to no chao, parsa\n"); speed.x = 0; speed.y = 0; check_idle(); check_left(); check_right(); check_crouch(); } break; case FighterState::JUMP_ATK_DOWN_DMG: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::IDLE_ATK_DOWN: if(sprite[state].is_finished()){ check_idle(); check_crouch(); } break; case FighterState::IDLE: combo = 0; attack_mask = attack_damage = 0; check_jump(); check_left(); check_right(); check_idle_atk_down(); check_crouch(); check_fall(); check_idle_atk_neutral_1(); check_idle_atk_front(); break; case FighterState::JUMPING: check_left(false); check_right(false); check_fall(); check_jump_atk_down_fallloop(); check_idle(); break; case FighterState::FALLING: check_idle(); check_left(false); check_right(false); check_fall(); check_crouch(); check_jump_atk_down_fallloop(); break; case FighterState::RUNNING: check_jump(); check_left(false); check_right(false); check_idle(); check_crouch(); check_idle_atk_neutral_1(); check_idle_atk_front(); check_fall(); break; case FighterState::CROUCH: check_idle(); check_fall(); break; } } void Flesh::check_jump(bool change){ if(pressed[JUMP_BUTTON]){ if(change) temporary_state = FighterState::JUMPING; speed.y = -5; on_floor = false; } } void Flesh::check_fall(bool change){ if(speed.y > 0){ if(change) temporary_state = FighterState::FALLING; } } void Flesh::check_left(bool change){ if(is_holding[LEFT_BUTTON]){ if(change) temporary_state = FighterState::RUNNING; speed.x = -2; orientation = Orientation::LEFT; } } void Flesh::check_right(bool change){ if(is_holding[RIGHT_BUTTON]){ if(change) temporary_state = FighterState::RUNNING; speed.x = 2; orientation = Orientation::RIGHT; } } void Flesh::check_idle(bool change){ if(speed.x == 0 and on_floor and not is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::IDLE; printf("Temporary state = %d\n", temporary_state); } } void Flesh::check_crouch(bool change){ if(is_holding[DOWN_BUTTON] and on_floor){ if(change) temporary_state = FighterState::CROUCH; } } void Flesh::check_idle_atk_neutral_1(bool change){ if(pressed[ATTACK_BUTTON] and not is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::IDLE_ATK_NEUTRAL_1; } } void Flesh::check_idle_atk_neutral_2(bool change){ printf("Pressing: %d\n", is_holding[ATTACK_BUTTON]); if(combo){ combo--; if(change) temporary_state = FighterState::IDLE_ATK_NEUTRAL_2; } } void Flesh::check_idle_atk_neutral_3(bool change){ if(combo){ combo--; if(change) temporary_state = FighterState::IDLE_ATK_NEUTRAL_3; } } void Flesh::check_idle_atk_front(bool change){ if(pressed[ATTACK_BUTTON] and (is_holding[LEFT_BUTTON] or is_holding[RIGHT_BUTTON])){ if(change) temporary_state = FighterState::IDLE_ATK_FRONT; orientation = is_holding[LEFT_BUTTON] ? Orientation::LEFT : Orientation::RIGHT; } } void Flesh::check_jump_atk_down_fallloop(bool change){ if(pressed[ATTACK_BUTTON] and is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::JUMP_ATK_DOWN_FALLLOOP; } } void Flesh::check_jump_atk_down_dmg(bool change){ if(grab){ if(change) temporary_state = FighterState::JUMP_ATK_DOWN_DMG; } } void Flesh::check_idle_atk_down(bool change){ if(is_holding[ATTACK_BUTTON] and is_holding[DOWN_BUTTON]){ if(change) temporary_state = FighterState::IDLE_ATK_DOWN; } } void Flesh::check_pass_through_platform(bool change){ } void Flesh::check_defense(bool change){ } void Flesh::check_stunt(bool change){ } void Flesh::check_dead(bool change){ } <|endoftext|>
<commit_before>/*************************************************************************/ /* texture_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "texture_editor_plugin.h" #include "core/io/resource_loader.h" #include "core/project_settings.h" #include "editor/editor_settings.h" void TextureEditor::_gui_input(Ref<InputEvent> p_event) { } void TextureEditor::_notification(int p_what) { if (p_what == NOTIFICATION_READY) { //get_scene()->connect("node_removed",this,"_node_removed"); } if (p_what == NOTIFICATION_DRAW) { Ref<Texture2D> checkerboard = get_icon("Checkerboard", "EditorIcons"); Size2 size = get_size(); draw_texture_rect(checkerboard, Rect2(Point2(), size), true); int tex_width = texture->get_width() * size.height / texture->get_height(); int tex_height = size.height; if (tex_width > size.width) { tex_width = size.width; tex_height = texture->get_height() * tex_width / texture->get_width(); } // Prevent the texture from being unpreviewable after the rescale, so that we can still see something if (tex_height <= 0) tex_height = 1; if (tex_width <= 0) tex_width = 1; int ofs_x = (size.width - tex_width) / 2; int ofs_y = (size.height - tex_height) / 2; if (Object::cast_to<CurveTexture>(*texture)) { // In the case of CurveTextures we know they are 1 in height, so fill the preview to see the gradient ofs_y = 0; tex_height = size.height; } else if (Object::cast_to<GradientTexture>(*texture)) { ofs_y = size.height / 4.0; tex_height = size.height / 2.0; } draw_texture_rect(texture, Rect2(ofs_x, ofs_y, tex_width, tex_height)); Ref<Font> font = get_font("font", "Label"); String format; if (Object::cast_to<ImageTexture>(*texture)) { format = Image::get_format_name(Object::cast_to<ImageTexture>(*texture)->get_format()); } else if (Object::cast_to<StreamTexture>(*texture)) { format = Image::get_format_name(Object::cast_to<StreamTexture>(*texture)->get_format()); } else { format = texture->get_class(); } String text = itos(texture->get_width()) + "x" + itos(texture->get_height()) + " " + format; Size2 rect = font->get_string_size(text); Vector2 draw_from = size - rect + Size2(-2, font->get_ascent() - 2); if (draw_from.x < 0) draw_from.x = 0; draw_string(font, draw_from + Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width); draw_string(font, draw_from - Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width); draw_string(font, draw_from, text, Color(1, 1, 1, 1), size.width); } } void TextureEditor::_changed_callback(Object *p_changed, const char *p_prop) { if (!is_visible()) return; update(); } void TextureEditor::edit(Ref<Texture2D> p_texture) { if (!texture.is_null()) texture->remove_change_receptor(this); texture = p_texture; if (!texture.is_null()) { texture->add_change_receptor(this); update(); } else { hide(); } } void TextureEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &TextureEditor::_gui_input); } TextureEditor::TextureEditor() { set_custom_minimum_size(Size2(1, 150)); } TextureEditor::~TextureEditor() { if (!texture.is_null()) { texture->remove_change_receptor(this); } } // bool EditorInspectorPluginTexture::can_handle(Object *p_object) { return Object::cast_to<ImageTexture>(p_object) != NULL || Object::cast_to<AtlasTexture>(p_object) != NULL || Object::cast_to<StreamTexture>(p_object) != NULL || Object::cast_to<LargeTexture>(p_object) != NULL || Object::cast_to<AnimatedTexture>(p_object) != NULL; } void EditorInspectorPluginTexture::parse_begin(Object *p_object) { Texture2D *texture = Object::cast_to<Texture2D>(p_object); if (!texture) { return; } Ref<Texture2D> m(texture); TextureEditor *editor = memnew(TextureEditor); editor->edit(m); add_custom_control(editor); } TextureEditorPlugin::TextureEditorPlugin(EditorNode *p_node) { Ref<EditorInspectorPluginTexture> plugin; plugin.instance(); add_inspector_plugin(plugin); } <commit_msg>[Vulkan] Add repeat flag to texture preview checkerboard background<commit_after>/*************************************************************************/ /* texture_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "texture_editor_plugin.h" #include "core/io/resource_loader.h" #include "core/project_settings.h" #include "editor/editor_settings.h" void TextureEditor::_gui_input(Ref<InputEvent> p_event) { } void TextureEditor::_notification(int p_what) { if (p_what == NOTIFICATION_READY) { //get_scene()->connect("node_removed",this,"_node_removed"); } if (p_what == NOTIFICATION_DRAW) { Ref<Texture2D> checkerboard = get_icon("Checkerboard", "EditorIcons"); Size2 size = get_size(); draw_texture_rect(checkerboard, Rect2(Point2(), size), true); int tex_width = texture->get_width() * size.height / texture->get_height(); int tex_height = size.height; if (tex_width > size.width) { tex_width = size.width; tex_height = texture->get_height() * tex_width / texture->get_width(); } // Prevent the texture from being unpreviewable after the rescale, so that we can still see something if (tex_height <= 0) tex_height = 1; if (tex_width <= 0) tex_width = 1; int ofs_x = (size.width - tex_width) / 2; int ofs_y = (size.height - tex_height) / 2; if (Object::cast_to<CurveTexture>(*texture)) { // In the case of CurveTextures we know they are 1 in height, so fill the preview to see the gradient ofs_y = 0; tex_height = size.height; } else if (Object::cast_to<GradientTexture>(*texture)) { ofs_y = size.height / 4.0; tex_height = size.height / 2.0; } draw_texture_rect(texture, Rect2(ofs_x, ofs_y, tex_width, tex_height)); Ref<Font> font = get_font("font", "Label"); String format; if (Object::cast_to<ImageTexture>(*texture)) { format = Image::get_format_name(Object::cast_to<ImageTexture>(*texture)->get_format()); } else if (Object::cast_to<StreamTexture>(*texture)) { format = Image::get_format_name(Object::cast_to<StreamTexture>(*texture)->get_format()); } else { format = texture->get_class(); } String text = itos(texture->get_width()) + "x" + itos(texture->get_height()) + " " + format; Size2 rect = font->get_string_size(text); Vector2 draw_from = size - rect + Size2(-2, font->get_ascent() - 2); if (draw_from.x < 0) draw_from.x = 0; draw_string(font, draw_from + Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width); draw_string(font, draw_from - Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width); draw_string(font, draw_from, text, Color(1, 1, 1, 1), size.width); } } void TextureEditor::_changed_callback(Object *p_changed, const char *p_prop) { if (!is_visible()) return; update(); } void TextureEditor::edit(Ref<Texture2D> p_texture) { if (!texture.is_null()) texture->remove_change_receptor(this); texture = p_texture; if (!texture.is_null()) { texture->add_change_receptor(this); update(); } else { hide(); } } void TextureEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &TextureEditor::_gui_input); } TextureEditor::TextureEditor() { set_texture_repeat(TextureRepeat::TEXTURE_REPEAT_ENABLED); set_custom_minimum_size(Size2(1, 150)); } TextureEditor::~TextureEditor() { if (!texture.is_null()) { texture->remove_change_receptor(this); } } // bool EditorInspectorPluginTexture::can_handle(Object *p_object) { return Object::cast_to<ImageTexture>(p_object) != NULL || Object::cast_to<AtlasTexture>(p_object) != NULL || Object::cast_to<StreamTexture>(p_object) != NULL || Object::cast_to<LargeTexture>(p_object) != NULL || Object::cast_to<AnimatedTexture>(p_object) != NULL; } void EditorInspectorPluginTexture::parse_begin(Object *p_object) { Texture2D *texture = Object::cast_to<Texture2D>(p_object); if (!texture) { return; } Ref<Texture2D> m(texture); TextureEditor *editor = memnew(TextureEditor); editor->edit(m); add_custom_control(editor); } TextureEditorPlugin::TextureEditorPlugin(EditorNode *p_node) { Ref<EditorInspectorPluginTexture> plugin; plugin.instance(); add_inspector_plugin(plugin); } <|endoftext|>
<commit_before>// Solving a puzzle below // https://twitter.com/CTak_S/status/1064819923195580417 #include <cstdlib> #include <cmath> #include <iomanip> #include <iostream> #include <random> #include <sstream> #include <string> #include <vector> #include <boost/multi_array.hpp> namespace { using Count = long long int; // Bitmap (1 to alive) of survivors 0..(N_PLAYERS-1) using State = unsigned int; using Index = int; using Survivors = std::vector<Index>; struct Action { Index player; State state; Index target; }; using ActionChain = std::vector<Action>; // Rule of the game constexpr Index N_PLAYERS = 3; constexpr Index N_STATES = 1 << N_PLAYERS; // 2^N_PLAYERS combinations constexpr Index N_ACTIONS = N_PLAYERS + 1; // Shoot Player 0, ... (N_PLAYERS-1), or nobody constexpr Index N_WINNERS = N_PLAYERS; constexpr Index ALIVE = 1; const std::vector<double> HIT_RATE {0.3, 0.5, 1.0}; // Hyper parameters constexpr double LEARNING_RATE = 0.001; constexpr double EXPLORATION_EPSILON = 0.1; constexpr bool IID_CHOICE = false; constexpr bool USE_SOFTMAX = false; // I got unstable results with Softmax. constexpr Index MAX_DEPTH = 30; constexpr Count N_TRIALS = 10000000ll; } class OptimalAction { public: OptimalAction(void) : rand_gen_(rand_dev_()), unit_distribution_(0.0, 1.0), value_(boost::extents[N_PLAYERS][N_STATES][N_ACTIONS]) { for (Index player = 0; player < N_PLAYERS; ++player) { for (Index state = 0; state < N_STATES; ++state) { for (Index action = 0; action < N_ACTIONS; ++action) { // Do not shoot yourself! auto count = checkAliveOrNobody(player, state); value_[player][state][action] = count && checkAliveOrNobody(action, state) && (player != action) ? (1.0 / static_cast<double>(count)) : 0.0; } } } return; } virtual ~OptimalAction(void) = default; void Exec(Count n_trials) { for (Count i = 0; i < n_trials; ++i) { exec(); } for (Index player = 0; player < N_PLAYERS; ++player) { std::cout << printValue(player); } return; } void exec(void) { Survivors survivors(N_PLAYERS, ALIVE); ActionChain actionChain; aimAndShoot(0, 0, survivors, actionChain); return; } char printIndexChar(Index player) { return player + 'A'; } std::string printValue(Index player) { std::ostringstream os; os << std::setprecision(5) << "[States, actions and values for Player " << printIndexChar(player) << "]\n"; for (Index state = 0; state < N_STATES; ++state) { // Exclude when the player is not alive or only alive if (checkPlayerAlive(player, state) < 2) { continue; } for (Index action = 0; action < N_ACTIONS; ++action) { if ((player != action) && checkPlayerAlive(action, state)) { os << "Target " << printIndexChar(action) << ":" << value_[player][state][action] << ", "; } if (action >= N_PLAYERS) { os << "Nobody:" << value_[player][state][action] << "\n" ; } } } os << "\n"; return os.str(); } // Converts an array to a bitmap State survivorsToState(const Survivors& survivors) { State state = 0; State index = 1; for(const auto value : survivors) { state += index * (value ? 1 : 0); index <<= 1; } return state; } // Notice that nobody is always not alive (population - player(1) + nobady(1)) template<typename T> auto countPopulation(T state) { return __builtin_popcount(state); } // Return population of the state if the player is alive in the state, 0 othewise Index checkAliveOrNobody(Index player, State state) { return ((player >= N_PLAYERS) || (state & (1 << player))) ? countPopulation(state) : 0; } Index checkPlayerAlive(Index player, State state) { return (state & (1 << player)) ? countPopulation(state) : 0; } // Overwrites survivors void aimAndShoot(Index player, Index depth, Survivors& survivors, const ActionChain& actionChain) { if (depth >= MAX_DEPTH) { return; } const auto targets = getTargets(player, survivors); const auto state = survivorsToState(survivors); const auto target = getActionTarget(player, state, survivors, targets); ActionChain nextActionChain = actionChain; Action nextAction {player, state, target}; nextActionChain.push_back(nextAction); shoot(player, survivors, target); if (std::accumulate(survivors.begin(), survivors.end(), 0) == 1) { const auto winner = std::distance(survivors.begin(), std::find(survivors.begin(), survivors.end(), ALIVE)); // Pick up one sample to i.i.d. if (IID_CHOICE) { auto raw_index = unit_distribution_(rand_gen_) * static_cast<double>(nextActionChain.size()) - 0.5; auto index = std::min(nextActionChain.size() - 1, static_cast<decltype(nextActionChain.size())>( std::max(0, static_cast<int>(raw_index)))); propagate(nextActionChain.at(index), winner); } else { // Reverse if you deduct rewards for(const auto& action : nextActionChain) { propagate(action, winner); } } } else { aimAndShoot((player + 1) % N_PLAYERS, depth + 1, survivors, nextActionChain); } return; } std::vector<Index> getTargets(Index player, const Survivors& survivors) { std::vector<Index> targets; for(Index target = 0; target < N_PLAYERS; ++target) { if ((target != player) && survivors.at(target)) { targets.push_back(target); } } if (targets.size() > 1) { // Can shoot nobody targets.push_back(N_PLAYERS); } return targets; } std::vector<double> getProportions(Index player, State state) { // Number of targets = number of survivors - player(1) + nobody(1) std::vector<double> proportions(N_ACTIONS, 0.0); // Epsilon-greedy const auto rand_proportional = unit_distribution_(rand_gen_); const bool proportional = (rand_proportional < EXPLORATION_EPSILON); if (proportional) { // Number of targets = number of survivors - player(1) + nobody(1) const auto population = checkPlayerAlive(player, state); const double proportion = (population > 0) ? (1.0 / static_cast<double>(population)) : 0.0; for (Index action = 0; action < N_ACTIONS; ++action) { proportions.at(action) = (checkPlayerAlive(player, state) && checkAliveOrNobody(action, state) && (player != action)) ? proportion : 0.0; } } else { if (USE_SOFTMAX) { std::vector<double> exp_proportions(N_ACTIONS, 0.0); double sum = 0.0; for (Index action = 0; action < N_ACTIONS; ++action) { const auto value = ::exp(value_[player][state][action]); exp_proportions.at(action) = value; sum += value; } for (Index action = 0; action < N_ACTIONS; ++action) { proportions.at(action) = exp_proportions.at(action) / sum; } } else { for (Index action = 0; action < N_ACTIONS; ++action) { proportions.at(action) = value_[player][state][action]; } } } return proportions; } Index getActionTarget(Index player, State state, const Survivors& survivors, const std::vector<Index>& targets) { const auto proportions = getProportions(player, state); auto rand_value = unit_distribution_(rand_gen_); Index target = 0; while(rand_value >= 0.0) { rand_value -= proportions.at(target); target += 1; if (target >= N_ACTIONS) { break; } } return target - 1; } // Overwrites survivors void shoot(Index player, Survivors& survivors, Index target) { if (target < N_PLAYERS) { if (unit_distribution_(rand_gen_) < HIT_RATE.at(player)) { survivors.at(target) = 0; } } return; } void propagate(const Action& action, Index final_surviver) { // No deduction const auto target_value = value_[action.player][action.state][action.target]; const auto delta = target_value * LEARNING_RATE * ((action.player == final_surviver) ? 1.0 : -1.0); value_[action.player][action.state][action.target] += delta; // Normalizes such that the sum of values is 1 double sum = 0.0; for (Index i = 0; i < N_ACTIONS; ++i) { sum += value_[action.player][action.state][i]; } for (Index i = 0; i < N_ACTIONS; ++i) { value_[action.player][action.state][i] /= sum; } } private: using CountMatrix = boost::multi_array<Count, 4>; using StateActionValue = boost::multi_array<double, 3>; std::random_device rand_dev_; std::mt19937 rand_gen_; std::uniform_real_distribution<double> unit_distribution_; StateActionValue value_; }; int main(int argc, char* argv[]) { OptimalAction optimalAction; Count n_trials = N_TRIALS; if (argc > 1) { n_trials = ::atoll(argv[1]); } optimalAction.Exec(n_trials); return 0; } /* Local Variables: mode: c++ coding: utf-8-dos tab-width: nil c-file-style: "stroustrup" End: */ <commit_msg>Adjust the learning rate<commit_after>// Solving a puzzle below // https://twitter.com/CTak_S/status/1064819923195580417 #include <cstdlib> #include <cmath> #include <iomanip> #include <iostream> #include <random> #include <sstream> #include <string> #include <vector> #include <boost/multi_array.hpp> namespace { using Count = long long int; // Bitmap (1 to alive) of survivors 0..(N_PLAYERS-1) using State = unsigned int; using Index = int; using Survivors = std::vector<Index>; struct Action { Index player; State state; Index target; }; using ActionChain = std::vector<Action>; // Rule of the game constexpr Index N_PLAYERS = 3; constexpr Index N_STATES = 1 << N_PLAYERS; // 2^N_PLAYERS combinations constexpr Index N_ACTIONS = N_PLAYERS + 1; // Shoot Player 0, ... (N_PLAYERS-1), or nobody constexpr Index N_WINNERS = N_PLAYERS; constexpr Index ALIVE = 1; const std::vector<double> HIT_RATE {0.3, 0.5, 1.0}; // Hyper parameters constexpr double LEARNING_RATE = 0.00001; constexpr double EXPLORATION_EPSILON = 0.1; constexpr bool IID_CHOICE = false; constexpr bool USE_SOFTMAX = false; // I got unstable results with Softmax. constexpr Index MAX_DEPTH = 30; constexpr Count N_TRIALS = 10000000ll; } class OptimalAction { public: OptimalAction(void) : rand_gen_(rand_dev_()), unit_distribution_(0.0, 1.0), value_(boost::extents[N_PLAYERS][N_STATES][N_ACTIONS]) { for (Index player = 0; player < N_PLAYERS; ++player) { for (Index state = 0; state < N_STATES; ++state) { for (Index action = 0; action < N_ACTIONS; ++action) { // Do not shoot yourself! auto count = checkAliveOrNobody(player, state); value_[player][state][action] = count && checkAliveOrNobody(action, state) && (player != action) ? (1.0 / static_cast<double>(count)) : 0.0; } } } return; } virtual ~OptimalAction(void) = default; void Exec(Count n_trials) { for (Count i = 0; i < n_trials; ++i) { exec(); } for (Index player = 0; player < N_PLAYERS; ++player) { std::cout << printValue(player); } return; } void exec(void) { Survivors survivors(N_PLAYERS, ALIVE); ActionChain actionChain; aimAndShoot(0, 0, survivors, actionChain); return; } char printIndexChar(Index player) { return player + 'A'; } std::string printValue(Index player) { std::ostringstream os; os << std::setprecision(5) << "[States, actions and values for Player " << printIndexChar(player) << "]\n"; for (Index state = 0; state < N_STATES; ++state) { // Exclude when the player is not alive or only alive if (checkPlayerAlive(player, state) < 2) { continue; } for (Index action = 0; action < N_ACTIONS; ++action) { if ((player != action) && checkPlayerAlive(action, state)) { os << "Target " << printIndexChar(action) << ":" << value_[player][state][action] << ", "; } if (action >= N_PLAYERS) { os << "Nobody:" << value_[player][state][action] << "\n" ; } } } os << "\n"; return os.str(); } // Converts an array to a bitmap State survivorsToState(const Survivors& survivors) { State state = 0; State index = 1; for(const auto value : survivors) { state += index * (value ? 1 : 0); index <<= 1; } return state; } // Notice that nobody is always not alive (population - player(1) + nobady(1)) template<typename T> auto countPopulation(T state) { return __builtin_popcount(state); } // Return population of the state if the player is alive in the state, 0 othewise Index checkAliveOrNobody(Index player, State state) { return ((player >= N_PLAYERS) || (state & (1 << player))) ? countPopulation(state) : 0; } Index checkPlayerAlive(Index player, State state) { return (state & (1 << player)) ? countPopulation(state) : 0; } // Overwrites survivors void aimAndShoot(Index player, Index depth, Survivors& survivors, const ActionChain& actionChain) { if (depth >= MAX_DEPTH) { return; } const auto targets = getTargets(player, survivors); const auto state = survivorsToState(survivors); const auto target = getActionTarget(player, state, survivors, targets); ActionChain nextActionChain = actionChain; Action nextAction {player, state, target}; nextActionChain.push_back(nextAction); shoot(player, survivors, target); if (std::accumulate(survivors.begin(), survivors.end(), 0) == 1) { const auto winner = std::distance(survivors.begin(), std::find(survivors.begin(), survivors.end(), ALIVE)); // Pick up one sample to i.i.d. if (IID_CHOICE) { auto raw_index = unit_distribution_(rand_gen_) * static_cast<double>(nextActionChain.size()) - 0.5; auto index = std::min(nextActionChain.size() - 1, static_cast<decltype(nextActionChain.size())>( std::max(0, static_cast<int>(raw_index)))); propagate(nextActionChain.at(index), winner); } else { // Reverse if you deduct rewards for(const auto& action : nextActionChain) { propagate(action, winner); } } } else { aimAndShoot((player + 1) % N_PLAYERS, depth + 1, survivors, nextActionChain); } return; } std::vector<Index> getTargets(Index player, const Survivors& survivors) { std::vector<Index> targets; for(Index target = 0; target < N_PLAYERS; ++target) { if ((target != player) && survivors.at(target)) { targets.push_back(target); } } if (targets.size() > 1) { // Can shoot nobody targets.push_back(N_PLAYERS); } return targets; } std::vector<double> getProportions(Index player, State state) { // Number of targets = number of survivors - player(1) + nobody(1) std::vector<double> proportions(N_ACTIONS, 0.0); // Epsilon-greedy const auto rand_proportional = unit_distribution_(rand_gen_); const bool proportional = (rand_proportional < EXPLORATION_EPSILON); if (proportional) { // Number of targets = number of survivors - player(1) + nobody(1) const auto population = checkPlayerAlive(player, state); const double proportion = (population > 0) ? (1.0 / static_cast<double>(population)) : 0.0; for (Index action = 0; action < N_ACTIONS; ++action) { proportions.at(action) = (checkPlayerAlive(player, state) && checkAliveOrNobody(action, state) && (player != action)) ? proportion : 0.0; } } else { if (USE_SOFTMAX) { std::vector<double> exp_proportions(N_ACTIONS, 0.0); double sum = 0.0; for (Index action = 0; action < N_ACTIONS; ++action) { const auto value = ::exp(value_[player][state][action]); exp_proportions.at(action) = value; sum += value; } for (Index action = 0; action < N_ACTIONS; ++action) { proportions.at(action) = exp_proportions.at(action) / sum; } } else { for (Index action = 0; action < N_ACTIONS; ++action) { proportions.at(action) = value_[player][state][action]; } } } return proportions; } Index getActionTarget(Index player, State state, const Survivors& survivors, const std::vector<Index>& targets) { const auto proportions = getProportions(player, state); auto rand_value = unit_distribution_(rand_gen_); Index target = 0; while(rand_value >= 0.0) { rand_value -= proportions.at(target); target += 1; if (target >= N_ACTIONS) { break; } } return target - 1; } // Overwrites survivors void shoot(Index player, Survivors& survivors, Index target) { if (target < N_PLAYERS) { if (unit_distribution_(rand_gen_) < HIT_RATE.at(player)) { survivors.at(target) = 0; } } return; } void propagate(const Action& action, Index final_surviver) { // No deduction const auto target_value = value_[action.player][action.state][action.target]; const auto delta = target_value * LEARNING_RATE * ((action.player == final_surviver) ? 1.0 : -1.0); value_[action.player][action.state][action.target] += delta; // Normalizes such that the sum of values is 1 double sum = 0.0; for (Index i = 0; i < N_ACTIONS; ++i) { sum += value_[action.player][action.state][i]; } for (Index i = 0; i < N_ACTIONS; ++i) { value_[action.player][action.state][i] /= sum; } } private: using CountMatrix = boost::multi_array<Count, 4>; using StateActionValue = boost::multi_array<double, 3>; std::random_device rand_dev_; std::mt19937 rand_gen_; std::uniform_real_distribution<double> unit_distribution_; StateActionValue value_; }; int main(int argc, char* argv[]) { OptimalAction optimalAction; Count n_trials = N_TRIALS; if (argc > 1) { n_trials = ::atoll(argv[1]); } optimalAction.Exec(n_trials); return 0; } /* Local Variables: mode: c++ coding: utf-8-dos tab-width: nil c-file-style: "stroustrup" End: */ <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> // StdAir #include <stdair/stdair_exceptions.hpp> #include <stdair/basic/BasConst_Event.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/service/Logger.hpp> // SEvMgr #include <sevmgr/basic/BasConst_EventQueueManager.hpp> #include <sevmgr/bom/EventQueue.hpp> namespace SEVMGR { // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue() : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (stdair::DEFAULT_PROGRESS_STATUS, stdair::DEFAULT_PROGRESS_STATUS) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const Key_T& iKey) : _key (iKey), _parent (NULL), _progressStatus (stdair::DEFAULT_PROGRESS_STATUS, stdair::DEFAULT_PROGRESS_STATUS) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const EventQueue& iEventQueue) : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (stdair::DEFAULT_PROGRESS_STATUS, stdair::DEFAULT_PROGRESS_STATUS) { assert (false); } // ////////////////////////////////////////////////////////////////////// EventQueue::~EventQueue() { _eventList.clear(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::toString() const { std::ostringstream oStr; oStr << "(" << _eventList.size() << ") " << _progressStatus.getCurrentNb() << "/{" << _progressStatus.getExpectedNb() << "," << _progressStatus.getActualNb() << "}"; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::display() const { std::ostringstream oStr; oStr << toString(); return oStr.str(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::list () const { std::ostringstream oStr; oStr << describeKey () << "\n" << toString() << "\n"; // Browse the events for (stdair::EventList_T::const_iterator itEvent = _eventList.begin(); itEvent != _eventList.end(); ++itEvent) { const stdair::EventListElement_T* lEventListElement_ptr = &(*itEvent); assert (lEventListElement_ptr != NULL); const stdair::EventListElement_T& lEventListElement = *lEventListElement_ptr; const stdair::EventStruct& lEvent = lEventListElement.second; // Delegate the JSON export to the dedicated service oStr << lEvent.describe() << "\n"; } return oStr.str(); } // ////////////////////////////////////////////////////////////////////// stdair::Count_T EventQueue::getQueueSize () const { return _eventList.size(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueEmpty () const { return _eventList.empty(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueDone () const { const bool isQueueEmpty = _eventList.empty(); return isQueueEmpty; } // ////////////////////////////////////////////////////////////////////// void EventQueue::reset () { // Reset only the current number of events, not the expected one _progressStatus.reset(); // Empty the list of events _eventList.clear(); // Reset the progress statuses for all the event types for (ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.begin(); itProgressStatus != _progressStatusMap.end(); ++itProgressStatus) { stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; lProgressStatus.reset(); } } // ////////////////////////////////////////////////////////////////////// bool EventQueue:: hasProgressStatus (const stdair::EventType::EN_EventType& iType) const { bool hasProgressStatus = true; // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_DEBUG ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); hasProgressStatus = false; } return hasProgressStatus; } // ////////////////////////////////////////////////////////////////////// const stdair::Count_T& EventQueue:: getCurrentNbOfEvents (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_ERROR ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); assert (false); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.getCurrentNb(); } // ////////////////////////////////////////////////////////////////////// const stdair::Count_T& EventQueue:: getExpectedTotalNbOfEvents (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { std::ostringstream oStr; oStr << "No ProgressStatus structure can be retrieved in the EventQueue '" << display() << "'. The EventQueue should be initialised, e.g., by " << "calling a buildSampleBom() method."; // STDAIR_LOG_ERROR (oStr.str()); throw EventQueueException (oStr.str()); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.getExpectedNb(); } // ////////////////////////////////////////////////////////////////////// const stdair::Count_T& EventQueue:: getActualTotalNbOfEvents (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_ERROR ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); assert (false); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.getActualNb(); } // ////////////////////////////////////////////////////////////////////// void EventQueue::updateStatus (const stdair::EventType::EN_EventType& iType, const stdair::ProgressStatus& iProgressStatus) { // Retrieve, if existing, the ProgressStatus structure // corresponding to the given event type ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { const bool hasInsertBeenSuccessful = _progressStatusMap.insert (ProgressStatusMap_T:: value_type (iType, iProgressStatus)).second; if (hasInsertBeenSuccessful == false) { STDAIR_LOG_ERROR ("No progress_status can be inserted " << "for the following event type: " << stdair::EventType::getLabel(iType) << ". EventQueue: " << toString()); throw stdair::EventException ("No progress_status can be inserted for the " "following event type: " + stdair::EventType::getLabel(iType) + ". EventQueue: " + toString()); } return; } stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; // Update the progress status const stdair::Count_T& lCurrentNb = iProgressStatus.getCurrentNb(); lProgressStatus.setCurrentNb (lCurrentNb); const stdair::Count_T& lExpectedNb = iProgressStatus.getExpectedNb(); lProgressStatus.setExpectedNb(lProgressStatus.getExpectedNb() + lExpectedNb); const stdair::Count_T& lActualNb = iProgressStatus.getActualNb(); lProgressStatus.setActualNb (lProgressStatus.getActualNb() + lActualNb); } // ////////////////////////////////////////////////////////////////////// void EventQueue:: addStatus (const stdair::EventType::EN_EventType& iType, const stdair::NbOfEvents_T& iExpectedTotalNbOfEvents) { // Initialise the progress status object const stdair::Count_T lExpectedTotalNbOfEventsInt = static_cast<const stdair::Count_T> (std::floor (iExpectedTotalNbOfEvents)); const stdair::ProgressStatus lProgressStatus (lExpectedTotalNbOfEventsInt); // Update the progress status for the given event type updateStatus (iType, lProgressStatus); // Update the overall progress status const stdair::Count_T lExpectedNb = static_cast<const stdair::Count_T> (_progressStatus.getExpectedNb() + iExpectedTotalNbOfEvents); _progressStatus.setExpectedNb (lExpectedNb); const stdair::Count_T lActualNb = static_cast<const stdair::Count_T> (_progressStatus.getActualNb() + iExpectedTotalNbOfEvents); _progressStatus.setActualNb (lActualNb); } // ////////////////////////////////////////////////////////////////////// void EventQueue::updateStatus (const stdair::EventType::EN_EventType& iType, const stdair::NbOfEvents_T& iActualNbOfEvents) { // Initialise the progress status object for the type key stdair:: Count_T lActualNbOfEventsInt = static_cast<const stdair::Count_T> (std::floor (iActualNbOfEvents)); // Update the progress status for the corresponding content type key ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus != _progressStatusMap.end()) { // stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; // Update the overall progress status const stdair::Count_T lActualEventTypeNb = lProgressStatus.getActualNb(); const stdair::Count_T lActualTotalNb = _progressStatus.getActualNb(); _progressStatus.setActualNb (lActualTotalNb + iActualNbOfEvents - lActualEventTypeNb); // Update the progress status for the corresponding type key lProgressStatus.setActualNb (lActualNbOfEventsInt); } } // ////////////////////////////////////////////////////////////////////// void EventQueue::setStatus (const stdair::EventType::EN_EventType& iType, const stdair::ProgressStatus& iProgressStatus) { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.find (iType); // assert (itProgressStatus != _progressStatusMap.end()); if (itProgressStatus != _progressStatusMap.end()) { // Update the ProgressStatus structure itProgressStatus->second = iProgressStatus; } } // ////////////////////////////////////////////////////////////////////// stdair::ProgressStatus EventQueue:: getStatus (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus != _progressStatusMap.end()) { const stdair::ProgressStatus& oProgressStatus = itProgressStatus->second; return oProgressStatus; } return stdair::ProgressStatus(); } // ////////////////////////////////////////////////////////////////////// stdair::ProgressPercentage_T EventQueue:: calculateProgress (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_ERROR ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); assert (false); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.progress(); } // ////////////////////////////////////////////////////////////////////// stdair::ProgressStatusSet EventQueue::popEvent (stdair::EventStruct& ioEventStruct) { if (_eventList.empty() == true) { std::ostringstream oStr; oStr << "The event queue '" << describeKey() << "' is empty. " << "No event can be popped."; // STDAIR_LOG_ERROR (oStr.str()); throw EventQueueException (oStr.str()); } /** * 1. Update the event queue itself. */ // Get an iterator on the first event (sorted by date-time stamps) stdair::EventList_T::iterator itEvent = _eventList.begin(); /** * Extract (a copy of) the corresponding Event structure. We make * a copy here, as the original EventStruct structure is removed * from the list (and erased). Moreover, the resulting EventStruct * structure will be returned by this method. */ ioEventStruct = itEvent->second; // Retrieve the event type const stdair::EventType::EN_EventType& lEventType = ioEventStruct.getEventType(); stdair::ProgressStatusSet oProgressStatusSet (lEventType); // Update the (current number part of the) overall progress status, // to account for the event that is being popped out of the event // queue. ++_progressStatus; // Remove the event, which has just been retrieved _eventList.erase (itEvent); /** * 2. Update the progress statuses held by the EventStruct structure. * * 2.1. Update the progress status specific to the event type (e.g., * booking request, optimisation notification). */ // Retrieve the progress status specific to that event type stdair::ProgressStatus lEventTypeProgressStatus = getStatus (lEventType); // Increase the current number of events ++lEventTypeProgressStatus; // Store back the progress status setStatus (lEventType, lEventTypeProgressStatus); // Update the progress status of the progress status set, specific to // the event type. oProgressStatusSet.setTypeSpecificStatus (lEventTypeProgressStatus); /** * 2.2. Update the overall progress status. */ // Update the overall progress status of the progress status set. oProgressStatusSet.setOverallStatus (_progressStatus); // return oProgressStatusSet; } // ////////////////////////////////////////////////////////////////////// bool EventQueue::addEvent (stdair::EventStruct& ioEventStruct) { bool insertionSucceeded = _eventList.insert (stdair::EventListElement_T (ioEventStruct.getEventTimeStamp(), ioEventStruct)).second; /** * If the insertion has not been successful, try repeatedly until * the insertion becomes successful. * * The date-time is counted in milliseconds (1e-3 second). Hence, * one thousand (1e3) of attempts correspond to 1 second. * * The check on one thousand (1e3) is made in order to avoid * potential infinite loops. In such case, however, an assertion * will fail: it is always better that an assertion fails rather * than entering an infinite loop. */ const unsigned int idx = 0; while (insertionSucceeded == false && idx != 1e3) { // Increment the date-time stamp (expressed in milliseconds) ioEventStruct.incrementEventTimeStamp(); // Retry to insert into the event queue insertionSucceeded = _eventList.insert (stdair::EventListElement_T (ioEventStruct.getEventTimeStamp(), ioEventStruct)).second; } assert (idx != 1e3); return insertionSucceeded; } // ////////////////////////////////////////////////////////////////////// bool EventQueue::hasEventDateTime (const stdair::DateTime_T& iDateTime) { bool hasSearchEventBeenSucessful = true; /** * Compute the number of milliseconds between the * date-time of the event and DEFAULT_EVENT_OLDEST_DATETIME * (as of Feb. 2011, that date is set to Jan. 1, 2010). */ const stdair::Duration_T lDuration = iDateTime - stdair::DEFAULT_EVENT_OLDEST_DATETIME; const stdair::LongDuration_T lDateTimeStamp = lDuration.total_milliseconds(); // Searches the container for an element with iDateTime as key stdair::EventList_T::iterator itEvent = _eventList.find (lDateTimeStamp); // An iterator to map::end means the specified key has not found in the // container. if (itEvent == _eventList.end()) { hasSearchEventBeenSucessful = false; } return hasSearchEventBeenSucessful; } } <commit_msg>[Dev] Removed the display of rm events and snap shots for a lighter display of the queue.<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> // StdAir #include <stdair/stdair_exceptions.hpp> #include <stdair/basic/BasConst_Event.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/service/Logger.hpp> // SEvMgr #include <sevmgr/basic/BasConst_EventQueueManager.hpp> #include <sevmgr/bom/EventQueue.hpp> namespace SEVMGR { // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue() : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (stdair::DEFAULT_PROGRESS_STATUS, stdair::DEFAULT_PROGRESS_STATUS) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const Key_T& iKey) : _key (iKey), _parent (NULL), _progressStatus (stdair::DEFAULT_PROGRESS_STATUS, stdair::DEFAULT_PROGRESS_STATUS) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const EventQueue& iEventQueue) : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (stdair::DEFAULT_PROGRESS_STATUS, stdair::DEFAULT_PROGRESS_STATUS) { assert (false); } // ////////////////////////////////////////////////////////////////////// EventQueue::~EventQueue() { _eventList.clear(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::toString() const { std::ostringstream oStr; oStr << "(" << _eventList.size() << ") " << _progressStatus.getCurrentNb() << "/{" << _progressStatus.getExpectedNb() << "," << _progressStatus.getActualNb() << "}"; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::display() const { std::ostringstream oStr; oStr << toString(); return oStr.str(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::list () const { std::ostringstream oStr; oStr << describeKey () << "\n" << toString() << "\n"; // Browse the events for (stdair::EventList_T::const_iterator itEvent = _eventList.begin(); itEvent != _eventList.end(); ++itEvent) { const stdair::EventListElement_T* lEventListElement_ptr = &(*itEvent); assert (lEventListElement_ptr != NULL); const stdair::EventListElement_T& lEventListElement = *lEventListElement_ptr; const stdair::EventStruct& lEvent = lEventListElement.second; const stdair::EventType::EN_EventType& lEventType = lEvent.getEventType(); switch (lEventType) { case stdair::EventType::BKG_REQ: case stdair::EventType::CX: case stdair::EventType::BRK_PT: { // Delegate the JSON export to the dedicated service oStr << lEvent.describe(); break; } case stdair::EventType::OPT_NOT_4_FD: case stdair::EventType::SNAPSHOT: case stdair::EventType::RM: default: break; } } return oStr.str(); } // ////////////////////////////////////////////////////////////////////// stdair::Count_T EventQueue::getQueueSize () const { return _eventList.size(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueEmpty () const { return _eventList.empty(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueDone () const { const bool isQueueEmpty = _eventList.empty(); return isQueueEmpty; } // ////////////////////////////////////////////////////////////////////// void EventQueue::reset () { // Reset only the current number of events, not the expected one _progressStatus.reset(); // Empty the list of events _eventList.clear(); // Reset the progress statuses for all the event types for (ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.begin(); itProgressStatus != _progressStatusMap.end(); ++itProgressStatus) { stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; lProgressStatus.reset(); } } // ////////////////////////////////////////////////////////////////////// bool EventQueue:: hasProgressStatus (const stdair::EventType::EN_EventType& iType) const { bool hasProgressStatus = true; // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_DEBUG ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); hasProgressStatus = false; } return hasProgressStatus; } // ////////////////////////////////////////////////////////////////////// const stdair::Count_T& EventQueue:: getCurrentNbOfEvents (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_ERROR ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); assert (false); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.getCurrentNb(); } // ////////////////////////////////////////////////////////////////////// const stdair::Count_T& EventQueue:: getExpectedTotalNbOfEvents (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { std::ostringstream oStr; oStr << "No ProgressStatus structure can be retrieved in the EventQueue '" << display() << "'. The EventQueue should be initialised, e.g., by " << "calling a buildSampleBom() method."; // STDAIR_LOG_ERROR (oStr.str()); throw EventQueueException (oStr.str()); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.getExpectedNb(); } // ////////////////////////////////////////////////////////////////////// const stdair::Count_T& EventQueue:: getActualTotalNbOfEvents (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_ERROR ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); assert (false); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.getActualNb(); } // ////////////////////////////////////////////////////////////////////// void EventQueue::updateStatus (const stdair::EventType::EN_EventType& iType, const stdair::ProgressStatus& iProgressStatus) { // Retrieve, if existing, the ProgressStatus structure // corresponding to the given event type ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { const bool hasInsertBeenSuccessful = _progressStatusMap.insert (ProgressStatusMap_T:: value_type (iType, iProgressStatus)).second; if (hasInsertBeenSuccessful == false) { STDAIR_LOG_ERROR ("No progress_status can be inserted " << "for the following event type: " << stdair::EventType::getLabel(iType) << ". EventQueue: " << toString()); throw stdair::EventException ("No progress_status can be inserted for the " "following event type: " + stdair::EventType::getLabel(iType) + ". EventQueue: " + toString()); } return; } stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; // Update the progress status const stdair::Count_T& lCurrentNb = iProgressStatus.getCurrentNb(); lProgressStatus.setCurrentNb (lCurrentNb); const stdair::Count_T& lExpectedNb = iProgressStatus.getExpectedNb(); lProgressStatus.setExpectedNb(lProgressStatus.getExpectedNb() + lExpectedNb); const stdair::Count_T& lActualNb = iProgressStatus.getActualNb(); lProgressStatus.setActualNb (lProgressStatus.getActualNb() + lActualNb); } // ////////////////////////////////////////////////////////////////////// void EventQueue:: addStatus (const stdair::EventType::EN_EventType& iType, const stdair::NbOfEvents_T& iExpectedTotalNbOfEvents) { // Initialise the progress status object const stdair::Count_T lExpectedTotalNbOfEventsInt = static_cast<const stdair::Count_T> (std::floor (iExpectedTotalNbOfEvents)); const stdair::ProgressStatus lProgressStatus (lExpectedTotalNbOfEventsInt); // Update the progress status for the given event type updateStatus (iType, lProgressStatus); // Update the overall progress status const stdair::Count_T lExpectedNb = static_cast<const stdair::Count_T> (_progressStatus.getExpectedNb() + iExpectedTotalNbOfEvents); _progressStatus.setExpectedNb (lExpectedNb); const stdair::Count_T lActualNb = static_cast<const stdair::Count_T> (_progressStatus.getActualNb() + iExpectedTotalNbOfEvents); _progressStatus.setActualNb (lActualNb); } // ////////////////////////////////////////////////////////////////////// void EventQueue::updateStatus (const stdair::EventType::EN_EventType& iType, const stdair::NbOfEvents_T& iActualNbOfEvents) { // Initialise the progress status object for the type key stdair:: Count_T lActualNbOfEventsInt = static_cast<const stdair::Count_T> (std::floor (iActualNbOfEvents)); // Update the progress status for the corresponding content type key ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus != _progressStatusMap.end()) { // stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; // Update the overall progress status const stdair::Count_T lActualEventTypeNb = lProgressStatus.getActualNb(); const stdair::Count_T lActualTotalNb = _progressStatus.getActualNb(); _progressStatus.setActualNb (lActualTotalNb + iActualNbOfEvents - lActualEventTypeNb); // Update the progress status for the corresponding type key lProgressStatus.setActualNb (lActualNbOfEventsInt); } } // ////////////////////////////////////////////////////////////////////// void EventQueue::setStatus (const stdair::EventType::EN_EventType& iType, const stdair::ProgressStatus& iProgressStatus) { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::iterator itProgressStatus = _progressStatusMap.find (iType); // assert (itProgressStatus != _progressStatusMap.end()); if (itProgressStatus != _progressStatusMap.end()) { // Update the ProgressStatus structure itProgressStatus->second = iProgressStatus; } } // ////////////////////////////////////////////////////////////////////// stdair::ProgressStatus EventQueue:: getStatus (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus != _progressStatusMap.end()) { const stdair::ProgressStatus& oProgressStatus = itProgressStatus->second; return oProgressStatus; } return stdair::ProgressStatus(); } // ////////////////////////////////////////////////////////////////////// stdair::ProgressPercentage_T EventQueue:: calculateProgress (const stdair::EventType::EN_EventType& iType) const { // Retrieve the ProgressStatus structure corresponding to the // given event type ProgressStatusMap_T::const_iterator itProgressStatus = _progressStatusMap.find (iType); if (itProgressStatus == _progressStatusMap.end()) { // STDAIR_LOG_ERROR ("No ProgressStatus structure can be retrieved in the " << "EventQueue: " << display()); assert (false); } const stdair::ProgressStatus& lProgressStatus = itProgressStatus->second; return lProgressStatus.progress(); } // ////////////////////////////////////////////////////////////////////// stdair::ProgressStatusSet EventQueue::popEvent (stdair::EventStruct& ioEventStruct) { if (_eventList.empty() == true) { std::ostringstream oStr; oStr << "The event queue '" << describeKey() << "' is empty. " << "No event can be popped."; // STDAIR_LOG_ERROR (oStr.str()); throw EventQueueException (oStr.str()); } /** * 1. Update the event queue itself. */ // Get an iterator on the first event (sorted by date-time stamps) stdair::EventList_T::iterator itEvent = _eventList.begin(); /** * Extract (a copy of) the corresponding Event structure. We make * a copy here, as the original EventStruct structure is removed * from the list (and erased). Moreover, the resulting EventStruct * structure will be returned by this method. */ ioEventStruct = itEvent->second; // Retrieve the event type const stdair::EventType::EN_EventType& lEventType = ioEventStruct.getEventType(); stdair::ProgressStatusSet oProgressStatusSet (lEventType); // Update the (current number part of the) overall progress status, // to account for the event that is being popped out of the event // queue. ++_progressStatus; // Remove the event, which has just been retrieved _eventList.erase (itEvent); /** * 2. Update the progress statuses held by the EventStruct structure. * * 2.1. Update the progress status specific to the event type (e.g., * booking request, optimisation notification). */ // Retrieve the progress status specific to that event type stdair::ProgressStatus lEventTypeProgressStatus = getStatus (lEventType); // Increase the current number of events ++lEventTypeProgressStatus; // Store back the progress status setStatus (lEventType, lEventTypeProgressStatus); // Update the progress status of the progress status set, specific to // the event type. oProgressStatusSet.setTypeSpecificStatus (lEventTypeProgressStatus); /** * 2.2. Update the overall progress status. */ // Update the overall progress status of the progress status set. oProgressStatusSet.setOverallStatus (_progressStatus); // return oProgressStatusSet; } // ////////////////////////////////////////////////////////////////////// bool EventQueue::addEvent (stdair::EventStruct& ioEventStruct) { bool insertionSucceeded = _eventList.insert (stdair::EventListElement_T (ioEventStruct.getEventTimeStamp(), ioEventStruct)).second; /** * If the insertion has not been successful, try repeatedly until * the insertion becomes successful. * * The date-time is counted in milliseconds (1e-3 second). Hence, * one thousand (1e3) of attempts correspond to 1 second. * * The check on one thousand (1e3) is made in order to avoid * potential infinite loops. In such case, however, an assertion * will fail: it is always better that an assertion fails rather * than entering an infinite loop. */ const unsigned int idx = 0; while (insertionSucceeded == false && idx != 1e3) { // Increment the date-time stamp (expressed in milliseconds) ioEventStruct.incrementEventTimeStamp(); // Retry to insert into the event queue insertionSucceeded = _eventList.insert (stdair::EventListElement_T (ioEventStruct.getEventTimeStamp(), ioEventStruct)).second; } assert (idx != 1e3); return insertionSucceeded; } // ////////////////////////////////////////////////////////////////////// bool EventQueue::hasEventDateTime (const stdair::DateTime_T& iDateTime) { bool hasSearchEventBeenSucessful = true; /** * Compute the number of milliseconds between the * date-time of the event and DEFAULT_EVENT_OLDEST_DATETIME * (as of Feb. 2011, that date is set to Jan. 1, 2010). */ const stdair::Duration_T lDuration = iDateTime - stdair::DEFAULT_EVENT_OLDEST_DATETIME; const stdair::LongDuration_T lDateTimeStamp = lDuration.total_milliseconds(); // Searches the container for an element with iDateTime as key stdair::EventList_T::iterator itEvent = _eventList.find (lDateTimeStamp); // An iterator to map::end means the specified key has not found in the // container. if (itEvent == _eventList.end()) { hasSearchEventBeenSucessful = false; } return hasSearchEventBeenSucessful; } } <|endoftext|>
<commit_before>/* * code.cpp * * Created on: Oct 30, 2015 * Author: (Bu)nn TODO * Background Subtration to get just the hand (binarized image) * */ #include <core/cvdef.h> #include <core/cvstd.hpp> #include <core/cvstd.inl.hpp> #include <core/mat.hpp> #include <core/mat.inl.hpp> #include <core/matx.hpp> #include <core/ptr.inl.hpp> #include <core/types.hpp> #include <core.hpp> #include <highgui.hpp> #include <imgproc/types_c.h> #include <imgproc.hpp> #include <video/background_segm.hpp> #include <videoio.hpp> #include <algorithm> #include <cmath> #include <iostream> #include <utility> #include <vector> using namespace cv; using namespace std; Mat frame; //current frame Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method Mat back; Ptr<BackgroundSubtractorMOG2> pMOG2; //MOG2 Background subtractor vector<pair<Point, double>> palm_centers; //This function returns the square of the euclidean distance between 2 points. double dist(Point x, Point y) { return (x.x - y.x) * (x.x - y.x) + (x.y - y.y) * (x.y - y.y); } Mat pre_processing(Mat frame) { GaussianBlur(frame, frame, Size(7, 7), 10, 10); Mat gray_scale; cvtColor(frame, gray_scale, COLOR_BGR2GRAY, 1); Mat element = (Mat_<uchar>(3, 3) << 0, 1, 0, 1, 1, 1, 0, 1, 0); morphologyEx(gray_scale, gray_scale, MORPH_OPEN, element); return gray_scale; } Mat bg_subtraction(VideoCapture cap, Mat frame) { //update the background model pMOG2->apply(frame, fgMaskMOG2); //Get background image to display it pMOG2->getBackgroundImage(back); pMOG2->setDetectShadows(0); pMOG2->setNMixtures(3); return fgMaskMOG2; } //This function returns the radius and the center of the circle given 3 points //If a circle cannot be formed , it returns a zero radius circle centered at (0,0) pair<Point, double> circleFromPoints(Point p1, Point p2, Point p3) { double offset = pow(p2.x, 2) + pow(p2.y, 2); double bc = (pow(p1.x, 2) + pow(p1.y, 2) - offset) / 2.0; double cd = (offset - pow(p3.x, 2) - pow(p3.y, 2)) / 2.0; double det = (p1.x - p2.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p2.y); double TOL = 0.0000001; if (abs(det) < TOL) { cout << "POINTS TOO CLOSE" << endl; return make_pair(Point(0, 0), 0); } double idet = 1 / det; double centerx = (bc * (p2.y - p3.y) - cd * (p1.y - p2.y)) * idet; double centery = (cd * (p1.x - p2.x) - bc * (p2.x - p3.x)) * idet; double radius = sqrt(pow(p2.x - centerx, 2) + pow(p2.y - centery, 2)); return make_pair(Point(centerx, centery), radius); } Mat contouring(Mat binarized, Mat pre_processed) { vector<vector<Point>> contours; //Find the contours in the foreground findContours(binarized, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); imshow("Binary", binarized); for (int i = 0; i < contours.size(); i++) //Ignore all small insignificant areas if (contourArea(contours[i]) >= 5000) { //Draw contour vector<vector<Point>> tcontours; tcontours.push_back(contours[i]); drawContours(pre_processed, tcontours, -1, Scalar(0, 0, 255), 2); //Detect Hull in current contour vector<vector<Point> > hulls(1); vector<vector<int> > hullsI(1); convexHull(Mat(tcontours[0]), hulls[0], false); convexHull(Mat(tcontours[0]), hullsI[0], false); drawContours(pre_processed, hulls, -1, Scalar(0, 255, 0), 2); //Find minimum area rectangle to enclose hand RotatedRect rect = minAreaRect(Mat(tcontours[0])); //Find Convex Defects vector<Vec4i> defects; if (hullsI[0].size() > 0) { Point2f rect_points[4]; rect.points(rect_points); for (int j = 0; j < 4; j++) line(pre_processed, rect_points[j], rect_points[(j + 1) % 4], Scalar(255, 0, 0), 1, 8); Point rough_palm_center; convexityDefects(tcontours[0], hullsI[0], defects); if (defects.size() >= 3) { vector<Point> palm_points; for (int j = 0; j < defects.size(); j++) { int startidx = defects[j][0]; Point ptStart(tcontours[0][startidx]); int endidx = defects[j][1]; Point ptEnd(tcontours[0][endidx]); int faridx = defects[j][2]; Point ptFar(tcontours[0][faridx]); //Sum up all the hull and defect points to compute average rough_palm_center += ptFar + ptStart + ptEnd; palm_points.push_back(ptFar); palm_points.push_back(ptStart); palm_points.push_back(ptEnd); } //Get palm center by 1st getting the average of all defect points, this is the rough palm center, //Then U chose the closest 3 points ang get the circle radius and center formed from them which is the palm center. rough_palm_center.x /= defects.size() * 3; rough_palm_center.y /= defects.size() * 3; Point closest_pt = palm_points[0]; vector<pair<double, int> > distvec; for (int i = 0; i < palm_points.size(); i++) distvec.push_back( make_pair(dist(rough_palm_center, palm_points[i]), i)); sort(distvec.begin(), distvec.end()); //Keep choosing 3 points till you find a circle with a valid radius //As there is a high chance that the closes points might be in a linear line or too close that it forms a very large circle pair<Point, double> soln_circle; for (int i = 0; i + 2 < distvec.size(); i++) { Point p1 = palm_points[distvec[i + 0].second]; Point p2 = palm_points[distvec[i + 1].second]; Point p3 = palm_points[distvec[i + 2].second]; soln_circle = circleFromPoints(p1, p2, p3); //Final palm center,radius if (soln_circle.second != 0) break; } //Find avg palm centers for the last few frames to stabilize its centers, also find the avg radius palm_centers.push_back(soln_circle); if (palm_centers.size() > 10) palm_centers.erase(palm_centers.begin()); Point palm_center; double radius = 0; for (int i = 0; i < palm_centers.size(); i++) { palm_center += palm_centers[i].first; radius += palm_centers[i].second; } palm_center.x /= palm_centers.size(); palm_center.y /= palm_centers.size(); radius /= palm_centers.size(); //Draw the palm center and the palm circle //The size of the palm gives the depth of the hand circle(frame, palm_center, 5, Scalar(144, 144, 255), 3); circle(frame, palm_center, radius, Scalar(144, 144, 255), 2); //Detect fingers by finding points that form an almost isosceles triangle with certain thesholds int no_of_fingers = 0; for (int j = 0; j < defects.size(); j++) { int startidx = defects[j][0]; Point ptStart(tcontours[0][startidx]); int endidx = defects[j][1]; Point ptEnd(tcontours[0][endidx]); int faridx = defects[j][2]; Point ptFar(tcontours[0][faridx]); //X o--------------------------o Y double Xdist = sqrt(dist(palm_center, ptFar)); double Ydist = sqrt(dist(palm_center, ptStart)); double length = sqrt(dist(ptFar, ptStart)); double retLength = sqrt(dist(ptEnd, ptFar)); //Play with these thresholds to improve performance if (length <= 3 * radius && Ydist >= 0.4 * radius && length >= 10 && retLength >= 10 && max(length, retLength) / min(length, retLength) >= 0.8) if (min(Xdist, Ydist) / max(Xdist, Ydist) <= 0.8) { if ((Xdist >= 0.1 * radius && Xdist <= 1.3 * radius && Xdist < Ydist) || (Ydist >= 0.1 * radius && Ydist <= 1.3 * radius && Xdist > Ydist)) line(frame, ptEnd, ptFar, Scalar(0, 255, 0), 1), no_of_fingers++; } } no_of_fingers = min(5, no_of_fingers); // cout << "NO OF FINGERS: " << no_of_fingers << endl; if(no_of_fingers == 1){ cout << "NO OF FINGERS: " << no_of_fingers << endl; // Draw a line line( frame, Point( 15, 20 ), Point( 70, 50), Scalar( 110, 220, 0 ), 2, 8 ); // imshow("Line",frame); } } } } return pre_processed; } int process_video() { VideoCapture cap(0); // open the default camera if (!cap.isOpened()) // check if we succeeded return -1; for (;;) { //Capture the Frame and convert it to Grayscale cap >> frame; // get a new frame from camera Mat foreground; Mat i1 = pre_processing(frame); Mat bg_sub = bg_subtraction(cap, i1); absdiff(i1, back, foreground); Mat fg_binarized; threshold(foreground, fg_binarized, 0, 255, THRESH_BINARY | THRESH_OTSU); Mat contour = contouring(fg_binarized,frame); imshow("Frame", contour); // imshow("FG Mask MOG 2",bg_sub); // imshow("Background",back); if (waitKey(30) >= 0) break; } return 0; } int main(int, char**) { //create Background Subtractor objects pMOG2 = createBackgroundSubtractorMOG2(); //MOG2 approach int res = process_video(); return 0; } <commit_msg>mouse<commit_after>/* * code.cpp * * Created on: Oct 30, 2015 * Author: (Bu)nn TODO * Background Subtration to get just the hand (binarized image) * */ #include <core/cvdef.h> #include <core/cvstd.hpp> #include <core/cvstd.inl.hpp> #include <core/mat.hpp> #include <core/mat.inl.hpp> #include <core/matx.hpp> #include <core/ptr.inl.hpp> #include <core/types.hpp> #include <core.hpp> #include <highgui.hpp> #include <imgproc/types_c.h> #include <imgproc.hpp> #include <video/background_segm.hpp> #include <videoio.hpp> #include <algorithm> #include <cmath> #include <iostream> #include <utility> #include <vector> using namespace cv; using namespace std; Mat frame; //current frame Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method Mat back; Ptr<BackgroundSubtractorMOG2> pMOG2; //MOG2 Background subtractor vector<pair<Point, double>> palm_centers; //This function returns the square of the euclidean distance between 2 points. double dist(Point x, Point y) { return (x.x - y.x) * (x.x - y.x) + (x.y - y.y) * (x.y - y.y); } /* void CallBackFunc(int event, int x, int y, int d, void *ptr) { if ( event == EVENT_LBUTTONDOWN ) { cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << endl; } else if ( event == EVENT_RBUTTONDOWN ) { cout << "Right button of the mouse is clicked - position (" << x << ", " << y << ")" << endl; } else if ( event == EVENT_MBUTTONDOWN ) { cout << "Middle button of the mouse is clicked - position (" << x << ", " << y << ")" << endl; } else if ( event == EVENT_MOUSEMOVE ) { cout << "Mouse move over the window - position (" << x << ", " << y << ")" << endl; } Point*p = (Point*)ptr; p->x = x; p->y = y; } */ void on_mouse( int e, int x, int y, int d, void *ptr ) { Point*p = (Point*)ptr; p->x = x; p->y = y; } Mat pre_processing(Mat frame) { GaussianBlur(frame, frame, Size(7, 7), 10, 10); Mat gray_scale; cvtColor(frame, gray_scale, COLOR_BGR2GRAY, 1); Mat element = (Mat_<uchar>(3, 3) << 0, 1, 0, 1, 1, 1, 0, 1, 0); morphologyEx(gray_scale, gray_scale, MORPH_OPEN, element); return gray_scale; } Mat bg_subtraction(VideoCapture cap, Mat frame) { //update the background model pMOG2->apply(frame, fgMaskMOG2); //Get background image to display it pMOG2->getBackgroundImage(back); pMOG2->setDetectShadows(0); pMOG2->setNMixtures(3); return fgMaskMOG2; } //This function returns the radius and the center of the circle given 3 points //If a circle cannot be formed , it returns a zero radius circle centered at (0,0) pair<Point, double> circleFromPoints(Point p1, Point p2, Point p3) { double offset = pow(p2.x, 2) + pow(p2.y, 2); double bc = (pow(p1.x, 2) + pow(p1.y, 2) - offset) / 2.0; double cd = (offset - pow(p3.x, 2) - pow(p3.y, 2)) / 2.0; double det = (p1.x - p2.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p2.y); double TOL = 0.0000001; if (abs(det) < TOL) { cout << "POINTS TOO CLOSE" << endl; return make_pair(Point(0, 0), 0); } double idet = 1 / det; double centerx = (bc * (p2.y - p3.y) - cd * (p1.y - p2.y)) * idet; double centery = (cd * (p1.x - p2.x) - bc * (p2.x - p3.x)) * idet; double radius = sqrt(pow(p2.x - centerx, 2) + pow(p2.y - centery, 2)); return make_pair(Point(centerx, centery), radius); } Mat contouring(Mat binarized, Mat pre_processed) { vector<vector<Point>> contours; //Find the contours in the foreground findContours(binarized, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); imshow("Binary", binarized); for (int i = 0; i < contours.size(); i++) //Ignore all small insignificant areas if (contourArea(contours[i]) >= 5000) { //Draw contour vector<vector<Point>> tcontours; tcontours.push_back(contours[i]); drawContours(pre_processed, tcontours, -1, Scalar(0, 0, 255), 2); //Detect Hull in current contour vector<vector<Point> > hulls(1); vector<vector<int> > hullsI(1); convexHull(Mat(tcontours[0]), hulls[0], false); convexHull(Mat(tcontours[0]), hullsI[0], false); drawContours(pre_processed, hulls, -1, Scalar(0, 255, 0), 2); //Find minimum area rectangle to enclose hand RotatedRect rect = minAreaRect(Mat(tcontours[0])); //Find Convex Defects vector<Vec4i> defects; if (hullsI[0].size() > 0) { Point2f rect_points[4]; rect.points(rect_points); for (int j = 0; j < 4; j++) line(pre_processed, rect_points[j], rect_points[(j + 1) % 4], Scalar(255, 0, 0), 1, 8); Point rough_palm_center; convexityDefects(tcontours[0], hullsI[0], defects); if (defects.size() >= 3) { vector<Point> palm_points; for (int j = 0; j < defects.size(); j++) { int startidx = defects[j][0]; Point ptStart(tcontours[0][startidx]); int endidx = defects[j][1]; Point ptEnd(tcontours[0][endidx]); int faridx = defects[j][2]; Point ptFar(tcontours[0][faridx]); //Sum up all the hull and defect points to compute average rough_palm_center += ptFar + ptStart + ptEnd; palm_points.push_back(ptFar); palm_points.push_back(ptStart); palm_points.push_back(ptEnd); } //Get palm center by 1st getting the average of all defect points, this is the rough palm center, //Then U chose the closest 3 points ang get the circle radius and center formed from them which is the palm center. rough_palm_center.x /= defects.size() * 3; rough_palm_center.y /= defects.size() * 3; Point closest_pt = palm_points[0]; vector<pair<double, int> > distvec; for (int i = 0; i < palm_points.size(); i++) distvec.push_back( make_pair(dist(rough_palm_center, palm_points[i]), i)); sort(distvec.begin(), distvec.end()); //Keep choosing 3 points till you find a circle with a valid radius //As there is a high chance that the closes points might be in a linear line or too close that it forms a very large circle pair<Point, double> soln_circle; for (int i = 0; i + 2 < distvec.size(); i++) { Point p1 = palm_points[distvec[i + 0].second]; Point p2 = palm_points[distvec[i + 1].second]; Point p3 = palm_points[distvec[i + 2].second]; soln_circle = circleFromPoints(p1, p2, p3); //Final palm center,radius if (soln_circle.second != 0) break; } //Find avg palm centers for the last few frames to stabilize its centers, also find the avg radius palm_centers.push_back(soln_circle); if (palm_centers.size() > 10) palm_centers.erase(palm_centers.begin()); Point palm_center; double radius = 0; //averaging all palm centres for (int i = 0; i < palm_centers.size(); i++) { palm_center += palm_centers[i].first; radius += palm_centers[i].second; } palm_center.x /= palm_centers.size(); palm_center.y /= palm_centers.size(); radius /= palm_centers.size(); //Draw the palm center and the palm circle //The size of the palm gives the depth of the hand circle(frame, palm_center, 5, Scalar(144, 144, 255), 3); circle(frame, palm_center, radius, Scalar(144, 144, 255), 2); //Detect fingers by finding points that form an almost isosceles triangle with certain thesholds int no_of_fingers = 0; for (int j = 0; j < defects.size(); j++) { int startidx = defects[j][0]; Point ptStart(tcontours[0][startidx]); int endidx = defects[j][1]; Point ptEnd(tcontours[0][endidx]); int faridx = defects[j][2]; Point ptFar(tcontours[0][faridx]); //X o--------------------------o Y double Xdist = sqrt(dist(palm_center, ptFar)); double Ydist = sqrt(dist(palm_center, ptStart)); double length = sqrt(dist(ptFar, ptStart)); double retLength = sqrt(dist(ptEnd, ptFar)); //Play with these thresholds to improve performance if (length <= 3 * radius && Ydist >= 0.4 * radius && length >= 10 && retLength >= 10 && max(length, retLength) / min(length, retLength) >= 0.8) if (min(Xdist, Ydist) / max(Xdist, Ydist) <= 0.8) { if ((Xdist >= 0.1 * radius && Xdist <= 1.3 * radius && Xdist < Ydist) || (Ydist >= 0.1 * radius && Ydist <= 1.3 * radius && Xdist > Ydist)) line(frame, ptEnd, ptFar, Scalar(0, 255, 0), 1), no_of_fingers++; } } no_of_fingers = min(5, no_of_fingers); cout << "NO OF FINGERS: " << no_of_fingers << endl; setMouseCallback("Frame", on_mouse, &palm_center); /* if(no_of_fingers == 1){ cout << "NO OF FINGERS: " << no_of_fingers << endl; // Draw a line line( frame, palm_center,palm_centers[10].first, Scalar( 110, 220, 0 ), 2, 8 ); // imshow("Line",frame); }*/ } } } return pre_processed; } int process_video() { VideoCapture cap(0); // open the default camera if (!cap.isOpened()) // check if we succeeded return -1; for (;;) { //Capture the Frame and convert it to Grayscale cap >> frame; // get a new frame from camera Mat foreground; Mat i1 = pre_processing(frame); Mat bg_sub = bg_subtraction(cap, i1); absdiff(i1, back, foreground); Mat fg_binarized; threshold(foreground, fg_binarized, 0, 255, THRESH_BINARY | THRESH_OTSU); Mat contour = contouring(fg_binarized,frame); imshow("Frame", contour); // imshow("FG Mask MOG 2",bg_sub); // imshow("Background",back); if (waitKey(30) >= 0) break; } return 0; } int main(int, char**) { //create Background Subtractor objects pMOG2 = createBackgroundSubtractorMOG2(); //MOG2 approach int res = process_video(); //Create a window namedWindow("Frame", 1); return 0; } <|endoftext|>
<commit_before>#include "vga/timing.h" namespace vga { Timing const timing_vesa_640x480_60hz = { { 8000000, // external crystal Hz 8, // divide down to 1Mhz 201, // multiply up to 201MHz VCO 2, // divide by 2 for 100.5MHz CPU clock 3, // divide by 3 for 48MHz-ish SDIO clock 1, // divide CPU clock by 1 for 100.5MHz AHB clock 4, // divide CPU clock by 4 for 25.125MHz APB1 clock. 2, // divide CPU clock by 2 for 50.25MHz APB2 clock. 3, // 3 wait states for 100.5MHz at 3.3V. }, 800, // line_pixels 96, // sync_pixels 48, // back_porch_pixels 22, // video_lead 640, // video_pixels, Timing::Polarity::negative, 10, 10 + 2, 10 + 2 + 33, 10 + 2 + 33 + 480, Timing::Polarity::negative, }; Timing const timing_vesa_800x600_60hz = { { 8000000, // external crystal Hz 8, // divide down to 1Mhz 320, // multiply up to 320MHz VCO 2, // divide by 2 for 160MHz CPU clock 7, // divide by 7 for 48MHz-ish SDIO clock 1, // divide CPU clock by 1 for 160MHz AHB clock 4, // divide CPU clock by 4 for 40MHz APB1 clock. 2, // divide CPU clock by 2 for 80MHz APB2 clock. 5, // 5 wait states for 160MHz at 3.3V. }, 1056, // line_pixels 128, // sync_pixels 88, // back_porch_pixels 22, // video_lead 800, // video_pixels, Timing::Polarity::positive, 1, 1 + 4, 1 + 4 + 23, 1 + 4 + 23 + 600, Timing::Polarity::positive, }; } // namespace vga <commit_msg>vga: adjust 800x600 timing.<commit_after>#include "vga/timing.h" namespace vga { Timing const timing_vesa_640x480_60hz = { { 8000000, // external crystal Hz 8, // divide down to 1Mhz 201, // multiply up to 201MHz VCO 2, // divide by 2 for 100.5MHz CPU clock 3, // divide by 3 for 48MHz-ish SDIO clock 1, // divide CPU clock by 1 for 100.5MHz AHB clock 4, // divide CPU clock by 4 for 25.125MHz APB1 clock. 2, // divide CPU clock by 2 for 50.25MHz APB2 clock. 3, // 3 wait states for 100.5MHz at 3.3V. }, 800, // line_pixels 96, // sync_pixels 48, // back_porch_pixels 22, // video_lead 640, // video_pixels, Timing::Polarity::negative, 10, 10 + 2, 10 + 2 + 33, 10 + 2 + 33 + 480, Timing::Polarity::negative, }; Timing const timing_vesa_800x600_60hz = { { 8000000, // external crystal Hz 8, // divide down to 1Mhz 320, // multiply up to 320MHz VCO 2, // divide by 2 for 160MHz CPU clock 7, // divide by 7 for 48MHz-ish SDIO clock 1, // divide CPU clock by 1 for 160MHz AHB clock 4, // divide CPU clock by 4 for 40MHz APB1 clock. 2, // divide CPU clock by 2 for 80MHz APB2 clock. 5, // 5 wait states for 160MHz at 3.3V. }, 1056, // line_pixels 128, // sync_pixels 88, // back_porch_pixels 19, // video_lead 800, // video_pixels, Timing::Polarity::positive, 1, 1 + 4, 1 + 4 + 23, 1 + 4 + 23 + 600, Timing::Polarity::positive, }; } // namespace vga <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright 2015 Cloudius Systems */ #ifndef APPS_HTTPD_HTTPD_HH_ #define APPS_HTTPD_HTTPD_HH_ #include "http/request_parser.hh" #include "http/request.hh" #include "core/reactor.hh" #include "core/sstring.hh" #include <experimental/string_view> #include "core/app-template.hh" #include "core/circular_buffer.hh" #include "core/distributed.hh" #include "core/queue.hh" #include "core/future-util.hh" #include "core/scollectd.hh" #include <iostream> #include <algorithm> #include <unordered_map> #include <queue> #include <bitset> #include <limits> #include <cctype> #include <vector> #include <boost/intrusive/list.hpp> #include "reply.hh" #include "http/routes.hh" namespace httpd { class http_server; class http_stats; using namespace std::chrono_literals; class http_stats { scollectd::registrations _regs; public: http_stats(http_server& server); }; class http_server { std::vector<server_socket> _listeners; http_stats _stats { *this }; uint64_t _total_connections = 0; uint64_t _current_connections = 0; uint64_t _requests_served = 0; uint64_t _connections_being_accepted = 0; sstring _date = http_date(); timer<> _date_format_timer { [this] {_date = http_date();} }; bool _stopping = false; promise<> _all_connections_stopped; future<> _stopped = _all_connections_stopped.get_future(); private: void maybe_idle() { if (_stopping && !_connections_being_accepted && !_current_connections) { _all_connections_stopped.set_value(); } } public: routes _routes; http_server() { _date_format_timer.arm_periodic(1s); } future<> listen(ipv4_addr addr) { listen_options lo; lo.reuse_address = true; _listeners.push_back(engine().listen(make_ipv4_address(addr), lo)); _stopped = when_all(std::move(_stopped), do_accepts(_listeners.size() - 1)).discard_result(); return make_ready_future<>(); } future<> stop() { _stopping = true; for (auto&& l : _listeners) { l.abort_accept(); } for (auto&& c : _connections) { c.shutdown(); } return std::move(_stopped); } future<> do_accepts(int which) { ++_connections_being_accepted; return _listeners[which].accept().then_wrapped( [this, which] (future<connected_socket, socket_address> f_cs_sa) mutable { --_connections_being_accepted; if (_stopping) { maybe_idle(); return; } auto cs_sa = f_cs_sa.get(); auto conn = new connection(*this, std::get<0>(std::move(cs_sa)), std::get<1>(std::move(cs_sa))); conn->process().then_wrapped([this, conn] (auto&& f) { delete conn; try { f.get(); } catch (std::exception& ex) { std::cerr << "request error " << ex.what() << std::endl; } }); do_accepts(which); }).then_wrapped([] (auto f) { try { f.get(); } catch (std::exception& ex) { std::cerr << "accept failed: " << ex.what() << std::endl; } }); } class connection : public boost::intrusive::list_base_hook<> { http_server& _server; connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; static constexpr size_t limit = 4096; using tmp_buf = temporary_buffer<char>; http_request_parser _parser; std::unique_ptr<request> _req; std::unique_ptr<reply> _resp; // null element marks eof queue<std::unique_ptr<reply>> _replies { 10 };bool _done = false; public: connection(http_server& server, connected_socket&& fd, socket_address addr) : _server(server), _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf( _fd.output()) { ++_server._total_connections; ++_server._current_connections; _server._connections.push_back(*this); } ~connection() { --_server._current_connections; _server._connections.erase(_server._connections.iterator_to(*this)); _server.maybe_idle(); } future<> process() { // Launch read and write "threads" simultaneously: return when_all(read(), respond()).then( [] (std::tuple<future<>, future<>> joined) { // FIXME: notify any exceptions in joined? return make_ready_future<>(); }); } void shutdown() { _fd.shutdown_input(); _fd.shutdown_output(); } future<> read() { return do_until([this] {return _done;}, [this] { return read_one(); }).then_wrapped([this] (future<> f) { // swallow error // FIXME: count it? return _replies.push_eventually( {}); }); } future<> read_one() { _parser.init(); return _read_buf.consume(_parser).then([this] () mutable { if (_parser.eof()) { _done = true; return make_ready_future<>(); } ++_server._requests_served; std::unique_ptr<httpd::request> req = _parser.get_parsed_request(); return _replies.not_full().then([req = std::move(req), this] () mutable { return generate_reply(std::move(req)); }).then([this](bool done) { _done = done; }); }); } future<> respond() { return _replies.pop_eventually().then( [this] (std::unique_ptr<reply> resp) { if (!resp) { // eof return make_ready_future<>(); } _resp = std::move(resp); return start_response().then([this] { return respond(); }); }); } future<> start_response() { _resp->_headers["Server"] = "Seastar httpd"; _resp->_headers["Date"] = _server._date; _resp->_headers["Content-Length"] = to_sstring( _resp->_content.size()); return _write_buf.write(_resp->_response_line.begin(), _resp->_response_line.size()).then([this] { return write_reply_headers(_resp->_headers.begin()); }).then([this] { return _write_buf.write("\r\n", 2); }).then([this] { return write_body(); }).then([this] { return _write_buf.flush(); }).then([this] { _resp.reset(); }); } future<> write_reply_headers( std::unordered_map<sstring, sstring>::iterator hi) { if (hi == _resp->_headers.end()) { return make_ready_future<>(); } return _write_buf.write(hi->first.begin(), hi->first.size()).then( [this] { return _write_buf.write(": ", 2); }).then([hi, this] { return _write_buf.write(hi->second.begin(), hi->second.size()); }).then([this] { return _write_buf.write("\r\n", 2); }).then([hi, this] () mutable { return write_reply_headers(++hi); }); } static short hex_to_byte(char c) { if (c >='a' && c <= 'z') { return c - 'a' + 10; } else if (c >='A' && c <= 'Z') { return c - 'A' + 10; } return c - '0'; } /** * Convert a hex encoded 2 bytes substring to char */ static char hexstr_to_char(const std::experimental::string_view& in, size_t from) { return static_cast<char>(hex_to_byte(in[from]) * 16 + hex_to_byte(in[from + 1])); } /** * URL_decode a substring and place it in the given out sstring */ static bool url_decode(const std::experimental::string_view& in, sstring& out) { size_t pos = 0; char buff[in.length()]; for (size_t i = 0; i < in.length(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { buff[pos++] = hexstr_to_char(in, i + 1); i += 2; } else { return false; } } else if (in[i] == '+') { buff[pos++] = ' '; } else { buff[pos++] = in[i]; } } out = sstring(buff, pos); return true; } /** * Add a single query parameter to the parameter list */ static void add_param(request& req, const std::experimental::string_view& param) { size_t split = param.find('='); if (split >= param.length() - 1) { sstring key; if (url_decode(param.substr(0,split) , key)) { req.query_parameters[key] = ""; } } else { sstring key; sstring value; if (url_decode(param.substr(0,split), key) && url_decode(param.substr(split + 1), value)) { req.query_parameters[key] = value; } } } /** * Set the query parameters in the request objects. * query param appear after the question mark and are separated * by the ampersand sign */ static sstring set_query_param(request& req) { size_t pos = req._url.find('?'); if (pos == sstring::npos) { return req._url; } size_t curr = pos + 1; size_t end_param; std::experimental::string_view url = req._url; while ((end_param = req._url.find('&', curr)) != sstring::npos) { add_param(req, url.substr(curr, end_param - curr) ); curr = end_param + 1; } add_param(req, url.substr(curr)); return req._url.substr(0, pos); } future<bool> generate_reply(std::unique_ptr<request> req) { auto resp = std::make_unique<reply>(); bool conn_keep_alive = false; bool conn_close = false; auto it = req->_headers.find("Connection"); if (it != req->_headers.end()) { if (it->second == "Keep-Alive") { conn_keep_alive = true; } else if (it->second == "Close") { conn_close = true; } } bool should_close; // TODO: Handle HTTP/2.0 when it releases resp->set_version(req->_version); if (req->_version == "1.0") { if (conn_keep_alive) { resp->_headers["Connection"] = "Keep-Alive"; } should_close = !conn_keep_alive; } else if (req->_version == "1.1") { should_close = conn_close; } else { // HTTP/0.9 goes here should_close = true; } sstring url = set_query_param(*req.get()); return _server._routes.handle(url, std::move(req), std::move(resp)). // Caller guarantees enough room then([this, should_close](std::unique_ptr<reply> rep) { this->_replies.push(std::move(rep)); return make_ready_future<bool>(should_close); }); } future<> write_body() { return _write_buf.write(_resp->_content.begin(), _resp->_content.size()); } }; uint64_t total_connections() const { return _total_connections; } uint64_t current_connections() const { return _current_connections; } uint64_t requests_served() const { return _requests_served; } static sstring http_date() { auto t = ::time(nullptr); struct tm tm; gmtime_r(&t, &tm); char tmp[100]; strftime(tmp, sizeof(tmp), "%d %b %Y %H:%M:%S GMT", &tm); return tmp; } private: boost::intrusive::list<connection> _connections; }; /* * A helper class to start, set and listen an http server * typical use would be: * * auto server = new http_server_control(); * server->start().then([server] { * server->set_routes(set_routes); * }).then([server, port] { * server->listen(port); * }).then([port] { * std::cout << "Seastar HTTP server listening on port " << port << " ...\n"; * }); */ class http_server_control { distributed<http_server>* _server_dist; public: http_server_control() : _server_dist(new distributed<http_server>) { } future<> start() { return _server_dist->start(); } future<> stop() { return _server_dist->stop(); } future<> set_routes(std::function<void(routes& r)> fun) { return _server_dist->invoke_on_all([fun](http_server& server) { fun(server._routes); }); } future<> listen(ipv4_addr addr) { return _server_dist->invoke_on_all(&http_server::listen, addr); } distributed<http_server>& server() { return *_server_dist; } }; } #endif /* APPS_HTTPD_HTTPD_HH_ */ <commit_msg>http: All http replies should have version set<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright 2015 Cloudius Systems */ #ifndef APPS_HTTPD_HTTPD_HH_ #define APPS_HTTPD_HTTPD_HH_ #include "http/request_parser.hh" #include "http/request.hh" #include "core/reactor.hh" #include "core/sstring.hh" #include <experimental/string_view> #include "core/app-template.hh" #include "core/circular_buffer.hh" #include "core/distributed.hh" #include "core/queue.hh" #include "core/future-util.hh" #include "core/scollectd.hh" #include <iostream> #include <algorithm> #include <unordered_map> #include <queue> #include <bitset> #include <limits> #include <cctype> #include <vector> #include <boost/intrusive/list.hpp> #include "reply.hh" #include "http/routes.hh" namespace httpd { class http_server; class http_stats; using namespace std::chrono_literals; class http_stats { scollectd::registrations _regs; public: http_stats(http_server& server); }; class http_server { std::vector<server_socket> _listeners; http_stats _stats { *this }; uint64_t _total_connections = 0; uint64_t _current_connections = 0; uint64_t _requests_served = 0; uint64_t _connections_being_accepted = 0; sstring _date = http_date(); timer<> _date_format_timer { [this] {_date = http_date();} }; bool _stopping = false; promise<> _all_connections_stopped; future<> _stopped = _all_connections_stopped.get_future(); private: void maybe_idle() { if (_stopping && !_connections_being_accepted && !_current_connections) { _all_connections_stopped.set_value(); } } public: routes _routes; http_server() { _date_format_timer.arm_periodic(1s); } future<> listen(ipv4_addr addr) { listen_options lo; lo.reuse_address = true; _listeners.push_back(engine().listen(make_ipv4_address(addr), lo)); _stopped = when_all(std::move(_stopped), do_accepts(_listeners.size() - 1)).discard_result(); return make_ready_future<>(); } future<> stop() { _stopping = true; for (auto&& l : _listeners) { l.abort_accept(); } for (auto&& c : _connections) { c.shutdown(); } return std::move(_stopped); } future<> do_accepts(int which) { ++_connections_being_accepted; return _listeners[which].accept().then_wrapped( [this, which] (future<connected_socket, socket_address> f_cs_sa) mutable { --_connections_being_accepted; if (_stopping) { maybe_idle(); return; } auto cs_sa = f_cs_sa.get(); auto conn = new connection(*this, std::get<0>(std::move(cs_sa)), std::get<1>(std::move(cs_sa))); conn->process().then_wrapped([this, conn] (auto&& f) { delete conn; try { f.get(); } catch (std::exception& ex) { std::cerr << "request error " << ex.what() << std::endl; } }); do_accepts(which); }).then_wrapped([] (auto f) { try { f.get(); } catch (std::exception& ex) { std::cerr << "accept failed: " << ex.what() << std::endl; } }); } class connection : public boost::intrusive::list_base_hook<> { http_server& _server; connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; static constexpr size_t limit = 4096; using tmp_buf = temporary_buffer<char>; http_request_parser _parser; std::unique_ptr<request> _req; std::unique_ptr<reply> _resp; // null element marks eof queue<std::unique_ptr<reply>> _replies { 10 };bool _done = false; public: connection(http_server& server, connected_socket&& fd, socket_address addr) : _server(server), _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf( _fd.output()) { ++_server._total_connections; ++_server._current_connections; _server._connections.push_back(*this); } ~connection() { --_server._current_connections; _server._connections.erase(_server._connections.iterator_to(*this)); _server.maybe_idle(); } future<> process() { // Launch read and write "threads" simultaneously: return when_all(read(), respond()).then( [] (std::tuple<future<>, future<>> joined) { // FIXME: notify any exceptions in joined? return make_ready_future<>(); }); } void shutdown() { _fd.shutdown_input(); _fd.shutdown_output(); } future<> read() { return do_until([this] {return _done;}, [this] { return read_one(); }).then_wrapped([this] (future<> f) { // swallow error // FIXME: count it? return _replies.push_eventually( {}); }); } future<> read_one() { _parser.init(); return _read_buf.consume(_parser).then([this] () mutable { if (_parser.eof()) { _done = true; return make_ready_future<>(); } ++_server._requests_served; std::unique_ptr<httpd::request> req = _parser.get_parsed_request(); return _replies.not_full().then([req = std::move(req), this] () mutable { return generate_reply(std::move(req)); }).then([this](bool done) { _done = done; }); }); } future<> respond() { return _replies.pop_eventually().then( [this] (std::unique_ptr<reply> resp) { if (!resp) { // eof return make_ready_future<>(); } _resp = std::move(resp); return start_response().then([this] { return respond(); }); }); } future<> start_response() { _resp->_headers["Server"] = "Seastar httpd"; _resp->_headers["Date"] = _server._date; _resp->_headers["Content-Length"] = to_sstring( _resp->_content.size()); return _write_buf.write(_resp->_response_line.begin(), _resp->_response_line.size()).then([this] { return write_reply_headers(_resp->_headers.begin()); }).then([this] { return _write_buf.write("\r\n", 2); }).then([this] { return write_body(); }).then([this] { return _write_buf.flush(); }).then([this] { _resp.reset(); }); } future<> write_reply_headers( std::unordered_map<sstring, sstring>::iterator hi) { if (hi == _resp->_headers.end()) { return make_ready_future<>(); } return _write_buf.write(hi->first.begin(), hi->first.size()).then( [this] { return _write_buf.write(": ", 2); }).then([hi, this] { return _write_buf.write(hi->second.begin(), hi->second.size()); }).then([this] { return _write_buf.write("\r\n", 2); }).then([hi, this] () mutable { return write_reply_headers(++hi); }); } static short hex_to_byte(char c) { if (c >='a' && c <= 'z') { return c - 'a' + 10; } else if (c >='A' && c <= 'Z') { return c - 'A' + 10; } return c - '0'; } /** * Convert a hex encoded 2 bytes substring to char */ static char hexstr_to_char(const std::experimental::string_view& in, size_t from) { return static_cast<char>(hex_to_byte(in[from]) * 16 + hex_to_byte(in[from + 1])); } /** * URL_decode a substring and place it in the given out sstring */ static bool url_decode(const std::experimental::string_view& in, sstring& out) { size_t pos = 0; char buff[in.length()]; for (size_t i = 0; i < in.length(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { buff[pos++] = hexstr_to_char(in, i + 1); i += 2; } else { return false; } } else if (in[i] == '+') { buff[pos++] = ' '; } else { buff[pos++] = in[i]; } } out = sstring(buff, pos); return true; } /** * Add a single query parameter to the parameter list */ static void add_param(request& req, const std::experimental::string_view& param) { size_t split = param.find('='); if (split >= param.length() - 1) { sstring key; if (url_decode(param.substr(0,split) , key)) { req.query_parameters[key] = ""; } } else { sstring key; sstring value; if (url_decode(param.substr(0,split), key) && url_decode(param.substr(split + 1), value)) { req.query_parameters[key] = value; } } } /** * Set the query parameters in the request objects. * query param appear after the question mark and are separated * by the ampersand sign */ static sstring set_query_param(request& req) { size_t pos = req._url.find('?'); if (pos == sstring::npos) { return req._url; } size_t curr = pos + 1; size_t end_param; std::experimental::string_view url = req._url; while ((end_param = req._url.find('&', curr)) != sstring::npos) { add_param(req, url.substr(curr, end_param - curr) ); curr = end_param + 1; } add_param(req, url.substr(curr)); return req._url.substr(0, pos); } future<bool> generate_reply(std::unique_ptr<request> req) { auto resp = std::make_unique<reply>(); bool conn_keep_alive = false; bool conn_close = false; auto it = req->_headers.find("Connection"); if (it != req->_headers.end()) { if (it->second == "Keep-Alive") { conn_keep_alive = true; } else if (it->second == "Close") { conn_close = true; } } bool should_close; // TODO: Handle HTTP/2.0 when it releases resp->set_version(req->_version); if (req->_version == "1.0") { if (conn_keep_alive) { resp->_headers["Connection"] = "Keep-Alive"; } should_close = !conn_keep_alive; } else if (req->_version == "1.1") { should_close = conn_close; } else { // HTTP/0.9 goes here should_close = true; } sstring url = set_query_param(*req.get()); sstring version = req->_version; return _server._routes.handle(url, std::move(req), std::move(resp)). // Caller guarantees enough room then([this, should_close, version = std::move(version)](std::unique_ptr<reply> rep) { rep->set_version(version).done(); this->_replies.push(std::move(rep)); return make_ready_future<bool>(should_close); }); } future<> write_body() { return _write_buf.write(_resp->_content.begin(), _resp->_content.size()); } }; uint64_t total_connections() const { return _total_connections; } uint64_t current_connections() const { return _current_connections; } uint64_t requests_served() const { return _requests_served; } static sstring http_date() { auto t = ::time(nullptr); struct tm tm; gmtime_r(&t, &tm); char tmp[100]; strftime(tmp, sizeof(tmp), "%d %b %Y %H:%M:%S GMT", &tm); return tmp; } private: boost::intrusive::list<connection> _connections; }; /* * A helper class to start, set and listen an http server * typical use would be: * * auto server = new http_server_control(); * server->start().then([server] { * server->set_routes(set_routes); * }).then([server, port] { * server->listen(port); * }).then([port] { * std::cout << "Seastar HTTP server listening on port " << port << " ...\n"; * }); */ class http_server_control { distributed<http_server>* _server_dist; public: http_server_control() : _server_dist(new distributed<http_server>) { } future<> start() { return _server_dist->start(); } future<> stop() { return _server_dist->stop(); } future<> set_routes(std::function<void(routes& r)> fun) { return _server_dist->invoke_on_all([fun](http_server& server) { fun(server._routes); }); } future<> listen(ipv4_addr addr) { return _server_dist->invoke_on_all(&http_server::listen, addr); } distributed<http_server>& server() { return *_server_dist; } }; } #endif /* APPS_HTTPD_HTTPD_HH_ */ <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //------------------------------------------------------------------------------ // Implementation of the AliPerformanceTask class. It checks reconstruction performance // for the reconstructed vs MC particle tracks under several conditions. For real data // the control QA histograms are filled. // // The comparison output objects deriving from AliPerformanceObject // (e.g. AliPerformanceRes, AliPerformanceEff, AliPerformanceDEdx, AliPerformanceDCA ...) // are stored in the output file (details in description of these classes). // // Author: J.Otwinowski 01/04/2009 // Changes by M.Knichel 15/10/2010 //------------------------------------------------------------------------------ #include "iostream" #include "TChain.h" #include "TTree.h" #include "TH1F.h" #include "TCanvas.h" #include "TList.h" #include "TFile.h" #include "TSystem.h" #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliESDfriend.h" #include "AliMCEvent.h" #include "AliESDInputHandler.h" #include "AliMCEventHandler.h" #include "AliESDVertex.h" #include "AliMagF.h" #include "AliTracker.h" #include "AliGeomManager.h" #include "AliMCInfo.h" #include "AliESDRecInfo.h" #include "AliMCInfoCuts.h" #include "AliRecInfoCuts.h" #include "AliComparisonObject.h" #include "AliPerformanceObject.h" #include "AliTPCPerformanceSummary.h" #include "AliPerformanceTPC.h" #include "AliPerformanceDEdx.h" #include "AliPerformanceTask.h" using namespace std; ClassImp(AliPerformanceTask) //_____________________________________________________________________________ AliPerformanceTask::AliPerformanceTask() : AliAnalysisTaskSE("Performance") , fESD(0) , fESDfriend(0) , fMC(0) , fOutput(0) , fOutputSummary(0) , fPitList(0) , fCompList(0) , fUseMCInfo(kFALSE) , fUseESDfriend(kFALSE) , fUseHLT(kFALSE) { // Dummy Constructor // should not be used } //_____________________________________________________________________________ AliPerformanceTask::AliPerformanceTask(const char *name, const char */*title*/) : AliAnalysisTaskSE(name) , fESD(0) , fESDfriend(0) , fMC(0) , fOutput(0) , fOutputSummary(0) , fPitList(0) , fCompList(0) , fUseMCInfo(kFALSE) , fUseESDfriend(kFALSE) , fUseHLT(kFALSE) { // Constructor // Define input and output slots here DefineOutput(1, TList::Class()); DefineOutput(2, TTree::Class()); // create the list for comparison objects fCompList = new TList; } //_____________________________________________________________________________ AliPerformanceTask::~AliPerformanceTask() { if (fOutput) delete fOutput; fOutput = 0; if (fOutputSummary) delete fOutputSummary; fOutputSummary = 0; if (fCompList) delete fCompList; fCompList = 0; } //_____________________________________________________________________________ Bool_t AliPerformanceTask::AddPerformanceObject(AliPerformanceObject *pObj) { // add comparison object to the list if(pObj == 0) { Printf("ERROR: Could not add comparison object"); return kFALSE; } // add object to the list fCompList->AddLast(pObj); return kTRUE; } //_____________________________________________________________________________ void AliPerformanceTask::UserCreateOutputObjects() { // Create histograms // Called once // create output list fOutput = new TList; fOutput->SetOwner(); fPitList = fOutput->MakeIterator(); // create output list //fOutputSummary = new TTree; // add comparison objects to the output AliPerformanceObject *pObj=0; Int_t count=0; TIterator *pitCompList = fCompList->MakeIterator(); pitCompList->Reset(); while(( pObj = (AliPerformanceObject *)pitCompList->Next()) != NULL) { fOutput->Add(pObj); count++; } Printf("UserCreateOutputObjects(): Number of output comparison objects: %d \n", count); PostData(1, fOutput); //PostData(2, fOutputSummary); } //_____________________________________________________________________________ void AliPerformanceTask::UserExec(Option_t *) { // Main loop // Called for each event // Decide whether to use HLT or Offline ESD if(fUseHLT){ AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!esdH) { printf("ERROR: Could not get ESDInputHandler"); return; } fESD = esdH->GetHLTEvent(); }// end if fUseHLT else fESD = (AliESDEvent*) (InputEvent()); if(fUseESDfriend) { fESDfriend = static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend")); if(!fESDfriend) { Printf("ERROR: ESD friends not available"); } } if(fUseMCInfo) { fMC = MCEvent(); } // AliPerformanceObject *pObj=0; if (!fESD) { Printf("ERROR: ESD event not available"); return; } if (fUseMCInfo && !fMC) { Printf("ERROR: MC event not available"); return; } if(fUseESDfriend) { if(!fESDfriend) { Printf("ERROR: ESD friends not available"); } } // Process comparison fPitList->Reset(); while(( pObj = (AliPerformanceObject *)fPitList->Next()) != NULL) { pObj->Exec(fMC,fESD,fESDfriend,fUseMCInfo,fUseESDfriend); } // Post output data. PostData(1, fOutput); } //_____________________________________________________________________________ void AliPerformanceTask::Terminate(Option_t *) { // Called once at the end // check output data fOutputSummary = dynamic_cast<TTree*> (GetOutputData(2)); fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { Printf("ERROR: AliPerformanceTask::FinishTaskOutput(): fOutput data not available ..." ); return; } if (fOutputSummary) { delete fOutputSummary; fOutputSummary=0; } AliPerformanceObject* pObj=0; AliPerformanceTPC* pTPC = 0; AliPerformanceDEdx* pDEdx = 0; TIterator* itOut = fOutput->MakeIterator(); itOut->Reset(); while(( pObj = dynamic_cast<AliPerformanceObject*>(itOut->Next())) != NULL) { if (! pTPC) { pTPC = dynamic_cast<AliPerformanceTPC*>(pObj); } if (! pDEdx) { pDEdx = dynamic_cast<AliPerformanceDEdx*>(pObj); } } TUUID uuid; TString tmpFile = gSystem->TempDirectory() + TString("/TPCQASummary.") + uuid.AsString() + TString(".root"); AliTPCPerformanceSummary::WriteToFile(pTPC, pDEdx, tmpFile.Data()); TChain* chain = new TChain("tpcQA"); chain->Add(tmpFile.Data()); TTree *tree = chain->CopyTree("1"); if (chain) { delete chain; chain=0; } fOutputSummary = tree; // Post output data. PostData(2, fOutputSummary); } //_____________________________________________________________________________ void AliPerformanceTask::FinishTaskOutput() { // called once at the end of each job (on the workernode) // // projects THnSparse to TH1,2,3 fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { Printf("ERROR: AliPerformanceTask::FinishTaskOutput(): fOutput data not available ..." ); return; } AliPerformanceObject* pObj=0; TIterator* itOut = fOutput->MakeIterator(); itOut->Reset(); while(( pObj = dynamic_cast<AliPerformanceObject*>(itOut->Next())) != NULL) { pObj->SetRunNumber(fCurrentRunNumber); pObj->Analyse(); } // Post output data. PostData(1, fOutput); } //_____________________________________________________________________________ Bool_t AliPerformanceTask::Notify() { static Int_t count = 0; count++; Printf("Processing %d. file", count); return kTRUE; } <commit_msg>init OCDB in Terminate necessary for trending (M. Knichel)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //------------------------------------------------------------------------------ // Implementation of the AliPerformanceTask class. It checks reconstruction performance // for the reconstructed vs MC particle tracks under several conditions. For real data // the control QA histograms are filled. // // The comparison output objects deriving from AliPerformanceObject // (e.g. AliPerformanceRes, AliPerformanceEff, AliPerformanceDEdx, AliPerformanceDCA ...) // are stored in the output file (details in description of these classes). // // Author: J.Otwinowski 01/04/2009 // Changes by M.Knichel 15/10/2010 //------------------------------------------------------------------------------ #include "iostream" #include "TChain.h" #include "TTree.h" #include "TH1F.h" #include "TCanvas.h" #include "TList.h" #include "TFile.h" #include "TSystem.h" #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliESDfriend.h" #include "AliMCEvent.h" #include "AliESDInputHandler.h" #include "AliMCEventHandler.h" #include "AliESDVertex.h" #include "AliMagF.h" #include "AliTracker.h" #include "AliGeomManager.h" #include "AliMCInfo.h" #include "AliESDRecInfo.h" #include "AliMCInfoCuts.h" #include "AliRecInfoCuts.h" #include "AliComparisonObject.h" #include "AliPerformanceObject.h" #include "AliTPCPerformanceSummary.h" #include "AliPerformanceTPC.h" #include "AliPerformanceDEdx.h" #include "AliPerformanceTask.h" using namespace std; ClassImp(AliPerformanceTask) //_____________________________________________________________________________ AliPerformanceTask::AliPerformanceTask() : AliAnalysisTaskSE("Performance") , fESD(0) , fESDfriend(0) , fMC(0) , fOutput(0) , fOutputSummary(0) , fPitList(0) , fCompList(0) , fUseMCInfo(kFALSE) , fUseESDfriend(kFALSE) , fUseHLT(kFALSE) { // Dummy Constructor // should not be used } //_____________________________________________________________________________ AliPerformanceTask::AliPerformanceTask(const char *name, const char */*title*/) : AliAnalysisTaskSE(name) , fESD(0) , fESDfriend(0) , fMC(0) , fOutput(0) , fOutputSummary(0) , fPitList(0) , fCompList(0) , fUseMCInfo(kFALSE) , fUseESDfriend(kFALSE) , fUseHLT(kFALSE) { // Constructor // Define input and output slots here DefineOutput(1, TList::Class()); DefineOutput(2, TTree::Class()); // create the list for comparison objects fCompList = new TList; } //_____________________________________________________________________________ AliPerformanceTask::~AliPerformanceTask() { if (fOutput) delete fOutput; fOutput = 0; if (fOutputSummary) delete fOutputSummary; fOutputSummary = 0; if (fCompList) delete fCompList; fCompList = 0; } //_____________________________________________________________________________ Bool_t AliPerformanceTask::AddPerformanceObject(AliPerformanceObject *pObj) { // add comparison object to the list if(pObj == 0) { Printf("ERROR: Could not add comparison object"); return kFALSE; } // add object to the list fCompList->AddLast(pObj); return kTRUE; } //_____________________________________________________________________________ void AliPerformanceTask::UserCreateOutputObjects() { // Create histograms // Called once // create output list fOutput = new TList; fOutput->SetOwner(); fPitList = fOutput->MakeIterator(); // create output list //fOutputSummary = new TTree; // add comparison objects to the output AliPerformanceObject *pObj=0; Int_t count=0; TIterator *pitCompList = fCompList->MakeIterator(); pitCompList->Reset(); while(( pObj = (AliPerformanceObject *)pitCompList->Next()) != NULL) { fOutput->Add(pObj); count++; } Printf("UserCreateOutputObjects(): Number of output comparison objects: %d \n", count); PostData(1, fOutput); //PostData(2, fOutputSummary); } //_____________________________________________________________________________ void AliPerformanceTask::UserExec(Option_t *) { // Main loop // Called for each event // Decide whether to use HLT or Offline ESD if(fUseHLT){ AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!esdH) { printf("ERROR: Could not get ESDInputHandler"); return; } fESD = esdH->GetHLTEvent(); }// end if fUseHLT else fESD = (AliESDEvent*) (InputEvent()); if(fUseESDfriend) { fESDfriend = static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend")); if(!fESDfriend) { Printf("ERROR: ESD friends not available"); } } if(fUseMCInfo) { fMC = MCEvent(); } // AliPerformanceObject *pObj=0; if (!fESD) { Printf("ERROR: ESD event not available"); return; } if (fUseMCInfo && !fMC) { Printf("ERROR: MC event not available"); return; } if(fUseESDfriend) { if(!fESDfriend) { Printf("ERROR: ESD friends not available"); } } // Process comparison fPitList->Reset(); while(( pObj = (AliPerformanceObject *)fPitList->Next()) != NULL) { pObj->Exec(fMC,fESD,fESDfriend,fUseMCInfo,fUseESDfriend); } // Post output data. PostData(1, fOutput); } //_____________________________________________________________________________ void AliPerformanceTask::Terminate(Option_t *) { // Called once at the end // check output data fOutputSummary = dynamic_cast<TTree*> (GetOutputData(2)); fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { Printf("ERROR: AliPerformanceTask::Terminate(): fOutput data not available ..." ); return; } if (fOutputSummary) { delete fOutputSummary; fOutputSummary=0; } AliPerformanceObject* pObj=0; AliPerformanceTPC* pTPC = 0; AliPerformanceDEdx* pDEdx = 0; TIterator* itOut = fOutput->MakeIterator(); itOut->Reset(); while(( pObj = dynamic_cast<AliPerformanceObject*>(itOut->Next())) != NULL) { if (! pTPC) { pTPC = dynamic_cast<AliPerformanceTPC*>(pObj); } if (! pDEdx) { pDEdx = dynamic_cast<AliPerformanceDEdx*>(pObj); } } if (! AliCDBManager::Instance()->GetDefaultStorage()) { AliCDBManager::Instance()->SetDefaultStorage("raw://"); } TUUID uuid; TString tmpFile = gSystem->TempDirectory() + TString("/TPCQASummary.") + uuid.AsString() + TString(".root"); AliTPCPerformanceSummary::WriteToFile(pTPC, pDEdx, tmpFile.Data()); TChain* chain = new TChain("tpcQA"); chain->Add(tmpFile.Data()); TTree *tree = chain->CopyTree("1"); if (chain) { delete chain; chain=0; } fOutputSummary = tree; // Post output data. PostData(2, fOutputSummary); } //_____________________________________________________________________________ void AliPerformanceTask::FinishTaskOutput() { // called once at the end of each job (on the workernode) // // projects THnSparse to TH1,2,3 fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { Printf("ERROR: AliPerformanceTask::FinishTaskOutput(): fOutput data not available ..." ); return; } AliPerformanceObject* pObj=0; TIterator* itOut = fOutput->MakeIterator(); itOut->Reset(); while(( pObj = dynamic_cast<AliPerformanceObject*>(itOut->Next())) != NULL) { pObj->SetRunNumber(fCurrentRunNumber); pObj->Analyse(); } // Post output data. PostData(1, fOutput); } //_____________________________________________________________________________ Bool_t AliPerformanceTask::Notify() { static Int_t count = 0; count++; Printf("Processing %d. file", count); return kTRUE; } <|endoftext|>
<commit_before>#include "pybind11/pybind11.h" #include "pybind11/stl_bind.h" #define FORCE_IMPORT_ARRAY #include "RANS3PSed.h" #include "RANS3PSed2D.h" #if defined(__GNUC__) && !defined(__clang__) namespace workaround { inline void define_allocators() { std::allocator<int> a0; std::allocator<double> a1; } } #endif namespace py = pybind11; using proteus::cppRANS3PSed_base; using proteus::cppRANS3PSed2D_base; PYBIND11_MODULE(RANS3PSed, m) { xt::import_numpy(); py::class_<cppRANS3PSed_base>(m, "cppRANS3PSed_base") .def(py::init(&proteus::newRANS3PSed)) .def("calculateResidual", &cppRANS3PSed_base::calculateResidual) .def("calculateJacobian", &cppRANS3PSed_base::calculateJacobian) .def("calculateVelocityAverage", &cppRANS3PSed_base::calculateVelocityAverage); } PYBIND11_MODULE(RANS3PSed2D, m) { xt::import_numpy(); py::class_<cppRANS3PSed2D_base>(m, "cppRANS3PSed2D_base") .def(py::init(&proteus::newRANS3PSed2D)) .def("calculateResidual", &cppRANS3PSed2D_base::calculateResidual) .def("calculateJacobian", &cppRANS3PSed2D_base::calculateJacobian) .def("calculateVelocityAverage", &cppRANS3PSed2D_base::calculateVelocityAverage); } <commit_msg>Fixed RANS3PSed cpp module name<commit_after>#include "pybind11/pybind11.h" #include "pybind11/stl_bind.h" #define FORCE_IMPORT_ARRAY #include "RANS3PSed.h" #include "RANS3PSed2D.h" #if defined(__GNUC__) && !defined(__clang__) namespace workaround { inline void define_allocators() { std::allocator<int> a0; std::allocator<double> a1; } } #endif namespace py = pybind11; using proteus::cppRANS3PSed_base; using proteus::cppRANS3PSed2D_base; PYBIND11_MODULE(cRANS3PSed, m) { xt::import_numpy(); py::class_<cppRANS3PSed_base>(m, "cppRANS3PSed_base") .def(py::init(&proteus::newRANS3PSed)) .def("calculateResidual", &cppRANS3PSed_base::calculateResidual) .def("calculateJacobian", &cppRANS3PSed_base::calculateJacobian) .def("calculateVelocityAverage", &cppRANS3PSed_base::calculateVelocityAverage); py::class_<cppRANS3PSed2D_base>(m, "cppRANS3PSed2D_base") .def(py::init(&proteus::newRANS3PSed2D)) .def("calculateResidual", &cppRANS3PSed2D_base::calculateResidual) .def("calculateJacobian", &cppRANS3PSed2D_base::calculateJacobian) .def("calculateVelocityAverage", &cppRANS3PSed2D_base::calculateVelocityAverage); } <|endoftext|>
<commit_before>#define BOOST_LOG_DYN_LINK #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/log/trivial.hpp> #include <openssl/evp.h> #include "chunky.hpp" // This is a simple implementation of the WebSocket frame protocol for // a server. It can be used to communicate with a WebSocket client // after a successful handshake. The class is stateless, so all // methods are static and require a stream argument. class WebSocket { public: typedef std::vector<char> FramePayload; enum FrameType { continuation = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xa, fin = 0x80 }; // Receive frames from the stream continuously. template<typename Stream, typename ReadHandler> static void receive_frames(Stream& stream, ReadHandler&& handler) { receive_frame( stream, [=, &stream](const boost::system::error_code& error, uint8_t type, const std::shared_ptr<FramePayload>& payload) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } handler(boost::system::error_code(), type, payload); if (type != (fin | close)) receive_frames(stream, handler); }); } // Receive frame asynchronously. template<typename Stream, typename ReadHandler> static void receive_frame(Stream& stream, ReadHandler&& handler) { // Read the first two bytes of the frame header. auto header = std::make_shared<std::array<char, 14> >(); boost::asio::async_read( stream, boost::asio::mutable_buffers_1(&(*header)[0], 2), [=, &stream](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } // Determine the payload size format. size_t nLengthBytes = 0; size_t nPayloadBytes = (*header)[1] & 0x7f; switch (nPayloadBytes) { case 126: nLengthBytes = 2; nPayloadBytes = 0; break; case 127: nLengthBytes = 8; nPayloadBytes = 0; break; } // Configure the mask. const size_t nMaskBytes = ((*header)[1] & 0x80) ? 4 : 0; char* mask = &(*header)[2 + nLengthBytes]; std::fill(mask, mask + nMaskBytes, 0); // Read the payload size and mask. boost::asio::async_read( stream, boost::asio::mutable_buffers_1(&(*header)[2], nLengthBytes + nMaskBytes), [=, &stream](const boost::system::error_code& error, size_t) mutable { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } for (size_t i = 0; i < nLengthBytes; ++i) { nPayloadBytes <<= 8; nPayloadBytes |= static_cast<uint8_t>((*header)[2 + i]); } // Read the payload itself. auto payload = std::make_shared<FramePayload>(nPayloadBytes); boost::asio::async_read( stream, boost::asio::buffer(*payload), [=](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } // Unmask the payload buffer. size_t cindex = 0; for (char& c : *payload) c ^= mask[cindex++ & 0x3]; // Dispatch the frame. const uint8_t type = static_cast<uint8_t>((*header)[0]); handler(boost::system::error_code(), type, payload); }); }); }); } // Send frame asynchronously. template<typename Stream, typename ConstBufferSequence, typename WriteHandler> static void send_frame( Stream& stream, uint8_t type, const ConstBufferSequence& buffers, WriteHandler&& handler) { // Build the frame header. auto header = std::make_shared<FramePayload>(build_header(type, buffers)); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header->data(), header->size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::async_write( stream, frame, [=](const boost::system::error_code& error, size_t) { if (error) { handler(error); return; } header.get(); handler(error); }); } // Send frame synchronously returning error via error_code argument. template<typename Stream, typename ConstBufferSequence> static void send_frame( Stream& stream, uint8_t type, const ConstBufferSequence& buffers, boost::system::error_code& error) { auto header = build_header(type, buffers); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header.data(), header.size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::write(stream, frame, error); } // Send frame synchronously returning error via exception. template<typename Stream, typename ConstBufferSequence> static void send_frame( Stream& stream, uint8_t type, const ConstBufferSequence& buffers) { boost::system::error_code error; send_frame(stream, type, buffers, error); if (error) throw boost::system::system_error(error); } // Transform Sec-WebSocket-Key value to Sec-WebSocket-Accept value. static std::string process_key(const std::string& key) { EVP_MD_CTX sha1; EVP_DigestInit(&sha1, EVP_sha1()); EVP_DigestUpdate(&sha1, key.data(), key.size()); static const std::string suffix("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); EVP_DigestUpdate(&sha1, suffix.data(), suffix.size()); unsigned int digestSize; unsigned char digest[EVP_MAX_MD_SIZE]; EVP_DigestFinal(&sha1, digest, &digestSize); using namespace boost::archive::iterators; typedef base64_from_binary<transform_width<const unsigned char*, 6, 8>> Iterator; std::string result((Iterator(digest)), (Iterator(digest + digestSize))); result.resize((result.size() + 3) & ~size_t(3), '='); return result; } private: template<typename ConstBufferSequence> static FramePayload build_header(uint8_t type, const ConstBufferSequence& buffers) { FramePayload header; header.push_back(static_cast<char>(type)); const size_t bufferSize = boost::asio::buffer_size(buffers); if (bufferSize < 126) { header.push_back(static_cast<char>(bufferSize)); } else if (bufferSize < 65536) { header.push_back(static_cast<char>(126)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } else { header.push_back(static_cast<char>(127)); header.push_back(static_cast<char>((bufferSize >> 56) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 48) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 40) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 32) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 24) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 16) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } return header; } }; // This is a sample WebSocket session function. It manages one // connection over its stream argument. static void speak_websocket(const std::shared_ptr<chunky::TCP>& tcp) { static const std::vector<std::string> messages = { std::string(""), std::string(1, 'A'), std::string(2, 'B'), std::string(4, 'C'), std::string(8, 'D'), std::string(16, 'E'), std::string(32, 'F'), std::string(64, 'G'), std::string(128, 'H'), std::string(256, 'I'), std::string(512, 'J'), std::string(1024, 'K'), std::string(2048, 'L'), std::string(4096, 'M'), std::string(8192, 'N'), std::string(16384, 'O'), std::string(32768, 'P'), std::string(65536, 'Q'), std::string(131072, 'R'), std::string(262144, 'S'), }; // Start with a fragmented message. WebSocket::send_frame(*tcp, WebSocket::text, boost::asio::buffer(std::string("frag"))); WebSocket::send_frame(*tcp, WebSocket::continuation, boost::asio::buffer(std::string("ment"))); WebSocket::send_frame(*tcp, WebSocket::continuation, boost::asio::buffer(std::string("ation"))); WebSocket::send_frame(*tcp, WebSocket::continuation, boost::asio::buffer(std::string(" test"))); WebSocket::send_frame(*tcp, WebSocket::fin | WebSocket::continuation, boost::asio::null_buffers()); // Iterate through the array of test messages with this index. auto index = std::make_shared<int>(0); // Receive frames until an error or close. WebSocket::receive_frames( *tcp, [=](const boost::system::error_code& error, uint8_t type, const std::shared_ptr<WebSocket::FramePayload>& payload) { if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } try { switch(type & 0x7f) { case WebSocket::continuation: case WebSocket::text: case WebSocket::binary: BOOST_LOG_TRIVIAL(info) << boost::format("%02x %6d %s") % static_cast<unsigned int>(type) % payload->size() % std::string(payload->begin(), payload->begin() + std::min(payload->size(), size_t(20))); // Send the next test message (or close) when the // incoming message is complete. if (type & WebSocket::fin) { if (*index < messages.size()) { WebSocket::send_frame( *tcp, WebSocket::fin | WebSocket::text, boost::asio::buffer(messages[(*index)++]), [](const boost::system::error_code& error) { if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } }); } else WebSocket::send_frame(*tcp, WebSocket::fin | WebSocket::close, boost::asio::null_buffers()); } break; case WebSocket::ping: BOOST_LOG_TRIVIAL(info) << "WebSocket::ping"; WebSocket::send_frame(*tcp, WebSocket::fin | WebSocket::pong, boost::asio::buffer(*payload)); break; case WebSocket::pong: BOOST_LOG_TRIVIAL(info) << "WebSocket::pong"; break; case WebSocket::close: BOOST_LOG_TRIVIAL(info) << "WebSocket::close"; break; } } catch (const std::exception& e) { BOOST_LOG_TRIVIAL(error) << e.what(); } }); } int main() { chunky::SimpleHTTPServer server; // Simple web page that opens a WebSocket on the server. server.add_handler("/", [](const std::shared_ptr<chunky::HTTP>& http) { http->response_status() = 200; http->response_headers()["Content-Type"] = "text/html"; // The client will simply echo messages the server sends. static const std::string html = "<!DOCTYPE html>" "<title>chunky WebSocket</title>" "<h1>chunky WebSocket</h1>" "<script>\n" " var socket = new WebSocket('ws://' + location.host + '/ws');\n" " socket.onopen = function() {\n" " console.log('onopen')\n;" " }\n" " socket.onmessage = function(e) {\n" " console.log('onmessage');\n" " socket.send(e.data);\n" " }\n" " socket.onclose = function(error) {\n" " console.log('onclose');\n" " }\n" " socket.onerror = function(error) {\n" " console.log('onerror ' + error);\n" " }\n" "</script>\n"; boost::system::error_code error; boost::asio::write(*http, boost::asio::buffer(html), error); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } http->finish(error); }); // Perform the WebSocket handshake on /ws. server.add_handler("/ws", [](const std::shared_ptr<chunky::HTTP>& http) { BOOST_LOG_TRIVIAL(info) << boost::format("%s %s") % http->request_method() % http->request_resource(); auto key = http->request_headers().find("Sec-WebSocket-Key"); if (key != http->request_headers().end()) { http->response_status() = 101; // Switching Protocols http->response_headers()["Upgrade"] = "websocket"; http->response_headers()["Connection"] = "Upgrade"; http->response_headers()["Sec-WebSocket-Accept"] = WebSocket::process_key(key->second); } else { http->response_status() = 400; // Bad Request http->response_headers()["Connection"] = "close"; } boost::system::error_code error; http->finish(); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } // Handshake complete, hand off stream. speak_websocket(http->stream()); }); // Set the optional logging callback. server.set_logger([](const std::string& message) { BOOST_LOG_TRIVIAL(info) << message; }); // Run the server on all IPv4 and IPv6 interfaces. using boost::asio::ip::tcp; server.listen(tcp::endpoint(tcp::v4(), 8800)); server.listen(tcp::endpoint(tcp::v6(), 8800)); server.run(); BOOST_LOG_TRIVIAL(info) << "listening on port 8800"; // Accept new connections for 60 seconds. After that, the server // destructor will block until all existing TCP connections are // completed. Note that browsers may leave a connection open for // several minutes. std::this_thread::sleep_for(std::chrono::seconds(60)); BOOST_LOG_TRIVIAL(info) << "exiting (blocks until existing connections close)"; return 0; } <commit_msg>Deliver WebSocket payload by rvalue reference.<commit_after>#define BOOST_LOG_DYN_LINK #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/log/trivial.hpp> #include <openssl/evp.h> #include "chunky.hpp" // This is a simple implementation of the WebSocket frame protocol for // a server. It can be used to communicate with a WebSocket client // after a successful handshake. The class is stateless, so all // methods are static and require a stream argument. class WebSocket { public: typedef std::vector<char> FramePayload; enum FrameType { continuation = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xa, fin = 0x80 }; // Receive frames from the stream continuously. template<typename Stream, typename ReadHandler> static void receive_frames(Stream& stream, ReadHandler&& handler) { receive_frame( stream, [=, &stream](const boost::system::error_code& error, uint8_t type, FramePayload&& payload) { if (error) { handler(error, 0, FramePayload()); return; } handler(boost::system::error_code(), type, std::move(payload)); if (type != (fin | close)) receive_frames(stream, handler); }); } // Receive frame asynchronously. template<typename Stream, typename ReadHandler> static void receive_frame(Stream& stream, ReadHandler&& handler) { // Read the first two bytes of the frame header. auto header = std::make_shared<std::array<char, 14> >(); boost::asio::async_read( stream, boost::asio::mutable_buffers_1(&(*header)[0], 2), [=, &stream](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, FramePayload()); return; } // Determine the payload size format. size_t nLengthBytes = 0; size_t nPayloadBytes = (*header)[1] & 0x7f; switch (nPayloadBytes) { case 126: nLengthBytes = 2; nPayloadBytes = 0; break; case 127: nLengthBytes = 8; nPayloadBytes = 0; break; } // Configure the mask. const size_t nMaskBytes = ((*header)[1] & 0x80) ? 4 : 0; char* mask = &(*header)[2 + nLengthBytes]; std::fill(mask, mask + nMaskBytes, 0); // Read the payload size and mask. boost::asio::async_read( stream, boost::asio::mutable_buffers_1(&(*header)[2], nLengthBytes + nMaskBytes), [=, &stream](const boost::system::error_code& error, size_t) mutable { if (error) { handler(error, 0, FramePayload()); return; } for (size_t i = 0; i < nLengthBytes; ++i) { nPayloadBytes <<= 8; nPayloadBytes |= static_cast<uint8_t>((*header)[2 + i]); } // Read the payload itself. auto payload = std::make_shared<FramePayload>(nPayloadBytes); boost::asio::async_read( stream, boost::asio::buffer(*payload), [=](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, FramePayload()); return; } // Unmask the payload buffer. size_t cindex = 0; for (char& c : *payload) c ^= mask[cindex++ & 0x3]; // Dispatch the frame. const uint8_t type = static_cast<uint8_t>((*header)[0]); handler(boost::system::error_code(), type, std::move(*payload)); }); }); }); } // Send frame asynchronously. template<typename Stream, typename ConstBufferSequence, typename WriteHandler> static void send_frame( Stream& stream, uint8_t type, const ConstBufferSequence& buffers, WriteHandler&& handler) { // Build the frame header. auto header = std::make_shared<FramePayload>(build_header(type, buffers)); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header->data(), header->size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::async_write( stream, frame, [=](const boost::system::error_code& error, size_t) { if (error) { handler(error); return; } header.get(); handler(error); }); } // Send frame synchronously returning error via error_code argument. template<typename Stream, typename ConstBufferSequence> static void send_frame( Stream& stream, uint8_t type, const ConstBufferSequence& buffers, boost::system::error_code& error) { auto header = build_header(type, buffers); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header.data(), header.size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::write(stream, frame, error); } // Send frame synchronously returning error via exception. template<typename Stream, typename ConstBufferSequence> static void send_frame( Stream& stream, uint8_t type, const ConstBufferSequence& buffers) { boost::system::error_code error; send_frame(stream, type, buffers, error); if (error) throw boost::system::system_error(error); } // Transform Sec-WebSocket-Key value to Sec-WebSocket-Accept value. static std::string process_key(const std::string& key) { EVP_MD_CTX sha1; EVP_DigestInit(&sha1, EVP_sha1()); EVP_DigestUpdate(&sha1, key.data(), key.size()); static const std::string suffix("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); EVP_DigestUpdate(&sha1, suffix.data(), suffix.size()); unsigned int digestSize; unsigned char digest[EVP_MAX_MD_SIZE]; EVP_DigestFinal(&sha1, digest, &digestSize); using namespace boost::archive::iterators; typedef base64_from_binary<transform_width<const unsigned char*, 6, 8>> Iterator; std::string result((Iterator(digest)), (Iterator(digest + digestSize))); result.resize((result.size() + 3) & ~size_t(3), '='); return result; } private: template<typename ConstBufferSequence> static FramePayload build_header(uint8_t type, const ConstBufferSequence& buffers) { FramePayload header; header.push_back(static_cast<char>(type)); const size_t bufferSize = boost::asio::buffer_size(buffers); if (bufferSize < 126) { header.push_back(static_cast<char>(bufferSize)); } else if (bufferSize < 65536) { header.push_back(static_cast<char>(126)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } else { header.push_back(static_cast<char>(127)); header.push_back(static_cast<char>((bufferSize >> 56) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 48) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 40) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 32) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 24) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 16) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } return header; } }; // This is a sample WebSocket session function. It manages one // connection over its stream argument. static void speak_websocket(const std::shared_ptr<chunky::TCP>& tcp) { static const std::vector<std::string> messages = { std::string(""), std::string(1, 'A'), std::string(2, 'B'), std::string(4, 'C'), std::string(8, 'D'), std::string(16, 'E'), std::string(32, 'F'), std::string(64, 'G'), std::string(128, 'H'), std::string(256, 'I'), std::string(512, 'J'), std::string(1024, 'K'), std::string(2048, 'L'), std::string(4096, 'M'), std::string(8192, 'N'), std::string(16384, 'O'), std::string(32768, 'P'), std::string(65536, 'Q'), std::string(131072, 'R'), std::string(262144, 'S'), }; // Start with a fragmented message. WebSocket::send_frame(*tcp, WebSocket::text, boost::asio::buffer(std::string("frag"))); WebSocket::send_frame(*tcp, WebSocket::continuation, boost::asio::buffer(std::string("ment"))); WebSocket::send_frame(*tcp, WebSocket::continuation, boost::asio::buffer(std::string("ation"))); WebSocket::send_frame(*tcp, WebSocket::continuation, boost::asio::buffer(std::string(" test"))); WebSocket::send_frame(*tcp, WebSocket::fin | WebSocket::continuation, boost::asio::null_buffers()); // Iterate through the array of test messages with this index. auto index = std::make_shared<int>(0); // Receive frames until an error or close. WebSocket::receive_frames( *tcp, [=](const boost::system::error_code& error, uint8_t type, WebSocket::FramePayload&& payload) { if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } try { switch(type & 0x7f) { case WebSocket::continuation: case WebSocket::text: case WebSocket::binary: BOOST_LOG_TRIVIAL(info) << boost::format("%02x %6d %s") % static_cast<unsigned int>(type) % payload.size() % std::string(payload.begin(), payload.begin() + std::min(payload.size(), size_t(20))); // Send the next test message (or close) when the // incoming message is complete. if (type & WebSocket::fin) { if (*index < messages.size()) { WebSocket::send_frame( *tcp, WebSocket::fin | WebSocket::text, boost::asio::buffer(messages[(*index)++]), [](const boost::system::error_code& error) { if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } }); } else WebSocket::send_frame(*tcp, WebSocket::fin | WebSocket::close, boost::asio::null_buffers()); } break; case WebSocket::ping: BOOST_LOG_TRIVIAL(info) << "WebSocket::ping"; WebSocket::send_frame(*tcp, WebSocket::fin | WebSocket::pong, boost::asio::buffer(payload)); break; case WebSocket::pong: BOOST_LOG_TRIVIAL(info) << "WebSocket::pong"; break; case WebSocket::close: BOOST_LOG_TRIVIAL(info) << "WebSocket::close"; break; } } catch (const std::exception& e) { BOOST_LOG_TRIVIAL(error) << e.what(); } }); } int main() { chunky::SimpleHTTPServer server; // Simple web page that opens a WebSocket on the server. server.add_handler("/", [](const std::shared_ptr<chunky::HTTP>& http) { http->response_status() = 200; http->response_headers()["Content-Type"] = "text/html"; // The client will simply echo messages the server sends. static const std::string html = "<!DOCTYPE html>" "<title>chunky WebSocket</title>" "<h1>chunky WebSocket</h1>" "<script>\n" " var socket = new WebSocket('ws://' + location.host + '/ws');\n" " socket.onopen = function() {\n" " console.log('onopen')\n;" " }\n" " socket.onmessage = function(e) {\n" " console.log('onmessage');\n" " socket.send(e.data);\n" " }\n" " socket.onclose = function(error) {\n" " console.log('onclose');\n" " }\n" " socket.onerror = function(error) {\n" " console.log('onerror ' + error);\n" " }\n" "</script>\n"; boost::system::error_code error; boost::asio::write(*http, boost::asio::buffer(html), error); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } http->finish(error); }); // Perform the WebSocket handshake on /ws. server.add_handler("/ws", [](const std::shared_ptr<chunky::HTTP>& http) { BOOST_LOG_TRIVIAL(info) << boost::format("%s %s") % http->request_method() % http->request_resource(); auto key = http->request_headers().find("Sec-WebSocket-Key"); if (key != http->request_headers().end()) { http->response_status() = 101; // Switching Protocols http->response_headers()["Upgrade"] = "websocket"; http->response_headers()["Connection"] = "Upgrade"; http->response_headers()["Sec-WebSocket-Accept"] = WebSocket::process_key(key->second); } else { http->response_status() = 400; // Bad Request http->response_headers()["Connection"] = "close"; } boost::system::error_code error; http->finish(); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } // Handshake complete, hand off stream. speak_websocket(http->stream()); }); // Set the optional logging callback. server.set_logger([](const std::string& message) { BOOST_LOG_TRIVIAL(info) << message; }); // Run the server on all IPv4 and IPv6 interfaces. using boost::asio::ip::tcp; server.listen(tcp::endpoint(tcp::v4(), 8800)); server.listen(tcp::endpoint(tcp::v6(), 8800)); server.run(); BOOST_LOG_TRIVIAL(info) << "listening on port 8800"; // Accept new connections for 60 seconds. After that, the server // destructor will block until all existing TCP connections are // completed. Note that browsers may leave a connection open for // several minutes. std::this_thread::sleep_for(std::chrono::seconds(60)); BOOST_LOG_TRIVIAL(info) << "exiting (blocks until existing connections close)"; return 0; } <|endoftext|>
<commit_before>#include "petriproperties.h" #include "ui_petriproperties.h" #include "diagram/arcs/ipetriarc.h" #include "diagram/items/placeitem.h" PetriProperties::PetriProperties(QWidget *parent) : QWidget(parent), ui(new Ui::PetriProperties) { ui->setupUi(this); this->itemDataID = ""; this->netData = nullptr; this->currentPetriItem = nullptr; } PetriProperties::~PetriProperties() { delete ui; } void PetriProperties::setCurrentNet(spnp::Net *net) { this->netData = net; } void PetriProperties::onItemSelected(QGraphicsItem *item) { if(item == nullptr) { this->ui->stackedWidget->setCurrentIndex(7); this->itemDataID = ""; } else if(item->type() == IPetriItem::Type) { IPetriItem *other = qgraphicsitem_cast<IPetriItem *>(item); this->currentPetriItem = other; this->setData(other->getPetriItemId()); switch (other->petriType()) { case IPetriItem::Place: this->ui->stackedWidget->setCurrentIndex(0); this->loadPlace(); break; case IPetriItem::FPlace: this->ui->stackedWidget->setCurrentIndex(1); break; case IPetriItem::ITrans: this->ui->stackedWidget->setCurrentIndex(2); break; case IPetriItem::TTrans: this->ui->stackedWidget->setCurrentIndex(3); break; default: break; } } else if(item->type() == IPetriArc::Type) { IPetriArc *arc = qgraphicsitem_cast<IPetriArc *>(item); this->setData(arc->getArcId()); switch (arc->arcType()) { case IPetriArc::Activator: this->ui->stackedWidget->setCurrentIndex(4); break; case IPetriArc::FActivator: this->ui->stackedWidget->setCurrentIndex(5); break; case IPetriArc::Inhibitor: this->ui->stackedWidget->setCurrentIndex(6); break; default: break; } } } void PetriProperties::on_le_place_name_textEdited(const QString &arg1) { spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setName(arg1.toStdString()); } this->currentPetriItem->updateLabel(p); } void PetriProperties::on_le_place_tokens_textEdited(const QString &arg1) { QString newValue = this->clearArg(arg1); spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setToken(newValue.toStdString()); } PlaceItem *pi = qgraphicsitem_cast<PlaceItem*>(this->currentPetriItem); pi->updateToken(newValue); } void PetriProperties::setData(std::string itemId) { this->itemDataID = itemId; } void PetriProperties::loadPlace() { spnp::Place* place = this->netData->getPlace(this->itemDataID); if(place != nullptr) { this->ui->le_place_name->setText(QString::fromStdString(place->getName())); this->ui->le_place_tokens->setText(QString::fromStdString(place->getToken())); } } void PetriProperties::on_le_itrans_name_textEdited(const QString &arg1) { spnp::ImmediateTransition *it = this->netData->getTransition(itemDataID); if(it != nullptr) { it->setName(arg1.toStdString()); } } void PetriProperties::on_le_itrans_prior_textEdited(const QString &arg1) { //TODO (void)arg1; } void PetriProperties::on_le_itrans_guard_textEdited(const QString &arg1) { //TODO (void)arg1; } void PetriProperties::on_le_net_name_textEdited(const QString &arg1) { } void PetriProperties::on_le_fplace_name_textEdited(const QString &arg1) { } void PetriProperties::on_le_fplace_tokens_textEdited(const QString &arg1) { } void PetriProperties::on_le_fplace_limit_textEdited(const QString &arg1) { } void PetriProperties::on_le_fplace_break_textEdited(const QString &arg1) { } void PetriProperties::on_cb_itrans_prob_currentTextChanged(const QString &arg1) { } void PetriProperties::on_le_itrans_prob_value_textEdited(const QString &arg1) { } void PetriProperties::on_cb_itrans_prob_place_currentTextChanged(const QString &arg1) { } void PetriProperties::on_le_ttrans_name_textEdited(const QString &arg1) { } void PetriProperties::on_le_ttrans_guard_textEdited(const QString &arg1) { } void PetriProperties::on_le_ttrans_prior_textEdited(const QString &arg1) { } void PetriProperties::on_cb_ttrans_distr_currentTextChanged(const QString &arg1) { } void PetriProperties::on_pte_ttrans_distr_textChanged() { } void PetriProperties::on_le_ttrans_rate_textEdited(const QString &arg1) { } void PetriProperties::on_cb_ttrans_rate_currentTextChanged(const QString &arg1) { } void PetriProperties::on_cb_ttrans_place_currentTextChanged(const QString &arg1) { } void PetriProperties::on_cb_ttrans_pol_currentTextChanged(const QString &arg1) { } void PetriProperties::on_cb_ttrans_afected_currentTextChanged(const QString &arg1) { } void PetriProperties::on_rb_arc_const_toggled(bool checked) { } void PetriProperties::on_le_arc_mult_textEdited(const QString &arg1) { } QString PetriProperties::clearArg(QString arg1) { QString newValue = arg1; return newValue.remove(QRegExp("\001")); } <commit_msg>Nome da rede<commit_after>#include "petriproperties.h" #include "ui_petriproperties.h" #include "diagram/arcs/ipetriarc.h" #include "diagram/items/placeitem.h" PetriProperties::PetriProperties(QWidget *parent) : QWidget(parent), ui(new Ui::PetriProperties) { ui->setupUi(this); this->itemDataID = ""; this->netData = nullptr; this->currentPetriItem = nullptr; } PetriProperties::~PetriProperties() { delete ui; } void PetriProperties::setCurrentNet(spnp::Net *net) { this->netData = net; } void PetriProperties::onItemSelected(QGraphicsItem *item) { if(item == nullptr) { this->ui->stackedWidget->setCurrentIndex(7); this->itemDataID = ""; } else if(item->type() == IPetriItem::Type) { IPetriItem *other = qgraphicsitem_cast<IPetriItem *>(item); this->currentPetriItem = other; this->setData(other->getPetriItemId()); switch (other->petriType()) { case IPetriItem::Place: this->ui->stackedWidget->setCurrentIndex(0); this->loadPlace(); break; case IPetriItem::FPlace: this->ui->stackedWidget->setCurrentIndex(1); break; case IPetriItem::ITrans: this->ui->stackedWidget->setCurrentIndex(2); break; case IPetriItem::TTrans: this->ui->stackedWidget->setCurrentIndex(3); break; default: break; } } else if(item->type() == IPetriArc::Type) { IPetriArc *arc = qgraphicsitem_cast<IPetriArc *>(item); this->setData(arc->getArcId()); switch (arc->arcType()) { case IPetriArc::Activator: this->ui->stackedWidget->setCurrentIndex(4); break; case IPetriArc::FActivator: this->ui->stackedWidget->setCurrentIndex(5); break; case IPetriArc::Inhibitor: this->ui->stackedWidget->setCurrentIndex(6); break; default: break; } } } void PetriProperties::on_le_place_name_textEdited(const QString &arg1) { spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setName(arg1.toStdString()); } this->currentPetriItem->updateLabel(p); } void PetriProperties::on_le_place_tokens_textEdited(const QString &arg1) { QString newValue = this->clearArg(arg1); spnp::Place* p = this->netData->getPlace(itemDataID); if(p != nullptr) { p->setToken(newValue.toStdString()); } PlaceItem *pi = qgraphicsitem_cast<PlaceItem*>(this->currentPetriItem); pi->updateToken(newValue); } void PetriProperties::setData(std::string itemId) { this->itemDataID = itemId; } void PetriProperties::loadPlace() { spnp::Place* place = this->netData->getPlace(this->itemDataID); if(place != nullptr) { this->ui->le_place_name->setText(QString::fromStdString(place->getName())); this->ui->le_place_tokens->setText(QString::fromStdString(place->getToken())); } } void PetriProperties::on_le_itrans_name_textEdited(const QString &arg1) { spnp::ImmediateTransition *it = this->netData->getTransition(itemDataID); if(it != nullptr) { it->setName(arg1.toStdString()); } } void PetriProperties::on_le_itrans_prior_textEdited(const QString &arg1) { //TODO (void)arg1; } void PetriProperties::on_le_itrans_guard_textEdited(const QString &arg1) { //TODO (void)arg1; } void PetriProperties::on_le_net_name_textEdited(const QString &arg1) { this->netData->setName(arg1.toStdString()); } void PetriProperties::on_le_fplace_name_textEdited(const QString &arg1) { } void PetriProperties::on_le_fplace_tokens_textEdited(const QString &arg1) { } void PetriProperties::on_le_fplace_limit_textEdited(const QString &arg1) { } void PetriProperties::on_le_fplace_break_textEdited(const QString &arg1) { } void PetriProperties::on_cb_itrans_prob_currentTextChanged(const QString &arg1) { } void PetriProperties::on_le_itrans_prob_value_textEdited(const QString &arg1) { } void PetriProperties::on_cb_itrans_prob_place_currentTextChanged(const QString &arg1) { } void PetriProperties::on_le_ttrans_name_textEdited(const QString &arg1) { } void PetriProperties::on_le_ttrans_guard_textEdited(const QString &arg1) { } void PetriProperties::on_le_ttrans_prior_textEdited(const QString &arg1) { } void PetriProperties::on_cb_ttrans_distr_currentTextChanged(const QString &arg1) { } void PetriProperties::on_pte_ttrans_distr_textChanged() { } void PetriProperties::on_le_ttrans_rate_textEdited(const QString &arg1) { } void PetriProperties::on_cb_ttrans_rate_currentTextChanged(const QString &arg1) { } void PetriProperties::on_cb_ttrans_place_currentTextChanged(const QString &arg1) { } void PetriProperties::on_cb_ttrans_pol_currentTextChanged(const QString &arg1) { } void PetriProperties::on_cb_ttrans_afected_currentTextChanged(const QString &arg1) { } void PetriProperties::on_rb_arc_const_toggled(bool checked) { } void PetriProperties::on_le_arc_mult_textEdited(const QString &arg1) { } QString PetriProperties::clearArg(QString arg1) { QString newValue = arg1; return newValue.remove(QRegExp("\001")); } <|endoftext|>
<commit_before>//Create by Christine Nattrass, Rebecca Scott, Irakli Martashvili //University of Tennessee at Knoxville //by default this runs locally //With the argument true this submits jobs to the grid //As written this requires an xml script tag.xml in the ~/et directory on the grid to submit jobs void runCaloEt(bool submit = false, // true or false const char *dataType="sim", // "sim" or "real" etc. const char *pluginRunMode="full", // "test" or "full" or "terminate" const char *det = "EMCAL") // "PHOS" or "EMCAL" { TStopwatch timer; timer.Start(); gSystem->Load("libTree"); gSystem->Load("libGeom"); gSystem->Load("libVMC"); gSystem->Load("libPhysics"); gSystem->Load("libMinuit"); gSystem->AddIncludePath("-I$ALICE_ROOT/include"); gSystem->AddIncludePath("-I. -I$ALICE_ROOT/EMCAL -I$ALICE_ROOT/ANALYSIS"); gSystem->Load("libSTEERBase"); gSystem->Load("libESD"); gSystem->Load("libAOD"); gSystem->Load("libANALYSIS"); gSystem->Load("libANALYSISalice"); gSystem->Load("libCORRFW"); if (!submit) { cout << "local - no submitting" << endl; } else { cout << "submitting to grid" << endl; } gROOT->ProcessLine(".L AliAnalysisEtCuts.cxx+g"); gROOT->ProcessLine(".L AliAnalysisHadEtCorrections.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtCommon.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEt.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtMonteCarlo.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtMonteCarloPhos.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtMonteCarloEmcal.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtReconstructed.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtReconstructedPhos.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtReconstructedEmcal.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtSelectionContainer.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtSelectionHandler.cxx+g"); gROOT->ProcessLine(".L AliAnalysisTaskTransverseEnergy.cxx+g"); gROOT->ProcessLine(".L AliAnalysisTaskTotEt.cxx+g"); gInterpreter->GenerateDictionary("std::map<int, AliPhysicsSelection*>", "AliPhysicsSelection.h;map") ; gInterpreter->GenerateDictionary("std::pair<int, AliPhysicsSelection*>", "AliPhysicsSelection.h;utility"); char *kTreeName = "esdTree" ; TChain * chain = new TChain(kTreeName,"myESDTree") ; if(submit){ gSystem->Load("libNetx") ; gSystem->Load("libgapiUI"); gSystem->Load("libRAliEn"); TGrid::Connect("alien://") ; } // Make the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("TotEtManager"); TString detStr(det); TString taskName = "TaskTotEt" + detStr; TString dataStr(dataType); TString dataStrName(dataType); dataStrName.ReplaceAll("/","."); TString outputName = "Et.ESD." + dataStrName + "." + detStr + ".root"; TString outputDir = "totEt" + dataStr; cout << " taskName " << taskName << " outputName " << outputName << " outputDir (alien) " << outputDir << endl; if (submit) { gROOT->LoadMacro("CreateAlienHandlerCaloEtSim.C"); AliAnalysisGrid *alienHandler = CreateAlienHandlerCaloEtSim(outputDir, outputName, pluginRunMode); if (!alienHandler) return; mgr->SetGridHandler(alienHandler); } AliVEventHandler* esdH = new AliESDInputHandler; mgr->SetInputEventHandler(esdH); AliMCEventHandler* handler = new AliMCEventHandler; Bool_t isMc = kTRUE; Bool_t isPb = kFALSE; if ( dataStr.Contains("PbPb") ) { isPb = kTRUE;} if ( dataStr.Contains("sim") ) { cout << " MC " << endl; if ( dataStr.Contains("PbPb") ) { // a la: simPbPb/LHC10e18a cout << " PbPb " << endl; TString fileLocation = "/home/dsilverm/data/E_T/" + dataStr + "/dir/AliESDs.root"; cout << "fileLocation " << fileLocation.Data() << endl; chain->Add(fileLocation.Data()); // link to local test file } else { // pp chain->Add("/data/LHC10d15/1821/AliESDs.root"); //chain->Add("/data/LHC10dpass2/10000126403050.70/AliESDs.root");//data //chain->Add("/home/dsilverm/data/E_T/sim/LHC10d1/117222/100/AliESDs.root"); // link to local test file } handler->SetReadTR(kFALSE); mgr->SetMCtruthEventHandler(handler); } else { // real data isMc = kFALSE; chain->Add("/home/dsilverm/data/E_T/data/2010/LHC10b/000117222/ESDs/pass2/10000117222021.30/AliESDs.root"); // link to local test file cout << " not MC " << endl; } gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C"); AliPhysicsSelectionTask *physicsSelectionTask = AddTaskPhysicsSelection(isMc);//isMC is true when processing monte carlo if(isPb){ gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C"); gROOT->ProcessLine(".L AliCentralitySelectionTask.cxx++g"); AliCentralitySelectionTask *centTask = AddTaskCentrality(); } AliAnalysisTaskTotEt *task1 = new AliAnalysisTaskTotEt(taskName); task1->SetMcData(isMc);//necessary to tell the task to basically accept all MC events. mgr->AddTask(task1); AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("out1", TList::Class(), AliAnalysisManager::kOutputContainer, outputName); //____________________________________________// mgr->ConnectInput(task1,0,cinput1); mgr->ConnectOutput(task1,1,coutput1); mgr->SetDebugLevel(0); if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); if(submit){ mgr->StartAnalysis("grid"); } else{ mgr->StartAnalysis("local",chain); } timer.Stop(); timer.Print(); } <commit_msg>Adding lines to compile Marcelos code to driver macro<commit_after>//Create by Christine Nattrass, Rebecca Scott, Irakli Martashvili //University of Tennessee at Knoxville //by default this runs locally //With the argument true this submits jobs to the grid //As written this requires an xml script tag.xml in the ~/et directory on the grid to submit jobs void runCaloEt(bool submit = false, // true or false const char *dataType="sim", // "sim" or "real" etc. const char *pluginRunMode="full", // "test" or "full" or "terminate" const char *det = "EMCAL") // "PHOS" or "EMCAL" { TStopwatch timer; timer.Start(); gSystem->Load("libTree"); gSystem->Load("libGeom"); gSystem->Load("libVMC"); gSystem->Load("libPhysics"); gSystem->Load("libMinuit"); gSystem->AddIncludePath("-I$ALICE_ROOT/include"); gSystem->AddIncludePath("-I. -I$ALICE_ROOT/EMCAL -I$ALICE_ROOT/ANALYSIS"); gSystem->Load("libSTEERBase"); gSystem->Load("libESD"); gSystem->Load("libAOD"); gSystem->Load("libANALYSIS"); gSystem->Load("libANALYSISalice"); gSystem->Load("libCORRFW"); if (!submit) { cout << "local - no submitting" << endl; } else { cout << "submitting to grid" << endl; } gROOT->ProcessLine(".L AliAnalysisEtCuts.cxx+g"); gROOT->ProcessLine(".L AliAnalysisHadEtCorrections.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtCommon.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEt.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtMonteCarlo.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtMonteCarloPhos.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtMonteCarloEmcal.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtReconstructed.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtReconstructedPhos.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtReconstructedEmcal.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtSelectionContainer.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEtSelectionHandler.cxx+g"); gROOT->ProcessLine(".L AliAnalysisTaskTransverseEnergy.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEmEtMonteCarlo.cxx+g"); gROOT->ProcessLine(".L AliAnalysisEmEtReconstructed.cxx+g"); gROOT->ProcessLine(".L AliAnalysisTaskTotEt.cxx+g"); gInterpreter->GenerateDictionary("std::map<int, AliPhysicsSelection*>", "AliPhysicsSelection.h;map") ; gInterpreter->GenerateDictionary("std::pair<int, AliPhysicsSelection*>", "AliPhysicsSelection.h;utility"); char *kTreeName = "esdTree" ; TChain * chain = new TChain(kTreeName,"myESDTree") ; if(submit){ gSystem->Load("libNetx") ; gSystem->Load("libgapiUI"); gSystem->Load("libRAliEn"); TGrid::Connect("alien://") ; } // Make the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("TotEtManager"); TString detStr(det); TString taskName = "TaskTotEt" + detStr; TString dataStr(dataType); TString dataStrName(dataType); dataStrName.ReplaceAll("/","."); TString outputName = "Et.ESD." + dataStrName + "." + detStr + ".root"; TString outputDir = "totEt" + dataStr; cout << " taskName " << taskName << " outputName " << outputName << " outputDir (alien) " << outputDir << endl; if (submit) { gROOT->LoadMacro("CreateAlienHandlerCaloEtSim.C"); AliAnalysisGrid *alienHandler = CreateAlienHandlerCaloEtSim(outputDir, outputName, pluginRunMode); if (!alienHandler) return; mgr->SetGridHandler(alienHandler); } AliVEventHandler* esdH = new AliESDInputHandler; mgr->SetInputEventHandler(esdH); AliMCEventHandler* handler = new AliMCEventHandler; Bool_t isMc = kTRUE; Bool_t isPb = kFALSE; if ( dataStr.Contains("PbPb") ) { isPb = kTRUE;} if ( dataStr.Contains("sim") ) { cout << " MC " << endl; if ( dataStr.Contains("PbPb") ) { // a la: simPbPb/LHC10e18a cout << " PbPb " << endl; TString fileLocation = "/home/dsilverm/data/E_T/" + dataStr + "/dir/AliESDs.root"; cout << "fileLocation " << fileLocation.Data() << endl; chain->Add(fileLocation.Data()); // link to local test file } else { // pp chain->Add("/data/LHC10d15/1821/AliESDs.root"); //chain->Add("/data/LHC10dpass2/10000126403050.70/AliESDs.root");//data //chain->Add("/home/dsilverm/data/E_T/sim/LHC10d1/117222/100/AliESDs.root"); // link to local test file } handler->SetReadTR(kFALSE); mgr->SetMCtruthEventHandler(handler); } else { // real data isMc = kFALSE; chain->Add("/home/dsilverm/data/E_T/data/2010/LHC10b/000117222/ESDs/pass2/10000117222021.30/AliESDs.root"); // link to local test file cout << " not MC " << endl; } gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C"); AliPhysicsSelectionTask *physicsSelectionTask = AddTaskPhysicsSelection(isMc);//isMC is true when processing monte carlo if(isPb){ gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C"); gROOT->ProcessLine(".L AliCentralitySelectionTask.cxx++g"); AliCentralitySelectionTask *centTask = AddTaskCentrality(); } AliAnalysisTaskTotEt *task1 = new AliAnalysisTaskTotEt(taskName); task1->SetMcData(isMc);//necessary to tell the task to basically accept all MC events. mgr->AddTask(task1); AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("out1", TList::Class(), AliAnalysisManager::kOutputContainer, outputName); //____________________________________________// mgr->ConnectInput(task1,0,cinput1); mgr->ConnectOutput(task1,1,coutput1); mgr->SetDebugLevel(0); if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); if(submit){ mgr->StartAnalysis("grid"); } else{ mgr->StartAnalysis("local",chain); } timer.Stop(); timer.Print(); } <|endoftext|>
<commit_before>/* * Copyright 2018 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 "p2p/base/datagram_dtls_adaptor.h" #include <algorithm> #include <memory> #include <utility> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "api/rtc_error.h" #include "logging/rtc_event_log/events/rtc_event_dtls_transport_state.h" #include "logging/rtc_event_log/events/rtc_event_dtls_writable_state.h" #include "logging/rtc_event_log/rtc_event_log.h" #include "p2p/base/dtls_transport_internal.h" #include "p2p/base/packet_transport_internal.h" #include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/dscp.h" #include "rtc_base/flags.h" #include "rtc_base/logging.h" #include "rtc_base/message_queue.h" #include "rtc_base/rtc_certificate.h" #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/stream.h" #include "rtc_base/thread.h" #ifdef BYPASS_DATAGRAM_DTLS_TEST_ONLY // Send unencrypted packets directly to ICE, bypassing datagtram // transport. Use in tests only. constexpr bool kBypassDatagramDtlsTestOnly = true; #else constexpr bool kBypassDatagramDtlsTestOnly = false; #endif namespace cricket { DatagramDtlsAdaptor::DatagramDtlsAdaptor( std::unique_ptr<IceTransportInternal> ice_transport, std::unique_ptr<webrtc::DatagramTransportInterface> datagram_transport, const webrtc::CryptoOptions& crypto_options, webrtc::RtcEventLog* event_log) : crypto_options_(crypto_options), ice_transport_(std::move(ice_transport)), datagram_transport_(std::move(datagram_transport)), event_log_(event_log) { RTC_DCHECK(ice_transport_); RTC_DCHECK(datagram_transport_); ConnectToIceTransport(); } void DatagramDtlsAdaptor::ConnectToIceTransport() { if (kBypassDatagramDtlsTestOnly) { // In bypass mode we have to subscribe to ICE read and sent events. // Test only case to use ICE directly instead of data transport. ice_transport_->SignalReadPacket.connect( this, &DatagramDtlsAdaptor::OnReadPacket); ice_transport_->SignalSentPacket.connect( this, &DatagramDtlsAdaptor::OnSentPacket); ice_transport_->SignalWritableState.connect( this, &DatagramDtlsAdaptor::OnWritableState); ice_transport_->SignalReadyToSend.connect( this, &DatagramDtlsAdaptor::OnReadyToSend); ice_transport_->SignalReceivingState.connect( this, &DatagramDtlsAdaptor::OnReceivingState); } else { // Subscribe to Data Transport read packets. datagram_transport_->SetDatagramSink(this); datagram_transport_->SetTransportStateCallback(this); // Datagram transport does not propagate network route change. ice_transport_->SignalNetworkRouteChanged.connect( this, &DatagramDtlsAdaptor::OnNetworkRouteChanged); } } DatagramDtlsAdaptor::~DatagramDtlsAdaptor() { // Unsubscribe from Datagram Transport dinks. datagram_transport_->SetDatagramSink(nullptr); datagram_transport_->SetTransportStateCallback(nullptr); // Make sure datagram transport is destroyed before ICE. datagram_transport_.reset(); ice_transport_.reset(); } const webrtc::CryptoOptions& DatagramDtlsAdaptor::crypto_options() const { return crypto_options_; } int DatagramDtlsAdaptor::SendPacket(const char* data, size_t len, const rtc::PacketOptions& options, int flags) { // TODO(sukhanov): Handle options and flags. if (kBypassDatagramDtlsTestOnly) { // In bypass mode sent directly to ICE. return ice_transport_->SendPacket(data, len, options); } // Send datagram with id equal to options.packet_id, so we get it back // in DatagramDtlsAdaptor::OnDatagramSent() and propagate notification // up. webrtc::RTCError error = datagram_transport_->SendDatagram( rtc::MakeArrayView(reinterpret_cast<const uint8_t*>(data), len), /*datagram_id=*/options.packet_id); return (error.ok() ? len : -1); } void DatagramDtlsAdaptor::OnReadPacket(rtc::PacketTransportInternal* transport, const char* data, size_t size, const int64_t& packet_time_us, int flags) { // Only used in bypass mode. RTC_DCHECK(kBypassDatagramDtlsTestOnly); RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK_EQ(transport, ice_transport_.get()); RTC_DCHECK(flags == 0); PropagateReadPacket( rtc::MakeArrayView(reinterpret_cast<const uint8_t*>(data), size), packet_time_us); } void DatagramDtlsAdaptor::OnDatagramReceived( rtc::ArrayView<const uint8_t> data) { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(!kBypassDatagramDtlsTestOnly); // TODO(sukhanov): I am not filling out time, but on my video quality // test in WebRTC the time was not set either and higher layers of the stack // overwrite -1 with current current rtc time. Leaveing comment for now to // make sure it works as expected. int64_t packet_time_us = -1; PropagateReadPacket(data, packet_time_us); } void DatagramDtlsAdaptor::OnDatagramSent(webrtc::DatagramId datagram_id) { // When we called DatagramTransportInterface::SendDatagram, we passed // packet_id as datagram_id, so we simply need to set it in sent_packet // and propagate notification up the stack. // Also see how DatagramDtlsAdaptor::OnSentPacket handles OnSentPacket // notification from ICE in bypass mode. rtc::SentPacket sent_packet(/*packet_id=*/datagram_id, rtc::TimeMillis()); PropagateOnSentNotification(sent_packet); } void DatagramDtlsAdaptor::OnSentPacket(rtc::PacketTransportInternal* transport, const rtc::SentPacket& sent_packet) { // Only used in bypass mode. RTC_DCHECK(kBypassDatagramDtlsTestOnly); RTC_DCHECK_RUN_ON(&thread_checker_); PropagateOnSentNotification(sent_packet); } void DatagramDtlsAdaptor::PropagateOnSentNotification( const rtc::SentPacket& sent_packet) { RTC_DCHECK_RUN_ON(&thread_checker_); SignalSentPacket(this, sent_packet); } void DatagramDtlsAdaptor::PropagateReadPacket( rtc::ArrayView<const uint8_t> data, const int64_t& packet_time_us) { RTC_DCHECK_RUN_ON(&thread_checker_); SignalReadPacket(this, reinterpret_cast<const char*>(data.data()), data.size(), packet_time_us, /*flags=*/0); } int DatagramDtlsAdaptor::component() const { return kDatagramDtlsAdaptorComponent; } bool DatagramDtlsAdaptor::IsDtlsActive() const { return false; } bool DatagramDtlsAdaptor::GetDtlsRole(rtc::SSLRole* role) const { return false; } bool DatagramDtlsAdaptor::SetDtlsRole(rtc::SSLRole role) { return false; } bool DatagramDtlsAdaptor::GetSrtpCryptoSuite(int* cipher) { return false; } bool DatagramDtlsAdaptor::GetSslCipherSuite(int* cipher) { return false; } rtc::scoped_refptr<rtc::RTCCertificate> DatagramDtlsAdaptor::GetLocalCertificate() const { return nullptr; } bool DatagramDtlsAdaptor::SetLocalCertificate( const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) { return false; } std::unique_ptr<rtc::SSLCertChain> DatagramDtlsAdaptor::GetRemoteSSLCertChain() const { return nullptr; } bool DatagramDtlsAdaptor::ExportKeyingMaterial(const std::string& label, const uint8_t* context, size_t context_len, bool use_context, uint8_t* result, size_t result_len) { return false; } bool DatagramDtlsAdaptor::SetRemoteFingerprint(const std::string& digest_alg, const uint8_t* digest, size_t digest_len) { // TODO(sukhanov): We probably should not called with fingerptints in // datagram scenario, but we may need to change code up the stack before // we can return false or DCHECK. return true; } bool DatagramDtlsAdaptor::SetSslMaxProtocolVersion( rtc::SSLProtocolVersion version) { // TODO(sukhanov): We may be able to return false and/or DCHECK that we // are not called if datagram transport is used, but we need to change // integration before we can do it. return true; } IceTransportInternal* DatagramDtlsAdaptor::ice_transport() { return ice_transport_.get(); } webrtc::DatagramTransportInterface* DatagramDtlsAdaptor::datagram_transport() { return datagram_transport_.get(); } // Similar implementaton as in p2p/base/dtls_transport.cc. void DatagramDtlsAdaptor::OnReadyToSend( rtc::PacketTransportInternal* transport) { RTC_DCHECK_RUN_ON(&thread_checker_); if (writable()) { SignalReadyToSend(this); } } void DatagramDtlsAdaptor::OnWritableState( rtc::PacketTransportInternal* transport) { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(transport == ice_transport_.get()); RTC_LOG(LS_VERBOSE) << ": ice_transport writable state changed to " << ice_transport_->writable(); if (kBypassDatagramDtlsTestOnly) { // Note: SignalWritableState fired by set_writable. set_writable(ice_transport_->writable()); return; } switch (dtls_state()) { case DTLS_TRANSPORT_NEW: break; case DTLS_TRANSPORT_CONNECTED: // Note: SignalWritableState fired by set_writable. // Do we also need set_receiving(ice_transport_->receiving()) here now, in // case we lose that signal before "DTLS" connects? // DtlsTransport::OnWritableState does not set_receiving in a similar // case, so leaving it out for the time being, but it would be good to // understand why. set_writable(ice_transport_->writable()); break; case DTLS_TRANSPORT_CONNECTING: // Do nothing. break; case DTLS_TRANSPORT_FAILED: case DTLS_TRANSPORT_CLOSED: // Should not happen. Do nothing. break; } } void DatagramDtlsAdaptor::OnStateChanged(webrtc::MediaTransportState state) { // Convert MediaTransportState to DTLS state. switch (state) { case webrtc::MediaTransportState::kPending: set_dtls_state(DTLS_TRANSPORT_CONNECTING); break; case webrtc::MediaTransportState::kWritable: // Since we do not set writable state until datagram transport is // connected, we need to call set_writable first. set_writable(ice_transport_->writable()); set_dtls_state(DTLS_TRANSPORT_CONNECTED); break; case webrtc::MediaTransportState::kClosed: set_dtls_state(DTLS_TRANSPORT_CLOSED); break; } } DtlsTransportState DatagramDtlsAdaptor::dtls_state() const { return dtls_state_; } const std::string& DatagramDtlsAdaptor::transport_name() const { return ice_transport_->transport_name(); } bool DatagramDtlsAdaptor::writable() const { // NOTE that even if ice is writable, writable_ maybe false, because we // propagte writable only after DTLS is connect (this is consistent with // implementation in dtls_transport.cc). return writable_; } bool DatagramDtlsAdaptor::receiving() const { return receiving_; } int DatagramDtlsAdaptor::SetOption(rtc::Socket::Option opt, int value) { return ice_transport_->SetOption(opt, value); } int DatagramDtlsAdaptor::GetError() { return ice_transport_->GetError(); } void DatagramDtlsAdaptor::OnNetworkRouteChanged( absl::optional<rtc::NetworkRoute> network_route) { RTC_DCHECK_RUN_ON(&thread_checker_); SignalNetworkRouteChanged(network_route); } void DatagramDtlsAdaptor::OnReceivingState( rtc::PacketTransportInternal* transport) { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(transport == ice_transport_.get()); RTC_LOG(LS_VERBOSE) << "ice_transport receiving state changed to " << ice_transport_->receiving(); if (kBypassDatagramDtlsTestOnly || dtls_state() == DTLS_TRANSPORT_CONNECTED) { // Note: SignalReceivingState fired by set_receiving. set_receiving(ice_transport_->receiving()); } } void DatagramDtlsAdaptor::set_receiving(bool receiving) { if (receiving_ == receiving) { return; } receiving_ = receiving; SignalReceivingState(this); } // Similar implementaton as in p2p/base/dtls_transport.cc. void DatagramDtlsAdaptor::set_writable(bool writable) { if (writable_ == writable) { return; } if (event_log_) { event_log_->Log( absl::make_unique<webrtc::RtcEventDtlsWritableState>(writable)); } RTC_LOG(LS_VERBOSE) << "set_writable to: " << writable; writable_ = writable; if (writable_) { SignalReadyToSend(this); } SignalWritableState(this); } // Similar implementaton as in p2p/base/dtls_transport.cc. void DatagramDtlsAdaptor::set_dtls_state(DtlsTransportState state) { if (dtls_state_ == state) { return; } if (event_log_) { event_log_->Log(absl::make_unique<webrtc::RtcEventDtlsTransportState>( ConvertDtlsTransportState(state))); } RTC_LOG(LS_VERBOSE) << "set_dtls_state from:" << dtls_state_ << " to " << state; dtls_state_ = state; SignalDtlsState(this, state); } } // namespace cricket <commit_msg>Fix ICE connection in datagram_transport.<commit_after>/* * Copyright 2018 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 "p2p/base/datagram_dtls_adaptor.h" #include <algorithm> #include <memory> #include <utility> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "api/rtc_error.h" #include "logging/rtc_event_log/events/rtc_event_dtls_transport_state.h" #include "logging/rtc_event_log/events/rtc_event_dtls_writable_state.h" #include "logging/rtc_event_log/rtc_event_log.h" #include "p2p/base/dtls_transport_internal.h" #include "p2p/base/packet_transport_internal.h" #include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/dscp.h" #include "rtc_base/flags.h" #include "rtc_base/logging.h" #include "rtc_base/message_queue.h" #include "rtc_base/rtc_certificate.h" #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/stream.h" #include "rtc_base/thread.h" #ifdef BYPASS_DATAGRAM_DTLS_TEST_ONLY // Send unencrypted packets directly to ICE, bypassing datagtram // transport. Use in tests only. constexpr bool kBypassDatagramDtlsTestOnly = true; #else constexpr bool kBypassDatagramDtlsTestOnly = false; #endif namespace cricket { DatagramDtlsAdaptor::DatagramDtlsAdaptor( std::unique_ptr<IceTransportInternal> ice_transport, std::unique_ptr<webrtc::DatagramTransportInterface> datagram_transport, const webrtc::CryptoOptions& crypto_options, webrtc::RtcEventLog* event_log) : crypto_options_(crypto_options), ice_transport_(std::move(ice_transport)), datagram_transport_(std::move(datagram_transport)), event_log_(event_log) { RTC_DCHECK(ice_transport_); RTC_DCHECK(datagram_transport_); ConnectToIceTransport(); } void DatagramDtlsAdaptor::ConnectToIceTransport() { ice_transport_->SignalWritableState.connect( this, &DatagramDtlsAdaptor::OnWritableState); ice_transport_->SignalReadyToSend.connect( this, &DatagramDtlsAdaptor::OnReadyToSend); ice_transport_->SignalReceivingState.connect( this, &DatagramDtlsAdaptor::OnReceivingState); // Datagram transport does not propagate network route change. ice_transport_->SignalNetworkRouteChanged.connect( this, &DatagramDtlsAdaptor::OnNetworkRouteChanged); if (kBypassDatagramDtlsTestOnly) { // In bypass mode we have to subscribe to ICE read and sent events. // Test only case to use ICE directly instead of data transport. ice_transport_->SignalReadPacket.connect( this, &DatagramDtlsAdaptor::OnReadPacket); ice_transport_->SignalSentPacket.connect( this, &DatagramDtlsAdaptor::OnSentPacket); } else { // Subscribe to Data Transport read packets. datagram_transport_->SetDatagramSink(this); datagram_transport_->SetTransportStateCallback(this); } } DatagramDtlsAdaptor::~DatagramDtlsAdaptor() { // Unsubscribe from Datagram Transport dinks. datagram_transport_->SetDatagramSink(nullptr); datagram_transport_->SetTransportStateCallback(nullptr); // Make sure datagram transport is destroyed before ICE. datagram_transport_.reset(); ice_transport_.reset(); } const webrtc::CryptoOptions& DatagramDtlsAdaptor::crypto_options() const { return crypto_options_; } int DatagramDtlsAdaptor::SendPacket(const char* data, size_t len, const rtc::PacketOptions& options, int flags) { // TODO(sukhanov): Handle options and flags. if (kBypassDatagramDtlsTestOnly) { // In bypass mode sent directly to ICE. return ice_transport_->SendPacket(data, len, options); } // Send datagram with id equal to options.packet_id, so we get it back // in DatagramDtlsAdaptor::OnDatagramSent() and propagate notification // up. webrtc::RTCError error = datagram_transport_->SendDatagram( rtc::MakeArrayView(reinterpret_cast<const uint8_t*>(data), len), /*datagram_id=*/options.packet_id); return (error.ok() ? len : -1); } void DatagramDtlsAdaptor::OnReadPacket(rtc::PacketTransportInternal* transport, const char* data, size_t size, const int64_t& packet_time_us, int flags) { // Only used in bypass mode. RTC_DCHECK(kBypassDatagramDtlsTestOnly); RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK_EQ(transport, ice_transport_.get()); RTC_DCHECK(flags == 0); PropagateReadPacket( rtc::MakeArrayView(reinterpret_cast<const uint8_t*>(data), size), packet_time_us); } void DatagramDtlsAdaptor::OnDatagramReceived( rtc::ArrayView<const uint8_t> data) { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(!kBypassDatagramDtlsTestOnly); // TODO(sukhanov): I am not filling out time, but on my video quality // test in WebRTC the time was not set either and higher layers of the stack // overwrite -1 with current current rtc time. Leaveing comment for now to // make sure it works as expected. int64_t packet_time_us = -1; PropagateReadPacket(data, packet_time_us); } void DatagramDtlsAdaptor::OnDatagramSent(webrtc::DatagramId datagram_id) { // When we called DatagramTransportInterface::SendDatagram, we passed // packet_id as datagram_id, so we simply need to set it in sent_packet // and propagate notification up the stack. // Also see how DatagramDtlsAdaptor::OnSentPacket handles OnSentPacket // notification from ICE in bypass mode. rtc::SentPacket sent_packet(/*packet_id=*/datagram_id, rtc::TimeMillis()); PropagateOnSentNotification(sent_packet); } void DatagramDtlsAdaptor::OnSentPacket(rtc::PacketTransportInternal* transport, const rtc::SentPacket& sent_packet) { // Only used in bypass mode. RTC_DCHECK(kBypassDatagramDtlsTestOnly); RTC_DCHECK_RUN_ON(&thread_checker_); PropagateOnSentNotification(sent_packet); } void DatagramDtlsAdaptor::PropagateOnSentNotification( const rtc::SentPacket& sent_packet) { RTC_DCHECK_RUN_ON(&thread_checker_); SignalSentPacket(this, sent_packet); } void DatagramDtlsAdaptor::PropagateReadPacket( rtc::ArrayView<const uint8_t> data, const int64_t& packet_time_us) { RTC_DCHECK_RUN_ON(&thread_checker_); SignalReadPacket(this, reinterpret_cast<const char*>(data.data()), data.size(), packet_time_us, /*flags=*/0); } int DatagramDtlsAdaptor::component() const { return kDatagramDtlsAdaptorComponent; } bool DatagramDtlsAdaptor::IsDtlsActive() const { return false; } bool DatagramDtlsAdaptor::GetDtlsRole(rtc::SSLRole* role) const { return false; } bool DatagramDtlsAdaptor::SetDtlsRole(rtc::SSLRole role) { return false; } bool DatagramDtlsAdaptor::GetSrtpCryptoSuite(int* cipher) { return false; } bool DatagramDtlsAdaptor::GetSslCipherSuite(int* cipher) { return false; } rtc::scoped_refptr<rtc::RTCCertificate> DatagramDtlsAdaptor::GetLocalCertificate() const { return nullptr; } bool DatagramDtlsAdaptor::SetLocalCertificate( const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) { return false; } std::unique_ptr<rtc::SSLCertChain> DatagramDtlsAdaptor::GetRemoteSSLCertChain() const { return nullptr; } bool DatagramDtlsAdaptor::ExportKeyingMaterial(const std::string& label, const uint8_t* context, size_t context_len, bool use_context, uint8_t* result, size_t result_len) { return false; } bool DatagramDtlsAdaptor::SetRemoteFingerprint(const std::string& digest_alg, const uint8_t* digest, size_t digest_len) { // TODO(sukhanov): We probably should not called with fingerptints in // datagram scenario, but we may need to change code up the stack before // we can return false or DCHECK. return true; } bool DatagramDtlsAdaptor::SetSslMaxProtocolVersion( rtc::SSLProtocolVersion version) { // TODO(sukhanov): We may be able to return false and/or DCHECK that we // are not called if datagram transport is used, but we need to change // integration before we can do it. return true; } IceTransportInternal* DatagramDtlsAdaptor::ice_transport() { return ice_transport_.get(); } webrtc::DatagramTransportInterface* DatagramDtlsAdaptor::datagram_transport() { return datagram_transport_.get(); } // Similar implementaton as in p2p/base/dtls_transport.cc. void DatagramDtlsAdaptor::OnReadyToSend( rtc::PacketTransportInternal* transport) { RTC_DCHECK_RUN_ON(&thread_checker_); if (writable()) { SignalReadyToSend(this); } } void DatagramDtlsAdaptor::OnWritableState( rtc::PacketTransportInternal* transport) { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(transport == ice_transport_.get()); RTC_LOG(LS_VERBOSE) << ": ice_transport writable state changed to " << ice_transport_->writable(); if (kBypassDatagramDtlsTestOnly) { // Note: SignalWritableState fired by set_writable. set_writable(ice_transport_->writable()); return; } switch (dtls_state()) { case DTLS_TRANSPORT_NEW: break; case DTLS_TRANSPORT_CONNECTED: // Note: SignalWritableState fired by set_writable. // Do we also need set_receiving(ice_transport_->receiving()) here now, in // case we lose that signal before "DTLS" connects? // DtlsTransport::OnWritableState does not set_receiving in a similar // case, so leaving it out for the time being, but it would be good to // understand why. set_writable(ice_transport_->writable()); break; case DTLS_TRANSPORT_CONNECTING: // Do nothing. break; case DTLS_TRANSPORT_FAILED: case DTLS_TRANSPORT_CLOSED: // Should not happen. Do nothing. break; } } void DatagramDtlsAdaptor::OnStateChanged(webrtc::MediaTransportState state) { // Convert MediaTransportState to DTLS state. switch (state) { case webrtc::MediaTransportState::kPending: set_dtls_state(DTLS_TRANSPORT_CONNECTING); break; case webrtc::MediaTransportState::kWritable: // Since we do not set writable state until datagram transport is // connected, we need to call set_writable first. set_writable(ice_transport_->writable()); set_dtls_state(DTLS_TRANSPORT_CONNECTED); break; case webrtc::MediaTransportState::kClosed: set_dtls_state(DTLS_TRANSPORT_CLOSED); break; } } DtlsTransportState DatagramDtlsAdaptor::dtls_state() const { return dtls_state_; } const std::string& DatagramDtlsAdaptor::transport_name() const { return ice_transport_->transport_name(); } bool DatagramDtlsAdaptor::writable() const { // NOTE that even if ice is writable, writable_ maybe false, because we // propagte writable only after DTLS is connect (this is consistent with // implementation in dtls_transport.cc). return writable_; } bool DatagramDtlsAdaptor::receiving() const { return receiving_; } int DatagramDtlsAdaptor::SetOption(rtc::Socket::Option opt, int value) { return ice_transport_->SetOption(opt, value); } int DatagramDtlsAdaptor::GetError() { return ice_transport_->GetError(); } void DatagramDtlsAdaptor::OnNetworkRouteChanged( absl::optional<rtc::NetworkRoute> network_route) { RTC_DCHECK_RUN_ON(&thread_checker_); SignalNetworkRouteChanged(network_route); } void DatagramDtlsAdaptor::OnReceivingState( rtc::PacketTransportInternal* transport) { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(transport == ice_transport_.get()); RTC_LOG(LS_VERBOSE) << "ice_transport receiving state changed to " << ice_transport_->receiving(); if (kBypassDatagramDtlsTestOnly || dtls_state() == DTLS_TRANSPORT_CONNECTED) { // Note: SignalReceivingState fired by set_receiving. set_receiving(ice_transport_->receiving()); } } void DatagramDtlsAdaptor::set_receiving(bool receiving) { if (receiving_ == receiving) { return; } receiving_ = receiving; SignalReceivingState(this); } // Similar implementaton as in p2p/base/dtls_transport.cc. void DatagramDtlsAdaptor::set_writable(bool writable) { if (writable_ == writable) { return; } if (event_log_) { event_log_->Log( absl::make_unique<webrtc::RtcEventDtlsWritableState>(writable)); } RTC_LOG(LS_VERBOSE) << "set_writable to: " << writable; writable_ = writable; if (writable_) { SignalReadyToSend(this); } SignalWritableState(this); } // Similar implementaton as in p2p/base/dtls_transport.cc. void DatagramDtlsAdaptor::set_dtls_state(DtlsTransportState state) { if (dtls_state_ == state) { return; } if (event_log_) { event_log_->Log(absl::make_unique<webrtc::RtcEventDtlsTransportState>( ConvertDtlsTransportState(state))); } RTC_LOG(LS_VERBOSE) << "set_dtls_state from:" << dtls_state_ << " to " << state; dtls_state_ = state; SignalDtlsState(this, state); } } // namespace cricket <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> 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. */ // Author: E. Gil Jones #include <moveit_visualization_ros/planning_scene_file_menu.h> #include <moveit_visualization_ros/qt_helper_functions.h> #include <QAction> #include <QFileDialog> namespace moveit_visualization_ros { PlanningSceneFileMenu::PlanningSceneFileMenu(QWidget* parent) : QMenu("Scene Files", parent) { database_dialog_ = new PlanningSceneDatabaseDialog(this); QAction* connect_to_new_database = addAction("Connect to Planning Scene Database"); save_current_scene_ = addAction("Save Current Planning Scene"); save_current_scene_->setDisabled(true); load_planning_scene_ = addAction("Load Scene From Database"); load_planning_scene_->setDisabled(true); //QAction* new_planning_scene = addAction("Create New Planning Scene..."); connect(connect_to_new_database, SIGNAL(triggered()), SLOT(connectToNewDatabaseSignalled())); connect(save_current_scene_, SIGNAL(triggered()), SLOT(saveCurrentPlanningSceneSignalled())); connect(load_planning_scene_, SIGNAL(triggered()), SLOT(loadPlanningSceneSignalled())); } void PlanningSceneFileMenu::updatePlanningSceneSignalled(planning_scene::PlanningSceneConstPtr planning_scene) { planning_scene_ = planning_scene; } void PlanningSceneFileMenu::connectToNewDatabaseSignalled() { QFileDialog dialog(this); dialog.setFileMode(QFileDialog::DirectoryOnly); dialog.setOption(QFileDialog::ShowDirsOnly, true); if(dialog.exec()) { QStringList dirnames = dialog.selectedFiles(); warehouse_connector_.connectToDatabase(dirnames[0].toStdString(), storage_); save_current_scene_->setEnabled(true); load_planning_scene_->setEnabled(true); } } void PlanningSceneFileMenu::loadPlanningSceneSignalled() { database_dialog_->populateDatabaseDialog(storage_); database_dialog_->exec(); } void PlanningSceneFileMenu::saveCurrentPlanningSceneSignalled() { moveit_msgs::PlanningScene scene; planning_scene_->getPlanningSceneMsg(scene); scene.robot_state.joint_state.header.stamp = ros::Time(ros::WallTime::now().toSec()); storage_->addPlanningScene(scene); } } <commit_msg>Updating given change in warehouse<commit_after>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> 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. */ // Author: E. Gil Jones #include <moveit_visualization_ros/planning_scene_file_menu.h> #include <moveit_visualization_ros/qt_helper_functions.h> #include <QAction> #include <QFileDialog> namespace moveit_visualization_ros { PlanningSceneFileMenu::PlanningSceneFileMenu(QWidget* parent) : QMenu("Scene Files", parent), warehouse_connector_("/opt/ros/fuerte/stacks/warehousewg/mongodb/mongo/bin/mongod") { database_dialog_ = new PlanningSceneDatabaseDialog(this); QAction* connect_to_new_database = addAction("Connect to Planning Scene Database"); save_current_scene_ = addAction("Save Current Planning Scene"); save_current_scene_->setDisabled(true); load_planning_scene_ = addAction("Load Scene From Database"); load_planning_scene_->setDisabled(true); //QAction* new_planning_scene = addAction("Create New Planning Scene..."); connect(connect_to_new_database, SIGNAL(triggered()), SLOT(connectToNewDatabaseSignalled())); connect(save_current_scene_, SIGNAL(triggered()), SLOT(saveCurrentPlanningSceneSignalled())); connect(load_planning_scene_, SIGNAL(triggered()), SLOT(loadPlanningSceneSignalled())); } void PlanningSceneFileMenu::updatePlanningSceneSignalled(planning_scene::PlanningSceneConstPtr planning_scene) { planning_scene_ = planning_scene; } void PlanningSceneFileMenu::connectToNewDatabaseSignalled() { QFileDialog dialog(this); dialog.setFileMode(QFileDialog::DirectoryOnly); dialog.setOption(QFileDialog::ShowDirsOnly, true); if(dialog.exec()) { QStringList dirnames = dialog.selectedFiles(); warehouse_connector_.connectToDatabase(dirnames[0].toStdString(), storage_); save_current_scene_->setEnabled(true); load_planning_scene_->setEnabled(true); } } void PlanningSceneFileMenu::loadPlanningSceneSignalled() { database_dialog_->populateDatabaseDialog(storage_); database_dialog_->exec(); } void PlanningSceneFileMenu::saveCurrentPlanningSceneSignalled() { moveit_msgs::PlanningScene scene; planning_scene_->getPlanningSceneMsg(scene); scene.robot_state.joint_state.header.stamp = ros::Time(ros::WallTime::now().toSec()); storage_->addPlanningScene(scene); } } <|endoftext|>
<commit_before>/** * @file neuron_layer.hpp * @author Marcus Edel * @author Shangtong Zhang * * Definition of the NeuronLayer class, which implements a standard network * layer for 1-dimensional or 2-dimensional data. */ #ifndef __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP #define __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP #include <mlpack/core.hpp> #include <mlpack/methods/ann/layer/layer_traits.hpp> #include <mlpack/methods/ann/activation_functions/logistic_function.hpp> #include <mlpack/methods/ann/activation_functions/rectifier_function.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * An implementation of a standard network layer. * * This class allows the specification of the type of the activation function. * * A few convenience typedefs are given: * * - InputLayer * - HiddenLayer * - ReluLayer * * @tparam ActivationFunction Activation function used for the embedding layer. * @tparam DataType Type of data (arma::mat or arma::colvec). */ template < class ActivationFunction = LogisticFunction, typename DataType = arma::colvec > class NeuronLayer { public: /** * Create 2-dimensional NeuronLayer object using the specified rows and columns. * In this case, DataType must be aram::mat or other matrix type. * * @param layerRows The number of rows of neurons. * @param layerCols The number of columns of neurons. */ NeuronLayer(const size_t layerRows, const size_t layerCols) : layerRows(layerRows), layerCols(layerCols), localInputAcitvations(arma::ones<DataType>(layerRows, layerCols)), inputActivations(localInputAcitvations), localDelta(arma::zeros<DataType>(layerRows, layerCols)), delta(localDelta) { // Nothing to do. } /** * Create 2-dimensional NeuronLayer object using the specified inputActivations and delta. * This allow shared memory among layers, * which make it easier to combine layers together in some special condition. * * @param inputActivations Outside storage for storing input activations. * @param delta Outside storage for storing delta, * the passed error in backward propagation. */ NeuronLayer(DataType& inputActivations, DataType& delta) : layerRows(inputActivations.n_rows), layerCols(inputActivations.n_cols), inputActivations(inputActivations), delta(delta) { // Nothing to do. } /** * Create 1-dimensional NeuronLayer object using the specified layer size. * In this case, DataType must be aram::colvec or other vector type. * * @param layerSize The number of neurons. */ NeuronLayer(const size_t layerSize) : layerRows(layerSize), layerCols(1), localInputAcitvations(arma::ones<DataType>(layerRows)), inputActivations(localInputAcitvations), localDelta(arma::zeros<DataType>(layerRows)), delta(localDelta) { // Nothing to do. } /** * Copy Constructor */ NeuronLayer(const NeuronLayer& l) : layerRows(l.layerRows), layerCols(l.layerCols), localInputAcitvations(l.localInputAcitvations), inputActivations(l.localInputAcitvations.n_elem == 0 ? l.inputActivations : localInputAcitvations), localDelta(l.localDelta), delta(l.localDelta.n_elem == 0 ? l.delta : localDelta) { // Nothing to do. } /** * Ordinary feed forward pass of a neural network, evaluating the function * f(x) by propagating the activity forward through f. * * @param inputActivation Input data used for evaluating the specified * activity function. * @param outputActivation Data to store the resulting output activation. */ void FeedForward(const DataType& inputActivation, DataType& outputActivation) { ActivationFunction::fn(inputActivation, outputActivation); } /** * Ordinary feed backward pass of a neural network, calculating the function * f(x) by propagating x backwards trough f. Using the results from the feed * forward pass. * * @param inputActivation Input data used for calculating the function f(x). * @param error The backpropagated error. * @param delta The passed error in backward propagation. */ void FeedBackward(const DataType& inputActivation, const DataType& error, DataType& delta) { DataType derivative; ActivationFunction::deriv(inputActivation, derivative); delta = error % derivative; } //! Get the input activations. DataType& InputActivation() const { return inputActivations; } //! Modify the input activations. DataType& InputActivation() { return inputActivations; } //! Get the error passed in backward propagation. DataType& Delta() const { return delta; } //! Modify the error passed in backward propagation. DataType& Delta() { return delta; } //! Get the number of layer rows. size_t LayerRows() const { return layerRows; } //! Get the number of layer colums. size_t LayerCols() const { return layerCols; } /** * Get the number of layer size. * Only for 1-dimsenional type. */ size_t InputSize() const { return layerRows; } /** * Get the number of lyaer size. * Only for 1-dimsenional type. */ size_t OutputSize() const { return layerRows; } private: //! Locally-stored number of layer rows. size_t layerRows; //! Locally-stored number of layer cols. size_t layerCols; //! Locally-stored input activation object. DataType localInputAcitvations; //! Reference to locally-stored or outside input activation object. DataType& inputActivations; //! Locally-stored delta object. DataType localDelta; //! Reference to locally-stored or outside delta object. DataType& delta; }; // class NeuronLayer // Convenience typedefs. /** * Standard Input-Layer using the logistic activation function. */ template < class ActivationFunction = LogisticFunction, typename DataType = arma::colvec > using InputLayer = NeuronLayer<ActivationFunction, DataType>; /** * Standard Hidden-Layer using the logistic activation function. */ template < class ActivationFunction = LogisticFunction, typename DataType = arma::colvec > using HiddenLayer = NeuronLayer<ActivationFunction, DataType>; /** * Layer of rectified linear units (relu) using the rectifier activation * function. */ template < class ActivationFunction = RectifierFunction, typename DataType = arma::colvec > using ReluLayer = NeuronLayer<ActivationFunction, DataType>; }; // namespace ann }; // namespace mlpack #endif <commit_msg>Refactor neuron layer class to support 3rd order tensors.<commit_after>/** * @file neuron_layer.hpp * @author Marcus Edel * @author Shangtong Zhang * * Definition of the NeuronLayer class, which implements a standard network * layer. */ #ifndef __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP #define __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP #include <mlpack/core.hpp> #include <mlpack/methods/ann/layer/layer_traits.hpp> #include <mlpack/methods/ann/activation_functions/logistic_function.hpp> #include <mlpack/methods/ann/activation_functions/rectifier_function.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * An implementation of a standard network layer. * * This class allows the specification of the type of the activation function. * * A few convenience typedefs are given: * * - InputLayer * - HiddenLayer * - ReluLayer * * @tparam ActivationFunction Activation function used for the embedding layer. * @tparam DataType Type of data (arma::colvec, arma::mat or arma::sp_mat, * arma::cube). */ template < class ActivationFunction = LogisticFunction, typename DataType = arma::colvec > class NeuronLayer { public: /** * Create the NeuronLayer object using the specified number of neurons. * * @param layerSize The number of neurons. */ NeuronLayer(const size_t layerSize) : inputActivations(arma::zeros<DataType>(layerSize)), delta(arma::zeros<DataType>(layerSize)), layerRows(layerSize), layerSlices(1) { // Nothing to do here. } NeuronLayer(const size_t layerRows, const size_t layerCols) : inputActivations(arma::zeros<DataType>(layerRows, layerCols)), delta(arma::zeros<DataType>(layerRows, layerCols)), layerRows(layerRows), layerCols(layerCols), layerSlices(1) { // Nothing to do here. } NeuronLayer(const size_t layerRows, const size_t layerCols, const size_t layerSlices) : inputActivations(arma::zeros<DataType>(layerRows, layerCols, layerSlices)), delta(arma::zeros<DataType>(layerRows, layerCols, layerSlices)), layerRows(layerRows), layerCols(layerCols), layerSlices(layerSlices) { // Nothing to do here. } /** * Ordinary feed forward pass of a neural network, evaluating the function * f(x) by propagating the activity forward through f. * * @param inputActivation Input data used for evaluating the specified * activity function. * @param outputActivation Data to store the resulting output activation. */ void FeedForward(const DataType& inputActivation, DataType& outputActivation) { ActivationFunction::fn(inputActivation, outputActivation); } /** * Ordinary feed backward pass of a neural network, calculating the function * f(x) by propagating x backwards trough f. Using the results from the feed * forward pass. * * @param inputActivation Input data used for calculating the function f(x). * @param error The backpropagated error. * @param delta The calculating delta using the partial derivative of the * error with respect to a weight. */ void FeedBackward(const DataType& inputActivation, const DataType& error, DataType& delta) { DataType derivative; ActivationFunction::deriv(inputActivation, derivative); delta = error % derivative; } /** * Ordinary feed backward pass of a neural network, calculating the function * f(x) by propagating x backwards trough f. Using the results from the feed * forward pass. * * @param inputActivation Input data used for calculating the function f(x). * @param error The backpropagated error. * @param delta The calculating delta using the partial derivative of the * error with respect to a weight. */ template<typename eT> void FeedBackward(const arma::Cube<eT>& inputActivation, const arma::Mat<eT>& error, arma::Cube<eT>& delta) { DataType derivative; ActivationFunction::deriv(inputActivation, derivative); delta = arma::cube(error.memptr(), inputActivation.n_rows, inputActivation.n_cols, inputActivation.n_slices) % derivative; } //! Get the input activations. DataType& InputActivation() const { return inputActivations; } // //! Modify the input activations. DataType& InputActivation() { return inputActivations; } //! Get the detla. DataType& Delta() const { return delta; } //! Modify the delta. DataType& Delta() { return delta; } //! Get input size. size_t InputSize() const { return layerRows; } //! Modify the delta. size_t& InputSize() { return layerRows; } //! Get output size. size_t OutputSize() const { return layerRows; } //! Modify the output size. size_t& OutputSize() { return layerRows; } //! Get the number of layer rows. size_t LayerRows() const { return layerRows; } //! Modify the number of layer rows. size_t& LayerRows() { return layerRows; } //! Get the number of layer columns. size_t LayerCols() const { return layerCols; } //! Modify the number of layer columns. size_t& LayerCols() { return layerCols; } //! Get the number of layer slices. size_t LayerSlices() const { return layerSlices; } private: //! Locally-stored input activation object. DataType inputActivations; //! Locally-stored delta object. DataType delta; //! Locally-stored number of layer rows. size_t layerRows; //! Locally-stored number of layer cols. size_t layerCols; //! Locally-stored number of layer slices. size_t layerSlices; }; // class NeuronLayer // Convenience typedefs. /** * Standard Input-Layer using the logistic activation function. */ template < class ActivationFunction = LogisticFunction, typename DataType = arma::colvec > using InputLayer = NeuronLayer<ActivationFunction, DataType>; /** * Standard Hidden-Layer using the logistic activation function. */ template < class ActivationFunction = LogisticFunction, typename DataType = arma::colvec > using HiddenLayer = NeuronLayer<ActivationFunction, DataType>; /** * Layer of rectified linear units (relu) using the rectifier activation * function. */ template < class ActivationFunction = RectifierFunction, typename DataType = arma::colvec > using ReluLayer = NeuronLayer<ActivationFunction, DataType>; }; // namespace ann }; // namespace mlpack #endif <|endoftext|>
<commit_before><commit_msg>[ADD] added a buggy select implementation (commented out for now) and a proper shutdown of the socket to avoid being stuck accept. Solution seems suboptimal but works as expected<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2011 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 "modules/video_coding/codecs/test/stats.h" #include <algorithm> // min_element, max_element #include <cassert> #include <cstdio> namespace webrtc { namespace test { Stats::Stats() {} Stats::~Stats() {} bool LessForEncodeTime(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.encode_time_in_us < s2.encode_time_in_us; } bool LessForDecodeTime(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.decode_time_in_us < s2.decode_time_in_us; } bool LessForEncodedSize(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.encoded_frame_length_in_bytes < s2.encoded_frame_length_in_bytes; } bool LessForBitRate(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.bit_rate_in_kbps < s2.bit_rate_in_kbps; } FrameStatistic& Stats::NewFrame(int frame_number) { assert(frame_number >= 0); FrameStatistic stat; stat.frame_number = frame_number; stats_.push_back(stat); return stats_[frame_number]; } void Stats::PrintSummary() { printf("Processing summary:\n"); if (stats_.size() == 0) { printf("No frame statistics have been logged yet.\n"); return; } // Calculate min, max, average and total encoding time int total_encoding_time_in_us = 0; int total_decoding_time_in_us = 0; int total_encoded_frames_lengths = 0; int total_encoded_key_frames_lengths = 0; int total_encoded_nonkey_frames_lengths = 0; int nbr_keyframes = 0; int nbr_nonkeyframes = 0; for (FrameStatisticsIterator it = stats_.begin(); it != stats_.end(); ++it) { total_encoding_time_in_us += it->encode_time_in_us; total_decoding_time_in_us += it->decode_time_in_us; total_encoded_frames_lengths += it->encoded_frame_length_in_bytes; if (it->frame_type == webrtc::kKeyFrame) { total_encoded_key_frames_lengths += it->encoded_frame_length_in_bytes; nbr_keyframes++; } else { total_encoded_nonkey_frames_lengths += it->encoded_frame_length_in_bytes; nbr_nonkeyframes++; } } FrameStatisticsIterator frame; // ENCODING printf("Encoding time:\n"); frame = min_element(stats_.begin(), stats_.end(), LessForEncodeTime); printf(" Min : %7d us (frame %d)\n", frame->encode_time_in_us, frame->frame_number); frame = max_element(stats_.begin(), stats_.end(), LessForEncodeTime); printf(" Max : %7d us (frame %d)\n", frame->encode_time_in_us, frame->frame_number); printf(" Average : %7d us\n", total_encoding_time_in_us / stats_.size()); // DECODING printf("Decoding time:\n"); // only consider frames that were successfully decoded (packet loss may cause // failures) std::vector<FrameStatistic> decoded_frames; for (std::vector<FrameStatistic>::iterator it = stats_.begin(); it != stats_.end(); ++it) { if (it->decoding_successful) { decoded_frames.push_back(*it); } } if (decoded_frames.size() == 0) { printf("No successfully decoded frames exist in this statistics.\n"); } else { frame = min_element(decoded_frames.begin(), decoded_frames.end(), LessForDecodeTime); printf(" Min : %7d us (frame %d)\n", frame->decode_time_in_us, frame->frame_number); frame = max_element(decoded_frames.begin(), decoded_frames.end(), LessForDecodeTime); printf(" Max : %7d us (frame %d)\n", frame->decode_time_in_us, frame->frame_number); printf(" Average : %7d us\n", total_decoding_time_in_us / decoded_frames.size()); printf(" Failures: %d frames failed to decode.\n", (stats_.size() - decoded_frames.size())); } // SIZE printf("Frame sizes:\n"); frame = min_element(stats_.begin(), stats_.end(), LessForEncodedSize); printf(" Min : %7d bytes (frame %d)\n", frame->encoded_frame_length_in_bytes, frame->frame_number); frame = max_element(stats_.begin(), stats_.end(), LessForEncodedSize); printf(" Max : %7d bytes (frame %d)\n", frame->encoded_frame_length_in_bytes, frame->frame_number); printf(" Average : %7d bytes\n", total_encoded_frames_lengths / stats_.size()); if (nbr_keyframes > 0) { printf(" Average key frame size : %7d bytes (%d keyframes)\n", total_encoded_key_frames_lengths / nbr_keyframes, nbr_keyframes); } if (nbr_nonkeyframes > 0) { printf(" Average non-key frame size: %7d bytes (%d frames)\n", total_encoded_nonkey_frames_lengths / nbr_nonkeyframes, nbr_nonkeyframes); } // BIT RATE printf("Bit rates:\n"); frame = min_element(stats_.begin(), stats_.end(), LessForBitRate); printf(" Min bit rate: %7d kbps (frame %d)\n", frame->bit_rate_in_kbps, frame->frame_number); frame = max_element(stats_.begin(), stats_.end(), LessForBitRate); printf(" Max bit rate: %7d kbps (frame %d)\n", frame->bit_rate_in_kbps, frame->frame_number); printf("\n"); printf("Total encoding time : %7d ms.\n", total_encoding_time_in_us / 1000); printf("Total decoding time : %7d ms.\n", total_decoding_time_in_us / 1000); printf("Total processing time: %7d ms.\n", (total_encoding_time_in_us + total_decoding_time_in_us) / 1000); } } // namespace test } // namespace webrtc <commit_msg>Fixing compilation error on Linux 64-bit<commit_after>/* * Copyright (c) 2011 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 "modules/video_coding/codecs/test/stats.h" #include <algorithm> // min_element, max_element #include <cassert> #include <cstdio> namespace webrtc { namespace test { Stats::Stats() {} Stats::~Stats() {} bool LessForEncodeTime(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.encode_time_in_us < s2.encode_time_in_us; } bool LessForDecodeTime(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.decode_time_in_us < s2.decode_time_in_us; } bool LessForEncodedSize(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.encoded_frame_length_in_bytes < s2.encoded_frame_length_in_bytes; } bool LessForBitRate(const FrameStatistic& s1, const FrameStatistic& s2) { return s1.bit_rate_in_kbps < s2.bit_rate_in_kbps; } FrameStatistic& Stats::NewFrame(int frame_number) { assert(frame_number >= 0); FrameStatistic stat; stat.frame_number = frame_number; stats_.push_back(stat); return stats_[frame_number]; } void Stats::PrintSummary() { printf("Processing summary:\n"); if (stats_.size() == 0) { printf("No frame statistics have been logged yet.\n"); return; } // Calculate min, max, average and total encoding time int total_encoding_time_in_us = 0; int total_decoding_time_in_us = 0; int total_encoded_frames_lengths = 0; int total_encoded_key_frames_lengths = 0; int total_encoded_nonkey_frames_lengths = 0; int nbr_keyframes = 0; int nbr_nonkeyframes = 0; for (FrameStatisticsIterator it = stats_.begin(); it != stats_.end(); ++it) { total_encoding_time_in_us += it->encode_time_in_us; total_decoding_time_in_us += it->decode_time_in_us; total_encoded_frames_lengths += it->encoded_frame_length_in_bytes; if (it->frame_type == webrtc::kKeyFrame) { total_encoded_key_frames_lengths += it->encoded_frame_length_in_bytes; nbr_keyframes++; } else { total_encoded_nonkey_frames_lengths += it->encoded_frame_length_in_bytes; nbr_nonkeyframes++; } } FrameStatisticsIterator frame; // ENCODING printf("Encoding time:\n"); frame = min_element(stats_.begin(), stats_.end(), LessForEncodeTime); printf(" Min : %7d us (frame %d)\n", frame->encode_time_in_us, frame->frame_number); frame = max_element(stats_.begin(), stats_.end(), LessForEncodeTime); printf(" Max : %7d us (frame %d)\n", frame->encode_time_in_us, frame->frame_number); printf(" Average : %7d us\n", static_cast<int>(total_encoding_time_in_us / stats_.size())); // DECODING printf("Decoding time:\n"); // only consider frames that were successfully decoded (packet loss may cause // failures) std::vector<FrameStatistic> decoded_frames; for (std::vector<FrameStatistic>::iterator it = stats_.begin(); it != stats_.end(); ++it) { if (it->decoding_successful) { decoded_frames.push_back(*it); } } if (decoded_frames.size() == 0) { printf("No successfully decoded frames exist in this statistics.\n"); } else { frame = min_element(decoded_frames.begin(), decoded_frames.end(), LessForDecodeTime); printf(" Min : %7d us (frame %d)\n", frame->decode_time_in_us, frame->frame_number); frame = max_element(decoded_frames.begin(), decoded_frames.end(), LessForDecodeTime); printf(" Max : %7d us (frame %d)\n", frame->decode_time_in_us, frame->frame_number); printf(" Average : %7d us\n", static_cast<int>(total_decoding_time_in_us / decoded_frames.size())); printf(" Failures: %d frames failed to decode.\n", static_cast<int>(stats_.size() - decoded_frames.size())); } // SIZE printf("Frame sizes:\n"); frame = min_element(stats_.begin(), stats_.end(), LessForEncodedSize); printf(" Min : %7d bytes (frame %d)\n", frame->encoded_frame_length_in_bytes, frame->frame_number); frame = max_element(stats_.begin(), stats_.end(), LessForEncodedSize); printf(" Max : %7d bytes (frame %d)\n", frame->encoded_frame_length_in_bytes, frame->frame_number); printf(" Average : %7d bytes\n", static_cast<int>(total_encoded_frames_lengths / stats_.size())); if (nbr_keyframes > 0) { printf(" Average key frame size : %7d bytes (%d keyframes)\n", total_encoded_key_frames_lengths / nbr_keyframes, nbr_keyframes); } if (nbr_nonkeyframes > 0) { printf(" Average non-key frame size: %7d bytes (%d frames)\n", total_encoded_nonkey_frames_lengths / nbr_nonkeyframes, nbr_nonkeyframes); } // BIT RATE printf("Bit rates:\n"); frame = min_element(stats_.begin(), stats_.end(), LessForBitRate); printf(" Min bit rate: %7d kbps (frame %d)\n", frame->bit_rate_in_kbps, frame->frame_number); frame = max_element(stats_.begin(), stats_.end(), LessForBitRate); printf(" Max bit rate: %7d kbps (frame %d)\n", frame->bit_rate_in_kbps, frame->frame_number); printf("\n"); printf("Total encoding time : %7d ms.\n", total_encoding_time_in_us / 1000); printf("Total decoding time : %7d ms.\n", total_decoding_time_in_us / 1000); printf("Total processing time: %7d ms.\n", (total_encoding_time_in_us + total_decoding_time_in_us) / 1000); } } // namespace test } // namespace webrtc <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetParameterGroup.h" #include "otbWrapperQtWidgetChoiceParameter.h" #include "otbWrapperQtWidgetParameterLabel.h" #include "otbWrapperQtWidgetParameterFactory.h" namespace otb { namespace Wrapper { QtWidgetParameterGroup::QtWidgetParameterGroup(ParameterGroup::Pointer paramList, QtWidgetModel* m) : QtWidgetParameterBase(paramList, m), m_ParamList(paramList) { } QtWidgetParameterGroup::~QtWidgetParameterGroup() { } void QtWidgetParameterGroup::DoUpdateGUI() { WidgetListIteratorType it = m_WidgetList.begin(); for (it = m_WidgetList.begin(); it != m_WidgetList.end(); ++it) { (*it)->UpdateGUI(); } } void QtWidgetParameterGroup::DoCreateWidget() { // a GridLayout with two columns : parameter label / parameter widget QGridLayout *gridLayout = new QGridLayout; gridLayout->setSpacing(1); gridLayout->setContentsMargins(0, 0, 0, 0); unsigned int nbParams = m_ParamList->GetNumberOfParameters(); for (unsigned int i = 0; i < nbParams; ++i) { Parameter* param = m_ParamList->GetParameterByIndex(i); if (param != 0) { ParameterGroup* paramAsGroup = dynamic_cast<ParameterGroup*>(param); ChoiceParameter* paramAsChoice = dynamic_cast<ChoiceParameter*>(param); if (paramAsGroup == 0 && paramAsChoice == 0) { // Label (col 0) QWidget* label = new QtWidgetParameterLabel( param ); gridLayout->addWidget(label, i, 1); // Parameter Widget (col 2) QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() ); gridLayout->addWidget(specificWidget, i, 2 ); // CheckBox (col 1) QCheckBox * checkBox = new QCheckBox; connect( checkBox, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool))); connect( checkBox, SIGNAL(clicked(bool)), GetModel(), SLOT(NotifyUpdate()) ); connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), checkBox, SLOT(setChecked(bool))); connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), specificWidget, SLOT(SetActivationState(bool))); if (param->IsRoot()) { // if Mandatory make the checkbox checked and deactivated if (param->GetMandatory()) { checkBox->setCheckState(Qt::Checked); checkBox->setEnabled(false); specificWidget->setEnabled(true); } else { checkBox->setCheckState(Qt::Unchecked); checkBox->setEnabled(true); specificWidget->setEnabled(false); } } else { // If this widget belongs to a Group, make it disabled by // defaut specificWidget->setEnabled(false); } gridLayout->addWidget(checkBox, i, 0); m_WidgetList.push_back(specificWidget); } else { QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() ); QVBoxLayout* vboxLayout = new QVBoxLayout; vboxLayout->addWidget(specificWidget); QGroupBox* group = new QGroupBox; group->setLayout(vboxLayout); // Make the paramter Group checkable when it is not mandatory if (!param->GetMandatory() ) { group->setCheckable(true); } connect(group, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool))); group->setTitle(param->GetName()); gridLayout->addWidget(group, i, 0, 1, -1); m_WidgetList.push_back(specificWidget); } } } this->setLayout(gridLayout); } // Slot connected to the signal emitted the checkBox relative to // current widget void QtWidgetParameterGroup::SetActivationState( bool value ) { // First call the superclass implementation this->QtWidgetParameterBase::SetActivationState(value); // Update the Group status this->setEnabled(value); // Update iteratively the children status for (unsigned int idx = 0; idx < m_ParamList->GetChildrenList().size(); ++idx) { this->ProcessChild(m_ParamList->GetChildrenList()[idx], value); } } // Activate iteratively the children void QtWidgetParameterGroup::ProcessChild(Parameter* currentNode, bool status) { // Activate the current node if it was checked if ( currentNode->IsChecked() && status) { currentNode->SetActive(status); } // If the status is false (deactivating) deactivate all the children // tree if (!status) { currentNode->SetActive(status); } unsigned int counter = 0; while(counter < currentNode->GetChildrenList().size()) { this->ProcessChild(currentNode->GetChildrenList()[counter], status); ++counter; } } } } <commit_msg>ENH: Better handling of a Group and its parameter Mandatory Group : no checkbox, all the mandatory params are activated Non Mandatory Group : checkbox (non checked by default), all the params are deactivated<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetParameterGroup.h" #include "otbWrapperQtWidgetChoiceParameter.h" #include "otbWrapperQtWidgetParameterLabel.h" #include "otbWrapperQtWidgetParameterFactory.h" namespace otb { namespace Wrapper { QtWidgetParameterGroup::QtWidgetParameterGroup(ParameterGroup::Pointer paramList, QtWidgetModel* m) : QtWidgetParameterBase(paramList, m), m_ParamList(paramList) { } QtWidgetParameterGroup::~QtWidgetParameterGroup() { } void QtWidgetParameterGroup::DoUpdateGUI() { WidgetListIteratorType it = m_WidgetList.begin(); for (it = m_WidgetList.begin(); it != m_WidgetList.end(); ++it) { (*it)->UpdateGUI(); } } void QtWidgetParameterGroup::DoCreateWidget() { // a GridLayout with two columns : parameter label / parameter widget QGridLayout *gridLayout = new QGridLayout; gridLayout->setSpacing(1); gridLayout->setContentsMargins(0, 0, 0, 0); unsigned int nbParams = m_ParamList->GetNumberOfParameters(); for (unsigned int i = 0; i < nbParams; ++i) { Parameter* param = m_ParamList->GetParameterByIndex(i); if (param != 0) { ParameterGroup* paramAsGroup = dynamic_cast<ParameterGroup*>(param); ChoiceParameter* paramAsChoice = dynamic_cast<ChoiceParameter*>(param); if (paramAsGroup == 0 && paramAsChoice == 0) { // Label (col 0) QWidget* label = new QtWidgetParameterLabel( param ); gridLayout->addWidget(label, i, 1); // Parameter Widget (col 2) QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() ); gridLayout->addWidget(specificWidget, i, 2 ); // CheckBox (col 1) QCheckBox * checkBox = new QCheckBox; connect( checkBox, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool))); connect( checkBox, SIGNAL(clicked(bool)), GetModel(), SLOT(NotifyUpdate()) ); connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), checkBox, SLOT(setChecked(bool))); connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), specificWidget, SLOT(SetActivationState(bool))); // if Mandatory make the checkbox checked and deactivated if (param->GetMandatory()) { checkBox->setCheckState(Qt::Checked); checkBox->setEnabled(false); specificWidget->setEnabled(true); } else { checkBox->setCheckState(Qt::Unchecked); checkBox->setEnabled(true); specificWidget->setEnabled(false); } gridLayout->addWidget(checkBox, i, 0); m_WidgetList.push_back(specificWidget); } else { QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() ); QVBoxLayout* vboxLayout = new QVBoxLayout; vboxLayout->addWidget(specificWidget); QGroupBox* group = new QGroupBox; group->setLayout(vboxLayout); // Make the paramter Group checkable when it is not mandatory if (!param->GetMandatory() ) { group->setCheckable(true); group->setChecked(false); // Update iteratively the children status for (unsigned int idx = 0; idx < param->GetChildrenList().size(); ++idx) { // deactivate the children tree this->ProcessChild(param->GetChildrenList()[idx], false); } } else { param->SetActive(true); } connect(group, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool))); group->setTitle(param->GetName()); gridLayout->addWidget(group, i, 0, 1, -1); m_WidgetList.push_back(specificWidget); } } } this->setLayout(gridLayout); } // Slot connected to the signal emitted the checkBox relative to // current widget void QtWidgetParameterGroup::SetActivationState( bool value ) { // First call the superclass implementation this->QtWidgetParameterBase::SetActivationState(value); // Update the Group status this->setEnabled(value); // Update iteratively the children status for (unsigned int idx = 0; idx < m_ParamList->GetChildrenList().size(); ++idx) { this->ProcessChild(m_ParamList->GetChildrenList()[idx], value); } } // Activate iteratively the children void QtWidgetParameterGroup::ProcessChild(Parameter* currentNode, bool status) { // Activate the current node if it was checked if ( currentNode->IsChecked() && status) { currentNode->SetActive(status); } // If the status is false (deactivating) deactivate all the children // tree if (!status) { currentNode->SetActive(status); } unsigned int counter = 0; while(counter < currentNode->GetChildrenList().size()) { this->ProcessChild(currentNode->GetChildrenList()[counter], status); ++counter; } } } } <|endoftext|>
<commit_before>// 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/net/pref_proxy_config_service.h" #include "base/command_line.h" #include "base/file_path.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/prefs/pref_service_mock_builder.h" #include "chrome/browser/prefs/proxy_config_dictionary.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_pref_service.h" #include "net/proxy/proxy_config_service_common_unittest.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::Mock; namespace { const char kFixedPacUrl[] = "http://chromium.org/fixed_pac_url"; // Testing proxy config service that allows us to fire notifications at will. class TestProxyConfigService : public net::ProxyConfigService { public: TestProxyConfigService(const net::ProxyConfig& config, ConfigAvailability availability) : config_(config), availability_(availability) {} void SetProxyConfig(const net::ProxyConfig config, ConfigAvailability availability) { config_ = config; availability_ = availability; FOR_EACH_OBSERVER(net::ProxyConfigService::Observer, observers_, OnProxyConfigChanged(config, availability)); } private: virtual void AddObserver(net::ProxyConfigService::Observer* observer) { observers_.AddObserver(observer); } virtual void RemoveObserver(net::ProxyConfigService::Observer* observer) { observers_.RemoveObserver(observer); } virtual net::ProxyConfigService::ConfigAvailability GetLatestProxyConfig( net::ProxyConfig* config) { *config = config_; return availability_; } net::ProxyConfig config_; ConfigAvailability availability_; ObserverList<net::ProxyConfigService::Observer, true> observers_; }; // A mock observer for capturing callbacks. class MockObserver : public net::ProxyConfigService::Observer { public: MOCK_METHOD2(OnProxyConfigChanged, void(const net::ProxyConfig&, net::ProxyConfigService::ConfigAvailability)); }; template<typename TESTBASE> class PrefProxyConfigServiceTestBase : public TESTBASE { protected: PrefProxyConfigServiceTestBase() : ui_thread_(BrowserThread::UI, &loop_), io_thread_(BrowserThread::IO, &loop_) {} virtual void Init(PrefService* pref_service) { ASSERT_TRUE(pref_service); PrefProxyConfigService::RegisterPrefs(pref_service); fixed_config_.set_pac_url(GURL(kFixedPacUrl)); delegate_service_ = new TestProxyConfigService(fixed_config_, net::ProxyConfigService::CONFIG_VALID); proxy_config_tracker_ = new PrefProxyConfigTracker(pref_service); proxy_config_service_.reset( new PrefProxyConfigService(proxy_config_tracker_.get(), delegate_service_)); } virtual void TearDown() { proxy_config_tracker_->DetachFromPrefService(); loop_.RunAllPending(); proxy_config_service_.reset(); } MessageLoop loop_; TestProxyConfigService* delegate_service_; // weak scoped_ptr<PrefProxyConfigService> proxy_config_service_; net::ProxyConfig fixed_config_; private: scoped_refptr<PrefProxyConfigTracker> proxy_config_tracker_; BrowserThread ui_thread_; BrowserThread io_thread_; }; class PrefProxyConfigServiceTest : public PrefProxyConfigServiceTestBase<testing::Test> { protected: virtual void SetUp() { pref_service_.reset(new TestingPrefService()); Init(pref_service_.get()); } scoped_ptr<TestingPrefService> pref_service_; }; TEST_F(PrefProxyConfigServiceTest, BaseConfiguration) { net::ProxyConfig actual_config; EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_EQ(GURL(kFixedPacUrl), actual_config.pac_url()); } TEST_F(PrefProxyConfigServiceTest, DynamicPrefOverrides) { pref_service_->SetManagedPref( prefs::kProxy, ProxyConfigDictionary::CreateFixedServers("http://example.com:3128", "")); loop_.RunAllPending(); net::ProxyConfig actual_config; EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_FALSE(actual_config.auto_detect()); EXPECT_EQ(net::ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY, actual_config.proxy_rules().type); EXPECT_EQ(actual_config.proxy_rules().single_proxy, net::ProxyServer::FromURI("http://example.com:3128", net::ProxyServer::SCHEME_HTTP)); pref_service_->SetManagedPref(prefs::kProxy, ProxyConfigDictionary::CreateAutoDetect()); loop_.RunAllPending(); EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_TRUE(actual_config.auto_detect()); } // Compares proxy configurations, but allows different identifiers. MATCHER_P(ProxyConfigMatches, config, "") { net::ProxyConfig reference(config); reference.set_id(arg.id()); return reference.Equals(arg); } TEST_F(PrefProxyConfigServiceTest, Observers) { const net::ProxyConfigService::ConfigAvailability CONFIG_VALID = net::ProxyConfigService::CONFIG_VALID; MockObserver observer; proxy_config_service_->AddObserver(&observer); // Firing the observers in the delegate should trigger a notification. net::ProxyConfig config2; config2.set_auto_detect(true); EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config2), CONFIG_VALID)).Times(1); delegate_service_->SetProxyConfig(config2, CONFIG_VALID); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Override configuration, this should trigger a notification. net::ProxyConfig pref_config; pref_config.set_pac_url(GURL(kFixedPacUrl)); EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(pref_config), CONFIG_VALID)).Times(1); pref_service_->SetManagedPref( prefs::kProxy, ProxyConfigDictionary::CreatePacScript(kFixedPacUrl)); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Since there are pref overrides, delegate changes should be ignored. net::ProxyConfig config3; config3.proxy_rules().ParseFromString("http=config3:80"); EXPECT_CALL(observer, OnProxyConfigChanged(_, _)).Times(0); fixed_config_.set_auto_detect(true); delegate_service_->SetProxyConfig(config3, CONFIG_VALID); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Clear the override should switch back to the fixed configuration. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config3), CONFIG_VALID)).Times(1); pref_service_->RemoveManagedPref(prefs::kProxy); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Delegate service notifications should show up again. net::ProxyConfig config4; config4.proxy_rules().ParseFromString("socks:config4"); EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config4), CONFIG_VALID)).Times(1); delegate_service_->SetProxyConfig(config4, CONFIG_VALID); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); proxy_config_service_->RemoveObserver(&observer); } TEST_F(PrefProxyConfigServiceTest, Fallback) { const net::ProxyConfigService::ConfigAvailability CONFIG_VALID = net::ProxyConfigService::CONFIG_VALID; MockObserver observer; net::ProxyConfig actual_config; delegate_service_->SetProxyConfig(net::ProxyConfig::CreateDirect(), net::ProxyConfigService::CONFIG_UNSET); proxy_config_service_->AddObserver(&observer); // Prepare test data. net::ProxyConfig recommended_config = net::ProxyConfig::CreateAutoDetect(); net::ProxyConfig user_config = net::ProxyConfig::CreateFromCustomPacURL(GURL(kFixedPacUrl)); // Set a recommended pref. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(recommended_config), CONFIG_VALID)).Times(1); pref_service_->SetRecommendedPref( prefs::kProxy, ProxyConfigDictionary::CreateAutoDetect()); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_EQ(CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_THAT(actual_config, ProxyConfigMatches(recommended_config)); // Override in user prefs. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(user_config), CONFIG_VALID)).Times(1); pref_service_->SetManagedPref( prefs::kProxy, ProxyConfigDictionary::CreatePacScript(kFixedPacUrl)); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_EQ(CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_THAT(actual_config, ProxyConfigMatches(user_config)); // Go back to recommended pref. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(recommended_config), CONFIG_VALID)).Times(1); pref_service_->RemoveManagedPref(prefs::kProxy); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_EQ(CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_THAT(actual_config, ProxyConfigMatches(recommended_config)); proxy_config_service_->RemoveObserver(&observer); } // Test parameter object for testing command line proxy configuration. struct CommandLineTestParams { // Explicit assignment operator, so testing::TestWithParam works with MSVC. CommandLineTestParams& operator=(const CommandLineTestParams& other) { description = other.description; for (unsigned int i = 0; i < arraysize(switches); i++) switches[i] = other.switches[i]; is_null = other.is_null; auto_detect = other.auto_detect; pac_url = other.pac_url; proxy_rules = other.proxy_rules; return *this; } // Short description to identify the test. const char* description; // The command line to build a ProxyConfig from. struct SwitchValue { const char* name; const char* value; } switches[2]; // Expected outputs (fields of the ProxyConfig). bool is_null; bool auto_detect; GURL pac_url; net::ProxyRulesExpectation proxy_rules; }; void PrintTo(const CommandLineTestParams& params, std::ostream* os) { *os << params.description; } class PrefProxyConfigServiceCommandLineTest : public PrefProxyConfigServiceTestBase< testing::TestWithParam<CommandLineTestParams> > { protected: PrefProxyConfigServiceCommandLineTest() : command_line_(CommandLine::NO_PROGRAM) {} virtual void SetUp() { for (size_t i = 0; i < arraysize(GetParam().switches); i++) { const char* name = GetParam().switches[i].name; const char* value = GetParam().switches[i].value; if (name && value) command_line_.AppendSwitchASCII(name, value); else if (name) command_line_.AppendSwitch(name); } pref_service_.reset( PrefServiceMockBuilder().WithCommandLine(&command_line_).Create()); Init(pref_service_.get()); } private: CommandLine command_line_; scoped_ptr<PrefService> pref_service_; }; TEST_P(PrefProxyConfigServiceCommandLineTest, CommandLine) { net::ProxyConfig config; EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&config)); if (GetParam().is_null) { EXPECT_EQ(GURL(kFixedPacUrl), config.pac_url()); } else { EXPECT_NE(GURL(kFixedPacUrl), config.pac_url()); EXPECT_EQ(GetParam().auto_detect, config.auto_detect()); EXPECT_EQ(GetParam().pac_url, config.pac_url()); EXPECT_TRUE(GetParam().proxy_rules.Matches(config.proxy_rules())); } } static const CommandLineTestParams kCommandLineTestParams[] = { { "Empty command line", // Input { }, // Expected result true, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, { "No proxy", // Input { { switches::kNoProxyServer, NULL }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, { "No proxy with extra parameters.", // Input { { switches::kNoProxyServer, NULL }, { switches::kProxyServer, "http://proxy:8888" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, { "Single proxy.", // Input { { switches::kProxyServer, "http://proxy:8888" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Single( "proxy:8888", // single proxy ""), // bypass rules }, { "Per scheme proxy.", // Input { { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::PerScheme( "httpproxy:8888", // http "", // https "ftpproxy:8889", // ftp ""), // bypass rules }, { "Per scheme proxy with bypass URLs.", // Input { { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" }, { switches::kProxyBypassList, ".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::PerScheme( "httpproxy:8888", // http "", // https "ftpproxy:8889", // ftp "*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"), }, { "Pac URL", // Input { { switches::kProxyPacUrl, "http://wpad/wpad.dat" }, }, // Expected result false, // is_null false, // auto_detect GURL("http://wpad/wpad.dat"), // pac_url net::ProxyRulesExpectation::Empty(), }, { "Autodetect", // Input { { switches::kProxyAutoDetect, NULL }, }, // Expected result false, // is_null true, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, }; INSTANTIATE_TEST_CASE_P( PrefProxyConfigServiceCommandLineTestInstance, PrefProxyConfigServiceCommandLineTest, testing::ValuesIn(kCommandLineTestParams)); } // namespace <commit_msg>Replace gmock's EXPECT_THAT by an explicit check when comparing proxy config in PrefProxyConfigServiceTest.Fallback. This should avoid having gtest print the objects, which results in uninitialized memory accesses.<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/net/pref_proxy_config_service.h" #include "base/command_line.h" #include "base/file_path.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/prefs/pref_service_mock_builder.h" #include "chrome/browser/prefs/proxy_config_dictionary.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_pref_service.h" #include "net/proxy/proxy_config_service_common_unittest.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::Mock; namespace { const char kFixedPacUrl[] = "http://chromium.org/fixed_pac_url"; // Testing proxy config service that allows us to fire notifications at will. class TestProxyConfigService : public net::ProxyConfigService { public: TestProxyConfigService(const net::ProxyConfig& config, ConfigAvailability availability) : config_(config), availability_(availability) {} void SetProxyConfig(const net::ProxyConfig config, ConfigAvailability availability) { config_ = config; availability_ = availability; FOR_EACH_OBSERVER(net::ProxyConfigService::Observer, observers_, OnProxyConfigChanged(config, availability)); } private: virtual void AddObserver(net::ProxyConfigService::Observer* observer) { observers_.AddObserver(observer); } virtual void RemoveObserver(net::ProxyConfigService::Observer* observer) { observers_.RemoveObserver(observer); } virtual net::ProxyConfigService::ConfigAvailability GetLatestProxyConfig( net::ProxyConfig* config) { *config = config_; return availability_; } net::ProxyConfig config_; ConfigAvailability availability_; ObserverList<net::ProxyConfigService::Observer, true> observers_; }; // A mock observer for capturing callbacks. class MockObserver : public net::ProxyConfigService::Observer { public: MOCK_METHOD2(OnProxyConfigChanged, void(const net::ProxyConfig&, net::ProxyConfigService::ConfigAvailability)); }; template<typename TESTBASE> class PrefProxyConfigServiceTestBase : public TESTBASE { protected: PrefProxyConfigServiceTestBase() : ui_thread_(BrowserThread::UI, &loop_), io_thread_(BrowserThread::IO, &loop_) {} virtual void Init(PrefService* pref_service) { ASSERT_TRUE(pref_service); PrefProxyConfigService::RegisterPrefs(pref_service); fixed_config_.set_pac_url(GURL(kFixedPacUrl)); delegate_service_ = new TestProxyConfigService(fixed_config_, net::ProxyConfigService::CONFIG_VALID); proxy_config_tracker_ = new PrefProxyConfigTracker(pref_service); proxy_config_service_.reset( new PrefProxyConfigService(proxy_config_tracker_.get(), delegate_service_)); } virtual void TearDown() { proxy_config_tracker_->DetachFromPrefService(); loop_.RunAllPending(); proxy_config_service_.reset(); } MessageLoop loop_; TestProxyConfigService* delegate_service_; // weak scoped_ptr<PrefProxyConfigService> proxy_config_service_; net::ProxyConfig fixed_config_; private: scoped_refptr<PrefProxyConfigTracker> proxy_config_tracker_; BrowserThread ui_thread_; BrowserThread io_thread_; }; class PrefProxyConfigServiceTest : public PrefProxyConfigServiceTestBase<testing::Test> { protected: virtual void SetUp() { pref_service_.reset(new TestingPrefService()); Init(pref_service_.get()); } scoped_ptr<TestingPrefService> pref_service_; }; TEST_F(PrefProxyConfigServiceTest, BaseConfiguration) { net::ProxyConfig actual_config; EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_EQ(GURL(kFixedPacUrl), actual_config.pac_url()); } TEST_F(PrefProxyConfigServiceTest, DynamicPrefOverrides) { pref_service_->SetManagedPref( prefs::kProxy, ProxyConfigDictionary::CreateFixedServers("http://example.com:3128", "")); loop_.RunAllPending(); net::ProxyConfig actual_config; EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_FALSE(actual_config.auto_detect()); EXPECT_EQ(net::ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY, actual_config.proxy_rules().type); EXPECT_EQ(actual_config.proxy_rules().single_proxy, net::ProxyServer::FromURI("http://example.com:3128", net::ProxyServer::SCHEME_HTTP)); pref_service_->SetManagedPref(prefs::kProxy, ProxyConfigDictionary::CreateAutoDetect()); loop_.RunAllPending(); EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_TRUE(actual_config.auto_detect()); } // Compares proxy configurations, but allows different identifiers. MATCHER_P(ProxyConfigMatches, config, "") { net::ProxyConfig reference(config); reference.set_id(arg.id()); return reference.Equals(arg); } TEST_F(PrefProxyConfigServiceTest, Observers) { const net::ProxyConfigService::ConfigAvailability CONFIG_VALID = net::ProxyConfigService::CONFIG_VALID; MockObserver observer; proxy_config_service_->AddObserver(&observer); // Firing the observers in the delegate should trigger a notification. net::ProxyConfig config2; config2.set_auto_detect(true); EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config2), CONFIG_VALID)).Times(1); delegate_service_->SetProxyConfig(config2, CONFIG_VALID); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Override configuration, this should trigger a notification. net::ProxyConfig pref_config; pref_config.set_pac_url(GURL(kFixedPacUrl)); EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(pref_config), CONFIG_VALID)).Times(1); pref_service_->SetManagedPref( prefs::kProxy, ProxyConfigDictionary::CreatePacScript(kFixedPacUrl)); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Since there are pref overrides, delegate changes should be ignored. net::ProxyConfig config3; config3.proxy_rules().ParseFromString("http=config3:80"); EXPECT_CALL(observer, OnProxyConfigChanged(_, _)).Times(0); fixed_config_.set_auto_detect(true); delegate_service_->SetProxyConfig(config3, CONFIG_VALID); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Clear the override should switch back to the fixed configuration. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config3), CONFIG_VALID)).Times(1); pref_service_->RemoveManagedPref(prefs::kProxy); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); // Delegate service notifications should show up again. net::ProxyConfig config4; config4.proxy_rules().ParseFromString("socks:config4"); EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config4), CONFIG_VALID)).Times(1); delegate_service_->SetProxyConfig(config4, CONFIG_VALID); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); proxy_config_service_->RemoveObserver(&observer); } TEST_F(PrefProxyConfigServiceTest, Fallback) { const net::ProxyConfigService::ConfigAvailability CONFIG_VALID = net::ProxyConfigService::CONFIG_VALID; MockObserver observer; net::ProxyConfig actual_config; delegate_service_->SetProxyConfig(net::ProxyConfig::CreateDirect(), net::ProxyConfigService::CONFIG_UNSET); proxy_config_service_->AddObserver(&observer); // Prepare test data. net::ProxyConfig recommended_config = net::ProxyConfig::CreateAutoDetect(); net::ProxyConfig user_config = net::ProxyConfig::CreateFromCustomPacURL(GURL(kFixedPacUrl)); // Set a recommended pref. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(recommended_config), CONFIG_VALID)).Times(1); pref_service_->SetRecommendedPref( prefs::kProxy, ProxyConfigDictionary::CreateAutoDetect()); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_EQ(CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_TRUE(actual_config.Equals(recommended_config)); // Override in user prefs. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(user_config), CONFIG_VALID)).Times(1); pref_service_->SetManagedPref( prefs::kProxy, ProxyConfigDictionary::CreatePacScript(kFixedPacUrl)); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_EQ(CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_TRUE(actual_config.Equals(user_config)); // Go back to recommended pref. EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(recommended_config), CONFIG_VALID)).Times(1); pref_service_->RemoveManagedPref(prefs::kProxy); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_EQ(CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&actual_config)); EXPECT_TRUE(actual_config.Equals(recommended_config)); proxy_config_service_->RemoveObserver(&observer); } // Test parameter object for testing command line proxy configuration. struct CommandLineTestParams { // Explicit assignment operator, so testing::TestWithParam works with MSVC. CommandLineTestParams& operator=(const CommandLineTestParams& other) { description = other.description; for (unsigned int i = 0; i < arraysize(switches); i++) switches[i] = other.switches[i]; is_null = other.is_null; auto_detect = other.auto_detect; pac_url = other.pac_url; proxy_rules = other.proxy_rules; return *this; } // Short description to identify the test. const char* description; // The command line to build a ProxyConfig from. struct SwitchValue { const char* name; const char* value; } switches[2]; // Expected outputs (fields of the ProxyConfig). bool is_null; bool auto_detect; GURL pac_url; net::ProxyRulesExpectation proxy_rules; }; void PrintTo(const CommandLineTestParams& params, std::ostream* os) { *os << params.description; } class PrefProxyConfigServiceCommandLineTest : public PrefProxyConfigServiceTestBase< testing::TestWithParam<CommandLineTestParams> > { protected: PrefProxyConfigServiceCommandLineTest() : command_line_(CommandLine::NO_PROGRAM) {} virtual void SetUp() { for (size_t i = 0; i < arraysize(GetParam().switches); i++) { const char* name = GetParam().switches[i].name; const char* value = GetParam().switches[i].value; if (name && value) command_line_.AppendSwitchASCII(name, value); else if (name) command_line_.AppendSwitch(name); } pref_service_.reset( PrefServiceMockBuilder().WithCommandLine(&command_line_).Create()); Init(pref_service_.get()); } private: CommandLine command_line_; scoped_ptr<PrefService> pref_service_; }; TEST_P(PrefProxyConfigServiceCommandLineTest, CommandLine) { net::ProxyConfig config; EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, proxy_config_service_->GetLatestProxyConfig(&config)); if (GetParam().is_null) { EXPECT_EQ(GURL(kFixedPacUrl), config.pac_url()); } else { EXPECT_NE(GURL(kFixedPacUrl), config.pac_url()); EXPECT_EQ(GetParam().auto_detect, config.auto_detect()); EXPECT_EQ(GetParam().pac_url, config.pac_url()); EXPECT_TRUE(GetParam().proxy_rules.Matches(config.proxy_rules())); } } static const CommandLineTestParams kCommandLineTestParams[] = { { "Empty command line", // Input { }, // Expected result true, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, { "No proxy", // Input { { switches::kNoProxyServer, NULL }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, { "No proxy with extra parameters.", // Input { { switches::kNoProxyServer, NULL }, { switches::kProxyServer, "http://proxy:8888" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, { "Single proxy.", // Input { { switches::kProxyServer, "http://proxy:8888" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Single( "proxy:8888", // single proxy ""), // bypass rules }, { "Per scheme proxy.", // Input { { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::PerScheme( "httpproxy:8888", // http "", // https "ftpproxy:8889", // ftp ""), // bypass rules }, { "Per scheme proxy with bypass URLs.", // Input { { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" }, { switches::kProxyBypassList, ".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8" }, }, // Expected result false, // is_null false, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::PerScheme( "httpproxy:8888", // http "", // https "ftpproxy:8889", // ftp "*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"), }, { "Pac URL", // Input { { switches::kProxyPacUrl, "http://wpad/wpad.dat" }, }, // Expected result false, // is_null false, // auto_detect GURL("http://wpad/wpad.dat"), // pac_url net::ProxyRulesExpectation::Empty(), }, { "Autodetect", // Input { { switches::kProxyAutoDetect, NULL }, }, // Expected result false, // is_null true, // auto_detect GURL(), // pac_url net::ProxyRulesExpectation::Empty(), }, }; INSTANTIATE_TEST_CASE_P( PrefProxyConfigServiceCommandLineTestInstance, PrefProxyConfigServiceCommandLineTest, testing::ValuesIn(kCommandLineTestParams)); } // namespace <|endoftext|>
<commit_before>/* * Copyright 2011 The Regents of the University of California * * 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 <cusp/array1d.h> #include <cusp/blas.h> #include <cusp/multiply.h> #include <cusp/monitor.h> #include <cusp/linear_operator.h> namespace blas = cusp::blas; namespace cusp { namespace krylov { template <typename ValueType> void ApplyPlaneRotation(ValueType& dx, ValueType& dy, ValueType& cs, ValueType& sn) { ValueType temp = cs * dx + sn *dy; dy = -sn*dx+cs*dy; dx = temp; } template <typename ValueType> void GeneratePlaneRotation(ValueType& dx, ValueType& dy, ValueType& cs, ValueType& sn) { if(dy == 0.0){ cs = 1.0; sn = 0.0; }else if (std::abs(dy) > std::abs (dx)) { ValueType tmp = dx / dy; sn = 1.0 / sqrt(ValueType(1.0) + tmp*tmp); cs = tmp*sn; }else { ValueType tmp = dy / dx; cs = 1.0 / sqrt(ValueType(1.0) + tmp*tmp); sn = tmp*cs; } } template <class LinearOperator,typename ValueType> void PlaneRotation(LinearOperator& H, ValueType& cs, ValueType& sn, ValueType& s, int i) { for (int k = 0; k < i; k++){ ApplyPlaneRotation(H(k,i), H(k+1,i), cs[k], sn[k]); } GeneratePlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]); ApplyPlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]); ApplyPlaneRotation(s[i], s[i+1], cs[i], sn[i]); } template <class LinearOperator, class Vector> void gmres(LinearOperator& A, Vector& x, Vector& b, const size_t restart) { typedef typename LinearOperator::value_type ValueType; cusp::default_monitor<ValueType> monitor(b); cusp::krylov::gmres(A, x, b, restart, monitor); } template <class LinearOperator, class Vector, class Monitor> void gmres(LinearOperator& A, Vector& x, Vector& b, const size_t restart, Monitor& monitor) { typedef typename LinearOperator::value_type ValueType; typedef typename LinearOperator::memory_space MemorySpace; cusp::identity_operator<ValueType,MemorySpace> M(A.num_rows, A.num_cols); cusp::krylov::gmres(A, x, b, restart, monitor, M); } template <class LinearOperator, class Vector, class Monitor, class Preconditioner> void gmres(LinearOperator& A, Vector& x, Vector& b, const size_t restart, Monitor& monitor, Preconditioner& M) { typedef typename LinearOperator::value_type ValueType; typedef typename LinearOperator::memory_space MemorySpace; assert(A.num_rows == A.num_cols); // sanity check const size_t N = A.num_rows; const int R = restart; int i, j, k; ValueType beta, resid0; cusp::array1d<ValueType,cusp::host_memory> rel_resid(1); //allocate workspace cusp::array1d<ValueType,MemorySpace> w(N); cusp::array1d<ValueType,MemorySpace> V0(N); //Arnoldi matrix pos 0 cusp::array2d<ValueType,MemorySpace,cusp::column_major> V(N,R+1,ValueType(0.0)); //Arnoldi matrix //duplicate copy of s on GPU cusp::array1d<ValueType,MemorySpace> sDev(R+1); //HOST WORKSPACE cusp::array2d<ValueType,cusp::host_memory,cusp::column_major> H(R+1, R); //Hessenberg matrix cusp::array1d<ValueType,cusp::host_memory> s(R+1); cusp::array1d<ValueType,cusp::host_memory> cs(R); cusp::array1d<ValueType,cusp::host_memory> sn(R); ValueType b_norm = blas::nrm2(b); do{ // compute initial residual and its norm // cusp::multiply(A, x, w); // V(0) = A*x // blas::axpy(b,w,ValueType(-1)); // V(0) = V(0) - b // cusp::multiply(M,w,w); // V(0) = M*V(0) // beta = blas::nrm2(w); // beta = norm(V(0)) // blas::scal(w, ValueType(-1.0/beta)); // V(0) = -V(0)/beta // blas::copy(w,V.column(0)); // save very first residual norm // if (monitor.iteration_count()== 0){ //resid0 = beta; cusp::multiply(M,b,V0); resid0 = blas::nrm2(V0)/b_norm; } //s = 0 // blas::fill(s,ValueType(0.0)); s[0] = beta; i = -1; do{ ++i; ++monitor; //apply preconditioner //can't pass in ref to column in V so need to use copy (w) cusp::multiply(A,w,V0); //V(i+1) = A*w = M*A*V(i) // cusp::multiply(M,V0,w); for (k = 0; k <= i; k++){ // H(k,i) = <V(i+1),V(k)> // H(k, i) = blas::dotc(w, V.column(k)); // V(i+1) -= H(k, i) * V(k) // blas::axpy(V.column(k),w,-H(k,i)); } H(i+1,i) = blas::nrm2(w); // V(i+1) = V(i+1) / H(i+1, i) // blas::scal(w,ValueType(1.0/H(i+1,i))); blas::copy(w,V.column(i+1)); PlaneRotation(H,cs,sn,s,i); rel_resid[0] = std::abs(s[i+1]) / resid0 + monitor.absolute_tolerance(); //check convergence condition //if (rel_resid < monitor.relative_tolerance()) if (monitor.finished(rel_resid)){ break; } }while (i+1 < R && monitor.iteration_count()+1 <= monitor.iteration_limit()); // solve upper triangular system in place // for (j = i; j >= 0; j--){ s[j] /= H(j,j); //S(0:j) = s(0:j) - s[j] H(0:j,j) typename cusp::array2d< ValueType, cusp::host_memory, cusp::column_major >::column_view H_j = H.column(j); blas::axpy(H_j,s,-s[j]); /* for (k = j-1; k >= 0; k--) s[k] -= H(k,j) * s[j]; */ } // update the solution // //copy s to gpu blas::copy(s,sDev); // x= V(1:N,0:i)*s(0:i)+x // for (j = 0; j <= i; j++){ // x = x + s[j] * V(j) // blas::axpy(V.column(j),x,s[j]); } } while (rel_resid[0] >= monitor.tolerance() && monitor.iteration_count()+1 <= monitor.iteration_limit()); } } // end namespace krylov } // end namespace cusp <commit_msg>Fix GMRES problem caused by fix to issue #62. Patch thanks to Joe Gordon.<commit_after>/* * Copyright 2011 The Regents of the University of California * * 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 <cusp/array1d.h> #include <cusp/blas.h> #include <cusp/multiply.h> #include <cusp/monitor.h> #include <cusp/linear_operator.h> namespace blas = cusp::blas; namespace cusp { namespace krylov { template <typename ValueType> void ApplyPlaneRotation(ValueType& dx, ValueType& dy, ValueType& cs, ValueType& sn) { ValueType temp = cs * dx + sn *dy; dy = -sn*dx+cs*dy; dx = temp; } template <typename ValueType> void GeneratePlaneRotation(ValueType& dx, ValueType& dy, ValueType& cs, ValueType& sn) { if(dy == 0.0){ cs = 1.0; sn = 0.0; }else if (std::abs(dy) > std::abs (dx)) { ValueType tmp = dx / dy; sn = 1.0 / sqrt(ValueType(1.0) + tmp*tmp); cs = tmp*sn; }else { ValueType tmp = dy / dx; cs = 1.0 / sqrt(ValueType(1.0) + tmp*tmp); sn = tmp*cs; } } template <class LinearOperator,typename ValueType> void PlaneRotation(LinearOperator& H, ValueType& cs, ValueType& sn, ValueType& s, int i) { for (int k = 0; k < i; k++){ ApplyPlaneRotation(H(k,i), H(k+1,i), cs[k], sn[k]); } GeneratePlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]); ApplyPlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]); ApplyPlaneRotation(s[i], s[i+1], cs[i], sn[i]); } template <class LinearOperator, class Vector> void gmres(LinearOperator& A, Vector& x, Vector& b, const size_t restart) { typedef typename LinearOperator::value_type ValueType; cusp::default_monitor<ValueType> monitor(b); cusp::krylov::gmres(A, x, b, restart, monitor); } template <class LinearOperator, class Vector, class Monitor> void gmres(LinearOperator& A, Vector& x, Vector& b, const size_t restart, Monitor& monitor) { typedef typename LinearOperator::value_type ValueType; typedef typename LinearOperator::memory_space MemorySpace; cusp::identity_operator<ValueType,MemorySpace> M(A.num_rows, A.num_cols); cusp::krylov::gmres(A, x, b, restart, monitor, M); } template <class LinearOperator, class Vector, class Monitor, class Preconditioner> void gmres(LinearOperator& A, Vector& x, Vector& b, const size_t restart, Monitor& monitor, Preconditioner& M) { typedef typename LinearOperator::value_type ValueType; typedef typename LinearOperator::memory_space MemorySpace; assert(A.num_rows == A.num_cols); // sanity check const size_t N = A.num_rows; const int R = restart; int i, j, k; ValueType beta, resid0; cusp::array1d<ValueType,cusp::host_memory> rel_resid(1); //allocate workspace cusp::array1d<ValueType,MemorySpace> w(N); cusp::array1d<ValueType,MemorySpace> V0(N); //Arnoldi matrix pos 0 cusp::array2d<ValueType,MemorySpace,cusp::column_major> V(N,R+1,ValueType(0.0)); //Arnoldi matrix //duplicate copy of s on GPU cusp::array1d<ValueType,MemorySpace> sDev(R+1); //HOST WORKSPACE cusp::array2d<ValueType,cusp::host_memory,cusp::column_major> H(R+1, R); //Hessenberg matrix cusp::array1d<ValueType,cusp::host_memory> s(R+1); cusp::array1d<ValueType,cusp::host_memory> cs(R); cusp::array1d<ValueType,cusp::host_memory> sn(R); ValueType b_norm = blas::nrm2(b); do{ // compute initial residual and its norm // cusp::multiply(A, x, w); // V(0) = A*x // blas::axpy(b,w,ValueType(-1)); // V(0) = V(0) - b // cusp::multiply(M,w,w); // V(0) = M*V(0) // beta = blas::nrm2(w); // beta = norm(V(0)) // blas::scal(w, ValueType(-1.0/beta)); // V(0) = -V(0)/beta // blas::copy(w,V.column(0)); // save very first residual norm // if (monitor.iteration_count()== 0){ //resid0 = beta; cusp::multiply(M,b,V0); resid0 = blas::nrm2(V0)/b_norm; } //s = 0 // blas::fill(s,ValueType(0.0)); s[0] = beta; i = -1; do{ ++i; ++monitor; //apply preconditioner //can't pass in ref to column in V so need to use copy (w) cusp::multiply(A,w,V0); //V(i+1) = A*w = M*A*V(i) // cusp::multiply(M,V0,w); for (k = 0; k <= i; k++){ // H(k,i) = <V(i+1),V(k)> // H(k, i) = blas::dotc(w, V.column(k)); // V(i+1) -= H(k, i) * V(k) // blas::axpy(V.column(k),w,-H(k,i)); } H(i+1,i) = blas::nrm2(w); // V(i+1) = V(i+1) / H(i+1, i) // blas::scal(w,ValueType(1.0/H(i+1,i))); blas::copy(w,V.column(i+1)); PlaneRotation(H,cs,sn,s,i); rel_resid[0] = std::abs(s[i+1]) / resid0 + monitor.absolute_tolerance(); //check convergence condition //if (rel_resid < monitor.relative_tolerance()) if (monitor.finished(rel_resid)){ break; } }while (i+1 < R && monitor.iteration_count()+1 <= monitor.iteration_limit()); // solve upper triangular system in place // for (j = i; j >= 0; j--){ s[j] /= H(j,j); //S(0:j) = s(0:j) - s[j] H(0:j,j) for (k = j-1; k >= 0; k--){ s[k] -= H(k,j) * s[j]; } } // update the solution // //copy s to gpu blas::copy(s,sDev); // x= V(1:N,0:i)*s(0:i)+x // for (j = 0; j <= i; j++){ // x = x + s[j] * V(j) // blas::axpy(V.column(j),x,s[j]); } } while (rel_resid[0] >= monitor.tolerance() && monitor.iteration_count()+1 <= monitor.iteration_limit()); } } // end namespace krylov } // end namespace cusp <|endoftext|>
<commit_before><commit_msg>Allow cookies and other storage data in extensions even when the user chose to block them on websites.<commit_after><|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <cstring> #include "ngraph/runtime/gpu/gpu_memory_manager.hpp" #include "ngraph/runtime/gpu/gpu_primitive_emitter.hpp" #include "ngraph/runtime/gpu/gpu_util.hpp" using namespace ngraph; constexpr const uint32_t initial_buffer_size = 10 * 1024 * 1024; runtime::gpu::GPUMemoryManager::GPUMemoryManager(GPUPrimitiveEmitter* emitter) : m_buffer_offset(0) , m_buffered_mem(initial_buffer_size) , m_workspace_manager(new pass::MemoryManager(runtime::gpu::GPUMemoryManager::alignment)) , m_argspace_mem(1, {nullptr, 0}) , m_workspace_mem(1, {nullptr, 0}) , m_primitive_emitter(emitter) { } size_t runtime::gpu::GPUMemoryManager::get_allocation_size() const { size_t allocation_size = 0; for (auto const& alloc : m_argspace_mem) { allocation_size += alloc.size; } for (auto const& alloc : m_workspace_mem) { allocation_size += alloc.size; } return allocation_size; } runtime::gpu::GPUMemoryManager::~GPUMemoryManager() { for (auto& alloc : m_argspace_mem) { runtime::gpu::free_gpu_buffer(alloc.ptr); } for (auto& alloc : m_workspace_mem) { runtime::gpu::free_gpu_buffer(alloc.ptr); } } void runtime::gpu::GPUMemoryManager::allocate() { if (m_workspace_manager->get_node_list().size() != 1) { throw std::runtime_error( "Attempt to allocate memory while reservations are inprogress. Ensure all " "GPUAllocators are closed before allocating."); } if (m_buffer_offset) { m_buffer_offset = ngraph::pass::MemoryManager::align( m_buffer_offset, runtime::gpu::GPUMemoryManager::alignment); // the back most node is always empty, fill it here m_argspace_mem.back().ptr = runtime::gpu::create_gpu_buffer(m_buffer_offset); m_argspace_mem.back().size = m_buffer_offset; // copy buffered kernel arguments to device runtime::gpu::cuda_memcpyHtD( m_argspace_mem.back().ptr, m_buffered_mem.data(), m_buffer_offset); // add an empty node to the end of the list and zero offset m_argspace_mem.push_back({nullptr, 0}); m_buffer_offset = 0; } auto workspace_size = m_workspace_manager->max_allocated(); if (workspace_size) { m_workspace_mem.back().ptr = runtime::gpu::create_gpu_buffer(workspace_size); m_workspace_mem.back().size = workspace_size; m_workspace_mem.push_back({nullptr, 0}); m_workspace_manager.reset( new pass::MemoryManager(runtime::gpu::GPUMemoryManager::alignment)); } } size_t runtime::gpu::GPUMemoryManager::queue_for_transfer(const void* data, size_t size) { // if the current allocation will overflow the host buffer if (m_buffer_offset + size > m_buffered_mem.size()) { // add more space to the managed buffer size_t new_size = m_buffered_mem.size() / initial_buffer_size + 1; m_buffered_mem.resize(new_size); } size_t offset = m_buffer_offset; std::memcpy(m_buffered_mem.data() + offset, data, size); m_buffer_offset += size; return offset; } runtime::gpu::GPUAllocator::GPUAllocator(GPUMemoryManager* mgr) : m_manager(mgr) { } runtime::gpu::GPUAllocator::GPUAllocator(const GPUAllocator& g) { m_manager = g.m_manager; m_active = g.m_active; } size_t runtime::gpu::GPUAllocator::reserve_argspace(const void* data, size_t size) { // add parameter data to host buffer that will be transfered to device size = ngraph::pass::MemoryManager::align(size, runtime::gpu::GPUMemoryManager::alignment); size_t offset = m_manager->queue_for_transfer(data, size); auto local = std::prev(m_manager->m_argspace_mem.end()); // return a lambda that will yield the gpu memory address. this // should only be evaluated by the runtime invoked primitive gpu::memory_primitive mem_primitive = [=]() { void* argspace = (*local).ptr; if (argspace == nullptr) { throw std::runtime_error("An attempt was made to use unallocated device memory."); } auto gpu_mem = static_cast<uint8_t*>(argspace); return static_cast<void*>(gpu_mem + offset); }; return m_manager->m_primitive_emitter->insert(mem_primitive); } size_t runtime::gpu::GPUAllocator::reserve_workspace(size_t size, bool zero_initialize) { size_t offset = m_manager->m_workspace_manager->allocate(size); m_active.push(offset); auto local = std::prev(m_manager->m_workspace_mem.end()); // return a lambda that will yield the gpu memory address. this // should only be evaluated by the runtime invoked primitive gpu::memory_primitive mem_primitive = [=]() { void* workspace = (*local).ptr; if (workspace == nullptr) { throw std::runtime_error("An attempt was made to use unallocated device memory."); } auto gpu_mem = static_cast<uint8_t*>(workspace); auto workspace_ptr = static_cast<void*>(gpu_mem + offset); if (zero_initialize) { runtime::gpu::cuda_memset(workspace_ptr, 0, size); } return workspace_ptr; }; return m_manager->m_primitive_emitter->insert(mem_primitive); } void runtime::gpu::GPUAllocator::close() { while (!m_active.empty()) { m_manager->m_workspace_manager->free(m_active.top()); m_active.pop(); } } runtime::gpu::GPUAllocator::~GPUAllocator() { this->close(); } <commit_msg>fix resize bug (#1745)<commit_after>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <cstring> #include "ngraph/runtime/gpu/gpu_memory_manager.hpp" #include "ngraph/runtime/gpu/gpu_primitive_emitter.hpp" #include "ngraph/runtime/gpu/gpu_util.hpp" using namespace ngraph; constexpr const uint32_t initial_buffer_size = 10 * 1024 * 1024; runtime::gpu::GPUMemoryManager::GPUMemoryManager(GPUPrimitiveEmitter* emitter) : m_buffer_offset(0) , m_buffered_mem(initial_buffer_size) , m_workspace_manager(new pass::MemoryManager(runtime::gpu::GPUMemoryManager::alignment)) , m_argspace_mem(1, {nullptr, 0}) , m_workspace_mem(1, {nullptr, 0}) , m_primitive_emitter(emitter) { } size_t runtime::gpu::GPUMemoryManager::get_allocation_size() const { size_t allocation_size = 0; for (auto const& alloc : m_argspace_mem) { allocation_size += alloc.size; } for (auto const& alloc : m_workspace_mem) { allocation_size += alloc.size; } return allocation_size; } runtime::gpu::GPUMemoryManager::~GPUMemoryManager() { for (auto& alloc : m_argspace_mem) { runtime::gpu::free_gpu_buffer(alloc.ptr); } for (auto& alloc : m_workspace_mem) { runtime::gpu::free_gpu_buffer(alloc.ptr); } } void runtime::gpu::GPUMemoryManager::allocate() { if (m_workspace_manager->get_node_list().size() != 1) { throw std::runtime_error( "Attempt to allocate memory while reservations are inprogress. Ensure all " "GPUAllocators are closed before allocating."); } if (m_buffer_offset) { m_buffer_offset = ngraph::pass::MemoryManager::align( m_buffer_offset, runtime::gpu::GPUMemoryManager::alignment); // the back most node is always empty, fill it here m_argspace_mem.back().ptr = runtime::gpu::create_gpu_buffer(m_buffer_offset); m_argspace_mem.back().size = m_buffer_offset; // copy buffered kernel arguments to device runtime::gpu::cuda_memcpyHtD( m_argspace_mem.back().ptr, m_buffered_mem.data(), m_buffer_offset); // add an empty node to the end of the list and zero offset m_argspace_mem.push_back({nullptr, 0}); m_buffer_offset = 0; } auto workspace_size = m_workspace_manager->max_allocated(); if (workspace_size) { m_workspace_mem.back().ptr = runtime::gpu::create_gpu_buffer(workspace_size); m_workspace_mem.back().size = workspace_size; m_workspace_mem.push_back({nullptr, 0}); m_workspace_manager.reset( new pass::MemoryManager(runtime::gpu::GPUMemoryManager::alignment)); } } size_t runtime::gpu::GPUMemoryManager::queue_for_transfer(const void* data, size_t size) { // if the current allocation will overflow the host buffer size_t new_size = m_buffer_offset + size; size_t buffer_size = m_buffered_mem.size(); bool need_resize = false; while (buffer_size < new_size) { // add more space to the managed buffer buffer_size <<= 1; need_resize = true; } if (need_resize) { m_buffered_mem.resize(buffer_size); } size_t offset = m_buffer_offset; std::memcpy(m_buffered_mem.data() + offset, data, size); m_buffer_offset += size; return offset; } runtime::gpu::GPUAllocator::GPUAllocator(GPUMemoryManager* mgr) : m_manager(mgr) { } runtime::gpu::GPUAllocator::GPUAllocator(const GPUAllocator& g) { m_manager = g.m_manager; m_active = g.m_active; } size_t runtime::gpu::GPUAllocator::reserve_argspace(const void* data, size_t size) { // add parameter data to host buffer that will be transfered to device size = ngraph::pass::MemoryManager::align(size, runtime::gpu::GPUMemoryManager::alignment); size_t offset = m_manager->queue_for_transfer(data, size); auto local = std::prev(m_manager->m_argspace_mem.end()); // return a lambda that will yield the gpu memory address. this // should only be evaluated by the runtime invoked primitive gpu::memory_primitive mem_primitive = [=]() { void* argspace = (*local).ptr; if (argspace == nullptr) { throw std::runtime_error("An attempt was made to use unallocated device memory."); } auto gpu_mem = static_cast<uint8_t*>(argspace); return static_cast<void*>(gpu_mem + offset); }; return m_manager->m_primitive_emitter->insert(mem_primitive); } size_t runtime::gpu::GPUAllocator::reserve_workspace(size_t size, bool zero_initialize) { size_t offset = m_manager->m_workspace_manager->allocate(size); m_active.push(offset); auto local = std::prev(m_manager->m_workspace_mem.end()); // return a lambda that will yield the gpu memory address. this // should only be evaluated by the runtime invoked primitive gpu::memory_primitive mem_primitive = [=]() { void* workspace = (*local).ptr; if (workspace == nullptr) { throw std::runtime_error("An attempt was made to use unallocated device memory."); } auto gpu_mem = static_cast<uint8_t*>(workspace); auto workspace_ptr = static_cast<void*>(gpu_mem + offset); if (zero_initialize) { runtime::gpu::cuda_memset(workspace_ptr, 0, size); } return workspace_ptr; }; return m_manager->m_primitive_emitter->insert(mem_primitive); } void runtime::gpu::GPUAllocator::close() { while (!m_active.empty()) { m_manager->m_workspace_manager->free(m_active.top()); m_active.pop(); } } runtime::gpu::GPUAllocator::~GPUAllocator() { this->close(); } <|endoftext|>
<commit_before><commit_msg>remove itself from parent when deleted. In most case, this won't happen because the parent view sets child view's parent to NULL before deletion. This is necessary to safely delete view that is not owned by parent.<commit_after><|endoftext|>
<commit_before>/* * Copyright 2016 timercrack * * 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 "MdSpi.h" #include "global.h" using namespace std; void CMdSpi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = pRspInfo->ErrorID; publisher.publish(CHANNEL_MARKET_DATA+"OnRspError:" + ntos(nRequestID), writer.write(root)); } void CMdSpi::OnFrontDisconnected(int nReason) { publisher.publish(CHANNEL_MARKET_DATA + "OnFrontDisconnected", ntos(nReason)); market_login = false; } void CMdSpi::OnHeartBeatWarning(int nTimeLapse) { publisher.publish(CHANNEL_MARKET_DATA + "OnHeartBeatWarning", ntos(nTimeLapse)); } void CMdSpi::OnFrontConnected() { publisher.publish(CHANNEL_MARKET_DATA + "OnFrontConnected", "OnFrontConnected"); } void CMdSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = 0; if (pRspInfo && pRspInfo->ErrorID != 0) { root["ErrorID"] = pRspInfo->ErrorID; } else { root["TradingDay"] = pRspUserLogin->TradingDay; root["LoginTime"] = pRspUserLogin->LoginTime; root["BrokerID"] = pRspUserLogin->BrokerID; root["UserID"] = pRspUserLogin->UserID; root["SystemName"] = pRspUserLogin->SystemName; root["FrontID"] = pRspUserLogin->FrontID; root["SessionID"] = pRspUserLogin->SessionID; root["MaxOrderRef"] = pRspUserLogin->MaxOrderRef; root["SHFETime"] = pRspUserLogin->SHFETime; root["DCETime"] = pRspUserLogin->DCETime; root["CZCETime"] = pRspUserLogin->CZCETime; root["FFEXTime"] = pRspUserLogin->FFEXTime; root["INETime"] = pRspUserLogin->INETime; market_login = true; } publisher.publish(CHANNEL_MARKET_DATA + "OnRspUserLogin", writer.write(root)); } void CMdSpi::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = 0; if (pRspInfo && pRspInfo->ErrorID != 0) { root["ErrorID"] = pRspInfo->ErrorID; } else { root["InstrumentID"] = "InstrumentID", pSpecificInstrument->InstrumentID; } publisher.publish(CHANNEL_MARKET_DATA + "OnRspSubMarketData", writer.write(root)); } void CMdSpi::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = 0; if (pRspInfo && pRspInfo->ErrorID != 0) { root["ErrorID"] = pRspInfo->ErrorID; } else { root["InstrumentID"] = "InstrumentID", pSpecificInstrument->InstrumentID; } publisher.publish(CHANNEL_MARKET_DATA + "OnRspUnSubMarketData", writer.write(root)); } void CMdSpi::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pData) { Json::Value root; root["TradingDay"] = pData->TradingDay; root["InstrumentID"] = pData->InstrumentID; root["ExchangeID"] = pData->ExchangeID; root["ExchangeInstID"] = pData->ExchangeInstID; root["LastPrice"] = pData->LastPrice; root["PreSettlementPrice"] = pData->PreSettlementPrice; root["PreClosePrice"] = pData->PreClosePrice; root["PreOpenInterest"] = pData->PreOpenInterest; root["OpenPrice"] = pData->OpenPrice; root["HighestPrice"] = pData->HighestPrice; root["LowestPrice"] = pData->LowestPrice; root["Volume"] = pData->Volume; root["Turnover"] = pData->Turnover; root["OpenInterest"] = pData->OpenInterest; root["ClosePrice"] = pData->ClosePrice; root["SettlementPrice"] = pData->SettlementPrice; root["UpperLimitPrice"] = pData->UpperLimitPrice; root["LowerLimitPrice"] = pData->LowerLimitPrice; root["PreDelta"] = pData->PreDelta; root["CurrDelta"] = pData->CurrDelta; root["UpdateMillisec"] = pData->UpdateMillisec; root["BidPrice1"] = pData->BidPrice1; root["BidVolume1"] = pData->BidVolume1; root["AskPrice1"] = pData->AskPrice1; root["AskVolume1"] = pData->AskVolume1; root["BidPrice2"] = pData->BidPrice2; root["BidVolume2"] = pData->BidVolume2; root["AskPrice2"] = pData->AskPrice2; root["AskVolume2"] = pData->AskVolume2; root["BidPrice3"] = pData->BidPrice3; root["BidVolume3"] = pData->BidVolume3; root["AskPrice3"] = pData->AskPrice3; root["AskVolume3"] = pData->AskVolume3; root["BidPrice4"] = pData->BidPrice4; root["BidVolume4"] = pData->BidVolume4; root["AskPrice4"] = pData->AskPrice4; root["AskVolume4"] = pData->AskVolume4; root["BidPrice5"] = pData->BidPrice5; root["BidVolume5"] = pData->BidVolume5; root["AskPrice5"] = pData->AskPrice5; root["AskVolume5"] = pData->AskVolume5; root["AveragePrice"] = pData->AveragePrice; root["ActionDay"] = pData->ActionDay; publisher.publish(CHANNEL_MARKET_DATA + "OnRtnDepthMarketData", writer.write(root)); } <commit_msg>add request id<commit_after>/* * Copyright 2016 timercrack * * 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 "MdSpi.h" #include "global.h" using namespace std; void CMdSpi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = pRspInfo->ErrorID; publisher.publish(CHANNEL_MARKET_DATA + "OnRspError:" + ntos(nRequestID), writer.write(root)); } void CMdSpi::OnFrontDisconnected(int nReason) { publisher.publish(CHANNEL_MARKET_DATA + "OnFrontDisconnected", ntos(nReason)); market_login = false; } void CMdSpi::OnHeartBeatWarning(int nTimeLapse) { publisher.publish(CHANNEL_MARKET_DATA + "OnHeartBeatWarning", ntos(nTimeLapse)); } void CMdSpi::OnFrontConnected() { publisher.publish(CHANNEL_MARKET_DATA + "OnFrontConnected", "OnFrontConnected"); } void CMdSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = 0; if (pRspInfo && pRspInfo->ErrorID != 0) { root["ErrorID"] = pRspInfo->ErrorID; } else { root["TradingDay"] = pRspUserLogin->TradingDay; root["LoginTime"] = pRspUserLogin->LoginTime; root["BrokerID"] = pRspUserLogin->BrokerID; root["UserID"] = pRspUserLogin->UserID; root["SystemName"] = pRspUserLogin->SystemName; root["FrontID"] = pRspUserLogin->FrontID; root["SessionID"] = pRspUserLogin->SessionID; root["MaxOrderRef"] = pRspUserLogin->MaxOrderRef; root["SHFETime"] = pRspUserLogin->SHFETime; root["DCETime"] = pRspUserLogin->DCETime; root["CZCETime"] = pRspUserLogin->CZCETime; root["FFEXTime"] = pRspUserLogin->FFEXTime; root["INETime"] = pRspUserLogin->INETime; market_login = true; } publisher.publish(CHANNEL_MARKET_DATA + "OnRspUserLogin", writer.write(root)); } void CMdSpi::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = 0; if (pRspInfo && pRspInfo->ErrorID != 0) { root["ErrorID"] = pRspInfo->ErrorID; } else { root["InstrumentID"] = "InstrumentID", pSpecificInstrument->InstrumentID; } publisher.publish(CHANNEL_MARKET_DATA + "OnRspSubMarketData:" + ntos(nRequestID), writer.write(root)); } void CMdSpi::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Json::Value root; root["nRequestID"] = nRequestID; root["bIsLast"] = bIsLast; root["ErrorID"] = 0; if (pRspInfo && pRspInfo->ErrorID != 0) { root["ErrorID"] = pRspInfo->ErrorID; } else { root["InstrumentID"] = "InstrumentID", pSpecificInstrument->InstrumentID; } publisher.publish(CHANNEL_MARKET_DATA + "OnRspUnSubMarketData:" + ntos(nRequestID), writer.write(root)); } void CMdSpi::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pData) { Json::Value root; root["TradingDay"] = pData->TradingDay; root["InstrumentID"] = pData->InstrumentID; root["ExchangeID"] = pData->ExchangeID; root["ExchangeInstID"] = pData->ExchangeInstID; root["LastPrice"] = pData->LastPrice; root["PreSettlementPrice"] = pData->PreSettlementPrice; root["PreClosePrice"] = pData->PreClosePrice; root["PreOpenInterest"] = pData->PreOpenInterest; root["OpenPrice"] = pData->OpenPrice; root["HighestPrice"] = pData->HighestPrice; root["LowestPrice"] = pData->LowestPrice; root["Volume"] = pData->Volume; root["Turnover"] = pData->Turnover; root["OpenInterest"] = pData->OpenInterest; root["ClosePrice"] = pData->ClosePrice; root["SettlementPrice"] = pData->SettlementPrice; root["UpperLimitPrice"] = pData->UpperLimitPrice; root["LowerLimitPrice"] = pData->LowerLimitPrice; root["PreDelta"] = pData->PreDelta; root["CurrDelta"] = pData->CurrDelta; root["UpdateMillisec"] = pData->UpdateMillisec; root["BidPrice1"] = pData->BidPrice1; root["BidVolume1"] = pData->BidVolume1; root["AskPrice1"] = pData->AskPrice1; root["AskVolume1"] = pData->AskVolume1; root["BidPrice2"] = pData->BidPrice2; root["BidVolume2"] = pData->BidVolume2; root["AskPrice2"] = pData->AskPrice2; root["AskVolume2"] = pData->AskVolume2; root["BidPrice3"] = pData->BidPrice3; root["BidVolume3"] = pData->BidVolume3; root["AskPrice3"] = pData->AskPrice3; root["AskVolume3"] = pData->AskVolume3; root["BidPrice4"] = pData->BidPrice4; root["BidVolume4"] = pData->BidVolume4; root["AskPrice4"] = pData->AskPrice4; root["AskVolume4"] = pData->AskVolume4; root["BidPrice5"] = pData->BidPrice5; root["BidVolume5"] = pData->BidVolume5; root["AskPrice5"] = pData->AskPrice5; root["AskVolume5"] = pData->AskVolume5; root["AveragePrice"] = pData->AveragePrice; root["ActionDay"] = pData->ActionDay; publisher.publish(CHANNEL_MARKET_DATA + "OnRtnDepthMarketData:" + root["InstrumentID"].asString(), writer.write(root)); } <|endoftext|>
<commit_before>#pragma once #include "./mozart/function.hpp" #include "./mozart/switcher.hpp" #include "./mozart/tuple.hpp" #include "./mozart/any.hpp" #include <stdexcept> #include <cstdio> #include <string> #include <deque> #include <list> namespace cov_basic { enum class signs { Null,And,Or,Not,Above,Under, Equ,NotEqu,AboveEqu,UnderEqu }; using number=long double; using boolean=bool; using string=std::string; class function { std::deque<string> mArgs; std::deque<string> mBuf; public: number* retval=nullptr; function()=delete; function(const std::deque<string>& args,const std::deque<string>& buf):mArgs(args),mBuf(buf) {} ~function()=default; number call(const std::deque<cov::any>&); bool operator==(const function& f) const { return this==&f; } }; class native_interface { cov::function<number(const std::deque<cov::any>&)> mFunc; public: native_interface()=delete; native_interface(const cov::function<number(const std::deque<cov::any>&)>& func):mFunc(func) {} ~native_interface()=default; number call(const std::deque<cov::any>& args) { return mFunc(args); } bool operator==(const native_interface& n) const { return this==&n; } }; class domain_manager { std::list<std::list<cov::tuple<string,cov::any>>> m_data; public: domain_manager() { m_data.emplace_front(); } domain_manager(const domain_manager&)=delete; ~domain_manager()=default; void add_domain() { m_data.emplace_front(); } void remove_domain() { if(m_data.size()>1) m_data.pop_front(); } bool var_exsist(const string& name) { for(auto& domain:m_data) for(auto& var:domain) if(var.get<0>()==name) return true; return false; } bool var_exsist_global(const string& name) { for(auto& var:m_data.back()) if(var.get<0>()==name) return true; return false; } cov::any& get_var(const string& name) { for(auto& domain:m_data) for(auto& var:domain) if(var.get<0>()==name) return var.get<1>(); throw std::logic_error("Use of undefined variable."); } cov::any& get_var_global(const string& name) { for(auto& var:m_data.back()) if(var.get<0>()==name) return var.get<1>(); throw std::logic_error("Use of undefined variable."); } void add_var(const string& name,const cov::any& var) { if(var_exsist(name)) get_var(name)=var; else m_data.front().push_front({name,var}); } void add_var_global(const string& name,const cov::any& var) { if(var_exsist(name)) get_var_global(name)=var; else m_data.back().push_front({name,var}); } }; static domain_manager storage; void split_str(char signal,const string& str,std::deque<string>& data) { string tmp; bool is_str=false; for(auto& c:str) { if(c=='\"'){ is_str=is_str?false:true; tmp+=c; continue; } if(is_str){ tmp+=c; continue; } if(c==signal) { if(!tmp.empty()) { data.push_back(tmp); tmp.clear(); } continue; } tmp+=c; } if(!tmp.empty()) data.push_back(tmp); } signs match_signal(const string& str) { signs ret; Switch(str) { Default { ret=signs::Null; } EndCase; Case("&&") { ret=signs::And; } EndCase; Case("||") { ret=signs::Or; } EndCase; Case("!") { ret=signs::Not; } EndCase; Case(">") { ret=signs::Above; } EndCase; Case("<") { ret=signs::Under; } EndCase; Case("==") { ret=signs::Equ; } EndCase; Case("!=") { ret=signs::NotEqu; } EndCase; Case(">=") { ret=signs::AboveEqu; } EndCase; Case("<=") { ret=signs::UnderEqu; } EndCase; } EndSwitch; return ret; } bool is_signal(char signal) { switch(signal) { case '>': break; case '<': break; case '=': break; case '!': break; case '&': break; case '|': break; default: return false; } return true; } bool is_bool_exp(const string& str) { for(auto& ch:str) { if(is_signal(ch)) return true; } return false; } cov::any& get_value(const string& name) { auto pos=name.find("::"); if(pos!=string::npos&&name.substr(0,pos)=="global") { string n=name.substr(pos+2); if(storage.var_exsist_global(n)) return storage.get_var_global(n); } return storage.get_var(name); } bool exsist(const string& name) { auto pos=name.find("::"); if(pos!=string::npos&&name.substr(0,pos)=="global") { string n=name.substr(pos+2); return storage.var_exsist_global(n); } return storage.var_exsist(name); } bool compute_boolean(const string&); number compute_number(const string&); cov::any infer_value(const string& str) { if(exsist(str)) return get_value(str); if(str.find('\"')!=string::npos) return str.substr(str.find('\"')+1,str.rfind('\"')-str.find('\"')-1); if(str=="True") return true; if(str=="False") return false; if(is_bool_exp(str)) return compute_boolean(str); else return compute_number(str); } bool compute_boolean(const string & exp) { bool reverse = false; bool is_str = false; std::deque < signs > signals; std::deque < string > conditions; string tmp; for (int i = 0; i < exp.size();) { if (std::isspace(exp[i])&&!is_str) { ++i; continue; } if(exp[i]=='\"') is_str=is_str?false:true; /*if (exp[i] == '(') { int level(1), pos(++i); for (; pos < exp.size() && level > 0; ++pos) { if (exp[pos] == '(') ++level; if (exp[pos] == ')') --level; } if (level > 0) throw std::logic_error("The lack of corresponding brackets."); if(compute_boolean(exp.substr(i, pos - i - 1))?(reverse?false:true):(reverse?true:false)) conditions.push_back("True"); else conditions.push_back("False"); reverse=false; i = pos; continue; }*/ if (is_signal(exp[i])&&(i<exp.size()?(is_signal(exp[i+1])?true:exp[i]!='!'):exp[i]!='!')) { if(!tmp.empty()) conditions.push_back(tmp); tmp.clear(); string currentSignal(1,exp[i]); if(i<exp.size()) { if(is_signal(exp[++i])) currentSignal+=exp[i]; else tmp+=exp[i]; } signals.push_back(match_signal(currentSignal)); ++i; continue; } if(i<exp.size()&&exp[i]=='!'&&exp[i+1]=='(') { reverse=true; ++i; continue; } tmp+=exp[i]; ++i; } if(!tmp.empty()) conditions.push_back(tmp); cov::any val; auto parse=[](const string& str) { cov::any value; if(str[0]=='!') { value=infer_value(str.substr(1)); if(value.type()!=typeid(bool)) throw std::logic_error("DE0003"); value=value.val<bool>()?false:true; } else value=infer_value(str); return value; }; val=parse(conditions.front()); conditions.pop_front(); for(auto &it:conditions) { cov::any v=parse(it); switch(signals.front()) { case signs::And: val=(v.val<bool>()&&val.val<bool>()); break; case signs::Or: val=(v.val<bool>()||val.val<bool>()); break; case signs::Above: if(val.type()==v.type()) { if(val.type()==typeid(number)) { val=(val.val<number>()>v.val<number>()); break; } } throw std::logic_error("DE0003"); break; case signs::Under: if(val.type()==v.type()) { if(val.type()==typeid(number)) { val=(val.val<number>()<v.val<number>()); break; } } throw std::logic_error("DE0003"); break; case signs::Equ: val=(val==v); break; case signs::NotEqu: val=(val!=v); break; case signs::AboveEqu: if(val.type()==v.type()) { if(val.type()==typeid(number)) { val=(val.val<number>()>=v.val<number>()); break; } } throw std::logic_error("DE0003"); break; case signs::UnderEqu: if(val.type()==v.type()) { if(val.type()==typeid(number)) { val=(val.val<number>()<=v.val<number>()); break; } } throw std::logic_error("DE0003"); break; } signals.pop_front(); } return val.val<bool>(); } number compute_number(const string& exp) { bool reverse = false; std::deque<number> nums; std::deque<char>operators; string tmp; for (int i = 0; i < exp.size();) { if (std::isspace(exp[i])) { ++i; continue; } if (exp[i] == '(') { int level(1), pos(++i); for (; pos < exp.size() && level > 0; ++pos) { if (exp[pos] == '(') ++level; if (exp[pos] == ')') --level; } if (level > 0) throw std::logic_error("The lack of corresponding brackets."); nums.push_back(compute_number(exp.substr(i, pos - i - 1))); i = pos; continue; } if (std::ispunct(exp[i])&&exp[i]!=':') { if (nums.empty()) { switch (exp[i]) { case '+': reverse = false; break; case '-': reverse = true; break; default: throw std::logic_error("Operator does not recognize.~~~"); } ++i; continue; } operators.push_back(exp[i]); ++i; continue; } if (std::isdigit(exp[i]) || exp[i] == '.') { tmp.clear(); for (; i < exp.size() && (isdigit(exp[i]) || exp[i] == '.'); ++i) tmp += exp[i]; nums.push_back(std::stof(tmp)); continue; } if (std::isalpha(exp[i]) || exp[i]==':') { tmp.clear(); for (; i < exp.size() && (std::isalnum(exp[i]) || exp[i] == '_' || exp[i]==':'); ++i) tmp += exp[i]; cov::any& obj=get_value(tmp); if (obj.type()==typeid(function)||obj.type()==typeid(native_interface)) { int level(1), pos(++i); for (; pos < exp.size() && level > 0; ++pos) { if (exp[pos] == '(') ++level; if (exp[pos] == ')') --level; } if (level > 0) throw std::logic_error("The lack of corresponding brackets."); std::deque <cov::any> args; if(pos-i>1) { string arglist = exp.substr(i, pos - i - 1); string temp; bool is_str=false; for (int i = 0; i < arglist.size(); ++i) { if(arglist[i]=='(') ++level; if(arglist[i]==')') --level; if(arglist[i]=='\"') is_str=is_str?false:true; if (is_str || level>0 || arglist[i] != ',') { temp += arglist[i]; } else { args.push_back(infer_value(temp)); temp.clear(); } } args.push_back(infer_value(temp)); } Switch(obj.type()) { Case(typeid(function)) { nums.push_back(obj.val<function>().call(args)); } EndCase; Case(typeid(native_interface)) { nums.push_back(obj.val<native_interface>().call(args)); } EndCase; } EndSwitch; i = pos; continue; } nums.push_back(infer_value(tmp).val<number>()); continue; } throw std::logic_error("Operator does not recognize.-----"); } if (nums.empty()) return -1; number left = nums.front(); number right = 0; char signal = 0; nums.pop_front(); for (auto & current:nums) { switch (operators.front()) { case '+': { if (right != 0) { switch (signal) { case '+': left += right; break; case '-': left -= right; break; } } right = current; signal = '+'; break; } case '-': { if (right != 0) { switch (signal) { case '+': left += right; break; case '-': left -= right; break; } } right = current; signal = '-'; break; } case '*': { if (right != 0) right *= current; else left *= current; break; } case '/': { if (right != 0) right /= current; else left /= current; break; } default: throw std::logic_error("Operator does not recognize."); } operators.pop_front(); } number result = 0; switch (signal) { case '+': result = left + right; break; case '-': result = left - right; break; default: result = left; break; } if (reverse) result = -result; return result; } enum class statements { If,While,For,Function }; std::deque<cov::tuple<statements,std::deque<string>>> buffer; int bracket_count=0; function* current_func=nullptr; void parse_define(const string& raw_str) { string str=raw_str.substr(raw_str.find("Define")+6); string name; for(auto& ch:str) { if(std::isspace(ch)) continue; if(ch=='=') break; name+=ch; } storage.add_var(name,infer_value(raw_str.substr(raw_str.find('=')+1))); } void parse_assign(const string& raw_str) { string name; for(auto& ch:raw_str) { if(std::isspace(ch)) continue; if(ch=='=') break; name+=ch; } storage.add_var(name,infer_value(raw_str.substr(raw_str.find('=')+1))); } void parse_return(const string& str) { if(current_func==nullptr) throw std::logic_error("Return in non-function area."); current_func->retval=new number(compute_number(str.substr(str.find("Return")+6))); } void parse_if(const std::deque<string>&); void parse_while(const std::deque<string>&); void parse_function(const std::deque<string>&); void parse(const string& str) { if(bracket_count!=0) { if(str.find("If")!=string::npos||str.find("While")!=string::npos||str.find("Function")!=string::npos) ++bracket_count; else if(str.find("End")!=string::npos) { --bracket_count; if(bracket_count==0) { switch(buffer.front().get<0>()) { case statements::If: parse_if(buffer.front().get<1>()); buffer.pop_front(); break; case statements::While: parse_while(buffer.front().get<1>()); buffer.pop_front(); break; case statements::Function: parse_function(buffer.front().get<1>()); buffer.pop_front(); break; } return; } } buffer.front().get<1>().push_back(str); return; } if(str.find("Define")!=string::npos) { parse_define(str); return; } if(str.find("Return")!=string::npos) { parse_return(str); return; } if(str.find("If")!=string::npos) { buffer.push_front(cov::tuple<statements,std::deque<string>>(statements::If,std::deque<string>({str}))); ++bracket_count; return; } if(str.find("While")!=string::npos) { buffer.push_front(cov::tuple<statements,std::deque<string>>(statements::While,std::deque<string>({str}))); ++bracket_count; return; } if(str.find("Function")!=string::npos) { buffer.push_front(cov::tuple<statements,std::deque<string>>(statements::Function,std::deque<string>({str}))); ++bracket_count; return; } if(str.find('=')!=string::npos) { parse_assign(str); return; } if(is_bool_exp(str)) compute_boolean(str); else compute_number(str); } void parse_if(const std::deque<string>& raw_buf) { if(raw_buf.empty()) throw std::logic_error(__func__); storage.add_domain(); string head=raw_buf.front(); auto if_pos=head.find("If"); auto then_pos=head.rfind("Then"); bool result=compute_boolean(head.substr(if_pos+2,then_pos-if_pos-2)); std::size_t pos=0; for(std::size_t i=1; i<raw_buf.size(); ++i) { if(raw_buf.at(i).find("Else")!=string::npos) { pos=i; break; } } if(pos==0) pos=raw_buf.size(); if(result) { for(std::size_t i=1; i<pos; ++i) parse(raw_buf.at(i)); } else { for(std::size_t i=pos+1; i<raw_buf.size(); ++i) parse(raw_buf.at(i)); } storage.remove_domain(); } void parse_while(const std::deque<string>& raw_buf) { if(raw_buf.empty()) throw std::logic_error(__func__); storage.add_domain(); string head=raw_buf.front(); auto while_pos=head.find("While")+5; auto do_pos=head.rfind("Do"); string condition=head.substr(while_pos,do_pos-while_pos); while(compute_boolean(condition)){ for(std::size_t i=1; i<raw_buf.size(); ++i) parse(raw_buf.at(i)); } storage.remove_domain(); } void parse_function(const std::deque<string>& raw_buf) { if(raw_buf.empty()) throw std::logic_error(__func__); string head=raw_buf.front(); string name; std::deque<string> arglist; auto lpos=head.find('(')+1; auto rpos=head.rfind(')'); if(lpos!=rpos) split_str(',',head.substr(lpos,rpos-lpos),arglist); for(auto i=head.find("Function")+8; i<lpos-1; ++i) if(!std::isspace(head.at(i))) name+=head.at(i); storage.add_var_global(name,function(arglist,std::deque<string>(raw_buf.begin()+1,raw_buf.end()))); } number function::call(const std::deque<cov::any>& args) { if(args.size()!=mArgs.size()) throw std::logic_error("Wrong size of arguments"); current_func=this; storage.add_domain(); for(std::size_t i=0; i<args.size(); ++i) storage.add_var(mArgs.at(i),args.at(i)); for(auto& it:mBuf){ parse(it); if(retval!=nullptr) { current_func=nullptr; number ret=*retval; delete retval; return ret; } } storage.remove_domain(); current_func=nullptr; return number(0); } } namespace std { template<>std::string to_string<bool>(const bool& v) { if(v) return "True"; else return "False"; } }<commit_msg>Delete core.hpp<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Movie.h" #include "Media.h" #include "database/SqliteTools.h" #include "database/SqliteQuery.h" namespace medialibrary { const std::string Movie::Table::Name = "Movie"; const std::string Movie::Table::PrimaryKeyColumn = "id_movie"; int64_t Movie::* const Movie::Table::PrimaryKey = &Movie::m_id; Movie::Movie(MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) , m_id( row.extract<decltype(m_id)>() ) , m_mediaId( row.extract<decltype(m_mediaId)>() ) , m_summary( row.extract<decltype(m_summary)>() ) , m_imdbId( row.extract<decltype(m_imdbId)>() ) { assert( row.hasRemainingColumns() == false ); } Movie::Movie( MediaLibraryPtr ml, int64_t mediaId ) : m_ml( ml ) , m_id( 0 ) , m_mediaId( mediaId ) { } int64_t Movie::id() const { return m_id; } const std::string& Movie::shortSummary() const { return m_summary; } bool Movie::setShortSummary( const std::string& summary ) { static const std::string req = "UPDATE " + Movie::Table::Name + " SET summary = ? WHERE id_movie = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, summary, m_id ) == false ) return false; m_summary = summary; return true; } const std::string& Movie::imdbId() const { return m_imdbId; } bool Movie::setImdbId( const std::string& imdbId ) { static const std::string req = "UPDATE " + Movie::Table::Name + " SET imdb_id = ? WHERE id_movie = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, imdbId, m_id ) == false ) return false; m_imdbId = imdbId; return true; } void Movie::createTable( sqlite::Connection* dbConnection ) { const std::string reqs[] = { schema( Table::Name, Settings::DbModelVersion ), "CREATE INDEX IF NOT EXISTS movie_media_idx ON " + Table::Name + "(media_id)", }; for ( const auto& req : reqs ) sqlite::Tools::executeRequest( dbConnection, req ); } std::string Movie::schema( const std::string& tableName, uint32_t ) { assert( tableName == Table::Name ); return "CREATE TABLE " + Table::Name + "(" "id_movie INTEGER PRIMARY KEY AUTOINCREMENT," "media_id UNSIGNED INTEGER NOT NULL," "summary TEXT," "imdb_id TEXT," "FOREIGN KEY(media_id) REFERENCES " + Media::Table::Name + "(id_media) ON DELETE CASCADE" ")"; } bool Movie::checkDbModel(MediaLibraryPtr ml) { return sqlite::Tools::checkSchema( ml->getConn(), schema( Table::Name, Settings::DbModelVersion ), Table::Name ); } std::shared_ptr<Movie> Movie::create(MediaLibraryPtr ml, int64_t mediaId ) { auto movie = std::make_shared<Movie>( ml, mediaId ); static const std::string req = "INSERT INTO " + Movie::Table::Name + "(media_id) VALUES(?)"; if ( insert( ml, movie, req, mediaId ) == false ) return nullptr; return movie; } MoviePtr Movie::fromMedia( MediaLibraryPtr ml, int64_t mediaId ) { static const std::string req = "SELECT * FROM " + Movie::Table::Name + " WHERE media_id = ?"; return fetch( ml, req, mediaId ); } } <commit_msg>Movie.cpp: Remove unneeded include<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Movie.h" #include "Media.h" #include "database/SqliteTools.h" namespace medialibrary { const std::string Movie::Table::Name = "Movie"; const std::string Movie::Table::PrimaryKeyColumn = "id_movie"; int64_t Movie::* const Movie::Table::PrimaryKey = &Movie::m_id; Movie::Movie(MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) , m_id( row.extract<decltype(m_id)>() ) , m_mediaId( row.extract<decltype(m_mediaId)>() ) , m_summary( row.extract<decltype(m_summary)>() ) , m_imdbId( row.extract<decltype(m_imdbId)>() ) { assert( row.hasRemainingColumns() == false ); } Movie::Movie( MediaLibraryPtr ml, int64_t mediaId ) : m_ml( ml ) , m_id( 0 ) , m_mediaId( mediaId ) { } int64_t Movie::id() const { return m_id; } const std::string& Movie::shortSummary() const { return m_summary; } bool Movie::setShortSummary( const std::string& summary ) { static const std::string req = "UPDATE " + Movie::Table::Name + " SET summary = ? WHERE id_movie = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, summary, m_id ) == false ) return false; m_summary = summary; return true; } const std::string& Movie::imdbId() const { return m_imdbId; } bool Movie::setImdbId( const std::string& imdbId ) { static const std::string req = "UPDATE " + Movie::Table::Name + " SET imdb_id = ? WHERE id_movie = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, imdbId, m_id ) == false ) return false; m_imdbId = imdbId; return true; } void Movie::createTable( sqlite::Connection* dbConnection ) { const std::string reqs[] = { schema( Table::Name, Settings::DbModelVersion ), "CREATE INDEX IF NOT EXISTS movie_media_idx ON " + Table::Name + "(media_id)", }; for ( const auto& req : reqs ) sqlite::Tools::executeRequest( dbConnection, req ); } std::string Movie::schema( const std::string& tableName, uint32_t ) { assert( tableName == Table::Name ); return "CREATE TABLE " + Table::Name + "(" "id_movie INTEGER PRIMARY KEY AUTOINCREMENT," "media_id UNSIGNED INTEGER NOT NULL," "summary TEXT," "imdb_id TEXT," "FOREIGN KEY(media_id) REFERENCES " + Media::Table::Name + "(id_media) ON DELETE CASCADE" ")"; } bool Movie::checkDbModel(MediaLibraryPtr ml) { return sqlite::Tools::checkSchema( ml->getConn(), schema( Table::Name, Settings::DbModelVersion ), Table::Name ); } std::shared_ptr<Movie> Movie::create(MediaLibraryPtr ml, int64_t mediaId ) { auto movie = std::make_shared<Movie>( ml, mediaId ); static const std::string req = "INSERT INTO " + Movie::Table::Name + "(media_id) VALUES(?)"; if ( insert( ml, movie, req, mediaId ) == false ) return nullptr; return movie; } MoviePtr Movie::fromMedia( MediaLibraryPtr ml, int64_t mediaId ) { static const std::string req = "SELECT * FROM " + Movie::Table::Name + " WHERE media_id = ?"; return fetch( ml, req, mediaId ); } } <|endoftext|>